repo
stringclasses 1
value | instance_id
stringlengths 22
24
| problem_statement
stringlengths 24
24.1k
| patch
stringlengths 0
1.9M
| test_patch
stringclasses 1
value | created_at
stringdate 2022-11-25 05:12:07
2025-10-09 08:44:51
| hints_text
stringlengths 11
235k
| base_commit
stringlengths 40
40
|
|---|---|---|---|---|---|---|---|
juspay/hyperswitch
|
juspay__hyperswitch-5770
|
Bug: feat(user): new invitations api
New api to list invitations for users (not just limited to merchant accounts).
Api should be compatibly with work with user jwt token and single purpose jwt token.
|
diff --git a/crates/api_models/src/user_role.rs b/crates/api_models/src/user_role.rs
index 4718da28d27..e4819b74fbc 100644
--- a/crates/api_models/src/user_role.rs
+++ b/crates/api_models/src/user_role.rs
@@ -1,5 +1,6 @@
use common_enums::PermissionGroup;
use common_utils::pii;
+use masking::Secret;
pub mod role;
@@ -138,3 +139,11 @@ pub struct ListUsersInEntityResponse {
pub email: pii::Email,
pub roles: Vec<role::MinimalRoleInfo>,
}
+
+#[derive(Debug, serde::Deserialize, serde::Serialize)]
+pub struct ListInvitationForUserResponse {
+ pub entity_id: String,
+ pub entity_type: common_enums::EntityType,
+ pub entity_name: Option<Secret<String>>,
+ pub role_id: String,
+}
diff --git a/crates/diesel_models/src/query/user_role.rs b/crates/diesel_models/src/query/user_role.rs
index fde146408a9..1cd25e54cb3 100644
--- a/crates/diesel_models/src/query/user_role.rs
+++ b/crates/diesel_models/src/query/user_role.rs
@@ -8,7 +8,11 @@ use error_stack::{report, ResultExt};
use router_env::logger;
use crate::{
- enums::UserRoleVersion, errors, query::generics, schema::user_roles::dsl, user_role::*,
+ enums::{UserRoleVersion, UserStatus},
+ errors,
+ query::generics,
+ schema::user_roles::dsl,
+ user_role::*,
PgPooledConn, StorageResult,
};
@@ -201,6 +205,7 @@ impl UserRole {
.await
}
+ #[allow(clippy::too_many_arguments)]
pub async fn generic_user_roles_list_for_user(
conn: &PgPooledConn,
user_id: String,
@@ -208,7 +213,9 @@ impl UserRole {
merchant_id: Option<id_type::MerchantId>,
profile_id: Option<id_type::ProfileId>,
entity_id: Option<String>,
+ status: Option<UserStatus>,
version: Option<UserRoleVersion>,
+ limit: Option<u32>,
) -> StorageResult<Vec<Self>> {
let mut query = <Self as HasTable>::table()
.filter(dsl::user_id.eq(user_id))
@@ -234,6 +241,14 @@ impl UserRole {
query = query.filter(dsl::version.eq(version));
}
+ if let Some(status) = status {
+ query = query.filter(dsl::status.eq(status));
+ }
+
+ if let Some(limit) = limit {
+ query = query.limit(limit.into());
+ }
+
router_env::logger::debug!(query = %debug_query::<Pg,_>(&query).to_string());
match generics::db_metrics::track_database_call::<Self, _, _>(
diff --git a/crates/diesel_models/src/user_role.rs b/crates/diesel_models/src/user_role.rs
index ac7def5ec2a..c454e8b58bc 100644
--- a/crates/diesel_models/src/user_role.rs
+++ b/crates/diesel_models/src/user_role.rs
@@ -26,7 +26,7 @@ pub struct UserRole {
pub version: enums::UserRoleVersion,
}
-fn get_entity_id_and_type(user_role: &UserRole) -> (Option<String>, Option<EntityType>) {
+pub fn get_entity_id_and_type(user_role: &UserRole) -> (Option<String>, Option<EntityType>) {
match (user_role.version, user_role.role_id.as_str()) {
(enums::UserRoleVersion::V1, consts::ROLE_ID_ORGANIZATION_ADMIN) => (
user_role
diff --git a/crates/router/src/core/user.rs b/crates/router/src/core/user.rs
index f06e804cecc..8e99a202dfe 100644
--- a/crates/router/src/core/user.rs
+++ b/crates/router/src/core/user.rs
@@ -33,7 +33,10 @@ use crate::services::email::types as email_types;
use crate::{
consts,
core::encryption::send_request_to_key_service_for_user,
- db::domain::user_authentication_method::DEFAULT_USER_AUTH_METHOD,
+ db::{
+ domain::user_authentication_method::DEFAULT_USER_AUTH_METHOD,
+ user_role::ListUserRolesByUserIdPayload,
+ },
routes::{app::ReqState, SessionState},
services::{authentication as auth, authorization::roles, openidconnect, ApplicationResponse},
types::{domain, transformers::ForeignInto},
@@ -2282,22 +2285,20 @@ pub async fn list_orgs_for_user(
) -> UserResponse<Vec<user_api::ListOrgsForUserResponse>> {
let orgs = state
.store
- .list_user_roles_by_user_id(
- user_from_token.user_id.as_str(),
- None,
- None,
- None,
- None,
- None,
- )
+ .list_user_roles_by_user_id(ListUserRolesByUserIdPayload {
+ user_id: user_from_token.user_id.as_str(),
+ org_id: None,
+ merchant_id: None,
+ profile_id: None,
+ entity_id: None,
+ version: None,
+ status: Some(UserStatus::Active),
+ limit: None,
+ })
.await
.change_context(UserErrors::InternalServerError)?
.into_iter()
- .filter_map(|user_role| {
- (user_role.status == UserStatus::Active)
- .then_some(user_role.org_id)
- .flatten()
- })
+ .filter_map(|user_role| user_role.org_id)
.collect::<HashSet<_>>();
let resp = futures::future::try_join_all(
@@ -2311,7 +2312,11 @@ pub async fn list_orgs_for_user(
org_id: org.get_organization_id(),
org_name: org.get_organization_name(),
})
- .collect();
+ .collect::<Vec<_>>();
+
+ if resp.is_empty() {
+ Err(UserErrors::InternalServerError).attach_printable("No orgs found for a user")?;
+ }
Ok(ApplicationResponse::Json(resp))
}
@@ -2344,26 +2349,24 @@ pub async fn list_merchants_for_user_in_org(
merchant_id: merchant_account.get_id().to_owned(),
},
)
- .collect()
+ .collect::<Vec<_>>()
} else {
let merchant_ids = state
.store
- .list_user_roles_by_user_id(
- user_from_token.user_id.as_str(),
- Some(&user_from_token.org_id),
- None,
- None,
- None,
- None,
- )
+ .list_user_roles_by_user_id(ListUserRolesByUserIdPayload {
+ user_id: user_from_token.user_id.as_str(),
+ org_id: Some(&user_from_token.org_id),
+ merchant_id: None,
+ profile_id: None,
+ entity_id: None,
+ version: None,
+ status: Some(UserStatus::Active),
+ limit: None,
+ })
.await
.change_context(UserErrors::InternalServerError)?
.into_iter()
- .filter_map(|user_role| {
- (user_role.status == UserStatus::Active)
- .then_some(user_role.merchant_id)
- .flatten()
- })
+ .filter_map(|user_role| user_role.merchant_id)
.collect::<HashSet<_>>()
.into_iter()
.collect();
@@ -2379,9 +2382,13 @@ pub async fn list_merchants_for_user_in_org(
merchant_id: merchant_account.get_id().to_owned(),
},
)
- .collect()
+ .collect::<Vec<_>>()
};
+ if merchant_accounts.is_empty() {
+ Err(UserErrors::InternalServerError).attach_printable("No merchant found for a user")?;
+ }
+
Ok(ApplicationResponse::Json(merchant_accounts))
}
@@ -2427,26 +2434,24 @@ pub async fn list_profiles_for_user_in_org_and_merchant_account(
profile_name: profile.profile_name,
},
)
- .collect()
+ .collect::<Vec<_>>()
} else {
let profile_ids = state
.store
- .list_user_roles_by_user_id(
- user_from_token.user_id.as_str(),
- Some(&user_from_token.org_id),
- Some(&user_from_token.merchant_id),
- None,
- None,
- None,
- )
+ .list_user_roles_by_user_id(ListUserRolesByUserIdPayload {
+ user_id: user_from_token.user_id.as_str(),
+ org_id: Some(&user_from_token.org_id),
+ merchant_id: Some(&user_from_token.merchant_id),
+ profile_id: None,
+ entity_id: None,
+ version: None,
+ status: Some(UserStatus::Active),
+ limit: None,
+ })
.await
.change_context(UserErrors::InternalServerError)?
.into_iter()
- .filter_map(|user_role| {
- (user_role.status == UserStatus::Active)
- .then_some(user_role.profile_id)
- .flatten()
- })
+ .filter_map(|user_role| user_role.profile_id)
.collect::<HashSet<_>>();
futures::future::try_join_all(profile_ids.iter().map(|profile_id| {
@@ -2465,9 +2470,13 @@ pub async fn list_profiles_for_user_in_org_and_merchant_account(
profile_name: profile.profile_name,
},
)
- .collect()
+ .collect::<Vec<_>>()
};
+ if profiles.is_empty() {
+ Err(UserErrors::InternalServerError).attach_printable("No profile found for a user")?;
+ }
+
Ok(ApplicationResponse::Json(profiles))
}
@@ -2503,23 +2512,23 @@ pub async fn switch_org_for_user(
let user_role = state
.store
- .list_user_roles_by_user_id(
- &user_from_token.user_id,
- Some(&request.org_id),
- None,
- None,
- None,
- None,
- )
+ .list_user_roles_by_user_id(ListUserRolesByUserIdPayload {
+ user_id: &user_from_token.user_id,
+ org_id: Some(&request.org_id),
+ merchant_id: None,
+ profile_id: None,
+ entity_id: None,
+ version: None,
+ status: Some(UserStatus::Active),
+ limit: Some(1),
+ })
.await
.change_context(UserErrors::InternalServerError)
.attach_printable("Failed to list user roles by user_id and org_id")?
- .into_iter()
- .find(|role| role.status == UserStatus::Active)
+ .pop()
.ok_or(UserErrors::InvalidRoleOperationWithMessage(
"No user role found for the requested org_id".to_string(),
- ))?
- .to_owned();
+ ))?;
let merchant_id = utils::user_role::get_single_merchant_id(&state, &user_role).await?;
@@ -2547,7 +2556,7 @@ pub async fn switch_org_for_user(
.await
.change_context(UserErrors::InternalServerError)
.attach_printable("Failed to list business profiles by merchant_id")?
- .first()
+ .pop()
.ok_or(UserErrors::InternalServerError)
.attach_printable("No business profile found for the merchant_id")?
.get_id()
@@ -2635,7 +2644,7 @@ pub async fn switch_merchant_for_user_in_org(
.await
.change_context(UserErrors::InternalServerError)
.attach_printable("Failed to list business profiles by merchant_id")?
- .first()
+ .pop()
.ok_or(UserErrors::InternalServerError)
.attach_printable("No business profile found for the given merchant_id")?
.get_id()
@@ -2688,12 +2697,11 @@ pub async fn switch_merchant_for_user_in_org(
.await
.change_context(UserErrors::InternalServerError)
.attach_printable("Failed to list business profiles by merchant_id")?
- .first()
+ .pop()
.ok_or(UserErrors::InternalServerError)
.attach_printable("No business profile found for the merchant_id")?
.get_id()
.to_owned();
-
(
user_from_token.org_id.clone(),
merchant_id,
@@ -2705,25 +2713,25 @@ pub async fn switch_merchant_for_user_in_org(
EntityType::Merchant | EntityType::Profile => {
let user_role = state
.store
- .list_user_roles_by_user_id(
- &user_from_token.user_id,
- Some(&user_from_token.org_id),
- Some(&request.merchant_id),
- None,
- None,
- None,
- )
+ .list_user_roles_by_user_id(ListUserRolesByUserIdPayload {
+ user_id: &user_from_token.user_id,
+ org_id: Some(&user_from_token.org_id),
+ merchant_id: Some(&request.merchant_id),
+ profile_id: None,
+ entity_id: None,
+ version: None,
+ status: Some(UserStatus::Active),
+ limit: Some(1),
+ })
.await
.change_context(UserErrors::InternalServerError)
.attach_printable(
"Failed to list user roles for the given user_id, org_id and merchant_id",
)?
- .into_iter()
- .find(|role| role.status == UserStatus::Active)
+ .pop()
.ok_or(UserErrors::InvalidRoleOperationWithMessage(
"No user role associated with the requested merchant_id".to_string(),
- ))?
- .to_owned();
+ ))?;
let profile_id = if let Some(profile_id) = &user_role.profile_id {
profile_id.clone()
@@ -2749,7 +2757,7 @@ pub async fn switch_merchant_for_user_in_org(
.await
.change_context(UserErrors::InternalServerError)
.attach_printable("Failed to list business profiles for the given merchant_id")?
- .first()
+ .pop()
.ok_or(UserErrors::InternalServerError)
.attach_printable("No business profile found for the given merchant_id")?
.get_id()
@@ -2846,23 +2854,24 @@ pub async fn switch_profile_for_user_in_org_and_merchant(
EntityType::Profile => {
let user_role = state
.store
- .list_user_roles_by_user_id(
- &user_from_token.user_id,
- Some(&user_from_token.org_id),
- Some(&user_from_token.merchant_id),
- Some(&request.profile_id),
- None,
- None,
+ .list_user_roles_by_user_id(ListUserRolesByUserIdPayload{
+ user_id:&user_from_token.user_id,
+ org_id: Some(&user_from_token.org_id),
+ merchant_id: Some(&user_from_token.merchant_id),
+ profile_id:Some(&request.profile_id),
+ entity_id: None,
+ version:None,
+ status: Some(UserStatus::Active),
+ limit: Some(1)
+ }
)
.await
.change_context(UserErrors::InternalServerError)
.attach_printable("Failed to list user roles for the given user_id, org_id, merchant_id and profile_id")?
- .into_iter()
- .find(|role| role.status == UserStatus::Active)
+ .pop()
.ok_or(UserErrors::InvalidRoleOperationWithMessage(
"No user role associated with the profile".to_string(),
- ))?
- .to_owned();
+ ))?;
(request.profile_id, user_role.role_id)
}
diff --git a/crates/router/src/core/user_role.rs b/crates/router/src/core/user_role.rs
index 7752ce06e9a..5ee71d0e509 100644
--- a/crates/router/src/core/user_role.rs
+++ b/crates/router/src/core/user_role.rs
@@ -3,14 +3,14 @@ use std::collections::{HashMap, HashSet};
use api_models::{user as user_api, user_role as user_role_api};
use diesel_models::{
enums::{UserRoleVersion, UserStatus},
- user_role::UserRoleUpdate,
+ user_role::{get_entity_id_and_type, UserRoleUpdate},
};
use error_stack::{report, ResultExt};
use once_cell::sync::Lazy;
use crate::{
core::errors::{StorageErrorExt, UserErrors, UserResponse},
- db::user_role::ListUserRolesByOrgIdPayload,
+ db::user_role::{ListUserRolesByOrgIdPayload, ListUserRolesByUserIdPayload},
routes::{app::ReqState, SessionState},
services::{
authentication as auth,
@@ -687,3 +687,41 @@ pub async fn list_users_in_lineage(
.collect::<Result<Vec<_>, _>>()?,
))
}
+
+pub async fn list_invitations_for_user(
+ state: SessionState,
+ user_from_token: auth::UserIdFromAuth,
+) -> UserResponse<Vec<user_role_api::ListInvitationForUserResponse>> {
+ let invitations = state
+ .store
+ .list_user_roles_by_user_id(ListUserRolesByUserIdPayload {
+ user_id: &user_from_token.user_id,
+ org_id: None,
+ merchant_id: None,
+ profile_id: None,
+ entity_id: None,
+ version: None,
+ status: Some(UserStatus::InvitationSent),
+ limit: None,
+ })
+ .await
+ .change_context(UserErrors::InternalServerError)
+ .attach_printable("Failed to list user roles by user id and invitation sent")?
+ .into_iter()
+ .collect::<HashSet<_>>()
+ .into_iter()
+ .filter_map(|user_role| {
+ let (entity_id, entity_type) = get_entity_id_and_type(&user_role);
+ entity_id.zip(entity_type).map(|(entity_id, entity_type)| {
+ user_role_api::ListInvitationForUserResponse {
+ entity_id,
+ entity_type,
+ entity_name: None,
+ role_id: user_role.role_id,
+ }
+ })
+ })
+ .collect();
+
+ Ok(ApplicationResponse::Json(invitations))
+}
diff --git a/crates/router/src/db/kafka_store.rs b/crates/router/src/db/kafka_store.rs
index d8a6947a5c7..6b9caf90a91 100644
--- a/crates/router/src/db/kafka_store.rs
+++ b/crates/router/src/db/kafka_store.rs
@@ -35,7 +35,10 @@ use super::{
user::{sample_data::BatchSampleDataInterface, UserInterface},
user_authentication_method::UserAuthenticationMethodInterface,
user_key_store::UserKeyStoreInterface,
- user_role::{InsertUserRolePayload, ListUserRolesByOrgIdPayload, UserRoleInterface},
+ user_role::{
+ InsertUserRolePayload, ListUserRolesByOrgIdPayload, ListUserRolesByUserIdPayload,
+ UserRoleInterface,
+ },
};
#[cfg(feature = "payouts")]
use crate::services::kafka::payout::KafkaPayout;
@@ -2872,25 +2875,11 @@ impl UserRoleInterface for KafkaStore {
.await
}
- async fn list_user_roles_by_user_id(
+ async fn list_user_roles_by_user_id<'a>(
&self,
- user_id: &str,
- org_id: Option<&id_type::OrganizationId>,
- merchant_id: Option<&id_type::MerchantId>,
- profile_id: Option<&id_type::ProfileId>,
- entity_id: Option<&String>,
- version: Option<enums::UserRoleVersion>,
+ payload: ListUserRolesByUserIdPayload<'a>,
) -> CustomResult<Vec<storage::UserRole>, errors::StorageError> {
- self.diesel_store
- .list_user_roles_by_user_id(
- user_id,
- org_id,
- merchant_id,
- profile_id,
- entity_id,
- version,
- )
- .await
+ self.diesel_store.list_user_roles_by_user_id(payload).await
}
async fn list_user_roles_by_org_id<'a>(
diff --git a/crates/router/src/db/user_role.rs b/crates/router/src/db/user_role.rs
index eadd1ef4a5b..d511010e6b5 100644
--- a/crates/router/src/db/user_role.rs
+++ b/crates/router/src/db/user_role.rs
@@ -1,5 +1,8 @@
use common_utils::id_type;
-use diesel_models::{enums, user_role as storage};
+use diesel_models::{
+ enums::{self, UserStatus},
+ user_role as storage,
+};
use error_stack::{report, ResultExt};
use router_env::{instrument, tracing};
@@ -33,6 +36,17 @@ pub struct ListUserRolesByOrgIdPayload<'a> {
pub version: Option<enums::UserRoleVersion>,
}
+pub struct ListUserRolesByUserIdPayload<'a> {
+ pub user_id: &'a str,
+ pub org_id: Option<&'a id_type::OrganizationId>,
+ pub merchant_id: Option<&'a id_type::MerchantId>,
+ pub profile_id: Option<&'a id_type::ProfileId>,
+ pub entity_id: Option<&'a String>,
+ pub version: Option<enums::UserRoleVersion>,
+ pub status: Option<UserStatus>,
+ pub limit: Option<u32>,
+}
+
#[async_trait::async_trait]
pub trait UserRoleInterface {
async fn insert_user_role(
@@ -93,14 +107,9 @@ pub trait UserRoleInterface {
version: enums::UserRoleVersion,
) -> CustomResult<storage::UserRole, errors::StorageError>;
- async fn list_user_roles_by_user_id(
+ async fn list_user_roles_by_user_id<'a>(
&self,
- user_id: &str,
- org_id: Option<&id_type::OrganizationId>,
- merchant_id: Option<&id_type::MerchantId>,
- profile_id: Option<&id_type::ProfileId>,
- entity_id: Option<&String>,
- version: Option<enums::UserRoleVersion>,
+ payload: ListUserRolesByUserIdPayload<'a>,
) -> CustomResult<Vec<storage::UserRole>, errors::StorageError>;
async fn list_user_roles_by_org_id<'a>(
@@ -244,24 +253,21 @@ impl UserRoleInterface for Store {
.map_err(|error| report!(errors::StorageError::from(error)))
}
- async fn list_user_roles_by_user_id(
+ async fn list_user_roles_by_user_id<'a>(
&self,
- user_id: &str,
- org_id: Option<&id_type::OrganizationId>,
- merchant_id: Option<&id_type::MerchantId>,
- profile_id: Option<&id_type::ProfileId>,
- entity_id: Option<&String>,
- version: Option<enums::UserRoleVersion>,
+ payload: ListUserRolesByUserIdPayload<'a>,
) -> CustomResult<Vec<storage::UserRole>, errors::StorageError> {
let conn = connection::pg_connection_read(self).await?;
storage::UserRole::generic_user_roles_list_for_user(
&conn,
- user_id.to_owned(),
- org_id.cloned(),
- merchant_id.cloned(),
- profile_id.cloned(),
- entity_id.cloned(),
- version,
+ payload.user_id.to_owned(),
+ payload.org_id.cloned(),
+ payload.merchant_id.cloned(),
+ payload.profile_id.cloned(),
+ payload.entity_id.cloned(),
+ payload.status,
+ payload.version,
+ payload.limit,
)
.await
.map_err(|error| report!(errors::StorageError::from(error)))
@@ -552,50 +558,52 @@ impl UserRoleInterface for MockDb {
}
}
- async fn list_user_roles_by_user_id(
+ async fn list_user_roles_by_user_id<'a>(
&self,
- user_id: &str,
- org_id: Option<&id_type::OrganizationId>,
- merchant_id: Option<&id_type::MerchantId>,
- profile_id: Option<&id_type::ProfileId>,
- entity_id: Option<&String>,
- version: Option<enums::UserRoleVersion>,
+ payload: ListUserRolesByUserIdPayload<'a>,
) -> CustomResult<Vec<storage::UserRole>, errors::StorageError> {
let user_roles = self.user_roles.lock().await;
- let filtered_roles: Vec<_> = user_roles
+ let mut filtered_roles: Vec<_> = user_roles
.iter()
.filter_map(|role| {
- let mut filter_condition = role.user_id == user_id;
+ let mut filter_condition = role.user_id == payload.user_id;
role.org_id
.as_ref()
- .zip(org_id)
+ .zip(payload.org_id)
.inspect(|(role_org_id, org_id)| {
filter_condition = filter_condition && role_org_id == org_id
});
- role.merchant_id.as_ref().zip(merchant_id).inspect(
+ role.merchant_id.as_ref().zip(payload.merchant_id).inspect(
|(role_merchant_id, merchant_id)| {
filter_condition = filter_condition && role_merchant_id == merchant_id
},
);
- role.profile_id.as_ref().zip(profile_id).inspect(
+ role.profile_id.as_ref().zip(payload.profile_id).inspect(
|(role_profile_id, profile_id)| {
filter_condition = filter_condition && role_profile_id == profile_id
},
);
- role.entity_id
- .as_ref()
- .zip(entity_id)
- .inspect(|(role_entity_id, entity_id)| {
+ role.entity_id.as_ref().zip(payload.entity_id).inspect(
+ |(role_entity_id, entity_id)| {
filter_condition = filter_condition && role_entity_id == entity_id
- });
- version.inspect(|ver| filter_condition = filter_condition && ver == &role.version);
+ },
+ );
+ payload
+ .version
+ .inspect(|ver| filter_condition = filter_condition && ver == &role.version);
+ payload.status.inspect(|status| {
+ filter_condition = filter_condition && status == &role.status
+ });
filter_condition.then(|| role.to_owned())
})
.collect();
+ if let Some(Ok(limit)) = payload.limit.map(|val| val.try_into()) {
+ filtered_roles = filtered_roles.into_iter().take(limit).collect();
+ }
Ok(filtered_roles)
}
diff --git a/crates/router/src/routes/app.rs b/crates/router/src/routes/app.rs
index 9b35e3ca475..4b1f1bd8b14 100644
--- a/crates/router/src/routes/app.rs
+++ b/crates/router/src/routes/app.rs
@@ -1725,6 +1725,9 @@ impl User {
.service(
web::resource("/profile")
.route(web::get().to(list_profiles_for_user_in_org_and_merchant)),
+ )
+ .service(
+ web::resource("/invitation").route(web::get().to(list_invitations_for_user)),
),
);
diff --git a/crates/router/src/routes/lock_utils.rs b/crates/router/src/routes/lock_utils.rs
index 8f61d78c4a1..c6160497918 100644
--- a/crates/router/src/routes/lock_utils.rs
+++ b/crates/router/src/routes/lock_utils.rs
@@ -250,6 +250,7 @@ impl From<Flow> for ApiIdentifier {
| Flow::ListOrgForUser
| Flow::ListMerchantsForUserInOrg
| Flow::ListProfileForUserInOrgAndMerchant
+ | Flow::ListInvitationsForUser
| Flow::AuthSelect => Self::User,
Flow::ListRoles
diff --git a/crates/router/src/routes/user_role.rs b/crates/router/src/routes/user_role.rs
index 539409ab75f..61250774c10 100644
--- a/crates/router/src/routes/user_role.rs
+++ b/crates/router/src/routes/user_role.rs
@@ -310,3 +310,23 @@ pub async fn list_updatable_roles_at_entity_level(
))
.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
+}
diff --git a/crates/router_env/src/logger/types.rs b/crates/router_env/src/logger/types.rs
index 51bb4b64730..3aae72d8aa7 100644
--- a/crates/router_env/src/logger/types.rs
+++ b/crates/router_env/src/logger/types.rs
@@ -474,6 +474,8 @@ pub enum Flow {
ListProfileForUserInOrgAndMerchant,
/// List Users in Org
ListUsersInLineage,
+ /// List invitations for user
+ ListInvitationsForUser,
/// List initial webhook delivery attempts
WebhookEventInitialDeliveryAttemptList,
/// List delivery attempts for a webhook event
|
2024-09-02T09:26:13Z
|
## Type of Change
<!-- Put an `x` in the boxes that apply -->
- [ ] Bugfix
- [X] New feature
- [ ] Enhancement
- [ ] Refactoring
- [ ] Dependency updates
- [ ] Documentation
- [ ] CI/CD
## Description
New APIs to list of invitations for a user.
<!-- Describe your changes in detail -->
### Additional Changes
- [X] This PR modifies the API contract
- [ ] This PR modifies the database schema
- [ ] This PR modifies application configuration/environment variables
<!--
Provide links to the files with corresponding changes.
Following are the paths where you can find config files:
1. `config`
2. `crates/router/src/configs`
3. `loadtest/config`
-->
## Motivation and Context
To show user list of invitations.
<!--
Why is this change required? What problem does it solve?
If it fixes an open issue, please link to the issue here.
If you don't have an issue, we'd recommend starting with one first so the PR
can focus on the implementation (unless it is an obvious bug or documentation fix
that will have little conversation).
-->
## How did you test it?
```sh
curl --location 'localhost:8080/user/list/invitation' \
--header 'Authorization: Bearer <JWT>' \
```
Response
```json
[
{
"entity_id": "juspay2",
"entity_type": "merchant",
"entity_name": null,
"role_id": "merchant_view_only"
}
]
```
<!--
Did you write an integration/unit/API test to verify the code changes?
Or did you test this change manually (provide relevant screenshots)?
-->
## Checklist
<!-- Put an `x` in the boxes that apply -->
- [X] I formatted the code `cargo +nightly fmt --all`
- [X] I addressed lints thrown by `cargo clippy`
- [X] I reviewed the submitted code
- [ ] I added unit tests for my changes where possible
|
1d149716ba47d3e3f4c749687cff851e18ec77c0
|
|
juspay/hyperswitch
|
juspay__hyperswitch-5792
|
Bug: feat(users): Add profile level invites
Currently invites are at merchant level only. Invite, accept invite and accept invite from email should change because of this.
|
diff --git a/crates/api_models/src/user.rs b/crates/api_models/src/user.rs
index a0dadfea217..78157f62bc5 100644
--- a/crates/api_models/src/user.rs
+++ b/crates/api_models/src/user.rs
@@ -51,9 +51,6 @@ pub struct AuthorizeResponse {
//this field is added for audit/debug reasons
#[serde(skip_serializing)]
pub user_id: String,
- //this field is added for audit/debug reasons
- #[serde(skip_serializing)]
- pub merchant_id: id_type::MerchantId,
}
#[derive(serde::Deserialize, Debug, serde::Serialize)]
@@ -209,7 +206,6 @@ pub struct VerifyTokenResponse {
#[derive(Debug, serde::Deserialize, serde::Serialize)]
pub struct UpdateUserAccountDetailsRequest {
pub name: Option<Secret<String>>,
- pub preferred_merchant_id: Option<id_type::MerchantId>,
}
#[derive(Debug, serde::Deserialize, serde::Serialize)]
diff --git a/crates/api_models/src/user_role.rs b/crates/api_models/src/user_role.rs
index e4819b74fbc..05087d09e80 100644
--- a/crates/api_models/src/user_role.rs
+++ b/crates/api_models/src/user_role.rs
@@ -147,3 +147,12 @@ pub struct ListInvitationForUserResponse {
pub entity_name: Option<Secret<String>>,
pub role_id: String,
}
+
+pub type AcceptInvitationsV2Request = Vec<Entity>;
+pub type AcceptInvitationsPreAuthRequest = Vec<Entity>;
+
+#[derive(Debug, serde::Deserialize, serde::Serialize)]
+pub struct Entity {
+ pub entity_id: String,
+ pub entity_type: common_enums::EntityType,
+}
diff --git a/crates/diesel_models/src/schema.rs b/crates/diesel_models/src/schema.rs
index e0f2b9a0bd2..5986ddf2259 100644
--- a/crates/diesel_models/src/schema.rs
+++ b/crates/diesel_models/src/schema.rs
@@ -1333,8 +1333,6 @@ diesel::table! {
is_verified -> Bool,
created_at -> Timestamp,
last_modified_at -> Timestamp,
- #[max_length = 64]
- preferred_merchant_id -> Nullable<Varchar>,
totp_status -> TotpStatus,
totp_secret -> Nullable<Bytea>,
totp_recovery_codes -> Nullable<Array<Nullable<Text>>>,
diff --git a/crates/diesel_models/src/schema_v2.rs b/crates/diesel_models/src/schema_v2.rs
index 410c541441b..c3dc45e6b62 100644
--- a/crates/diesel_models/src/schema_v2.rs
+++ b/crates/diesel_models/src/schema_v2.rs
@@ -1316,8 +1316,6 @@ diesel::table! {
is_verified -> Bool,
created_at -> Timestamp,
last_modified_at -> Timestamp,
- #[max_length = 64]
- preferred_merchant_id -> Nullable<Varchar>,
totp_status -> TotpStatus,
totp_secret -> Nullable<Bytea>,
totp_recovery_codes -> Nullable<Array<Nullable<Text>>>,
diff --git a/crates/diesel_models/src/user.rs b/crates/diesel_models/src/user.rs
index 582041ec42e..9f7b77dc5d6 100644
--- a/crates/diesel_models/src/user.rs
+++ b/crates/diesel_models/src/user.rs
@@ -18,7 +18,6 @@ pub struct User {
pub is_verified: bool,
pub created_at: PrimitiveDateTime,
pub last_modified_at: PrimitiveDateTime,
- pub preferred_merchant_id: Option<common_utils::id_type::MerchantId>,
pub totp_status: TotpStatus,
pub totp_secret: Option<Encryption>,
#[diesel(deserialize_as = OptionalDieselArray<Secret<String>>)]
@@ -38,7 +37,6 @@ pub struct UserNew {
pub is_verified: bool,
pub created_at: Option<PrimitiveDateTime>,
pub last_modified_at: Option<PrimitiveDateTime>,
- pub preferred_merchant_id: Option<common_utils::id_type::MerchantId>,
pub totp_status: TotpStatus,
pub totp_secret: Option<Encryption>,
pub totp_recovery_codes: Option<Vec<Secret<String>>>,
@@ -52,7 +50,6 @@ pub struct UserUpdateInternal {
password: Option<Secret<String>>,
is_verified: Option<bool>,
last_modified_at: PrimitiveDateTime,
- preferred_merchant_id: Option<common_utils::id_type::MerchantId>,
totp_status: Option<TotpStatus>,
totp_secret: Option<Encryption>,
totp_recovery_codes: Option<Vec<Secret<String>>>,
@@ -65,7 +62,6 @@ pub enum UserUpdate {
AccountUpdate {
name: Option<String>,
is_verified: Option<bool>,
- preferred_merchant_id: Option<common_utils::id_type::MerchantId>,
},
TotpUpdate {
totp_status: Option<TotpStatus>,
@@ -86,22 +82,16 @@ impl From<UserUpdate> for UserUpdateInternal {
password: None,
is_verified: Some(true),
last_modified_at,
- preferred_merchant_id: None,
totp_status: None,
totp_secret: None,
totp_recovery_codes: None,
last_password_modified_at: None,
},
- UserUpdate::AccountUpdate {
- name,
- is_verified,
- preferred_merchant_id,
- } => Self {
+ UserUpdate::AccountUpdate { name, is_verified } => Self {
name,
password: None,
is_verified,
last_modified_at,
- preferred_merchant_id,
totp_status: None,
totp_secret: None,
totp_recovery_codes: None,
@@ -116,7 +106,6 @@ impl From<UserUpdate> for UserUpdateInternal {
password: None,
is_verified: None,
last_modified_at,
- preferred_merchant_id: None,
totp_status,
totp_secret,
totp_recovery_codes,
@@ -127,7 +116,6 @@ impl From<UserUpdate> for UserUpdateInternal {
password: Some(password),
is_verified: None,
last_modified_at,
- preferred_merchant_id: None,
last_password_modified_at: Some(last_modified_at),
totp_status: None,
totp_secret: None,
diff --git a/crates/diesel_models/src/user_role.rs b/crates/diesel_models/src/user_role.rs
index c454e8b58bc..29be4d62aef 100644
--- a/crates/diesel_models/src/user_role.rs
+++ b/crates/diesel_models/src/user_role.rs
@@ -26,52 +26,53 @@ pub struct UserRole {
pub version: enums::UserRoleVersion,
}
-pub fn get_entity_id_and_type(user_role: &UserRole) -> (Option<String>, Option<EntityType>) {
- match (user_role.version, user_role.role_id.as_str()) {
- (enums::UserRoleVersion::V1, consts::ROLE_ID_ORGANIZATION_ADMIN) => (
- user_role
- .org_id
- .clone()
- .map(|org_id| org_id.get_string_repr().to_string()),
- Some(EntityType::Organization),
- ),
- (enums::UserRoleVersion::V1, consts::ROLE_ID_INTERNAL_VIEW_ONLY_USER)
- | (enums::UserRoleVersion::V1, consts::ROLE_ID_INTERNAL_ADMIN) => (
- user_role
- .merchant_id
- .clone()
- .map(|merchant_id| merchant_id.get_string_repr().to_string()),
- Some(EntityType::Internal),
- ),
- (enums::UserRoleVersion::V1, _) => (
- user_role
- .merchant_id
- .clone()
- .map(|merchant_id| merchant_id.get_string_repr().to_string()),
- Some(EntityType::Merchant),
- ),
- (enums::UserRoleVersion::V2, _) => (user_role.entity_id.clone(), user_role.entity_type),
+impl UserRole {
+ pub fn get_entity_id_and_type(&self) -> Option<(String, EntityType)> {
+ match (self.version, self.role_id.as_str()) {
+ (enums::UserRoleVersion::V1, consts::ROLE_ID_ORGANIZATION_ADMIN) => {
+ let org_id = self.org_id.clone()?.get_string_repr().to_string();
+ Some((org_id, EntityType::Organization))
+ }
+ (enums::UserRoleVersion::V1, consts::ROLE_ID_INTERNAL_VIEW_ONLY_USER)
+ | (enums::UserRoleVersion::V1, consts::ROLE_ID_INTERNAL_ADMIN) => {
+ let merchant_id = self.merchant_id.clone()?.get_string_repr().to_string();
+ Some((merchant_id, EntityType::Internal))
+ }
+ (enums::UserRoleVersion::V1, _) => {
+ let merchant_id = self.merchant_id.clone()?.get_string_repr().to_string();
+ Some((merchant_id, EntityType::Merchant))
+ }
+ (enums::UserRoleVersion::V2, _) => self.entity_id.clone().zip(self.entity_type),
+ }
}
}
impl Hash for UserRole {
fn hash<H: std::hash::Hasher>(&self, state: &mut H) {
- let (entity_id, entity_type) = get_entity_id_and_type(self);
-
self.user_id.hash(state);
- entity_id.hash(state);
- entity_type.hash(state);
+ if let Some((entity_id, entity_type)) = self.get_entity_id_and_type() {
+ entity_id.hash(state);
+ entity_type.hash(state);
+ }
}
}
impl PartialEq for UserRole {
fn eq(&self, other: &Self) -> bool {
- let (self_entity_id, self_entity_type) = get_entity_id_and_type(self);
- let (other_entity_id, other_entity_type) = get_entity_id_and_type(other);
-
- self.user_id == other.user_id
- && self_entity_id == other_entity_id
- && self_entity_type == other_entity_type
+ match (
+ self.get_entity_id_and_type(),
+ other.get_entity_id_and_type(),
+ ) {
+ (
+ Some((self_entity_id, self_entity_type)),
+ Some((other_entity_id, other_entity_type)),
+ ) => {
+ self.user_id == other.user_id
+ && self_entity_id == other_entity_id
+ && self_entity_type == other_entity_type
+ }
+ _ => self.user_id == other.user_id,
+ }
}
}
diff --git a/crates/router/src/core/user.rs b/crates/router/src/core/user.rs
index 8e99a202dfe..0c4afbe4ecd 100644
--- a/crates/router/src/core/user.rs
+++ b/crates/router/src/core/user.rs
@@ -18,8 +18,6 @@ use diesel_models::{
user_authentication_method::{UserAuthenticationMethodNew, UserAuthenticationMethodUpdate},
};
use error_stack::{report, ResultExt};
-#[cfg(feature = "email")]
-use external_services::email::EmailData;
use masking::{ExposeInterface, PeekInterface, Secret};
#[cfg(feature = "email")]
use router_env::env;
@@ -64,7 +62,7 @@ pub async fn signup_with_merchant_id(
.insert_user_and_merchant_in_db(state.clone())
.await?;
- let user_role = new_user
+ let _user_role = new_user
.insert_org_level_user_role_in_db(
state.clone(),
common_utils::consts::ROLE_ID_ORGANIZATION_ADMIN.to_string(),
@@ -89,16 +87,10 @@ pub async fn signup_with_merchant_id(
)
.await;
- let Some(merchant_id) = user_role.merchant_id else {
- return Err(report!(UserErrors::InternalServerError)
- .attach_printable("merchant_id not found for user_role"));
- };
-
logger::info!(?send_email_result);
Ok(ApplicationResponse::Json(user_api::AuthorizeResponse {
is_email_sent: send_email_result.is_ok(),
user_id: user_from_db.get_user_id().to_string(),
- merchant_id,
}))
}
@@ -195,7 +187,6 @@ pub async fn connect_account(
if let Ok(found_user) = find_user {
let user_from_db: domain::UserFromStorage = found_user.into();
- let user_role = user_from_db.get_role_from_db(state.clone()).await?;
let email_contents = email_types::MagicLink {
recipient_email: domain::UserEmail::from_pii_email(user_from_db.get_email())?,
@@ -212,18 +203,12 @@ pub async fn connect_account(
state.conf.proxy.https_url.as_ref(),
)
.await;
-
- let Some(merchant_id) = user_role.merchant_id else {
- return Err(report!(UserErrors::InternalServerError)
- .attach_printable("merchant_id not found for user_role"));
- };
logger::info!(?send_email_result);
return Ok(ApplicationResponse::Json(
user_api::ConnectAccountResponse {
is_email_sent: send_email_result.is_ok(),
user_id: user_from_db.get_user_id().to_string(),
- merchant_id,
},
));
} else if find_user
@@ -245,7 +230,7 @@ pub async fn connect_account(
let user_from_db = new_user
.insert_user_and_merchant_in_db(state.clone())
.await?;
- let user_role = new_user
+ let _user_role = new_user
.insert_org_level_user_role_in_db(
state.clone(),
common_utils::consts::ROLE_ID_ORGANIZATION_ADMIN.to_string(),
@@ -269,18 +254,12 @@ pub async fn connect_account(
)
.await;
- let Some(merchant_id) = user_role.merchant_id else {
- return Err(report!(UserErrors::InternalServerError)
- .attach_printable("merchant_id not found for user_role"));
- };
-
logger::info!(?send_email_result);
return Ok(ApplicationResponse::Json(
user_api::ConnectAccountResponse {
is_email_sent: send_email_result.is_ok(),
user_id: user_from_db.get_user_id().to_string(),
- merchant_id,
},
));
} else {
@@ -512,15 +491,19 @@ pub async fn invite_multiple_user(
.attach_printable("Number of invite requests must not exceed 10");
}
- let responses = futures::future::join_all(requests.iter().map(|request| async {
- match handle_invitation(&state, &user_from_token, request, &req_state, &auth_id).await {
+ let responses = futures::future::join_all(requests.into_iter().map(|request| async {
+ match handle_invitation(&state, &user_from_token, &request, &req_state, &auth_id).await {
Ok(response) => response,
- Err(error) => InviteMultipleUserResponse {
- email: request.email.clone(),
- is_email_sent: false,
- password: None,
- error: Some(error.current_context().get_error_message().to_string()),
- },
+ Err(error) => {
+ logger::error!(invite_error=?error);
+
+ InviteMultipleUserResponse {
+ email: request.email,
+ is_email_sent: false,
+ password: None,
+ error: Some(error.current_context().get_error_message().to_string()),
+ }
+ }
}
}))
.await;
@@ -570,6 +553,7 @@ async fn handle_invitation(
user_from_token,
request,
invitee_user.into(),
+ role_info,
auth_id,
)
.await
@@ -579,8 +563,15 @@ async fn handle_invitation(
.err()
.unwrap_or(false)
{
- handle_new_user_invitation(state, user_from_token, request, req_state.clone(), auth_id)
- .await
+ handle_new_user_invitation(
+ state,
+ user_from_token,
+ request,
+ role_info,
+ req_state.clone(),
+ auth_id,
+ )
+ .await
} else {
Err(UserErrors::InternalServerError.into())
}
@@ -592,6 +583,7 @@ async fn handle_existing_user_invitation(
user_from_token: &auth::UserFromToken,
request: &user_api::InviteUserRequest,
invitee_user_from_db: domain::UserFromStorage,
+ role_info: roles::RoleInfo,
auth_id: &Option<String>,
) -> UserResult<InviteMultipleUserResponse> {
let now = common_utils::date_time::now();
@@ -642,24 +634,66 @@ async fn handle_existing_user_invitation(
last_modified_by: user_from_token.user_id.clone(),
created_at: now,
last_modified: now,
- entity: domain::MerchantLevel {
- org_id: user_from_token.org_id.clone(),
- merchant_id: user_from_token.merchant_id.clone(),
- },
- }
- .insert_in_v1_and_v2(state)
- .await?;
+ entity: domain::NoLevel,
+ };
+
+ let _user_role = match role_info.get_entity_type() {
+ EntityType::Internal => return Err(UserErrors::InvalidRoleId.into()),
+ EntityType::Organization => return Err(UserErrors::InvalidRoleId.into()),
+ EntityType::Merchant => {
+ user_role
+ .add_entity(domain::MerchantLevel {
+ org_id: user_from_token.org_id.clone(),
+ merchant_id: user_from_token.merchant_id.clone(),
+ })
+ .insert_in_v1_and_v2(state)
+ .await?
+ }
+ EntityType::Profile => {
+ let profile_id = user_from_token
+ .profile_id
+ .clone()
+ .ok_or(UserErrors::InternalServerError)?;
+ user_role
+ .add_entity(domain::ProfileLevel {
+ org_id: user_from_token.org_id.clone(),
+ merchant_id: user_from_token.merchant_id.clone(),
+ profile_id: profile_id.clone(),
+ })
+ .insert_in_v2(state)
+ .await?
+ }
+ };
let is_email_sent;
#[cfg(feature = "email")]
{
let invitee_email = domain::UserEmail::from_pii_email(request.email.clone())?;
- let email_contents = email_types::InviteRegisteredUser {
+ let entity = match role_info.get_entity_type() {
+ EntityType::Internal => return Err(UserErrors::InvalidRoleId.into()),
+ EntityType::Organization => return Err(UserErrors::InvalidRoleId.into()),
+ EntityType::Merchant => email_types::Entity {
+ entity_id: user_from_token.merchant_id.get_string_repr().to_owned(),
+ entity_type: EntityType::Merchant,
+ },
+ EntityType::Profile => {
+ let profile_id = user_from_token
+ .profile_id
+ .clone()
+ .ok_or(UserErrors::InternalServerError)?;
+ email_types::Entity {
+ entity_id: profile_id.get_string_repr().to_owned(),
+ entity_type: EntityType::Profile,
+ }
+ }
+ };
+
+ let email_contents = email_types::InviteUser {
recipient_email: invitee_email,
user_name: domain::UserName::new(invitee_user_from_db.get_name())?,
settings: state.conf.clone(),
subject: "You have been invited to join Hyperswitch Community!",
- merchant_id: user_from_token.merchant_id.clone(),
+ entity,
auth_id: auth_id.clone(),
};
@@ -692,6 +726,7 @@ async fn handle_new_user_invitation(
state: &SessionState,
user_from_token: &auth::UserFromToken,
request: &user_api::InviteUserRequest,
+ role_info: roles::RoleInfo,
req_state: ReqState,
auth_id: &Option<String>,
) -> UserResult<InviteMultipleUserResponse> {
@@ -718,13 +753,36 @@ async fn handle_new_user_invitation(
last_modified_by: user_from_token.user_id.clone(),
created_at: now,
last_modified: now,
- entity: domain::MerchantLevel {
- merchant_id: user_from_token.merchant_id.clone(),
- org_id: user_from_token.org_id.clone(),
- },
- }
- .insert_in_v1_and_v2(state)
- .await?;
+ entity: domain::NoLevel,
+ };
+
+ let _user_role = match role_info.get_entity_type() {
+ EntityType::Internal => return Err(UserErrors::InvalidRoleId.into()),
+ EntityType::Organization => return Err(UserErrors::InvalidRoleId.into()),
+ EntityType::Merchant => {
+ user_role
+ .add_entity(domain::MerchantLevel {
+ org_id: user_from_token.org_id.clone(),
+ merchant_id: user_from_token.merchant_id.clone(),
+ })
+ .insert_in_v1_and_v2(state)
+ .await?
+ }
+ EntityType::Profile => {
+ let profile_id = user_from_token
+ .profile_id
+ .clone()
+ .ok_or(UserErrors::InternalServerError)?;
+ user_role
+ .add_entity(domain::ProfileLevel {
+ org_id: user_from_token.org_id.clone(),
+ merchant_id: user_from_token.merchant_id.clone(),
+ profile_id: profile_id.clone(),
+ })
+ .insert_in_v2(state)
+ .await?
+ }
+ };
let is_email_sent;
@@ -734,18 +792,39 @@ async fn handle_new_user_invitation(
// Will be adding actual usage for this variable later
let _ = req_state.clone();
let invitee_email = domain::UserEmail::from_pii_email(request.email.clone())?;
- let email_contents: Box<dyn EmailData + Send + 'static> =
- Box::new(email_types::InviteRegisteredUser {
- recipient_email: invitee_email,
- user_name: domain::UserName::new(new_user.get_name())?,
- settings: state.conf.clone(),
- subject: "You have been invited to join Hyperswitch Community!",
- merchant_id: user_from_token.merchant_id.clone(),
- auth_id: auth_id.clone(),
- });
+ let entity = match role_info.get_entity_type() {
+ EntityType::Internal => return Err(UserErrors::InvalidRoleId.into()),
+ EntityType::Organization => return Err(UserErrors::InvalidRoleId.into()),
+ EntityType::Merchant => email_types::Entity {
+ entity_id: user_from_token.merchant_id.get_string_repr().to_owned(),
+ entity_type: EntityType::Merchant,
+ },
+ EntityType::Profile => {
+ let profile_id = user_from_token
+ .profile_id
+ .clone()
+ .ok_or(UserErrors::InternalServerError)?;
+ email_types::Entity {
+ entity_id: profile_id.get_string_repr().to_owned(),
+ entity_type: EntityType::Profile,
+ }
+ }
+ };
+
+ let email_contents = email_types::InviteUser {
+ recipient_email: invitee_email,
+ user_name: domain::UserName::new(new_user.get_name())?,
+ settings: state.conf.clone(),
+ subject: "You have been invited to join Hyperswitch Community!",
+ entity,
+ auth_id: auth_id.clone(),
+ };
let send_email_result = state
.email_client
- .compose_and_send_email(email_contents, state.conf.proxy.https_url.as_ref())
+ .compose_and_send_email(
+ Box::new(email_contents),
+ state.conf.proxy.https_url.as_ref(),
+ )
.await;
logger::info!(?send_email_result);
is_email_sent = send_email_result.is_ok();
@@ -803,40 +882,66 @@ pub async fn resend_invite(
}
})?
.into();
- let user_role = state
+
+ let user_role = match state
.store
- .find_user_role_by_user_id_merchant_id(
+ .find_user_role_by_user_id_and_lineage(
user.get_user_id(),
+ &user_from_token.org_id,
&user_from_token.merchant_id,
- UserRoleVersion::V1,
+ user_from_token.profile_id.as_ref(),
+ UserRoleVersion::V2,
)
.await
- .map_err(|e| {
- if e.current_context().is_db_not_found() {
- e.change_context(UserErrors::InvalidRoleOperation)
- .attach_printable(format!(
- "User role with user_id = {} and merchant_id = {:?} is not found",
- user.get_user_id(),
- user_from_token.merchant_id
- ))
+ {
+ Ok(user_role) => Some(user_role),
+ Err(err) => {
+ if err.current_context().is_db_not_found() {
+ None
} else {
- e.change_context(UserErrors::InternalServerError)
+ return Err(report!(UserErrors::InternalServerError));
}
- })?;
+ }
+ };
+
+ let user_role = match user_role {
+ Some(user_role) => user_role,
+ None => state
+ .store
+ .find_user_role_by_user_id_and_lineage(
+ user.get_user_id(),
+ &user_from_token.org_id,
+ &user_from_token.merchant_id,
+ user_from_token.profile_id.as_ref(),
+ UserRoleVersion::V1,
+ )
+ .await
+ .to_not_found_response(UserErrors::InvalidRoleOperationWithMessage(
+ "User not found in records".to_string(),
+ ))?,
+ };
if !matches!(user_role.status, UserStatus::InvitationSent) {
return Err(report!(UserErrors::InvalidRoleOperation))
.attach_printable("User status is not InvitationSent".to_string());
}
+ let (entity_id, entity_type) = user_role
+ .get_entity_id_and_type()
+ .ok_or(UserErrors::InternalServerError)?;
+
let email_contents = email_types::InviteUser {
recipient_email: invitee_email,
user_name: domain::UserName::new(user.get_name())?,
settings: state.conf.clone(),
subject: "You have been invited to join Hyperswitch Community!",
- merchant_id: user_from_token.merchant_id,
- auth_id,
+ entity: email_types::Entity {
+ entity_id,
+ entity_type,
+ },
+ auth_id: auth_id.clone(),
};
+
state
.email_client
.compose_and_send_email(
@@ -878,36 +983,25 @@ pub async fn accept_invite_from_email_token_only_flow(
return Err(UserErrors::LinkInvalid.into());
}
- let merchant_id = email_token
- .get_merchant_id()
- .ok_or(UserErrors::LinkInvalid)?;
-
- let key_manager_state = &(&state).into();
+ let entity = email_token.get_entity().ok_or(UserErrors::LinkInvalid)?;
- let key_store = state
- .store
- .get_merchant_key_store_by_merchant_id(
- key_manager_state,
- merchant_id,
- &state.store.get_master_key().to_vec().into(),
+ let (org_id, merchant_id, profile_id) =
+ utils::user_role::get_lineage_for_user_id_and_entity_for_accepting_invite(
+ &state,
+ &user_token.user_id,
+ entity.entity_id.clone(),
+ entity.entity_type,
)
.await
- .change_context(UserErrors::InternalServerError)
- .attach_printable("merchant_key_store not found")?;
-
- let merchant_account = state
- .store
- .find_merchant_account_by_merchant_id(key_manager_state, merchant_id, &key_store)
- .await
- .change_context(UserErrors::InternalServerError)
- .attach_printable("merchant_account not found")?;
+ .change_context(UserErrors::InternalServerError)?
+ .ok_or(UserErrors::InternalServerError)?;
let (update_v1_result, update_v2_result) = utils::user_role::update_v1_and_v2_user_roles_in_db(
&state,
user_from_db.get_user_id(),
- &merchant_account.organization_id,
- merchant_id,
- None,
+ &org_id,
+ &merchant_id,
+ profile_id.as_ref(),
UserRoleUpdate::UpdateStatus {
status: UserStatus::Active,
modified_by: user_from_db.get_user_id().to_owned(),
@@ -951,14 +1045,7 @@ pub async fn accept_invite_from_email_token_only_flow(
)?;
let next_flow = current_flow.next(user_from_db.clone(), &state).await?;
- let user_role = user_from_db
- .get_preferred_or_active_user_role_from_db(&state)
- .await
- .change_context(UserErrors::InternalServerError)?;
-
- let token = next_flow
- .get_token_with_user_role(&state, &user_role)
- .await?;
+ let token = next_flow.get_token(&state).await?;
let response = user_api::TokenResponse {
token: token.clone(),
@@ -1534,28 +1621,9 @@ pub async fn update_user_details(
let name = req.name.map(domain::UserName::new).transpose()?;
- if let Some(ref preferred_merchant_id) = req.preferred_merchant_id {
- let _ = state
- .store
- .find_user_role_by_user_id_merchant_id(
- user.get_user_id(),
- preferred_merchant_id,
- UserRoleVersion::V1,
- )
- .await
- .map_err(|e| {
- if e.current_context().is_db_not_found() {
- e.change_context(UserErrors::MerchantIdNotFound)
- } else {
- e.change_context(UserErrors::InternalServerError)
- }
- })?;
- }
-
let user_update = storage_user::UserUpdate::AccountUpdate {
- name: name.map(|x| x.get_secret().expose()),
+ name: name.map(|name| name.get_secret().expose()),
is_verified: None,
- preferred_merchant_id: req.preferred_merchant_id,
};
state
@@ -2283,23 +2351,35 @@ pub async fn list_orgs_for_user(
state: SessionState,
user_from_token: auth::UserFromToken,
) -> UserResponse<Vec<user_api::ListOrgsForUserResponse>> {
- let orgs = state
- .store
- .list_user_roles_by_user_id(ListUserRolesByUserIdPayload {
- user_id: user_from_token.user_id.as_str(),
- org_id: None,
- merchant_id: None,
- profile_id: None,
- entity_id: None,
- version: None,
- status: Some(UserStatus::Active),
- limit: None,
- })
- .await
- .change_context(UserErrors::InternalServerError)?
- .into_iter()
- .filter_map(|user_role| user_role.org_id)
- .collect::<HashSet<_>>();
+ let role_info = roles::RoleInfo::from_role_id(
+ &state,
+ &user_from_token.role_id,
+ &user_from_token.merchant_id,
+ &user_from_token.org_id,
+ )
+ .await
+ .change_context(UserErrors::InternalServerError)?;
+
+ let orgs = match role_info.get_entity_type() {
+ EntityType::Internal => return Err(UserErrors::InvalidRoleOperation.into()),
+ EntityType::Organization | EntityType::Merchant | EntityType::Profile => state
+ .store
+ .list_user_roles_by_user_id(ListUserRolesByUserIdPayload {
+ user_id: user_from_token.user_id.as_str(),
+ org_id: None,
+ merchant_id: None,
+ profile_id: None,
+ entity_id: None,
+ version: None,
+ status: Some(UserStatus::Active),
+ limit: None,
+ })
+ .await
+ .change_context(UserErrors::InternalServerError)?
+ .into_iter()
+ .filter_map(|user_role| user_role.org_id)
+ .collect::<HashSet<_>>(),
+ };
let resp = futures::future::try_join_all(
orgs.iter()
@@ -2333,48 +2413,50 @@ pub async fn list_merchants_for_user_in_org(
)
.await
.change_context(UserErrors::InternalServerError)?;
- let merchant_accounts = if role_info.get_entity_type() == EntityType::Organization {
- state
+ let merchant_accounts = match role_info.get_entity_type() {
+ EntityType::Organization | EntityType::Internal => state
.store
.list_merchant_accounts_by_organization_id(
&(&state).into(),
user_from_token.org_id.get_string_repr(),
)
.await
- .change_context(UserErrors::InternalServerError)?
- .into_iter()
- .map(
- |merchant_account| user_api::ListMerchantsForUserInOrgResponse {
- merchant_name: merchant_account.merchant_name.clone(),
- merchant_id: merchant_account.get_id().to_owned(),
- },
- )
- .collect::<Vec<_>>()
- } else {
- let merchant_ids = state
- .store
- .list_user_roles_by_user_id(ListUserRolesByUserIdPayload {
- user_id: user_from_token.user_id.as_str(),
- org_id: Some(&user_from_token.org_id),
- merchant_id: None,
- profile_id: None,
- entity_id: None,
- version: None,
- status: Some(UserStatus::Active),
- limit: None,
- })
- .await
- .change_context(UserErrors::InternalServerError)?
- .into_iter()
- .filter_map(|user_role| user_role.merchant_id)
- .collect::<HashSet<_>>()
- .into_iter()
- .collect();
- state
- .store
- .list_multiple_merchant_accounts(&(&state).into(), merchant_ids)
- .await
- .change_context(UserErrors::InternalServerError)?
+ .change_context(UserErrors::InternalServerError)?,
+ EntityType::Merchant | EntityType::Profile => {
+ let merchant_ids = state
+ .store
+ .list_user_roles_by_user_id(ListUserRolesByUserIdPayload {
+ user_id: user_from_token.user_id.as_str(),
+ org_id: Some(&user_from_token.org_id),
+ merchant_id: None,
+ profile_id: None,
+ entity_id: None,
+ version: None,
+ status: Some(UserStatus::Active),
+ limit: None,
+ })
+ .await
+ .change_context(UserErrors::InternalServerError)?
+ .into_iter()
+ .filter_map(|user_role| user_role.merchant_id)
+ .collect::<HashSet<_>>()
+ .into_iter()
+ .collect();
+
+ state
+ .store
+ .list_multiple_merchant_accounts(&(&state).into(), merchant_ids)
+ .await
+ .change_context(UserErrors::InternalServerError)?
+ }
+ };
+
+ if merchant_accounts.is_empty() {
+ Err(UserErrors::InternalServerError).attach_printable("No merchant found for a user")?;
+ }
+
+ Ok(ApplicationResponse::Json(
+ merchant_accounts
.into_iter()
.map(
|merchant_account| user_api::ListMerchantsForUserInOrgResponse {
@@ -2382,14 +2464,8 @@ pub async fn list_merchants_for_user_in_org(
merchant_id: merchant_account.get_id().to_owned(),
},
)
- .collect::<Vec<_>>()
- };
-
- if merchant_accounts.is_empty() {
- Err(UserErrors::InternalServerError).attach_printable("No merchant found for a user")?;
- }
-
- Ok(ApplicationResponse::Json(merchant_accounts))
+ .collect::<Vec<_>>(),
+ ))
}
pub async fn list_profiles_for_user_in_org_and_merchant_account(
@@ -2415,27 +2491,17 @@ pub async fn list_profiles_for_user_in_org_and_merchant_account(
)
.await
.change_context(UserErrors::InternalServerError)?;
- let user_role_level = role_info.get_entity_type();
- let profiles =
- if user_role_level == EntityType::Organization || user_role_level == EntityType::Merchant {
- state
- .store
- .list_business_profile_by_merchant_id(
- key_manager_state,
- &key_store,
- &user_from_token.merchant_id,
- )
- .await
- .change_context(UserErrors::InternalServerError)?
- .into_iter()
- .map(
- |profile| user_api::ListProfilesForUserInOrgAndMerchantAccountResponse {
- profile_id: profile.get_id().to_owned(),
- profile_name: profile.profile_name,
- },
- )
- .collect::<Vec<_>>()
- } else {
+ let profiles = match role_info.get_entity_type() {
+ EntityType::Organization | EntityType::Merchant | EntityType::Internal => state
+ .store
+ .list_business_profile_by_merchant_id(
+ key_manager_state,
+ &key_store,
+ &user_from_token.merchant_id,
+ )
+ .await
+ .change_context(UserErrors::InternalServerError)?,
+ EntityType::Profile => {
let profile_ids = state
.store
.list_user_roles_by_user_id(ListUserRolesByUserIdPayload {
@@ -2463,6 +2529,15 @@ pub async fn list_profiles_for_user_in_org_and_merchant_account(
}))
.await
.change_context(UserErrors::InternalServerError)?
+ }
+ };
+
+ if profiles.is_empty() {
+ Err(UserErrors::InternalServerError).attach_printable("No profile found for a user")?;
+ }
+
+ Ok(ApplicationResponse::Json(
+ profiles
.into_iter()
.map(
|profile| user_api::ListProfilesForUserInOrgAndMerchantAccountResponse {
@@ -2470,14 +2545,8 @@ pub async fn list_profiles_for_user_in_org_and_merchant_account(
profile_name: profile.profile_name,
},
)
- .collect::<Vec<_>>()
- };
-
- if profiles.is_empty() {
- Err(UserErrors::InternalServerError).attach_printable("No profile found for a user")?;
- }
-
- Ok(ApplicationResponse::Json(profiles))
+ .collect::<Vec<_>>(),
+ ))
}
pub async fn switch_org_for_user(
diff --git a/crates/router/src/core/user_role.rs b/crates/router/src/core/user_role.rs
index 5ee71d0e509..9d57702e3be 100644
--- a/crates/router/src/core/user_role.rs
+++ b/crates/router/src/core/user_role.rs
@@ -3,7 +3,7 @@ use std::collections::{HashMap, HashSet};
use api_models::{user as user_api, user_role as user_role_api};
use diesel_models::{
enums::{UserRoleVersion, UserStatus},
- user_role::{get_entity_id_and_type, UserRoleUpdate},
+ user_role::UserRoleUpdate,
};
use error_stack::{report, ResultExt};
use once_cell::sync::Lazy;
@@ -289,7 +289,59 @@ pub async fn accept_invitation(
}))
.await;
- if update_result.iter().all(Result::is_err) {
+ if update_result.is_empty() || update_result.iter().all(Result::is_err) {
+ return Err(UserErrors::MerchantIdNotFound.into());
+ }
+
+ Ok(ApplicationResponse::StatusOk)
+}
+
+pub async fn accept_invitations_v2(
+ state: SessionState,
+ user_from_token: auth::UserFromToken,
+ req: user_role_api::AcceptInvitationsV2Request,
+) -> UserResponse<()> {
+ let lineages = futures::future::try_join_all(req.into_iter().map(|entity| {
+ utils::user_role::get_lineage_for_user_id_and_entity_for_accepting_invite(
+ &state,
+ &user_from_token.user_id,
+ entity.entity_id,
+ entity.entity_type,
+ )
+ }))
+ .await?
+ .into_iter()
+ .flatten()
+ .collect::<Vec<_>>();
+
+ let update_results = futures::future::join_all(lineages.iter().map(
+ |(org_id, merchant_id, profile_id)| async {
+ let (update_v1_result, update_v2_result) =
+ utils::user_role::update_v1_and_v2_user_roles_in_db(
+ &state,
+ user_from_token.user_id.as_str(),
+ org_id,
+ merchant_id,
+ profile_id.as_ref(),
+ UserRoleUpdate::UpdateStatus {
+ status: UserStatus::Active,
+ modified_by: user_from_token.user_id.clone(),
+ },
+ )
+ .await;
+
+ if update_v1_result.is_err_and(|err| !err.current_context().is_db_not_found())
+ || update_v2_result.is_err_and(|err| !err.current_context().is_db_not_found())
+ {
+ Err(report!(UserErrors::InternalServerError))
+ } else {
+ Ok(())
+ }
+ },
+ ))
+ .await;
+
+ if update_results.is_empty() || update_results.iter().all(Result::is_err) {
return Err(UserErrors::MerchantIdNotFound.into());
}
@@ -333,7 +385,7 @@ pub async fn merchant_select_token_only_flow(
}))
.await;
- if update_result.iter().all(Result::is_err) {
+ if update_result.is_empty() || update_result.iter().all(Result::is_err) {
return Err(UserErrors::MerchantIdNotFound.into());
}
@@ -344,18 +396,80 @@ pub async fn merchant_select_token_only_flow(
.change_context(UserErrors::InternalServerError)?
.into();
- let user_role = user_from_db
- .get_preferred_or_active_user_role_from_db(&state)
+ let current_flow =
+ domain::CurrentFlow::new(user_token, domain::SPTFlow::MerchantSelect.into())?;
+ let next_flow = current_flow.next(user_from_db.clone(), &state).await?;
+
+ let token = next_flow.get_token(&state).await?;
+
+ let response = user_api::TokenResponse {
+ token: token.clone(),
+ token_type: next_flow.get_flow().into(),
+ };
+ auth::cookies::set_cookie_response(response, token)
+}
+
+pub async fn accept_invitations_pre_auth(
+ state: SessionState,
+ user_token: auth::UserFromSinglePurposeToken,
+ req: user_role_api::AcceptInvitationsPreAuthRequest,
+) -> UserResponse<user_api::TokenResponse> {
+ let lineages = futures::future::try_join_all(req.into_iter().map(|entity| {
+ utils::user_role::get_lineage_for_user_id_and_entity_for_accepting_invite(
+ &state,
+ &user_token.user_id,
+ entity.entity_id,
+ entity.entity_type,
+ )
+ }))
+ .await?
+ .into_iter()
+ .flatten()
+ .collect::<Vec<_>>();
+
+ let update_results = futures::future::join_all(lineages.iter().map(
+ |(org_id, merchant_id, profile_id)| async {
+ let (update_v1_result, update_v2_result) =
+ utils::user_role::update_v1_and_v2_user_roles_in_db(
+ &state,
+ user_token.user_id.as_str(),
+ org_id,
+ merchant_id,
+ profile_id.as_ref(),
+ UserRoleUpdate::UpdateStatus {
+ status: UserStatus::Active,
+ modified_by: user_token.user_id.clone(),
+ },
+ )
+ .await;
+
+ if update_v1_result.is_err_and(|err| !err.current_context().is_db_not_found())
+ || update_v2_result.is_err_and(|err| !err.current_context().is_db_not_found())
+ {
+ Err(report!(UserErrors::InternalServerError))
+ } else {
+ Ok(())
+ }
+ },
+ ))
+ .await;
+
+ if update_results.is_empty() || update_results.iter().all(Result::is_err) {
+ return Err(UserErrors::MerchantIdNotFound.into());
+ }
+
+ let user_from_db: domain::UserFromStorage = state
+ .global_store
+ .find_user_by_id(user_token.user_id.as_str())
.await
- .change_context(UserErrors::InternalServerError)?;
+ .change_context(UserErrors::InternalServerError)?
+ .into();
let current_flow =
domain::CurrentFlow::new(user_token, domain::SPTFlow::MerchantSelect.into())?;
let next_flow = current_flow.next(user_from_db.clone(), &state).await?;
- let token = next_flow
- .get_token_with_user_role(&state, &user_role)
- .await?;
+ let token = next_flow.get_token(&state).await?;
let response = user_api::TokenResponse {
token: token.clone(),
@@ -711,14 +825,12 @@ pub async fn list_invitations_for_user(
.collect::<HashSet<_>>()
.into_iter()
.filter_map(|user_role| {
- let (entity_id, entity_type) = get_entity_id_and_type(&user_role);
- entity_id.zip(entity_type).map(|(entity_id, entity_type)| {
- user_role_api::ListInvitationForUserResponse {
- entity_id,
- entity_type,
- entity_name: None,
- role_id: user_role.role_id,
- }
+ let (entity_id, entity_type) = user_role.get_entity_id_and_type()?;
+ Some(user_role_api::ListInvitationForUserResponse {
+ entity_id,
+ entity_type,
+ entity_name: None,
+ role_id: user_role.role_id,
})
})
.collect();
diff --git a/crates/router/src/db/user.rs b/crates/router/src/db/user.rs
index b8c5001d910..c9244eb12b4 100644
--- a/crates/router/src/db/user.rs
+++ b/crates/router/src/db/user.rs
@@ -159,7 +159,6 @@ impl UserInterface for MockDb {
is_verified: user_data.is_verified,
created_at: user_data.created_at.unwrap_or(time_now),
last_modified_at: user_data.created_at.unwrap_or(time_now),
- preferred_merchant_id: user_data.preferred_merchant_id,
totp_status: user_data.totp_status,
totp_secret: user_data.totp_secret,
totp_recovery_codes: user_data.totp_recovery_codes,
@@ -218,16 +217,9 @@ impl UserInterface for MockDb {
is_verified: true,
..user.to_owned()
},
- storage::UserUpdate::AccountUpdate {
- name,
- is_verified,
- preferred_merchant_id,
- } => storage::User {
+ storage::UserUpdate::AccountUpdate { name, is_verified } => storage::User {
name: name.clone().map(Secret::new).unwrap_or(user.name.clone()),
is_verified: is_verified.unwrap_or(user.is_verified),
- preferred_merchant_id: preferred_merchant_id
- .clone()
- .or(user.preferred_merchant_id.clone()),
..user.to_owned()
},
storage::UserUpdate::TotpUpdate {
@@ -273,16 +265,9 @@ impl UserInterface for MockDb {
is_verified: true,
..user.to_owned()
},
- storage::UserUpdate::AccountUpdate {
- name,
- is_verified,
- preferred_merchant_id,
- } => storage::User {
+ storage::UserUpdate::AccountUpdate { name, is_verified } => storage::User {
name: name.clone().map(Secret::new).unwrap_or(user.name.clone()),
is_verified: is_verified.unwrap_or(user.is_verified),
- preferred_merchant_id: preferred_merchant_id
- .clone()
- .or(user.preferred_merchant_id.clone()),
..user.to_owned()
},
storage::UserUpdate::TotpUpdate {
diff --git a/crates/router/src/routes/app.rs b/crates/router/src/routes/app.rs
index bd05740acae..04d833ab985 100644
--- a/crates/router/src/routes/app.rs
+++ b/crates/router/src/routes/app.rs
@@ -1853,9 +1853,22 @@ impl User {
web::resource("/invite_multiple").route(web::post().to(invite_multiple_user)),
)
.service(
- web::resource("/invite/accept")
- .route(web::post().to(merchant_select))
- .route(web::put().to(accept_invitation)),
+ web::scope("/invite/accept")
+ .service(
+ web::resource("")
+ .route(web::post().to(merchant_select))
+ .route(web::put().to(accept_invitation)),
+ )
+ .service(
+ web::scope("/v2")
+ .service(
+ web::resource("").route(web::post().to(accept_invitations_v2)),
+ )
+ .service(
+ web::resource("/pre_auth")
+ .route(web::post().to(accept_invitations_pre_auth)),
+ ),
+ ),
)
.service(web::resource("/update_role").route(web::post().to(update_user_role)))
.service(web::resource("/delete").route(web::delete().to(delete_user_role))),
diff --git a/crates/router/src/routes/lock_utils.rs b/crates/router/src/routes/lock_utils.rs
index c6160497918..2b2a1be0878 100644
--- a/crates/router/src/routes/lock_utils.rs
+++ b/crates/router/src/routes/lock_utils.rs
@@ -263,7 +263,9 @@ impl From<Flow> for ApiIdentifier {
| Flow::GetAuthorizationInfo
| Flow::GetRolesInfo
| Flow::AcceptInvitation
+ | Flow::AcceptInvitationsV2
| Flow::MerchantSelect
+ | Flow::AcceptInvitationsPreAuth
| Flow::DeleteUserRole
| Flow::CreateRole
| Flow::UpdateRole
diff --git a/crates/router/src/routes/user_role.rs b/crates/router/src/routes/user_role.rs
index 61250774c10..35c9098edd2 100644
--- a/crates/router/src/routes/user_role.rs
+++ b/crates/router/src/routes/user_role.rs
@@ -168,6 +168,25 @@ pub async fn accept_invitation(
.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 merchant_select(
state: web::Data<AppState>,
req: HttpRequest,
@@ -189,6 +208,27 @@ pub async fn merchant_select(
.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,
diff --git a/crates/router/src/services/email/types.rs b/crates/router/src/services/email/types.rs
index 3a17966fac3..6ed03e1ea06 100644
--- a/crates/router/src/services/email/types.rs
+++ b/crates/router/src/services/email/types.rs
@@ -1,4 +1,5 @@
use api_models::user::dashboard_metadata::ProdIntent;
+use common_enums::EntityType;
use common_utils::{
errors::{self, CustomResult},
pii,
@@ -151,15 +152,31 @@ Email : {user_email}
#[derive(serde::Serialize, serde::Deserialize)]
pub struct EmailToken {
email: String,
- merchant_id: Option<common_utils::id_type::MerchantId>,
flow: domain::Origin,
exp: u64,
+ entity: Option<Entity>,
+}
+
+#[derive(serde::Serialize, serde::Deserialize, Clone)]
+pub struct Entity {
+ pub entity_id: String,
+ pub entity_type: EntityType,
+}
+
+impl Entity {
+ pub fn get_entity_type(&self) -> EntityType {
+ self.entity_type
+ }
+
+ pub fn get_entity_id(&self) -> &str {
+ &self.entity_id
+ }
}
impl EmailToken {
pub async fn new_token(
email: domain::UserEmail,
- merchant_id: Option<common_utils::id_type::MerchantId>,
+ entity: Option<Entity>,
flow: domain::Origin,
settings: &configs::Settings,
) -> CustomResult<String, UserErrors> {
@@ -167,9 +184,9 @@ impl EmailToken {
let exp = jwt::generate_exp(expiration_duration)?.as_secs();
let token_payload = Self {
email: email.get_secret().expose(),
- merchant_id,
flow,
exp,
+ entity,
};
jwt::generate_jwt(&token_payload, settings).await
}
@@ -178,8 +195,8 @@ impl EmailToken {
pii::Email::try_from(self.email.clone())
}
- pub fn get_merchant_id(&self) -> Option<&common_utils::id_type::MerchantId> {
- self.merchant_id.as_ref()
+ pub fn get_entity(&self) -> Option<&Entity> {
+ self.entity.as_ref()
}
pub fn get_flow(&self) -> domain::Origin {
@@ -320,13 +337,12 @@ impl EmailData for MagicLink {
}
}
-// TODO: Deprecate this and use InviteRegisteredUser for new invites
pub struct InviteUser {
pub recipient_email: domain::UserEmail,
pub user_name: domain::UserName,
pub settings: std::sync::Arc<configs::Settings>,
pub subject: &'static str,
- pub merchant_id: common_utils::id_type::MerchantId,
+ pub entity: Entity,
pub auth_id: Option<String>,
}
@@ -335,48 +351,7 @@ impl EmailData for InviteUser {
async fn get_email_data(&self) -> CustomResult<EmailContents, EmailError> {
let token = EmailToken::new_token(
self.recipient_email.clone(),
- Some(self.merchant_id.clone()),
- domain::Origin::ResetPassword,
- &self.settings,
- )
- .await
- .change_context(EmailError::TokenGenerationFailure)?;
-
- let invite_user_link = get_link_with_token(
- &self.settings.user.base_url,
- token,
- "set_password",
- &self.auth_id,
- );
-
- let body = html::get_html_body(EmailBody::InviteUser {
- link: invite_user_link,
- user_name: self.user_name.clone().get_secret().expose(),
- });
-
- Ok(EmailContents {
- subject: self.subject.to_string(),
- body: external_services::email::IntermediateString::new(body),
- recipient: self.recipient_email.clone().into_inner(),
- })
- }
-}
-
-pub struct InviteRegisteredUser {
- pub recipient_email: domain::UserEmail,
- pub user_name: domain::UserName,
- pub settings: std::sync::Arc<configs::Settings>,
- pub subject: &'static str,
- pub merchant_id: common_utils::id_type::MerchantId,
- pub auth_id: Option<String>,
-}
-
-#[async_trait::async_trait]
-impl EmailData for InviteRegisteredUser {
- async fn get_email_data(&self) -> CustomResult<EmailContents, EmailError> {
- let token = EmailToken::new_token(
- self.recipient_email.clone(),
- Some(self.merchant_id.clone()),
+ Some(self.entity.clone()),
domain::Origin::AcceptInvitationFromEmail,
&self.settings,
)
diff --git a/crates/router/src/types/domain/user.rs b/crates/router/src/types/domain/user.rs
index f41d7157eec..9f73276c280 100644
--- a/crates/router/src/types/domain/user.rs
+++ b/crates/router/src/types/domain/user.rs
@@ -706,7 +706,6 @@ impl TryFrom<NewUser> for storage_user::UserNew {
is_verified: false,
created_at: Some(now),
last_modified_at: Some(now),
- preferred_merchant_id: None,
totp_status: TotpStatus::NotSet,
totp_secret: None,
totp_recovery_codes: None,
@@ -934,10 +933,6 @@ impl UserFromStorage {
Ok(days_left_for_password_rotate.whole_days() < 0)
}
- pub fn get_preferred_merchant_id(&self) -> Option<id_type::MerchantId> {
- self.0.preferred_merchant_id.clone()
- }
-
pub async fn get_role_from_db_by_merchant_id(
&self,
state: &SessionState,
@@ -953,29 +948,6 @@ impl UserFromStorage {
.await
}
- pub async fn get_preferred_or_active_user_role_from_db(
- &self,
- state: &SessionState,
- ) -> CustomResult<UserRole, errors::StorageError> {
- if let Some(preferred_merchant_id) = self.get_preferred_merchant_id() {
- self.get_role_from_db_by_merchant_id(state, &preferred_merchant_id)
- .await
- } else {
- state
- .store
- .list_user_roles_by_user_id_and_version(&self.0.user_id, UserRoleVersion::V1)
- .await?
- .into_iter()
- .find(|role| role.status == UserStatus::Active)
- .ok_or(
- errors::StorageError::ValueNotFound(
- "No active role found for user".to_string(),
- )
- .into(),
- )
- }
- }
-
pub async fn get_or_create_key_store(&self, state: &SessionState) -> UserResult<UserKeyStore> {
let master_key = state.store.get_master_key();
let key_manager_state = &state.into();
diff --git a/crates/router/src/types/domain/user/decision_manager.rs b/crates/router/src/types/domain/user/decision_manager.rs
index 4206b16df6d..af9918af673 100644
--- a/crates/router/src/types/domain/user/decision_manager.rs
+++ b/crates/router/src/types/domain/user/decision_manager.rs
@@ -1,11 +1,15 @@
use common_enums::TokenPurpose;
-use diesel_models::{enums::UserStatus, user_role::UserRole};
+use diesel_models::{
+ enums::{UserRoleVersion, UserStatus},
+ user_role::UserRole,
+};
use error_stack::{report, ResultExt};
use masking::Secret;
use super::UserFromStorage;
use crate::{
- core::errors::{StorageErrorExt, UserErrors, UserResult},
+ core::errors::{UserErrors, UserResult},
+ db::user_role::ListUserRolesByUserIdPayload,
routes::SessionState,
services::authentication as auth,
utils,
@@ -284,11 +288,22 @@ impl NextFlow {
{
self.user.get_verification_days_left(state)?;
}
- let user_role = self
- .user
- .get_preferred_or_active_user_role_from_db(state)
+ let user_role = state
+ .store
+ .list_user_roles_by_user_id(ListUserRolesByUserIdPayload {
+ user_id: self.user.get_user_id(),
+ org_id: None,
+ merchant_id: None,
+ profile_id: None,
+ entity_id: None,
+ version: Some(UserRoleVersion::V1),
+ status: Some(UserStatus::Active),
+ limit: Some(1),
+ })
.await
- .to_not_found_response(UserErrors::InternalServerError)?;
+ .change_context(UserErrors::InternalServerError)?
+ .pop()
+ .ok_or(UserErrors::InternalServerError)?;
utils::user_role::set_role_permissions_in_cache_by_user_role(state, &user_role)
.await;
diff --git a/crates/router/src/utils/user_role.rs b/crates/router/src/utils/user_role.rs
index dbe3ed6d585..aeb866d8d03 100644
--- a/crates/router/src/utils/user_role.rs
+++ b/crates/router/src/utils/user_role.rs
@@ -4,7 +4,7 @@ use api_models::user_role as user_role_api;
use common_enums::{EntityType, PermissionGroup};
use common_utils::id_type;
use diesel_models::{
- enums::UserRoleVersion,
+ enums::{UserRoleVersion, UserStatus},
user_role::{UserRole, UserRoleUpdate},
};
use error_stack::{report, Report, ResultExt};
@@ -14,6 +14,7 @@ use storage_impl::errors::StorageError;
use crate::{
consts,
core::errors::{UserErrors, UserResult},
+ db::user_role::ListUserRolesByUserIdPayload,
routes::SessionState,
services::authorization::{self as authz, permissions::Permission, roles},
types::domain,
@@ -247,3 +248,113 @@ pub async fn get_single_merchant_id(
.attach_printable("merchant_id not found"),
}
}
+
+pub async fn get_lineage_for_user_id_and_entity_for_accepting_invite(
+ state: &SessionState,
+ user_id: &str,
+ entity_id: String,
+ entity_type: EntityType,
+) -> UserResult<
+ Option<(
+ id_type::OrganizationId,
+ id_type::MerchantId,
+ Option<id_type::ProfileId>,
+ )>,
+> {
+ match entity_type {
+ EntityType::Internal | EntityType::Organization => {
+ Err(UserErrors::InvalidRoleOperation.into())
+ }
+ EntityType::Merchant => {
+ let Ok(merchant_id) = id_type::MerchantId::wrap(entity_id) else {
+ return Ok(None);
+ };
+
+ let user_roles = state
+ .store
+ .list_user_roles_by_user_id(ListUserRolesByUserIdPayload {
+ user_id,
+ org_id: None,
+ merchant_id: Some(&merchant_id),
+ profile_id: None,
+ entity_id: None,
+ version: None,
+ status: Some(UserStatus::InvitationSent),
+ 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)?,
+ 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
+ .store
+ .list_user_roles_by_user_id(ListUserRolesByUserIdPayload {
+ user_id,
+ org_id: None,
+ merchant_id: None,
+ profile_id: Some(&profile_id),
+ entity_id: None,
+ version: None,
+ status: Some(UserStatus::InvitationSent),
+ 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)?,
+ user_role
+ .merchant_id
+ .ok_or(UserErrors::InternalServerError)?,
+ Some(profile_id),
+ )));
+ }
+
+ Ok(None)
+ }
+ }
+}
diff --git a/crates/router_env/src/logger/types.rs b/crates/router_env/src/logger/types.rs
index 3aae72d8aa7..34e4dc72036 100644
--- a/crates/router_env/src/logger/types.rs
+++ b/crates/router_env/src/logger/types.rs
@@ -424,10 +424,14 @@ pub enum Flow {
VerifyEmailRequest,
/// Update user account details
UpdateUserAccountDetails,
- /// Accept user invitation
+ /// Accept user invitation using merchant_ids
AcceptInvitation,
+ /// Accept user invitation using entities
+ AcceptInvitationsV2,
/// Select merchant from invitations
MerchantSelect,
+ /// Accept user invitation using entities before user login
+ AcceptInvitationsPreAuth,
/// Initiate external authentication for a payment
PaymentsExternalAuthentication,
/// Authorize the payment after external 3ds authentication
diff --git a/migrations/2024-09-01-094614_remove-preferred-merchant-from-users/down.sql b/migrations/2024-09-01-094614_remove-preferred-merchant-from-users/down.sql
new file mode 100644
index 00000000000..ab5ef65be8b
--- /dev/null
+++ b/migrations/2024-09-01-094614_remove-preferred-merchant-from-users/down.sql
@@ -0,0 +1,2 @@
+-- This file should undo anything in `up.sql`
+ALTER TABLE users ADD COLUMN preferred_merchant_id VARCHAR(64);
diff --git a/migrations/2024-09-01-094614_remove-preferred-merchant-from-users/up.sql b/migrations/2024-09-01-094614_remove-preferred-merchant-from-users/up.sql
new file mode 100644
index 00000000000..84af1f99e0c
--- /dev/null
+++ b/migrations/2024-09-01-094614_remove-preferred-merchant-from-users/up.sql
@@ -0,0 +1,2 @@
+-- Your SQL goes here
+ALTER TABLE users DROP COLUMN preferred_merchant_id;
|
2024-09-04T10:51:33Z
|
## Type of Change
<!-- Put an `x` in the boxes that apply -->
- [ ] Bugfix
- [x] New feature
- [ ] Enhancement
- [ ] Refactoring
- [ ] Dependency updates
- [ ] Documentation
- [ ] CI/CD
## Description
<!-- Describe your changes in detail -->
- Removed preferred_merchant_id from update user API.
- Invites will work at profile level as well.
- Handle internal users in list APIs
- Org List for internal users will throw error.
- Merchant list will list merchants.
- Profile list will list profiles.
- New API for accept invite and merchant select is created which takes entity as request.
- Email token will now have a entity instead of merchant_id.
### Additional Changes
- [x] This PR modifies the API contract
- [ ] This PR modifies the database schema
- [ ] This PR modifies application configuration/environment variables
<!--
Provide links to the files with corresponding changes.
Following are the paths where you can find config files:
1. `config`
2. `crates/router/src/configs`
3. `loadtest/config`
-->
## Motivation and Context
<!--
Why is this change required? What problem does it solve?
If it fixes an open issue, please link to the issue here.
If you don't have an issue, we'd recommend starting with one first so the PR
can focus on the implementation (unless it is an obvious bug or documentation fix
that will have little conversation).
-->
Closes #5792
## How did you test it?
<!--
Did you write an integration/unit/API test to verify the code changes?
Or did you test this change manually (provide relevant screenshots)?
-->
All the following APIs should work without any issues.
- Invite multiple
- Accept invite from email
- Accept invite
- Merchant select
- List orgs for user will throw the following error
```
{
"error": {
"type": "invalid_request",
"message": "User Role Operation Not Supported",
"code": "UR_23"
}
}
```
New APIs
Accept Invite (works with JWT Token)
```
curl --location 'http://localhost:8080/user/user/invite/accept/v2' \
--header 'Content-Type: application/json' \
--header 'Authorization: ••••••' \
--data '[
{
"entity_id": "merchant_id",
"entity_type": "merchant"
}
]'
```
Response: 200 OK
Accept Invite (works with Merchant Select SPT)
```
curl --location 'http://localhost:8080/user/user/invite/accept/v2/pre_auth' \
--header 'Content-Type: application/json' \
--header 'Authorization: ••••••' \
--data '[
{
"entity_id": "merchant_id",
"entity_type": "merchant"
}
]'
```
Response:
```json
{
"token": "token",
"token_type": "user_info"
}
```
## Checklist
<!-- Put an `x` in the boxes that apply -->
- [x] I formatted the code `cargo +nightly fmt --all`
- [x] I addressed lints thrown by `cargo clippy`
- [x] I reviewed the submitted code
- [ ] I added unit tests for my changes where possible
|
1c39cc1262e6b2521669639ae296211b7ebefd86
|
|
juspay/hyperswitch
|
juspay__hyperswitch-5767
|
Bug: feat(connector): [Thunes] Template for thunes payout
### Feature Description
Template connector code for Thunes payout connector
### Possible Implementation
Want to connect thunes with hyperswitch
### Have you spent some time checking if this feature request has been raised before?
- [X] I checked and didn't find a similar issue
### Have you read the Contributing Guidelines?
- [X] I have read the [Contributing Guidelines](https://github.com/juspay/hyperswitch/blob/main/docs/CONTRIBUTING.md)
### Are you willing to submit a PR?
Yes, I am willing to submit a PR!
|
diff --git a/config/config.example.toml b/config/config.example.toml
index 052b10d0b90..afdbdc954b6 100644
--- a/config/config.example.toml
+++ b/config/config.example.toml
@@ -253,6 +253,7 @@ stax.base_url = "https://apiprod.fattlabs.com/"
stripe.base_url = "https://api.stripe.com/"
taxjar.base_url = "https://api.sandbox.taxjar.com/v2/"
threedsecureio.base_url = "https://service.sandbox.3dsecure.io"
+thunes.base_url = "https://api.limonetikqualif.com/"
stripe.base_url_file_upload = "https://files.stripe.com/"
trustpay.base_url = "https://test-tpgw.trustpay.eu/"
trustpay.base_url_bank_redirects = "https://aapi.trustpay.eu/"
@@ -318,6 +319,7 @@ cards = [
"stax",
"stripe",
"threedsecureio",
+ "thunes",
"worldpay",
"zen",
"zsl",
diff --git a/config/deployments/integration_test.toml b/config/deployments/integration_test.toml
index 16803295896..142eaaa6c09 100644
--- a/config/deployments/integration_test.toml
+++ b/config/deployments/integration_test.toml
@@ -93,6 +93,7 @@ stax.base_url = "https://apiprod.fattlabs.com/"
stripe.base_url = "https://api.stripe.com/"
stripe.base_url_file_upload = "https://files.stripe.com/"
taxjar.base_url = "https://api.sandbox.taxjar.com/v2/"
+thunes.base_url = "https://api.limonetikqualif.com/"
trustpay.base_url = "https://test-tpgw.trustpay.eu/"
trustpay.base_url_bank_redirects = "https://aapi.trustpay.eu/"
tsys.base_url = "https://stagegw.transnox.com/"
diff --git a/config/deployments/production.toml b/config/deployments/production.toml
index cc16d88c169..e1b4f0a36f6 100644
--- a/config/deployments/production.toml
+++ b/config/deployments/production.toml
@@ -97,6 +97,7 @@ stax.base_url = "https://apiprod.fattlabs.com/"
stripe.base_url = "https://api.stripe.com/"
stripe.base_url_file_upload = "https://files.stripe.com/"
taxjar.base_url = "https://api.taxjar.com/v2/"
+thunes.base_url = "https://api.limonetik.com/"
trustpay.base_url = "https://tpgw.trustpay.eu/"
trustpay.base_url_bank_redirects = "https://aapi.trustpay.eu/"
tsys.base_url = "https://gateway.transit-pass.com/"
diff --git a/config/deployments/sandbox.toml b/config/deployments/sandbox.toml
index 8a8030db052..3b7993b4b1c 100644
--- a/config/deployments/sandbox.toml
+++ b/config/deployments/sandbox.toml
@@ -97,6 +97,7 @@ stax.base_url = "https://apiprod.fattlabs.com/"
stripe.base_url = "https://api.stripe.com/"
stripe.base_url_file_upload = "https://files.stripe.com/"
taxjar.base_url = "https://api.sandbox.taxjar.com/v2/"
+thunes.base_url = "https://api.limonetikqualif.com/"
trustpay.base_url = "https://test-tpgw.trustpay.eu/"
trustpay.base_url_bank_redirects = "https://aapi.trustpay.eu/"
tsys.base_url = "https://stagegw.transnox.com/"
diff --git a/config/development.toml b/config/development.toml
index 27ac5bb3f5f..687f0dc1ec8 100644
--- a/config/development.toml
+++ b/config/development.toml
@@ -155,6 +155,7 @@ cards = [
"stripe",
"taxjar",
"threedsecureio",
+ "thunes",
"trustpay",
"tsys",
"volt",
@@ -261,6 +262,7 @@ stax.base_url = "https://apiprod.fattlabs.com/"
stripe.base_url = "https://api.stripe.com/"
taxjar.base_url = "https://api.sandbox.taxjar.com/v2/"
threedsecureio.base_url = "https://service.sandbox.3dsecure.io"
+thunes.base_url = "https://api.limonetikqualif.com/"
stripe.base_url_file_upload = "https://files.stripe.com/"
wise.base_url = "https://api.sandbox.transferwise.tech/"
worldline.base_url = "https://eu.sandbox.api-ingenico.com/"
diff --git a/config/docker_compose.toml b/config/docker_compose.toml
index 98da1c30986..e3587986ee1 100644
--- a/config/docker_compose.toml
+++ b/config/docker_compose.toml
@@ -182,6 +182,7 @@ stax.base_url = "https://apiprod.fattlabs.com/"
stripe.base_url = "https://api.stripe.com/"
taxjar.base_url = "https://api.sandbox.taxjar.com/v2/"
threedsecureio.base_url = "https://service.sandbox.3dsecure.io"
+thunes.base_url = "https://api.limonetikqualif.com/"
stripe.base_url_file_upload = "https://files.stripe.com/"
trustpay.base_url = "https://test-tpgw.trustpay.eu/"
trustpay.base_url_bank_redirects = "https://aapi.trustpay.eu/"
@@ -264,6 +265,7 @@ cards = [
"stripe",
"taxjar",
"threedsecureio",
+ "thunes",
"trustpay",
"tsys",
"volt",
diff --git a/crates/api_models/src/enums.rs b/crates/api_models/src/enums.rs
index 5db816305bd..5bee91843bd 100644
--- a/crates/api_models/src/enums.rs
+++ b/crates/api_models/src/enums.rs
@@ -137,6 +137,7 @@ pub enum Connector {
Stripe,
Taxjar,
Threedsecureio,
+ //Thunes,
Trustpay,
Tsys,
Volt,
@@ -265,6 +266,7 @@ impl Connector {
| Self::Square
| Self::Stax
| Self::Taxjar
+ //| Self::Thunes
| Self::Trustpay
| Self::Tsys
| Self::Volt
diff --git a/crates/common_enums/src/enums.rs b/crates/common_enums/src/enums.rs
index eef23ff5b89..61acfa23304 100644
--- a/crates/common_enums/src/enums.rs
+++ b/crates/common_enums/src/enums.rs
@@ -251,6 +251,7 @@ pub enum RoutableConnectors {
Stripe,
// Taxjar,
Trustpay,
+ // Thunes
// Tsys,
Tsys,
Volt,
diff --git a/crates/hyperswitch_connectors/src/connectors.rs b/crates/hyperswitch_connectors/src/connectors.rs
index 79024411320..037f91e90ca 100644
--- a/crates/hyperswitch_connectors/src/connectors.rs
+++ b/crates/hyperswitch_connectors/src/connectors.rs
@@ -11,12 +11,13 @@ pub mod novalnet;
pub mod powertranz;
pub mod stax;
pub mod taxjar;
+pub mod thunes;
pub mod tsys;
pub mod worldline;
pub use self::{
bambora::Bambora, bitpay::Bitpay, deutschebank::Deutschebank, fiserv::Fiserv,
fiservemea::Fiservemea, fiuu::Fiuu, globepay::Globepay, helcim::Helcim, nexixpay::Nexixpay,
- novalnet::Novalnet, powertranz::Powertranz, stax::Stax, taxjar::Taxjar, tsys::Tsys,
- worldline::Worldline,
+ novalnet::Novalnet, powertranz::Powertranz, stax::Stax, taxjar::Taxjar, thunes::Thunes,
+ tsys::Tsys, worldline::Worldline,
};
diff --git a/crates/hyperswitch_connectors/src/connectors/thunes.rs b/crates/hyperswitch_connectors/src/connectors/thunes.rs
new file mode 100644
index 00000000000..972ba0d7dd3
--- /dev/null
+++ b/crates/hyperswitch_connectors/src/connectors/thunes.rs
@@ -0,0 +1,563 @@
+pub mod transformers;
+
+use common_utils::{
+ errors::CustomResult,
+ ext_traits::BytesExt,
+ request::{Method, Request, RequestBuilder, RequestContent},
+ types::{AmountConvertor, StringMinorUnit, StringMinorUnitForConnector},
+};
+use error_stack::{report, ResultExt};
+use hyperswitch_domain_models::{
+ router_data::{AccessToken, ConnectorAuthType, ErrorResponse, RouterData},
+ router_flow_types::{
+ access_token_auth::AccessTokenAuth,
+ payments::{Authorize, Capture, PSync, PaymentMethodToken, Session, SetupMandate, Void},
+ refunds::{Execute, RSync},
+ },
+ router_request_types::{
+ AccessTokenRequestData, PaymentMethodTokenizationData, PaymentsAuthorizeData,
+ PaymentsCancelData, PaymentsCaptureData, PaymentsSessionData, PaymentsSyncData,
+ RefundsData, SetupMandateRequestData,
+ },
+ router_response_types::{PaymentsResponseData, RefundsResponseData},
+ types::{
+ PaymentsAuthorizeRouterData, PaymentsCaptureRouterData, PaymentsSyncRouterData,
+ RefundSyncRouterData, RefundsRouterData,
+ },
+};
+use hyperswitch_interfaces::{
+ api::{self, ConnectorCommon, ConnectorCommonExt, ConnectorIntegration, ConnectorValidation},
+ configs::Connectors,
+ errors,
+ events::connector_api_logs::ConnectorEvent,
+ types::{self, Response},
+ webhooks,
+};
+use masking::{ExposeInterface, Mask};
+use transformers as thunes;
+
+use crate::{constants::headers, types::ResponseRouterData, utils};
+
+#[derive(Clone)]
+pub struct Thunes {
+ amount_converter: &'static (dyn AmountConvertor<Output = StringMinorUnit> + Sync),
+}
+
+impl Thunes {
+ pub fn new() -> &'static Self {
+ &Self {
+ amount_converter: &StringMinorUnitForConnector,
+ }
+ }
+}
+
+impl api::Payment for Thunes {}
+impl api::PaymentSession for Thunes {}
+impl api::ConnectorAccessToken for Thunes {}
+impl api::MandateSetup for Thunes {}
+impl api::PaymentAuthorize for Thunes {}
+impl api::PaymentSync for Thunes {}
+impl api::PaymentCapture for Thunes {}
+impl api::PaymentVoid for Thunes {}
+impl api::Refund for Thunes {}
+impl api::RefundExecute for Thunes {}
+impl api::RefundSync for Thunes {}
+impl api::PaymentToken for Thunes {}
+
+impl ConnectorIntegration<PaymentMethodToken, PaymentMethodTokenizationData, PaymentsResponseData>
+ for Thunes
+{
+ // Not Implemented (R)
+}
+
+impl<Flow, Request, Response> ConnectorCommonExt<Flow, Request, Response> for Thunes
+where
+ Self: ConnectorIntegration<Flow, Request, Response>,
+{
+ fn build_headers(
+ &self,
+ req: &RouterData<Flow, Request, Response>,
+ _connectors: &Connectors,
+ ) -> CustomResult<Vec<(String, masking::Maskable<String>)>, errors::ConnectorError> {
+ let mut header = vec![(
+ headers::CONTENT_TYPE.to_string(),
+ self.get_content_type().to_string().into(),
+ )];
+ let mut api_key = self.get_auth_header(&req.connector_auth_type)?;
+ header.append(&mut api_key);
+ Ok(header)
+ }
+}
+
+impl ConnectorCommon for Thunes {
+ fn id(&self) -> &'static str {
+ "thunes"
+ }
+
+ fn get_currency_unit(&self) -> api::CurrencyUnit {
+ api::CurrencyUnit::Base
+ // TODO! Check connector documentation, on which unit they are processing the currency.
+ // If the connector accepts amount in lower unit ( i.e cents for USD) then return api::CurrencyUnit::Minor,
+ // if connector accepts amount in base unit (i.e dollars for USD) then return api::CurrencyUnit::Base
+ }
+
+ fn common_get_content_type(&self) -> &'static str {
+ "application/json"
+ }
+
+ fn base_url<'a>(&self, connectors: &'a Connectors) -> &'a str {
+ connectors.thunes.base_url.as_ref()
+ }
+
+ fn get_auth_header(
+ &self,
+ auth_type: &ConnectorAuthType,
+ ) -> CustomResult<Vec<(String, masking::Maskable<String>)>, errors::ConnectorError> {
+ let auth = thunes::ThunesAuthType::try_from(auth_type)
+ .change_context(errors::ConnectorError::FailedToObtainAuthType)?;
+ Ok(vec![(
+ headers::AUTHORIZATION.to_string(),
+ auth.api_key.expose().into_masked(),
+ )])
+ }
+
+ fn build_error_response(
+ &self,
+ res: Response,
+ event_builder: Option<&mut ConnectorEvent>,
+ ) -> CustomResult<ErrorResponse, errors::ConnectorError> {
+ let response: thunes::ThunesErrorResponse = res
+ .response
+ .parse_struct("ThunesErrorResponse")
+ .change_context(errors::ConnectorError::ResponseDeserializationFailed)?;
+
+ event_builder.map(|i| i.set_response_body(&response));
+ router_env::logger::info!(connector_response=?response);
+
+ Ok(ErrorResponse {
+ status_code: res.status_code,
+ code: response.code,
+ message: response.message,
+ reason: response.reason,
+ attempt_status: None,
+ connector_transaction_id: None,
+ })
+ }
+}
+
+impl ConnectorValidation for Thunes {
+ //TODO: implement functions when support enabled
+}
+
+impl ConnectorIntegration<Session, PaymentsSessionData, PaymentsResponseData> for Thunes {
+ //TODO: implement sessions flow
+}
+
+impl ConnectorIntegration<AccessTokenAuth, AccessTokenRequestData, AccessToken> for Thunes {}
+
+impl ConnectorIntegration<SetupMandate, SetupMandateRequestData, PaymentsResponseData> for Thunes {}
+
+impl ConnectorIntegration<Authorize, PaymentsAuthorizeData, PaymentsResponseData> for Thunes {
+ fn get_headers(
+ &self,
+ req: &PaymentsAuthorizeRouterData,
+ connectors: &Connectors,
+ ) -> CustomResult<Vec<(String, masking::Maskable<String>)>, errors::ConnectorError> {
+ self.build_headers(req, connectors)
+ }
+
+ fn get_content_type(&self) -> &'static str {
+ self.common_get_content_type()
+ }
+
+ fn get_url(
+ &self,
+ _req: &PaymentsAuthorizeRouterData,
+ _connectors: &Connectors,
+ ) -> CustomResult<String, errors::ConnectorError> {
+ Err(errors::ConnectorError::NotImplemented("get_url method".to_string()).into())
+ }
+
+ fn get_request_body(
+ &self,
+ req: &PaymentsAuthorizeRouterData,
+ _connectors: &Connectors,
+ ) -> CustomResult<RequestContent, errors::ConnectorError> {
+ let amount = utils::convert_amount(
+ self.amount_converter,
+ req.request.minor_amount,
+ req.request.currency,
+ )?;
+
+ let connector_router_data = thunes::ThunesRouterData::from((amount, req));
+ let connector_req = thunes::ThunesPaymentsRequest::try_from(&connector_router_data)?;
+ Ok(RequestContent::Json(Box::new(connector_req)))
+ }
+
+ fn build_request(
+ &self,
+ req: &PaymentsAuthorizeRouterData,
+ connectors: &Connectors,
+ ) -> CustomResult<Option<Request>, errors::ConnectorError> {
+ Ok(Some(
+ RequestBuilder::new()
+ .method(Method::Post)
+ .url(&types::PaymentsAuthorizeType::get_url(
+ self, req, connectors,
+ )?)
+ .attach_default_headers()
+ .headers(types::PaymentsAuthorizeType::get_headers(
+ self, req, connectors,
+ )?)
+ .set_body(types::PaymentsAuthorizeType::get_request_body(
+ self, req, connectors,
+ )?)
+ .build(),
+ ))
+ }
+
+ fn handle_response(
+ &self,
+ data: &PaymentsAuthorizeRouterData,
+ event_builder: Option<&mut ConnectorEvent>,
+ res: Response,
+ ) -> CustomResult<PaymentsAuthorizeRouterData, errors::ConnectorError> {
+ let response: thunes::ThunesPaymentsResponse = res
+ .response
+ .parse_struct("Thunes PaymentsAuthorizeResponse")
+ .change_context(errors::ConnectorError::ResponseDeserializationFailed)?;
+ event_builder.map(|i| i.set_response_body(&response));
+ router_env::logger::info!(connector_response=?response);
+ RouterData::try_from(ResponseRouterData {
+ response,
+ data: data.clone(),
+ http_code: res.status_code,
+ })
+ }
+
+ fn get_error_response(
+ &self,
+ res: Response,
+ event_builder: Option<&mut ConnectorEvent>,
+ ) -> CustomResult<ErrorResponse, errors::ConnectorError> {
+ self.build_error_response(res, event_builder)
+ }
+}
+
+impl ConnectorIntegration<PSync, PaymentsSyncData, PaymentsResponseData> for Thunes {
+ fn get_headers(
+ &self,
+ req: &PaymentsSyncRouterData,
+ connectors: &Connectors,
+ ) -> CustomResult<Vec<(String, masking::Maskable<String>)>, errors::ConnectorError> {
+ self.build_headers(req, connectors)
+ }
+
+ fn get_content_type(&self) -> &'static str {
+ self.common_get_content_type()
+ }
+
+ fn get_url(
+ &self,
+ _req: &PaymentsSyncRouterData,
+ _connectors: &Connectors,
+ ) -> CustomResult<String, errors::ConnectorError> {
+ Err(errors::ConnectorError::NotImplemented("get_url method".to_string()).into())
+ }
+
+ fn build_request(
+ &self,
+ req: &PaymentsSyncRouterData,
+ connectors: &Connectors,
+ ) -> CustomResult<Option<Request>, errors::ConnectorError> {
+ Ok(Some(
+ RequestBuilder::new()
+ .method(Method::Get)
+ .url(&types::PaymentsSyncType::get_url(self, req, connectors)?)
+ .attach_default_headers()
+ .headers(types::PaymentsSyncType::get_headers(self, req, connectors)?)
+ .build(),
+ ))
+ }
+
+ fn handle_response(
+ &self,
+ data: &PaymentsSyncRouterData,
+ event_builder: Option<&mut ConnectorEvent>,
+ res: Response,
+ ) -> CustomResult<PaymentsSyncRouterData, errors::ConnectorError> {
+ let response: thunes::ThunesPaymentsResponse = res
+ .response
+ .parse_struct("thunes PaymentsSyncResponse")
+ .change_context(errors::ConnectorError::ResponseDeserializationFailed)?;
+ event_builder.map(|i| i.set_response_body(&response));
+ router_env::logger::info!(connector_response=?response);
+ RouterData::try_from(ResponseRouterData {
+ response,
+ data: data.clone(),
+ http_code: res.status_code,
+ })
+ }
+
+ fn get_error_response(
+ &self,
+ res: Response,
+ event_builder: Option<&mut ConnectorEvent>,
+ ) -> CustomResult<ErrorResponse, errors::ConnectorError> {
+ self.build_error_response(res, event_builder)
+ }
+}
+
+impl ConnectorIntegration<Capture, PaymentsCaptureData, PaymentsResponseData> for Thunes {
+ fn get_headers(
+ &self,
+ req: &PaymentsCaptureRouterData,
+ connectors: &Connectors,
+ ) -> CustomResult<Vec<(String, masking::Maskable<String>)>, errors::ConnectorError> {
+ self.build_headers(req, connectors)
+ }
+
+ fn get_content_type(&self) -> &'static str {
+ self.common_get_content_type()
+ }
+
+ fn get_url(
+ &self,
+ _req: &PaymentsCaptureRouterData,
+ _connectors: &Connectors,
+ ) -> CustomResult<String, errors::ConnectorError> {
+ Err(errors::ConnectorError::NotImplemented("get_url method".to_string()).into())
+ }
+
+ fn get_request_body(
+ &self,
+ _req: &PaymentsCaptureRouterData,
+ _connectors: &Connectors,
+ ) -> CustomResult<RequestContent, errors::ConnectorError> {
+ Err(errors::ConnectorError::NotImplemented("get_request_body method".to_string()).into())
+ }
+
+ fn build_request(
+ &self,
+ req: &PaymentsCaptureRouterData,
+ connectors: &Connectors,
+ ) -> CustomResult<Option<Request>, errors::ConnectorError> {
+ Ok(Some(
+ RequestBuilder::new()
+ .method(Method::Post)
+ .url(&types::PaymentsCaptureType::get_url(self, req, connectors)?)
+ .attach_default_headers()
+ .headers(types::PaymentsCaptureType::get_headers(
+ self, req, connectors,
+ )?)
+ .set_body(types::PaymentsCaptureType::get_request_body(
+ self, req, connectors,
+ )?)
+ .build(),
+ ))
+ }
+
+ fn handle_response(
+ &self,
+ data: &PaymentsCaptureRouterData,
+ event_builder: Option<&mut ConnectorEvent>,
+ res: Response,
+ ) -> CustomResult<PaymentsCaptureRouterData, errors::ConnectorError> {
+ let response: thunes::ThunesPaymentsResponse = res
+ .response
+ .parse_struct("Thunes PaymentsCaptureResponse")
+ .change_context(errors::ConnectorError::ResponseDeserializationFailed)?;
+ event_builder.map(|i| i.set_response_body(&response));
+ router_env::logger::info!(connector_response=?response);
+ RouterData::try_from(ResponseRouterData {
+ response,
+ data: data.clone(),
+ http_code: res.status_code,
+ })
+ }
+
+ fn get_error_response(
+ &self,
+ res: Response,
+ event_builder: Option<&mut ConnectorEvent>,
+ ) -> CustomResult<ErrorResponse, errors::ConnectorError> {
+ self.build_error_response(res, event_builder)
+ }
+}
+
+impl ConnectorIntegration<Void, PaymentsCancelData, PaymentsResponseData> for Thunes {}
+
+impl ConnectorIntegration<Execute, RefundsData, RefundsResponseData> for Thunes {
+ fn get_headers(
+ &self,
+ req: &RefundsRouterData<Execute>,
+ connectors: &Connectors,
+ ) -> CustomResult<Vec<(String, masking::Maskable<String>)>, errors::ConnectorError> {
+ self.build_headers(req, connectors)
+ }
+
+ fn get_content_type(&self) -> &'static str {
+ self.common_get_content_type()
+ }
+
+ fn get_url(
+ &self,
+ _req: &RefundsRouterData<Execute>,
+ _connectors: &Connectors,
+ ) -> CustomResult<String, errors::ConnectorError> {
+ Err(errors::ConnectorError::NotImplemented("get_url method".to_string()).into())
+ }
+
+ fn get_request_body(
+ &self,
+ req: &RefundsRouterData<Execute>,
+ _connectors: &Connectors,
+ ) -> CustomResult<RequestContent, errors::ConnectorError> {
+ let refund_amount = utils::convert_amount(
+ self.amount_converter,
+ req.request.minor_refund_amount,
+ req.request.currency,
+ )?;
+
+ let connector_router_data = thunes::ThunesRouterData::from((refund_amount, req));
+ let connector_req = thunes::ThunesRefundRequest::try_from(&connector_router_data)?;
+ Ok(RequestContent::Json(Box::new(connector_req)))
+ }
+
+ fn build_request(
+ &self,
+ req: &RefundsRouterData<Execute>,
+ connectors: &Connectors,
+ ) -> CustomResult<Option<Request>, errors::ConnectorError> {
+ let request = RequestBuilder::new()
+ .method(Method::Post)
+ .url(&types::RefundExecuteType::get_url(self, req, connectors)?)
+ .attach_default_headers()
+ .headers(types::RefundExecuteType::get_headers(
+ self, req, connectors,
+ )?)
+ .set_body(types::RefundExecuteType::get_request_body(
+ self, req, connectors,
+ )?)
+ .build();
+ Ok(Some(request))
+ }
+
+ fn handle_response(
+ &self,
+ data: &RefundsRouterData<Execute>,
+ event_builder: Option<&mut ConnectorEvent>,
+ res: Response,
+ ) -> CustomResult<RefundsRouterData<Execute>, errors::ConnectorError> {
+ let response: thunes::RefundResponse =
+ res.response
+ .parse_struct("thunes RefundResponse")
+ .change_context(errors::ConnectorError::ResponseDeserializationFailed)?;
+ event_builder.map(|i| i.set_response_body(&response));
+ router_env::logger::info!(connector_response=?response);
+ RouterData::try_from(ResponseRouterData {
+ response,
+ data: data.clone(),
+ http_code: res.status_code,
+ })
+ }
+
+ fn get_error_response(
+ &self,
+ res: Response,
+ event_builder: Option<&mut ConnectorEvent>,
+ ) -> CustomResult<ErrorResponse, errors::ConnectorError> {
+ self.build_error_response(res, event_builder)
+ }
+}
+
+impl ConnectorIntegration<RSync, RefundsData, RefundsResponseData> for Thunes {
+ fn get_headers(
+ &self,
+ req: &RefundSyncRouterData,
+ connectors: &Connectors,
+ ) -> CustomResult<Vec<(String, masking::Maskable<String>)>, errors::ConnectorError> {
+ self.build_headers(req, connectors)
+ }
+
+ fn get_content_type(&self) -> &'static str {
+ self.common_get_content_type()
+ }
+
+ fn get_url(
+ &self,
+ _req: &RefundSyncRouterData,
+ _connectors: &Connectors,
+ ) -> CustomResult<String, errors::ConnectorError> {
+ Err(errors::ConnectorError::NotImplemented("get_url method".to_string()).into())
+ }
+
+ fn build_request(
+ &self,
+ req: &RefundSyncRouterData,
+ connectors: &Connectors,
+ ) -> CustomResult<Option<Request>, errors::ConnectorError> {
+ Ok(Some(
+ RequestBuilder::new()
+ .method(Method::Get)
+ .url(&types::RefundSyncType::get_url(self, req, connectors)?)
+ .attach_default_headers()
+ .headers(types::RefundSyncType::get_headers(self, req, connectors)?)
+ .set_body(types::RefundSyncType::get_request_body(
+ self, req, connectors,
+ )?)
+ .build(),
+ ))
+ }
+
+ fn handle_response(
+ &self,
+ data: &RefundSyncRouterData,
+ event_builder: Option<&mut ConnectorEvent>,
+ res: Response,
+ ) -> CustomResult<RefundSyncRouterData, errors::ConnectorError> {
+ let response: thunes::RefundResponse = res
+ .response
+ .parse_struct("thunes RefundSyncResponse")
+ .change_context(errors::ConnectorError::ResponseDeserializationFailed)?;
+ event_builder.map(|i| i.set_response_body(&response));
+ router_env::logger::info!(connector_response=?response);
+ RouterData::try_from(ResponseRouterData {
+ response,
+ data: data.clone(),
+ http_code: res.status_code,
+ })
+ }
+
+ fn get_error_response(
+ &self,
+ res: Response,
+ event_builder: Option<&mut ConnectorEvent>,
+ ) -> CustomResult<ErrorResponse, errors::ConnectorError> {
+ self.build_error_response(res, event_builder)
+ }
+}
+
+#[async_trait::async_trait]
+impl webhooks::IncomingWebhook for Thunes {
+ fn get_webhook_object_reference_id(
+ &self,
+ _request: &webhooks::IncomingWebhookRequestDetails<'_>,
+ ) -> CustomResult<api_models::webhooks::ObjectReferenceId, errors::ConnectorError> {
+ Err(report!(errors::ConnectorError::WebhooksNotImplemented))
+ }
+
+ fn get_webhook_event_type(
+ &self,
+ _request: &webhooks::IncomingWebhookRequestDetails<'_>,
+ ) -> CustomResult<api_models::webhooks::IncomingWebhookEvent, errors::ConnectorError> {
+ Err(report!(errors::ConnectorError::WebhooksNotImplemented))
+ }
+
+ fn get_webhook_resource_object(
+ &self,
+ _request: &webhooks::IncomingWebhookRequestDetails<'_>,
+ ) -> CustomResult<Box<dyn masking::ErasedMaskSerialize>, errors::ConnectorError> {
+ Err(report!(errors::ConnectorError::WebhooksNotImplemented))
+ }
+}
diff --git a/crates/hyperswitch_connectors/src/connectors/thunes/transformers.rs b/crates/hyperswitch_connectors/src/connectors/thunes/transformers.rs
new file mode 100644
index 00000000000..c0ee0fdae94
--- /dev/null
+++ b/crates/hyperswitch_connectors/src/connectors/thunes/transformers.rs
@@ -0,0 +1,228 @@
+use common_enums::enums;
+use common_utils::types::StringMinorUnit;
+use hyperswitch_domain_models::{
+ payment_method_data::PaymentMethodData,
+ router_data::{ConnectorAuthType, RouterData},
+ router_flow_types::refunds::{Execute, RSync},
+ router_request_types::ResponseId,
+ router_response_types::{PaymentsResponseData, RefundsResponseData},
+ types::{PaymentsAuthorizeRouterData, RefundsRouterData},
+};
+use hyperswitch_interfaces::errors;
+use masking::Secret;
+use serde::{Deserialize, Serialize};
+
+use crate::{
+ types::{RefundsResponseRouterData, ResponseRouterData},
+ utils::PaymentsAuthorizeRequestData,
+};
+
+//TODO: Fill the struct with respective fields
+pub struct ThunesRouterData<T> {
+ pub amount: StringMinorUnit, // The type of amount that a connector accepts, for example, String, i64, f64, etc.
+ pub router_data: T,
+}
+
+impl<T> From<(StringMinorUnit, T)> for ThunesRouterData<T> {
+ fn from((amount, item): (StringMinorUnit, T)) -> Self {
+ //Todo : use utils to convert the amount to the type of amount that a connector accepts
+ Self {
+ amount,
+ router_data: item,
+ }
+ }
+}
+
+//TODO: Fill the struct with respective fields
+#[derive(Default, Debug, Serialize, PartialEq)]
+pub struct ThunesPaymentsRequest {
+ amount: StringMinorUnit,
+ card: ThunesCard,
+}
+
+#[derive(Default, Debug, Serialize, Eq, PartialEq)]
+pub struct ThunesCard {
+ number: cards::CardNumber,
+ expiry_month: Secret<String>,
+ expiry_year: Secret<String>,
+ cvc: Secret<String>,
+ complete: bool,
+}
+
+impl TryFrom<&ThunesRouterData<&PaymentsAuthorizeRouterData>> for ThunesPaymentsRequest {
+ type Error = error_stack::Report<errors::ConnectorError>;
+ fn try_from(
+ item: &ThunesRouterData<&PaymentsAuthorizeRouterData>,
+ ) -> Result<Self, Self::Error> {
+ match item.router_data.request.payment_method_data.clone() {
+ PaymentMethodData::Card(req_card) => {
+ let card = ThunesCard {
+ number: req_card.card_number,
+ expiry_month: req_card.card_exp_month,
+ expiry_year: req_card.card_exp_year,
+ cvc: req_card.card_cvc,
+ complete: item.router_data.request.is_auto_capture()?,
+ };
+ Ok(Self {
+ amount: item.amount.clone(),
+ card,
+ })
+ }
+ _ => Err(errors::ConnectorError::NotImplemented("Payment methods".to_string()).into()),
+ }
+ }
+}
+
+//TODO: Fill the struct with respective fields
+// Auth Struct
+pub struct ThunesAuthType {
+ pub(super) api_key: Secret<String>,
+}
+
+impl TryFrom<&ConnectorAuthType> for ThunesAuthType {
+ type Error = error_stack::Report<errors::ConnectorError>;
+ fn try_from(auth_type: &ConnectorAuthType) -> Result<Self, Self::Error> {
+ match auth_type {
+ ConnectorAuthType::HeaderKey { api_key } => Ok(Self {
+ api_key: api_key.to_owned(),
+ }),
+ _ => Err(errors::ConnectorError::FailedToObtainAuthType.into()),
+ }
+ }
+}
+// PaymentsResponse
+//TODO: Append the remaining status flags
+#[derive(Debug, Clone, Default, Serialize, Deserialize, PartialEq)]
+#[serde(rename_all = "lowercase")]
+pub enum ThunesPaymentStatus {
+ Succeeded,
+ Failed,
+ #[default]
+ Processing,
+}
+
+impl From<ThunesPaymentStatus> for common_enums::AttemptStatus {
+ fn from(item: ThunesPaymentStatus) -> Self {
+ match item {
+ ThunesPaymentStatus::Succeeded => Self::Charged,
+ ThunesPaymentStatus::Failed => Self::Failure,
+ ThunesPaymentStatus::Processing => Self::Authorizing,
+ }
+ }
+}
+
+//TODO: Fill the struct with respective fields
+#[derive(Default, Debug, Clone, Serialize, Deserialize, PartialEq)]
+pub struct ThunesPaymentsResponse {
+ status: ThunesPaymentStatus,
+ id: String,
+}
+
+impl<F, T> TryFrom<ResponseRouterData<F, ThunesPaymentsResponse, T, PaymentsResponseData>>
+ for RouterData<F, T, PaymentsResponseData>
+{
+ type Error = error_stack::Report<errors::ConnectorError>;
+ fn try_from(
+ item: ResponseRouterData<F, ThunesPaymentsResponse, T, PaymentsResponseData>,
+ ) -> Result<Self, Self::Error> {
+ Ok(Self {
+ status: common_enums::AttemptStatus::from(item.response.status),
+ response: Ok(PaymentsResponseData::TransactionResponse {
+ resource_id: ResponseId::ConnectorTransactionId(item.response.id),
+ redirection_data: None,
+ mandate_reference: None,
+ connector_metadata: None,
+ network_txn_id: None,
+ connector_response_reference_id: None,
+ incremental_authorization_allowed: None,
+ charge_id: None,
+ }),
+ ..item.data
+ })
+ }
+}
+
+//TODO: Fill the struct with respective fields
+// REFUND :
+// Type definition for RefundRequest
+#[derive(Default, Debug, Serialize)]
+pub struct ThunesRefundRequest {
+ pub amount: StringMinorUnit,
+}
+
+impl<F> TryFrom<&ThunesRouterData<&RefundsRouterData<F>>> for ThunesRefundRequest {
+ type Error = error_stack::Report<errors::ConnectorError>;
+ fn try_from(item: &ThunesRouterData<&RefundsRouterData<F>>) -> Result<Self, Self::Error> {
+ Ok(Self {
+ amount: item.amount.to_owned(),
+ })
+ }
+}
+
+// Type definition for Refund Response
+
+#[allow(dead_code)]
+#[derive(Debug, Serialize, Default, Deserialize, Clone)]
+pub enum RefundStatus {
+ Succeeded,
+ Failed,
+ #[default]
+ Processing,
+}
+
+impl From<RefundStatus> for enums::RefundStatus {
+ fn from(item: RefundStatus) -> Self {
+ match item {
+ RefundStatus::Succeeded => Self::Success,
+ RefundStatus::Failed => Self::Failure,
+ RefundStatus::Processing => Self::Pending,
+ //TODO: Review mapping
+ }
+ }
+}
+
+//TODO: Fill the struct with respective fields
+#[derive(Default, Debug, Clone, Serialize, Deserialize)]
+pub struct RefundResponse {
+ id: String,
+ status: RefundStatus,
+}
+
+impl TryFrom<RefundsResponseRouterData<Execute, RefundResponse>> for RefundsRouterData<Execute> {
+ type Error = error_stack::Report<errors::ConnectorError>;
+ fn try_from(
+ item: RefundsResponseRouterData<Execute, RefundResponse>,
+ ) -> Result<Self, Self::Error> {
+ Ok(Self {
+ response: Ok(RefundsResponseData {
+ connector_refund_id: item.response.id.to_string(),
+ refund_status: enums::RefundStatus::from(item.response.status),
+ }),
+ ..item.data
+ })
+ }
+}
+
+impl TryFrom<RefundsResponseRouterData<RSync, RefundResponse>> for RefundsRouterData<RSync> {
+ type Error = error_stack::Report<errors::ConnectorError>;
+ fn try_from(
+ item: RefundsResponseRouterData<RSync, RefundResponse>,
+ ) -> Result<Self, Self::Error> {
+ Ok(Self {
+ response: Ok(RefundsResponseData {
+ connector_refund_id: item.response.id.to_string(),
+ refund_status: enums::RefundStatus::from(item.response.status),
+ }),
+ ..item.data
+ })
+ }
+}
+
+//TODO: Fill the struct with respective fields
+#[derive(Default, Debug, Serialize, Deserialize, PartialEq)]
+pub struct ThunesErrorResponse {
+ pub status_code: u16,
+ pub code: String,
+ pub message: String,
+ pub reason: Option<String>,
+}
diff --git a/crates/hyperswitch_connectors/src/default_implementations.rs b/crates/hyperswitch_connectors/src/default_implementations.rs
index 0210bfa551a..40aa36cc8ba 100644
--- a/crates/hyperswitch_connectors/src/default_implementations.rs
+++ b/crates/hyperswitch_connectors/src/default_implementations.rs
@@ -102,6 +102,7 @@ default_imp_for_authorize_session_token!(
connectors::Powertranz,
connectors::Stax,
connectors::Taxjar,
+ connectors::Thunes,
connectors::Tsys,
connectors::Worldline
);
@@ -133,6 +134,7 @@ default_imp_for_calculate_tax!(
connectors::Globepay,
connectors::Worldline,
connectors::Powertranz,
+ connectors::Thunes,
connectors::Tsys,
connectors::Deutschebank
);
@@ -165,6 +167,7 @@ default_imp_for_session_update!(
connectors::Globepay,
connectors::Worldline,
connectors::Powertranz,
+ connectors::Thunes,
connectors::Tsys,
connectors::Deutschebank
);
@@ -197,6 +200,7 @@ default_imp_for_complete_authorize!(
connectors::Nexixpay,
connectors::Stax,
connectors::Taxjar,
+ connectors::Thunes,
connectors::Tsys,
connectors::Worldline
);
@@ -230,6 +234,7 @@ default_imp_for_incremental_authorization!(
connectors::Powertranz,
connectors::Stax,
connectors::Taxjar,
+ connectors::Thunes,
connectors::Tsys,
connectors::Worldline
);
@@ -262,6 +267,7 @@ default_imp_for_create_customer!(
connectors::Nexixpay,
connectors::Powertranz,
connectors::Taxjar,
+ connectors::Thunes,
connectors::Tsys,
connectors::Worldline
);
@@ -296,6 +302,7 @@ default_imp_for_connector_redirect_response!(
connectors::Powertranz,
connectors::Stax,
connectors::Taxjar,
+ connectors::Thunes,
connectors::Tsys,
connectors::Worldline
);
@@ -329,6 +336,7 @@ default_imp_for_pre_processing_steps!(
connectors::Powertranz,
connectors::Stax,
connectors::Taxjar,
+ connectors::Thunes,
connectors::Tsys,
connectors::Worldline
);
@@ -362,6 +370,7 @@ default_imp_for_post_processing_steps!(
connectors::Powertranz,
connectors::Stax,
connectors::Taxjar,
+ connectors::Thunes,
connectors::Tsys,
connectors::Worldline
);
@@ -395,6 +404,7 @@ default_imp_for_approve!(
connectors::Powertranz,
connectors::Stax,
connectors::Taxjar,
+ connectors::Thunes,
connectors::Tsys,
connectors::Worldline
);
@@ -428,6 +438,7 @@ default_imp_for_reject!(
connectors::Powertranz,
connectors::Stax,
connectors::Taxjar,
+ connectors::Thunes,
connectors::Tsys,
connectors::Worldline
);
@@ -461,6 +472,7 @@ default_imp_for_webhook_source_verification!(
connectors::Powertranz,
connectors::Stax,
connectors::Taxjar,
+ connectors::Thunes,
connectors::Tsys,
connectors::Worldline
);
@@ -495,6 +507,7 @@ default_imp_for_accept_dispute!(
connectors::Powertranz,
connectors::Stax,
connectors::Taxjar,
+ connectors::Thunes,
connectors::Tsys,
connectors::Worldline
);
@@ -528,6 +541,7 @@ default_imp_for_submit_evidence!(
connectors::Powertranz,
connectors::Stax,
connectors::Taxjar,
+ connectors::Thunes,
connectors::Tsys,
connectors::Worldline
);
@@ -561,6 +575,7 @@ default_imp_for_defend_dispute!(
connectors::Powertranz,
connectors::Stax,
connectors::Taxjar,
+ connectors::Thunes,
connectors::Tsys,
connectors::Worldline
);
@@ -603,6 +618,7 @@ default_imp_for_file_upload!(
connectors::Powertranz,
connectors::Stax,
connectors::Taxjar,
+ connectors::Thunes,
connectors::Tsys,
connectors::Worldline
);
@@ -638,6 +654,7 @@ default_imp_for_payouts_create!(
connectors::Powertranz,
connectors::Stax,
connectors::Taxjar,
+ connectors::Thunes,
connectors::Tsys,
connectors::Worldline
);
@@ -673,6 +690,7 @@ default_imp_for_payouts_retrieve!(
connectors::Powertranz,
connectors::Stax,
connectors::Taxjar,
+ connectors::Thunes,
connectors::Tsys,
connectors::Worldline
);
@@ -708,6 +726,7 @@ default_imp_for_payouts_eligibility!(
connectors::Powertranz,
connectors::Stax,
connectors::Taxjar,
+ connectors::Thunes,
connectors::Tsys,
connectors::Worldline
);
@@ -743,6 +762,7 @@ default_imp_for_payouts_fulfill!(
connectors::Powertranz,
connectors::Stax,
connectors::Taxjar,
+ connectors::Thunes,
connectors::Tsys,
connectors::Worldline
);
@@ -778,6 +798,7 @@ default_imp_for_payouts_cancel!(
connectors::Powertranz,
connectors::Stax,
connectors::Taxjar,
+ connectors::Thunes,
connectors::Tsys,
connectors::Worldline
);
@@ -813,6 +834,7 @@ default_imp_for_payouts_quote!(
connectors::Powertranz,
connectors::Stax,
connectors::Taxjar,
+ connectors::Thunes,
connectors::Tsys,
connectors::Worldline
);
@@ -848,6 +870,7 @@ default_imp_for_payouts_recipient!(
connectors::Powertranz,
connectors::Stax,
connectors::Taxjar,
+ connectors::Thunes,
connectors::Tsys,
connectors::Worldline
);
@@ -883,6 +906,7 @@ default_imp_for_payouts_recipient_account!(
connectors::Powertranz,
connectors::Stax,
connectors::Taxjar,
+ connectors::Thunes,
connectors::Tsys,
connectors::Worldline
);
@@ -918,6 +942,7 @@ default_imp_for_frm_sale!(
connectors::Powertranz,
connectors::Stax,
connectors::Taxjar,
+ connectors::Thunes,
connectors::Tsys,
connectors::Worldline
);
@@ -953,6 +978,7 @@ default_imp_for_frm_checkout!(
connectors::Powertranz,
connectors::Stax,
connectors::Taxjar,
+ connectors::Thunes,
connectors::Tsys,
connectors::Worldline
);
@@ -988,6 +1014,7 @@ default_imp_for_frm_transaction!(
connectors::Powertranz,
connectors::Stax,
connectors::Taxjar,
+ connectors::Thunes,
connectors::Tsys,
connectors::Worldline
);
@@ -1023,6 +1050,7 @@ default_imp_for_frm_fulfillment!(
connectors::Powertranz,
connectors::Stax,
connectors::Taxjar,
+ connectors::Thunes,
connectors::Tsys,
connectors::Worldline
);
@@ -1058,6 +1086,7 @@ default_imp_for_frm_record_return!(
connectors::Powertranz,
connectors::Stax,
connectors::Taxjar,
+ connectors::Thunes,
connectors::Tsys,
connectors::Worldline
);
@@ -1090,6 +1119,7 @@ default_imp_for_revoking_mandates!(
connectors::Powertranz,
connectors::Stax,
connectors::Taxjar,
+ connectors::Thunes,
connectors::Tsys,
connectors::Worldline
);
diff --git a/crates/hyperswitch_connectors/src/default_implementations_v2.rs b/crates/hyperswitch_connectors/src/default_implementations_v2.rs
index e23f8fdb290..95c7ffec007 100644
--- a/crates/hyperswitch_connectors/src/default_implementations_v2.rs
+++ b/crates/hyperswitch_connectors/src/default_implementations_v2.rs
@@ -209,6 +209,7 @@ default_imp_for_new_connector_integration_payment!(
connectors::Powertranz,
connectors::Stax,
connectors::Taxjar,
+ connectors::Thunes,
connectors::Tsys,
connectors::Worldline
);
@@ -243,6 +244,7 @@ default_imp_for_new_connector_integration_refund!(
connectors::Powertranz,
connectors::Stax,
connectors::Taxjar,
+ connectors::Thunes,
connectors::Tsys,
connectors::Worldline
);
@@ -272,6 +274,7 @@ default_imp_for_new_connector_integration_connector_access_token!(
connectors::Powertranz,
connectors::Stax,
connectors::Taxjar,
+ connectors::Thunes,
connectors::Tsys,
connectors::Worldline
);
@@ -307,6 +310,7 @@ default_imp_for_new_connector_integration_accept_dispute!(
connectors::Powertranz,
connectors::Stax,
connectors::Taxjar,
+ connectors::Thunes,
connectors::Tsys,
connectors::Worldline
);
@@ -341,6 +345,7 @@ default_imp_for_new_connector_integration_submit_evidence!(
connectors::Powertranz,
connectors::Stax,
connectors::Taxjar,
+ connectors::Thunes,
connectors::Tsys,
connectors::Worldline
);
@@ -375,6 +380,7 @@ default_imp_for_new_connector_integration_defend_dispute!(
connectors::Powertranz,
connectors::Stax,
connectors::Taxjar,
+ connectors::Thunes,
connectors::Tsys,
connectors::Worldline
);
@@ -419,6 +425,7 @@ default_imp_for_new_connector_integration_file_upload!(
connectors::Powertranz,
connectors::Stax,
connectors::Taxjar,
+ connectors::Thunes,
connectors::Tsys,
connectors::Worldline
);
@@ -455,6 +462,7 @@ default_imp_for_new_connector_integration_payouts_create!(
connectors::Powertranz,
connectors::Stax,
connectors::Taxjar,
+ connectors::Thunes,
connectors::Tsys,
connectors::Worldline
);
@@ -491,6 +499,7 @@ default_imp_for_new_connector_integration_payouts_eligibility!(
connectors::Powertranz,
connectors::Stax,
connectors::Taxjar,
+ connectors::Thunes,
connectors::Tsys,
connectors::Worldline
);
@@ -527,6 +536,7 @@ default_imp_for_new_connector_integration_payouts_fulfill!(
connectors::Powertranz,
connectors::Stax,
connectors::Taxjar,
+ connectors::Thunes,
connectors::Tsys,
connectors::Worldline
);
@@ -563,6 +573,7 @@ default_imp_for_new_connector_integration_payouts_cancel!(
connectors::Powertranz,
connectors::Stax,
connectors::Taxjar,
+ connectors::Thunes,
connectors::Tsys,
connectors::Worldline
);
@@ -599,6 +610,7 @@ default_imp_for_new_connector_integration_payouts_quote!(
connectors::Powertranz,
connectors::Stax,
connectors::Taxjar,
+ connectors::Thunes,
connectors::Tsys,
connectors::Worldline
);
@@ -635,6 +647,7 @@ default_imp_for_new_connector_integration_payouts_recipient!(
connectors::Powertranz,
connectors::Stax,
connectors::Taxjar,
+ connectors::Thunes,
connectors::Tsys,
connectors::Worldline
);
@@ -671,6 +684,7 @@ default_imp_for_new_connector_integration_payouts_sync!(
connectors::Powertranz,
connectors::Stax,
connectors::Taxjar,
+ connectors::Thunes,
connectors::Tsys,
connectors::Worldline
);
@@ -707,6 +721,7 @@ default_imp_for_new_connector_integration_payouts_recipient_account!(
connectors::Powertranz,
connectors::Stax,
connectors::Taxjar,
+ connectors::Thunes,
connectors::Tsys,
connectors::Worldline
);
@@ -741,6 +756,7 @@ default_imp_for_new_connector_integration_webhook_source_verification!(
connectors::Powertranz,
connectors::Stax,
connectors::Taxjar,
+ connectors::Thunes,
connectors::Tsys,
connectors::Worldline
);
@@ -777,6 +793,7 @@ default_imp_for_new_connector_integration_frm_sale!(
connectors::Powertranz,
connectors::Stax,
connectors::Taxjar,
+ connectors::Thunes,
connectors::Tsys,
connectors::Worldline
);
@@ -813,6 +830,7 @@ default_imp_for_new_connector_integration_frm_checkout!(
connectors::Powertranz,
connectors::Stax,
connectors::Taxjar,
+ connectors::Thunes,
connectors::Tsys,
connectors::Worldline
);
@@ -849,6 +867,7 @@ default_imp_for_new_connector_integration_frm_transaction!(
connectors::Powertranz,
connectors::Stax,
connectors::Taxjar,
+ connectors::Thunes,
connectors::Tsys,
connectors::Worldline
);
@@ -885,6 +904,7 @@ default_imp_for_new_connector_integration_frm_fulfillment!(
connectors::Powertranz,
connectors::Stax,
connectors::Taxjar,
+ connectors::Thunes,
connectors::Tsys,
connectors::Worldline
);
@@ -921,6 +941,7 @@ default_imp_for_new_connector_integration_frm_record_return!(
connectors::Powertranz,
connectors::Stax,
connectors::Taxjar,
+ connectors::Thunes,
connectors::Tsys,
connectors::Worldline
);
@@ -954,6 +975,7 @@ default_imp_for_new_connector_integration_revoking_mandates!(
connectors::Powertranz,
connectors::Stax,
connectors::Taxjar,
+ connectors::Thunes,
connectors::Tsys,
connectors::Worldline
);
diff --git a/crates/hyperswitch_interfaces/src/configs.rs b/crates/hyperswitch_interfaces/src/configs.rs
index 37e5eecea6a..eae30eeb67b 100644
--- a/crates/hyperswitch_interfaces/src/configs.rs
+++ b/crates/hyperswitch_interfaces/src/configs.rs
@@ -78,6 +78,7 @@ pub struct Connectors {
pub stripe: ConnectorParamsWithFileUploadUrl,
pub taxjar: ConnectorParams,
pub threedsecureio: ConnectorParams,
+ pub thunes: ConnectorParams,
pub trustpay: ConnectorParamsWithMoreUrls,
pub tsys: ConnectorParams,
pub volt: ConnectorParams,
diff --git a/crates/router/src/connector.rs b/crates/router/src/connector.rs
index 1fea8015def..caa5b13b51c 100644
--- a/crates/router/src/connector.rs
+++ b/crates/router/src/connector.rs
@@ -68,7 +68,7 @@ pub use hyperswitch_connectors::connectors::{
fiserv, fiserv::Fiserv, fiservemea, fiservemea::Fiservemea, fiuu, fiuu::Fiuu, globepay,
globepay::Globepay, helcim, helcim::Helcim, nexixpay, nexixpay::Nexixpay, novalnet,
novalnet::Novalnet, powertranz, powertranz::Powertranz, stax, stax::Stax, taxjar,
- taxjar::Taxjar, tsys, tsys::Tsys, worldline, worldline::Worldline,
+ taxjar::Taxjar, thunes, thunes::Thunes, tsys, tsys::Tsys, worldline, worldline::Worldline,
};
#[cfg(feature = "dummy_connector")]
diff --git a/crates/router/src/core/payments/connector_integration_v2_impls.rs b/crates/router/src/core/payments/connector_integration_v2_impls.rs
index 0a4aa8348d4..a1a3cecd8fc 100644
--- a/crates/router/src/core/payments/connector_integration_v2_impls.rs
+++ b/crates/router/src/core/payments/connector_integration_v2_impls.rs
@@ -1287,6 +1287,7 @@ default_imp_for_new_connector_integration_payouts!(
connector::Taxjar,
connector::Trustpay,
connector::Threedsecureio,
+ connector::Thunes,
connector::Tsys,
connector::Volt,
connector::Wellsfargo,
@@ -2100,6 +2101,7 @@ default_imp_for_new_connector_integration_frm!(
connector::Taxjar,
connector::Trustpay,
connector::Threedsecureio,
+ connector::Thunes,
connector::Tsys,
connector::Volt,
connector::Wellsfargo,
@@ -2704,6 +2706,7 @@ default_imp_for_new_connector_integration_connector_authentication!(
connector::Taxjar,
connector::Trustpay,
connector::Threedsecureio,
+ connector::Thunes,
connector::Tsys,
connector::Volt,
connector::Wellsfargo,
diff --git a/crates/router/src/types/api.rs b/crates/router/src/types/api.rs
index 1c5e6eb5e95..598db0bdcc1 100644
--- a/crates/router/src/types/api.rs
+++ b/crates/router/src/types/api.rs
@@ -482,14 +482,17 @@ impl ConnectorData {
enums::Connector::Paypal => {
Ok(ConnectorEnum::Old(Box::new(connector::Paypal::new())))
}
+ // enums::Connector::Thunes => Ok(ConnectorEnum::Old(Box::new(connector::Thunes))),
enums::Connector::Trustpay => {
Ok(ConnectorEnum::Old(Box::new(connector::Trustpay::new())))
}
enums::Connector::Tsys => Ok(ConnectorEnum::Old(Box::new(&connector::Tsys))),
+
enums::Connector::Volt => Ok(ConnectorEnum::Old(Box::new(connector::Volt::new()))),
enums::Connector::Wellsfargo => {
Ok(ConnectorEnum::Old(Box::new(&connector::Wellsfargo)))
}
+
// enums::Connector::Wellsfargopayout => {
// Ok(Box::new(connector::Wellsfargopayout::new()))
// }
diff --git a/crates/router/src/types/transformers.rs b/crates/router/src/types/transformers.rs
index de897c816dd..f302cb00956 100644
--- a/crates/router/src/types/transformers.rs
+++ b/crates/router/src/types/transformers.rs
@@ -333,6 +333,8 @@ impl ForeignTryFrom<api_enums::Connector> for common_enums::RoutableConnectors {
api_enums::Connector::Square => Self::Square,
api_enums::Connector::Stax => Self::Stax,
api_enums::Connector::Stripe => Self::Stripe,
+ // api_enums::Connector::Taxjar => Self::Taxjar,
+ // api_enums::Connector::Thunes => Self::Thunes,
api_enums::Connector::Trustpay => Self::Trustpay,
api_enums::Connector::Tsys => Self::Tsys,
api_enums::Connector::Volt => Self::Volt,
diff --git a/crates/router/tests/connectors/sample_auth.toml b/crates/router/tests/connectors/sample_auth.toml
index fe5820d34e5..6ed9bd7103d 100644
--- a/crates/router/tests/connectors/sample_auth.toml
+++ b/crates/router/tests/connectors/sample_auth.toml
@@ -276,4 +276,7 @@ api_key = "API Key"
api_key="API Key"
[deutschebank]
+api_key="API Key"
+
+[thunes]
api_key="API Key"
\ No newline at end of file
diff --git a/crates/router/tests/connectors/thunes.rs b/crates/router/tests/connectors/thunes.rs
new file mode 100644
index 00000000000..379e102a53c
--- /dev/null
+++ b/crates/router/tests/connectors/thunes.rs
@@ -0,0 +1,402 @@
+use masking::Secret;
+// use router::{
+// types::{self, api, storage::enums,
+// }};
+
+use crate::utils::{self, ConnectorActions};
+use test_utils::connector_auth;
+
+#[derive(Clone, Copy)]
+struct ThunesTest;
+impl ConnectorActions for ThunesTest {}
+impl utils::Connector for ThunesTest {
+ fn get_data(&self) -> api::ConnectorData {
+ use router::connector::Thunes;
+ api::ConnectorData {
+ connector: Box::new(Thunes::new()),
+ connector_name: types::Connector::Thunes,
+ get_token: types::api::GetToken::Connector,
+ merchant_connector_id: None,
+ }
+ }
+
+ fn get_auth_token(&self) -> types::ConnectorAuthType {
+ utils::to_connector_auth_type(
+ connector_auth::ConnectorAuthentication::new()
+ .thunes
+ .expect("Missing connector authentication configuration").into(),
+ )
+ }
+
+ fn get_name(&self) -> String {
+ "thunes".to_string()
+ }
+}
+
+static CONNECTOR: ThunesTest = ThunesTest {};
+
+fn get_default_payment_info() -> Option<utils::PaymentInfo> {
+ None
+}
+
+fn payment_method_details() -> Option<types::PaymentsAuthorizeData> {
+ None
+}
+
+// Cards Positive Tests
+// Creates a payment using the manual capture flow (Non 3DS).
+#[actix_web::test]
+async fn should_only_authorize_payment() {
+ let response = CONNECTOR
+ .authorize_payment(payment_method_details(), get_default_payment_info())
+ .await
+ .expect("Authorize payment response");
+ assert_eq!(response.status, enums::AttemptStatus::Authorized);
+}
+
+// Captures a payment using the manual capture flow (Non 3DS).
+#[actix_web::test]
+async fn should_capture_authorized_payment() {
+ let response = CONNECTOR
+ .authorize_and_capture_payment(payment_method_details(), None, get_default_payment_info())
+ .await
+ .expect("Capture payment response");
+ assert_eq!(response.status, enums::AttemptStatus::Charged);
+}
+
+// Partially captures a payment using the manual capture flow (Non 3DS).
+#[actix_web::test]
+async fn should_partially_capture_authorized_payment() {
+ let response = CONNECTOR
+ .authorize_and_capture_payment(
+ payment_method_details(),
+ Some(types::PaymentsCaptureData {
+ amount_to_capture: 50,
+ ..utils::PaymentCaptureType::default().0
+ }),
+ get_default_payment_info(),
+ )
+ .await
+ .expect("Capture payment response");
+ assert_eq!(response.status, enums::AttemptStatus::Charged);
+}
+
+// Synchronizes a payment using the manual capture flow (Non 3DS).
+#[actix_web::test]
+async fn should_sync_authorized_payment() {
+ let authorize_response = CONNECTOR
+ .authorize_payment(payment_method_details(), get_default_payment_info())
+ .await
+ .expect("Authorize payment response");
+ let txn_id = utils::get_connector_transaction_id(authorize_response.response);
+ let response = CONNECTOR
+ .psync_retry_till_status_matches(
+ enums::AttemptStatus::Authorized,
+ Some(types::PaymentsSyncData {
+ connector_transaction_id: types::ResponseId::ConnectorTransactionId(
+ txn_id.unwrap(),
+ ),
+ ..Default::default()
+ }),
+ get_default_payment_info(),
+ )
+ .await
+ .expect("PSync response");
+ assert_eq!(response.status, enums::AttemptStatus::Authorized,);
+}
+
+// Voids a payment using the manual capture flow (Non 3DS).
+#[actix_web::test]
+async fn should_void_authorized_payment() {
+ let response = CONNECTOR
+ .authorize_and_void_payment(
+ payment_method_details(),
+ Some(types::PaymentsCancelData {
+ connector_transaction_id: String::from(""),
+ cancellation_reason: Some("requested_by_customer".to_string()),
+ ..Default::default()
+ }),
+ get_default_payment_info(),
+ )
+ .await
+ .expect("Void payment response");
+ assert_eq!(response.status, enums::AttemptStatus::Voided);
+}
+
+// Refunds a payment using the manual capture flow (Non 3DS).
+#[actix_web::test]
+async fn should_refund_manually_captured_payment() {
+ let response = CONNECTOR
+ .capture_payment_and_refund(payment_method_details(), None, None, get_default_payment_info())
+ .await
+ .unwrap();
+ assert_eq!(
+ response.response.unwrap().refund_status,
+ enums::RefundStatus::Success,
+ );
+}
+
+// Partially refunds a payment using the manual capture flow (Non 3DS).
+#[actix_web::test]
+async fn should_partially_refund_manually_captured_payment() {
+ let response = CONNECTOR
+ .capture_payment_and_refund(
+ payment_method_details(),
+ None,
+ Some(types::RefundsData {
+ refund_amount: 50,
+ ..utils::PaymentRefundType::default().0
+ }),
+ get_default_payment_info(),
+ )
+ .await
+ .unwrap();
+ assert_eq!(
+ response.response.unwrap().refund_status,
+ enums::RefundStatus::Success,
+ );
+}
+
+// Synchronizes a refund using the manual capture flow (Non 3DS).
+#[actix_web::test]
+async fn should_sync_manually_captured_refund() {
+ let refund_response = CONNECTOR
+ .capture_payment_and_refund(payment_method_details(), None, None, get_default_payment_info())
+ .await
+ .unwrap();
+ let response = CONNECTOR
+ .rsync_retry_till_status_matches(
+ enums::RefundStatus::Success,
+ refund_response.response.unwrap().connector_refund_id,
+ None,
+ get_default_payment_info(),
+ )
+ .await
+ .unwrap();
+ assert_eq!(
+ response.response.unwrap().refund_status,
+ enums::RefundStatus::Success,
+ );
+}
+
+// Creates a payment using the automatic capture flow (Non 3DS).
+#[actix_web::test]
+async fn should_make_payment() {
+ let authorize_response = CONNECTOR.make_payment(payment_method_details(), get_default_payment_info()).await.unwrap();
+ assert_eq!(authorize_response.status, enums::AttemptStatus::Charged);
+}
+
+// Synchronizes a payment using the automatic capture flow (Non 3DS).
+#[actix_web::test]
+async fn should_sync_auto_captured_payment() {
+ let authorize_response = CONNECTOR.make_payment(payment_method_details(), get_default_payment_info()).await.unwrap();
+ assert_eq!(authorize_response.status, enums::AttemptStatus::Charged);
+ let txn_id = utils::get_connector_transaction_id(authorize_response.response);
+ assert_ne!(txn_id, None, "Empty connector transaction id");
+ let response = CONNECTOR
+ .psync_retry_till_status_matches(
+ enums::AttemptStatus::Charged,
+ Some(types::PaymentsSyncData {
+ connector_transaction_id: types::ResponseId::ConnectorTransactionId(
+ txn_id.unwrap(),
+ ),
+ capture_method: Some(enums::CaptureMethod::Automatic),
+ ..Default::default()
+ }),
+ get_default_payment_info(),
+ )
+ .await
+ .unwrap();
+ assert_eq!(response.status, enums::AttemptStatus::Charged,);
+}
+
+// Refunds a payment using the automatic capture flow (Non 3DS).
+#[actix_web::test]
+async fn should_refund_auto_captured_payment() {
+ let response = CONNECTOR
+ .make_payment_and_refund(payment_method_details(), None, get_default_payment_info())
+ .await
+ .unwrap();
+ assert_eq!(
+ response.response.unwrap().refund_status,
+ enums::RefundStatus::Success,
+ );
+}
+
+// Partially refunds a payment using the automatic capture flow (Non 3DS).
+#[actix_web::test]
+async fn should_partially_refund_succeeded_payment() {
+ let refund_response = CONNECTOR
+ .make_payment_and_refund(
+ payment_method_details(),
+ Some(types::RefundsData {
+ refund_amount: 50,
+ ..utils::PaymentRefundType::default().0
+ }),
+ get_default_payment_info(),
+ )
+ .await
+ .unwrap();
+ assert_eq!(
+ refund_response.response.unwrap().refund_status,
+ enums::RefundStatus::Success,
+ );
+}
+
+// Creates multiple refunds against a payment using the automatic capture flow (Non 3DS).
+#[actix_web::test]
+async fn should_refund_succeeded_payment_multiple_times() {
+ CONNECTOR
+ .make_payment_and_multiple_refund(
+ payment_method_details(),
+ Some(types::RefundsData {
+ refund_amount: 50,
+ ..utils::PaymentRefundType::default().0
+ }),
+ get_default_payment_info(),
+ )
+ .await;
+}
+
+// Synchronizes a refund using the automatic capture flow (Non 3DS).
+#[actix_web::test]
+async fn should_sync_refund() {
+ let refund_response = CONNECTOR
+ .make_payment_and_refund(payment_method_details(), None, get_default_payment_info())
+ .await
+ .unwrap();
+ let response = CONNECTOR
+ .rsync_retry_till_status_matches(
+ enums::RefundStatus::Success,
+ refund_response.response.unwrap().connector_refund_id,
+ None,
+ get_default_payment_info(),
+ )
+ .await
+ .unwrap();
+ assert_eq!(
+ response.response.unwrap().refund_status,
+ enums::RefundStatus::Success,
+ );
+}
+
+// Cards Negative scenarios
+// Creates a payment with incorrect CVC.
+#[actix_web::test]
+async fn should_fail_payment_for_incorrect_cvc() {
+ let response = CONNECTOR
+ .make_payment(
+ Some(types::PaymentsAuthorizeData {
+ payment_method_data: types::api::PaymentMethodData::Card(api::Card {
+ card_cvc: Secret::new("12345".to_string()),
+ ..utils::CCardType::default().0
+ }),
+ ..utils::PaymentAuthorizeType::default().0
+ }),
+ get_default_payment_info(),
+ )
+ .await
+ .unwrap();
+ assert_eq!(
+ response.response.unwrap_err().message,
+ "Your card's security code is invalid.".to_string(),
+ );
+}
+
+// Creates a payment with incorrect expiry month.
+#[actix_web::test]
+async fn should_fail_payment_for_invalid_exp_month() {
+ let response = CONNECTOR
+ .make_payment(
+ Some(types::PaymentsAuthorizeData {
+ payment_method_data: api::PaymentMethodData::Card(api::Card {
+ card_exp_month: Secret::new("20".to_string()),
+ ..utils::CCardType::default().0
+ }),
+ ..utils::PaymentAuthorizeType::default().0
+ }),
+ get_default_payment_info(),
+ )
+ .await
+ .unwrap();
+ assert_eq!(
+ response.response.unwrap_err().message,
+ "Your card's expiration month is invalid.".to_string(),
+ );
+}
+
+// Creates a payment with incorrect expiry year.
+#[actix_web::test]
+async fn should_fail_payment_for_incorrect_expiry_year() {
+ let response = CONNECTOR
+ .make_payment(
+ Some(types::PaymentsAuthorizeData {
+ payment_method_data: api::PaymentMethodData::Card(api::Card {
+ card_exp_year: Secret::new("2000".to_string()),
+ ..utils::CCardType::default().0
+ }),
+ ..utils::PaymentAuthorizeType::default().0
+ }),
+ get_default_payment_info(),
+ )
+ .await
+ .unwrap();
+ assert_eq!(
+ response.response.unwrap_err().message,
+ "Your card's expiration year is invalid.".to_string(),
+ );
+}
+
+// Voids a payment using automatic capture flow (Non 3DS).
+#[actix_web::test]
+async fn should_fail_void_payment_for_auto_capture() {
+ let authorize_response = CONNECTOR.make_payment(payment_method_details(), get_default_payment_info()).await.unwrap();
+ assert_eq!(authorize_response.status, enums::AttemptStatus::Charged);
+ let txn_id = utils::get_connector_transaction_id(authorize_response.response);
+ assert_ne!(txn_id, None, "Empty connector transaction id");
+ let void_response = CONNECTOR
+ .void_payment(txn_id.unwrap(), None, get_default_payment_info())
+ .await
+ .unwrap();
+ assert_eq!(
+ void_response.response.unwrap_err().message,
+ "You cannot cancel this PaymentIntent because it has a status of succeeded."
+ );
+}
+
+// Captures a payment using invalid connector payment id.
+#[actix_web::test]
+async fn should_fail_capture_for_invalid_payment() {
+ let capture_response = CONNECTOR
+ .capture_payment("123456789".to_string(), None, get_default_payment_info())
+ .await
+ .unwrap();
+ assert_eq!(
+ capture_response.response.unwrap_err().message,
+ String::from("No such payment_intent: '123456789'")
+ );
+}
+
+// Refunds a payment with refund amount higher than payment amount.
+#[actix_web::test]
+async fn should_fail_for_refund_amount_higher_than_payment_amount() {
+ let response = CONNECTOR
+ .make_payment_and_refund(
+ payment_method_details(),
+ Some(types::RefundsData {
+ refund_amount: 150,
+ ..utils::PaymentRefundType::default().0
+ }),
+ get_default_payment_info(),
+ )
+ .await
+ .unwrap();
+ assert_eq!(
+ response.response.unwrap_err().message,
+ "Refund amount (₹1.50) is greater than charge amount (₹1.00)",
+ );
+}
+
+// Connector dependent test cases goes here
+
+// [#478]: add unit tests for non 3DS, wallets & webhooks in connector tests
diff --git a/crates/test_utils/src/connector_auth.rs b/crates/test_utils/src/connector_auth.rs
index a1261e6edb1..68895e5876e 100644
--- a/crates/test_utils/src/connector_auth.rs
+++ b/crates/test_utils/src/connector_auth.rs
@@ -77,6 +77,7 @@ pub struct ConnectorAuthentication {
pub stripe: Option<HeaderKey>,
pub taxjar: Option<HeaderKey>,
pub threedsecureio: Option<HeaderKey>,
+ pub thunes: Option<HeaderKey>,
pub stripe_au: Option<HeaderKey>,
pub stripe_uk: Option<HeaderKey>,
pub trustpay: Option<SignatureKey>,
diff --git a/loadtest/config/development.toml b/loadtest/config/development.toml
index 11a404e7c27..f352644ea7f 100644
--- a/loadtest/config/development.toml
+++ b/loadtest/config/development.toml
@@ -148,6 +148,7 @@ stax.base_url = "https://apiprod.fattlabs.com/"
stripe.base_url = "https://api.stripe.com/"
taxjar.base_url = "https://api.sandbox.taxjar.com/v2/"
threedsecureio.base_url = "https://service.sandbox.3dsecure.io"
+thunes.base_url = "https://api.limonetikqualif.com/"
stripe.base_url_file_upload = "https://files.stripe.com/"
trustpay.base_url = "https://test-tpgw.trustpay.eu/"
trustpay.base_url_bank_redirects = "https://aapi.trustpay.eu/"
@@ -230,6 +231,7 @@ cards = [
"stripe",
"taxjar",
"threedsecureio",
+ "thunes",
"trustpay",
"tsys",
"volt",
diff --git a/scripts/add_connector.sh b/scripts/add_connector.sh
index 0dd3b6434c8..fb7252833d5 100755
--- a/scripts/add_connector.sh
+++ b/scripts/add_connector.sh
@@ -6,7 +6,7 @@ function find_prev_connector() {
git checkout $self
cp $self $self.tmp
# Add new connector to existing list and sort it
- connectors=(aci adyen adyenplatform airwallex applepay authorizedotnet bambora bamboraapac bankofamerica billwerk bitpay bluesnap boku braintree cashtocode checkout coinbase cryptopay cybersource datatrans deutschebank dlocal dummyconnector ebanx fiserv fiservemea fiuu forte globalpay globepay gocardless gpayments helcim iatapay itaubank klarna mifinity mollie multisafepay netcetera nexinets nexixpay noon novalnet nuvei opayo opennode paybox payeezy payme payone paypal payu placetopay plaid powertranz prophetpay rapyd razorpay shift4 square stax stripe taxjar threedsecureio trustpay tsys volt wellsfargo wellsfargopayout wise worldline worldpay zsl "$1")
+ connectors=(aci adyen adyenplatform airwallex applepay authorizedotnet bambora bamboraapac bankofamerica billwerk bitpay bluesnap boku braintree cashtocode checkout coinbase cryptopay cybersource datatrans deutschebank dlocal dummyconnector ebanx fiserv fiservemea fiuu forte globalpay globepay gocardless gpayments helcim iatapay itaubank klarna mifinity mollie multisafepay netcetera nexinets nexixpay noon novalnet nuvei opayo opennode paybox payeezy payme payone paypal payu placetopay plaid powertranz prophetpay rapyd razorpay shift4 square stax stripe taxjar threedsecureio thunes trustpay tsys volt wellsfargo wellsfargopayout wise worldline worldpay zsl "$1")
IFS=$'\n' sorted=($(sort <<<"${connectors[*]}")); unset IFS
res=`echo ${sorted[@]}`
sed -i'' -e "s/^ connectors=.*/ connectors=($res \"\$1\")/" $self.tmp
|
2024-09-02T12:11:31Z
|
## Type of Change
<!-- Put an `x` in the boxes that apply -->
- [ ] Bugfix
- [x] New feature
- [ ] Enhancement
- [ ] Refactoring
- [ ] Dependency updates
- [ ] Documentation
- [ ] CI/CD
## Description
Template connector code for Thunes payout
<!-- Describe your changes in detail -->
### Additional Changes
- [ ] This PR modifies the API contract
- [ ] This PR modifies the database schema
- [ ] This PR modifies application configuration/environment variables
<!--
Provide links to the files with corresponding changes.
Following are the paths where you can find config files:
1. `config`
2. `crates/router/src/configs`
3. `loadtest/config`
-->
## Motivation and Context
<!--
Why is this change required? What problem does it solve?
If it fixes an open issue, please link to the issue here.
If you don't have an issue, we'd recommend starting with one first so the PR
can focus on the implementation (unless it is an obvious bug or documentation fix
that will have little conversation).
-->
## How did you test it?
Template PR
<!--
Did you write an integration/unit/API test to verify the code changes?
Or did you test this change manually (provide relevant screenshots)?
-->
## Checklist
<!-- Put an `x` in the boxes that apply -->
- [x] I formatted the code `cargo +nightly fmt --all`
- [x] I addressed lints thrown by `cargo clippy`
- [x] I reviewed the submitted code
- [ ] I added unit tests for my changes where possible
|
aa2f5d147561f6e996228d269e6a54c5d1f53a60
|
|
juspay/hyperswitch
|
juspay__hyperswitch-5753
|
Bug: feat(roles): add support for roles list
- Add support to list all roles for a user. Roles which are equal and below given entity level should be listed
- Add support to list roles at a given entity level for a user.
|
diff --git a/crates/api_models/src/events/user_role.rs b/crates/api_models/src/events/user_role.rs
index f88c318477a..81b38198cfc 100644
--- a/crates/api_models/src/events/user_role.rs
+++ b/crates/api_models/src/events/user_role.rs
@@ -2,8 +2,9 @@ use common_utils::events::{ApiEventMetric, ApiEventsType};
use crate::user_role::{
role::{
- CreateRoleRequest, GetRoleRequest, ListRolesResponse, RoleInfoWithGroupsResponse,
- RoleInfoWithPermissionsResponse, UpdateRoleRequest,
+ CreateRoleRequest, GetRoleRequest, ListRolesAtEntityLevelRequest, ListRolesResponse,
+ RoleInfoResponseNew, RoleInfoWithGroupsResponse, RoleInfoWithPermissionsResponse,
+ UpdateRoleRequest,
},
AcceptInvitationRequest, AuthorizationInfoResponse, DeleteUserRoleRequest,
MerchantSelectRequest, UpdateUserRoleRequest,
@@ -22,6 +23,8 @@ common_utils::impl_api_event_type!(
CreateRoleRequest,
UpdateRoleRequest,
ListRolesResponse,
+ ListRolesAtEntityLevelRequest,
+ RoleInfoResponseNew,
RoleInfoWithGroupsResponse
)
);
diff --git a/crates/api_models/src/user.rs b/crates/api_models/src/user.rs
index abc09c8bbee..a0dadfea217 100644
--- a/crates/api_models/src/user.rs
+++ b/crates/api_models/src/user.rs
@@ -387,15 +387,3 @@ pub struct ListProfilesForUserInOrgAndMerchantAccountResponse {
pub profile_id: id_type::ProfileId,
pub profile_name: String,
}
-
-#[derive(Debug, serde::Serialize)]
-pub struct ListUsersInEntityResponse {
- pub email: pii::Email,
- pub roles: Vec<MinimalRoleInfo>,
-}
-
-#[derive(Debug, serde::Serialize, Clone)]
-pub struct MinimalRoleInfo {
- pub role_id: String,
- pub role_name: String,
-}
diff --git a/crates/api_models/src/user_role.rs b/crates/api_models/src/user_role.rs
index ed6911016b1..4718da28d27 100644
--- a/crates/api_models/src/user_role.rs
+++ b/crates/api_models/src/user_role.rs
@@ -132,3 +132,9 @@ pub struct AcceptInvitationRequest {
pub struct DeleteUserRoleRequest {
pub email: pii::Email,
}
+
+#[derive(Debug, serde::Serialize)]
+pub struct ListUsersInEntityResponse {
+ pub email: pii::Email,
+ pub roles: Vec<role::MinimalRoleInfo>,
+}
diff --git a/crates/api_models/src/user_role/role.rs b/crates/api_models/src/user_role/role.rs
index acbad9152ae..828dfeb20f8 100644
--- a/crates/api_models/src/user_role/role.rs
+++ b/crates/api_models/src/user_role/role.rs
@@ -8,7 +8,6 @@ pub struct CreateRoleRequest {
pub role_name: String,
pub groups: Vec<PermissionGroup>,
pub role_scope: RoleScope,
- pub entity_type: Option<EntityType>,
}
#[derive(Debug, serde::Deserialize, serde::Serialize)]
@@ -36,7 +35,33 @@ pub struct RoleInfoWithGroupsResponse {
pub role_scope: RoleScope,
}
+#[derive(Debug, serde::Serialize)]
+pub struct RoleInfoResponseNew {
+ pub role_id: String,
+ pub role_name: String,
+ pub entity_type: EntityType,
+ pub groups: Vec<PermissionGroup>,
+ pub scope: RoleScope,
+}
+
#[derive(Debug, serde::Deserialize, serde::Serialize)]
pub struct GetRoleRequest {
pub role_id: String,
}
+
+#[derive(Debug, serde::Deserialize, serde::Serialize)]
+pub struct ListRolesAtEntityLevelRequest {
+ pub entity_type: EntityType,
+}
+
+#[derive(Debug, serde::Deserialize, serde::Serialize)]
+pub enum RoleCheckType {
+ Invite,
+ Update,
+}
+
+#[derive(Debug, serde::Serialize, Clone)]
+pub struct MinimalRoleInfo {
+ pub role_id: String,
+ pub role_name: String,
+}
diff --git a/crates/diesel_models/src/query/role.rs b/crates/diesel_models/src/query/role.rs
index 7a0b1f8eb65..0a3c0e6d42f 100644
--- a/crates/diesel_models/src/query/role.rs
+++ b/crates/diesel_models/src/query/role.rs
@@ -1,8 +1,14 @@
+use async_bb8_diesel::AsyncRunQueryDsl;
use common_utils::id_type;
-use diesel::{associations::HasTable, BoolExpressionMethods, ExpressionMethods};
+use diesel::{
+ associations::HasTable, debug_query, pg::Pg, result::Error as DieselError,
+ BoolExpressionMethods, ExpressionMethods, QueryDsl,
+};
+use error_stack::{report, ResultExt};
use crate::{
- enums::RoleScope, query::generics, role::*, schema::roles::dsl, PgPooledConn, StorageResult,
+ enums::RoleScope, errors, query::generics, role::*, schema::roles::dsl, PgPooledConn,
+ StorageResult,
};
impl RoleNew {
@@ -81,4 +87,49 @@ impl Role {
)
.await
}
+
+ pub async fn generic_roles_list_for_org(
+ conn: &PgPooledConn,
+ org_id: id_type::OrganizationId,
+ merchant_id: Option<id_type::MerchantId>,
+ entity_type: Option<common_enums::EntityType>,
+ limit: Option<u32>,
+ ) -> StorageResult<Vec<Self>> {
+ let mut query = <Self as HasTable>::table()
+ .filter(dsl::org_id.eq(org_id))
+ .into_boxed();
+
+ if let Some(merchant_id) = merchant_id {
+ query = query.filter(
+ dsl::merchant_id
+ .eq(merchant_id)
+ .or(dsl::scope.eq(RoleScope::Organization)),
+ );
+ }
+
+ if let Some(entity_type) = entity_type {
+ query = query.filter(dsl::entity_type.eq(entity_type))
+ }
+
+ if let Some(limit) = limit {
+ query = query.limit(limit.into());
+ }
+
+ router_env::logger::debug!(query = %debug_query::<Pg,_>(&query).to_string());
+
+ match generics::db_metrics::track_database_call::<Self, _, _>(
+ query.get_results_async(conn),
+ generics::db_metrics::DatabaseOperation::Filter,
+ )
+ .await
+ {
+ Ok(value) => Ok(value),
+ Err(err) => match err {
+ DieselError::NotFound => {
+ Err(report!(err)).change_context(errors::DatabaseError::NotFound)
+ }
+ _ => Err(report!(err)).change_context(errors::DatabaseError::Others),
+ },
+ }
+ }
}
diff --git a/crates/router/src/core/user_role.rs b/crates/router/src/core/user_role.rs
index 4204e91678d..7752ce06e9a 100644
--- a/crates/router/src/core/user_role.rs
+++ b/crates/router/src/core/user_role.rs
@@ -559,7 +559,7 @@ pub async fn delete_user_role(
pub async fn list_users_in_lineage(
state: SessionState,
user_from_token: auth::UserFromToken,
-) -> UserResponse<Vec<user_api::ListUsersInEntityResponse>> {
+) -> UserResponse<Vec<user_role_api::ListUsersInEntityResponse>> {
let requestor_role_info = roles::RoleInfo::from_role_id(
&state,
&user_from_token.role_id,
@@ -644,7 +644,7 @@ pub async fn list_users_in_lineage(
.map(|role_info| {
(
user_role.role_id.clone(),
- user_api::MinimalRoleInfo {
+ user_role_api::role::MinimalRoleInfo {
role_id: user_role.role_id.clone(),
role_name: role_info.get_role_name().to_string(),
},
@@ -669,7 +669,7 @@ pub async fn list_users_in_lineage(
user_role_map
.into_iter()
.map(|(user_id, role_id_vec)| {
- Ok::<_, error_stack::Report<UserErrors>>(user_api::ListUsersInEntityResponse {
+ Ok::<_, error_stack::Report<UserErrors>>(user_role_api::ListUsersInEntityResponse {
email: email_map
.remove(&user_id)
.ok_or(UserErrors::InternalServerError)?,
diff --git a/crates/router/src/core/user_role/role.rs b/crates/router/src/core/user_role/role.rs
index 7a2c7020512..1a81c49d5a9 100644
--- a/crates/router/src/core/user_role/role.rs
+++ b/crates/router/src/core/user_role/role.rs
@@ -1,5 +1,5 @@
use api_models::user_role::role::{self as role_api};
-use common_enums::RoleScope;
+use common_enums::{EntityType, RoleScope};
use common_utils::generate_id_with_default_len;
use diesel_models::role::{RoleNew, RoleUpdate};
use error_stack::{report, ResultExt};
@@ -64,7 +64,7 @@ pub async fn create_role(
org_id: user_from_token.org_id,
groups: req.groups,
scope: req.role_scope,
- entity_type: req.entity_type,
+ entity_type: Some(EntityType::Merchant),
created_by: user_from_token.user_id.clone(),
last_modified_by: user_from_token.user_id,
created_at: now,
@@ -213,3 +213,148 @@ pub async fn update_role(
},
))
}
+
+pub async fn list_roles_with_info(
+ state: SessionState,
+ user_from_token: UserFromToken,
+) -> UserResponse<Vec<role_api::RoleInfoResponseNew>> {
+ let user_role_info = user_from_token
+ .get_role_info_from_db(&state)
+ .await
+ .attach_printable("Invalid role_id in JWT")?;
+
+ let mut role_info_vec = PREDEFINED_ROLES
+ .iter()
+ .map(|(_, role_info)| role_info.clone())
+ .collect::<Vec<_>>();
+
+ let user_role_entity = user_role_info.get_entity_type();
+ let custom_roles = match user_role_entity {
+ EntityType::Organization => state
+ .store
+ .list_roles_for_org_by_parameters(&user_from_token.org_id, None, None, None)
+ .await
+ .change_context(UserErrors::InternalServerError)
+ .attach_printable("Failed to get roles")?,
+ EntityType::Merchant => state
+ .store
+ .list_roles_for_org_by_parameters(
+ &user_from_token.org_id,
+ Some(&user_from_token.merchant_id),
+ None,
+ None,
+ )
+ .await
+ .change_context(UserErrors::InternalServerError)
+ .attach_printable("Failed to get roles")?,
+ // TODO: Populate this from Db function when support for profile id and profile level custom roles is added
+ EntityType::Profile => Vec::new(),
+ EntityType::Internal => {
+ return Err(UserErrors::InvalidRoleOperationWithMessage(
+ "Internal roles are not allowed for this operation".to_string(),
+ )
+ .into());
+ }
+ };
+
+ role_info_vec.extend(custom_roles.into_iter().map(roles::RoleInfo::from));
+ let list_role_info_response = role_info_vec
+ .into_iter()
+ .filter_map(|role_info| {
+ if user_role_entity >= role_info.get_entity_type() {
+ Some(role_api::RoleInfoResponseNew {
+ role_id: role_info.get_role_id().to_string(),
+ role_name: role_info.get_role_name().to_string(),
+ groups: role_info.get_permission_groups().to_vec(),
+ entity_type: role_info.get_entity_type(),
+ scope: role_info.get_scope(),
+ })
+ } else {
+ None
+ }
+ })
+ .collect::<Vec<_>>();
+
+ Ok(ApplicationResponse::Json(list_role_info_response))
+}
+
+pub async fn list_roles_at_entity_level(
+ state: SessionState,
+ user_from_token: UserFromToken,
+ req: role_api::ListRolesAtEntityLevelRequest,
+ check_type: role_api::RoleCheckType,
+) -> UserResponse<Vec<role_api::MinimalRoleInfo>> {
+ let user_entity_type = user_from_token
+ .get_role_info_from_db(&state)
+ .await
+ .attach_printable("Invalid role_id in JWT")?
+ .get_entity_type();
+
+ if req.entity_type > user_entity_type {
+ return Err(UserErrors::InvalidRoleOperationWithMessage(
+ "User is attempting to request list roles above the current entity level".to_string(),
+ )
+ .into());
+ }
+ let mut role_info_vec = PREDEFINED_ROLES
+ .iter()
+ .map(|(_, role_info)| role_info.clone())
+ .collect::<Vec<_>>();
+
+ let custom_roles = match req.entity_type {
+ EntityType::Organization => state
+ .store
+ .list_roles_for_org_by_parameters(
+ &user_from_token.org_id,
+ None,
+ Some(req.entity_type),
+ None,
+ )
+ .await
+ .change_context(UserErrors::InternalServerError)
+ .attach_printable("Failed to get roles")?,
+
+ EntityType::Merchant => state
+ .store
+ .list_roles_for_org_by_parameters(
+ &user_from_token.org_id,
+ Some(&user_from_token.merchant_id),
+ Some(req.entity_type),
+ None,
+ )
+ .await
+ .change_context(UserErrors::InternalServerError)
+ .attach_printable("Failed to get roles")?,
+ // TODO: Populate this from Db function when support for profile id and profile level custom roles is added
+ EntityType::Profile => Vec::new(),
+
+ EntityType::Internal => {
+ return Err(UserErrors::InvalidRoleOperationWithMessage(
+ "Internal roles are not allowed for this operation".to_string(),
+ )
+ .into());
+ }
+ };
+
+ role_info_vec.extend(custom_roles.into_iter().map(roles::RoleInfo::from));
+
+ let list_minimal_role_info = role_info_vec
+ .into_iter()
+ .filter_map(|role_info| {
+ let check_type = match check_type {
+ role_api::RoleCheckType::Invite => role_info.is_invitable(),
+ role_api::RoleCheckType::Update => role_info.is_updatable(),
+ };
+ if check_type && role_info.get_entity_type() == req.entity_type {
+ Some(role_api::MinimalRoleInfo {
+ role_id: role_info.get_role_id().to_string(),
+ role_name: role_info.get_role_name().to_string(),
+ })
+ } else {
+ None
+ }
+ })
+ .collect::<Vec<_>>();
+
+ Ok(ApplicationResponse::Json(list_minimal_role_info))
+}
diff --git a/crates/router/src/db/kafka_store.rs b/crates/router/src/db/kafka_store.rs
index 316e8106c9d..fd8f387f001 100644
--- a/crates/router/src/db/kafka_store.rs
+++ b/crates/router/src/db/kafka_store.rs
@@ -3272,6 +3272,18 @@ impl RoleInterface for KafkaStore {
) -> CustomResult<Vec<storage::Role>, errors::StorageError> {
self.diesel_store.list_all_roles(merchant_id, org_id).await
}
+
+ async fn list_roles_for_org_by_parameters(
+ &self,
+ org_id: &id_type::OrganizationId,
+ merchant_id: Option<&id_type::MerchantId>,
+ entity_type: Option<enums::EntityType>,
+ limit: Option<u32>,
+ ) -> CustomResult<Vec<storage::Role>, errors::StorageError> {
+ self.diesel_store
+ .list_roles_for_org_by_parameters(org_id, merchant_id, entity_type, limit)
+ .await
+ }
}
#[async_trait::async_trait]
diff --git a/crates/router/src/db/role.rs b/crates/router/src/db/role.rs
index 5802142b166..ddcb24dc254 100644
--- a/crates/router/src/db/role.rs
+++ b/crates/router/src/db/role.rs
@@ -46,6 +46,14 @@ pub trait RoleInterface {
merchant_id: &id_type::MerchantId,
org_id: &id_type::OrganizationId,
) -> CustomResult<Vec<storage::Role>, errors::StorageError>;
+
+ async fn list_roles_for_org_by_parameters(
+ &self,
+ org_id: &id_type::OrganizationId,
+ merchant_id: Option<&id_type::MerchantId>,
+ entity_type: Option<enums::EntityType>,
+ limit: Option<u32>,
+ ) -> CustomResult<Vec<storage::Role>, errors::StorageError>;
}
#[async_trait::async_trait]
@@ -119,6 +127,26 @@ impl RoleInterface for Store {
.await
.map_err(|error| report!(errors::StorageError::from(error)))
}
+
+ #[instrument(skip_all)]
+ async fn list_roles_for_org_by_parameters(
+ &self,
+ org_id: &id_type::OrganizationId,
+ merchant_id: Option<&id_type::MerchantId>,
+ entity_type: Option<enums::EntityType>,
+ limit: Option<u32>,
+ ) -> CustomResult<Vec<storage::Role>, errors::StorageError> {
+ let conn = connection::pg_connection_write(self).await?;
+ storage::Role::generic_roles_list_for_org(
+ &conn,
+ org_id.to_owned(),
+ merchant_id.cloned(),
+ entity_type,
+ limit,
+ )
+ .await
+ .map_err(|error| report!(errors::StorageError::from(error)))
+ }
}
#[async_trait::async_trait]
@@ -271,4 +299,31 @@ impl RoleInterface for MockDb {
Ok(roles_list)
}
+
+ #[instrument(skip_all)]
+ async fn list_roles_for_org_by_parameters(
+ &self,
+ org_id: &id_type::OrganizationId,
+ merchant_id: Option<&id_type::MerchantId>,
+ entity_type: Option<enums::EntityType>,
+ limit: Option<u32>,
+ ) -> CustomResult<Vec<storage::Role>, errors::StorageError> {
+ let roles = self.roles.lock().await;
+ let limit_usize = limit.unwrap_or(u32::MAX).try_into().unwrap_or(usize::MAX);
+ let roles_list: Vec<_> = roles
+ .iter()
+ .filter(|role| {
+ let matches_merchant = match merchant_id {
+ Some(merchant_id) => role.merchant_id == *merchant_id,
+ None => true,
+ };
+
+ matches_merchant && role.org_id == *org_id && role.entity_type == entity_type
+ })
+ .take(limit_usize)
+ .cloned()
+ .collect();
+
+ Ok(roles_list)
+ }
}
diff --git a/crates/router/src/routes/app.rs b/crates/router/src/routes/app.rs
index 42f46e39d2e..9b35e3ca475 100644
--- a/crates/router/src/routes/app.rs
+++ b/crates/router/src/routes/app.rs
@@ -1842,7 +1842,19 @@ impl User {
.route(web::get().to(get_role_from_token))
.route(web::post().to(create_role)),
)
- .service(web::resource("/list").route(web::get().to(list_all_roles)))
+ .service(web::resource("/v2/list").route(web::get().to(list_roles_with_info)))
+ .service(
+ web::scope("/list")
+ .service(web::resource("").route(web::get().to(list_all_roles)))
+ .service(
+ web::resource("/invite")
+ .route(web::get().to(list_invitable_roles_at_entity_level)),
+ )
+ .service(
+ web::resource("/update")
+ .route(web::get().to(list_updatable_roles_at_entity_level)),
+ ),
+ )
.service(
web::resource("/{role_id}")
.route(web::get().to(get_role))
diff --git a/crates/router/src/routes/lock_utils.rs b/crates/router/src/routes/lock_utils.rs
index f2a1d7e3458..8f61d78c4a1 100644
--- a/crates/router/src/routes/lock_utils.rs
+++ b/crates/router/src/routes/lock_utils.rs
@@ -253,6 +253,9 @@ impl From<Flow> for ApiIdentifier {
| Flow::AuthSelect => Self::User,
Flow::ListRoles
+ | Flow::ListRolesV2
+ | Flow::ListInvitableRolesAtEntityLevel
+ | Flow::ListUpdatableRolesAtEntityLevel
| Flow::GetRole
| Flow::GetRoleFromToken
| Flow::UpdateUserRole
diff --git a/crates/router/src/routes/user_role.rs b/crates/router/src/routes/user_role.rs
index 5f1e4301d45..539409ab75f 100644
--- a/crates/router/src/routes/user_role.rs
+++ b/crates/router/src/routes/user_role.rs
@@ -243,3 +243,70 @@ pub async fn list_users_in_lineage(state: web::Data<AppState>, req: HttpRequest)
))
.await
}
+
+pub async fn list_roles_with_info(state: web::Data<AppState>, req: HttpRequest) -> HttpResponse {
+ let flow = Flow::ListRolesV2;
+
+ Box::pin(api::server_wrap(
+ flow,
+ state.clone(),
+ &req,
+ (),
+ |state, user_from_token, _, _| role_core::list_roles_with_info(state, user_from_token),
+ &auth::JWTAuth(Permission::UsersRead),
+ 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::UsersRead),
+ 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::UsersRead),
+ api_locking::LockAction::NotApplicable,
+ ))
+ .await
+}
diff --git a/crates/router_env/src/logger/types.rs b/crates/router_env/src/logger/types.rs
index 538ae888cd5..51bb4b64730 100644
--- a/crates/router_env/src/logger/types.rs
+++ b/crates/router_env/src/logger/types.rs
@@ -366,6 +366,12 @@ pub enum Flow {
GetRolesInfo,
/// List roles
ListRoles,
+ /// List roles v2
+ ListRolesV2,
+ /// List invitable roles at entity level
+ ListInvitableRolesAtEntityLevel,
+ /// List updatable roles at entity level
+ ListUpdatableRolesAtEntityLevel,
/// Get role
GetRole,
/// Get role from token
|
2024-08-30T11:27:23Z
|
## Type of Change
<!-- Put an `x` in the boxes that apply -->
- [ ] Bugfix
- [x] New feature
- [ ] Enhancement
- [ ] Refactoring
- [ ] Dependency updates
- [ ] Documentation
- [ ] CI/CD
## Description
Add support to
- List available roles with info for the user
- List roles at entity level for the user
### Additional Changes
- [ ] This PR modifies the API contract
- [ ] This PR modifies the database schema
- [ ] This PR modifies application configuration/environment variables
<!--
Provide links to the files with corresponding changes.
Following are the paths where you can find config files:
1. `config`
2. `crates/router/src/configs`
3. `loadtest/config`
-->
## Motivation and Context
Closes #5753
## How did you test it?
To List roles available roles in hierarchy with info:
```
curl --location 'http://localhost:8080/user/role/v2/list' \
--header 'Authorization: Bearer JWT'
```
Response
```
[
{
"role_id": "merchant_operator",
"role_name": "operator",
"entity_type": "merchant",
"groups": [
"operations_view",
"operations_manage",
"connectors_view",
"workflows_view",
"analytics_view",
"users_view",
"merchant_details_view"
],
"scope": "organization"
},
{
"role_id": "merchant_developer",
"role_name": "developer",
"entity_type": "merchant",
"groups": [
"operations_view",
"connectors_view",
"analytics_view",
"users_view",
"merchant_details_view",
"merchant_details_manage"
],
"scope": "organization"
},
{
"role_id": "merchant_iam_admin",
"role_name": "iam",
"entity_type": "merchant",
"groups": [
"operations_view",
"analytics_view",
"users_view",
"users_manage",
"merchant_details_view"
],
"scope": "organization"
},
{
"role_id": "merchant_view_only",
"role_name": "view_only",
"entity_type": "merchant",
"groups": [
"operations_view",
"connectors_view",
"workflows_view",
"analytics_view",
"users_view",
"merchant_details_view"
],
"scope": "organization"
},
{
"role_id": "merchant_customer_support",
"role_name": "customer_support",
"entity_type": "merchant",
"groups": [
"operations_view",
"analytics_view",
"users_view",
"merchant_details_view"
],
"scope": "organization"
},
{
"role_id": "merchant_admin",
"role_name": "admin",
"entity_type": "merchant",
"groups": [
"operations_view",
"operations_manage",
"connectors_view",
"connectors_manage",
"workflows_view",
"workflows_manage",
"analytics_view",
"users_view",
"users_manage",
"merchant_details_view",
"merchant_details_manage"
],
"scope": "organization"
},
{
"role_id": "org_admin",
"role_name": "organization_admin",
"entity_type": "organization",
"groups": [
"operations_view",
"operations_manage",
"connectors_view",
"connectors_manage",
"workflows_view",
"workflows_manage",
"analytics_view",
"users_view",
"users_manage",
"merchant_details_view",
"merchant_details_manage",
"organization_manage"
],
"scope": "organization"
}
]
```
To list roles at entity level for invite:
```
curl --location 'http://localhost:8080/user/role/list/invite?entity_type=merchant' \
--header 'Authorization: Bearer JWT'
```
Entity type can be `organization`, `merchant` or `profile`
Response:
```
[
{
"role_id": "merchant_customer_support",
"role_name": "customer_support"
},
{
"role_id": "merchant_admin",
"role_name": "admin"
},
{
"role_id": "merchant_view_only",
"role_name": "view_only"
},
{
"role_id": "merchant_developer",
"role_name": "developer"
},
{
"role_id": "merchant_iam_admin",
"role_name": "iam"
},
{
"role_id": "merchant_operator",
"role_name": "operator"
}
]
```
To list all roles at entity level for update
```
curl --location 'http://localhost:8080/user/role/list/update?entity_type=merchant' \
--header 'Authorization: Bearer JWT'
```
Response:
```
[
{
"role_id": "merchant_customer_support",
"role_name": "customer_support"
},
{
"role_id": "merchant_admin",
"role_name": "admin"
},
{
"role_id": "merchant_view_only",
"role_name": "view_only"
},
{
"role_id": "merchant_developer",
"role_name": "developer"
},
{
"role_id": "merchant_iam_admin",
"role_name": "iam"
},
{
"role_id": "merchant_operator",
"role_name": "operator"
}
]
```
## Checklist
<!-- Put an `x` in the boxes that apply -->
- [x] I formatted the code `cargo +nightly fmt --all`
- [x] I addressed lints thrown by `cargo clippy`
- [x] I reviewed the submitted code
- [ ] I added unit tests for my changes where possible
|
6b410505da3a2dbceaf6f07bb3f19f3ceef4efe2
|
|
juspay/hyperswitch
|
juspay__hyperswitch-5759
|
Bug: [FEATURE] [GLOBEPAY|POWERTRANZ|TSYS|WORLDLINE] Move connector code to crate hyperswitch_connectors
### Feature Description
Connector code for `globepay, powertranz, tsys, worldline` needs to be moved from crate `router` to new crate `hyperswitch_connectors`
### Possible Implementation
Connector code for `globepay, powertranz, tsys, worldline` needs to be moved from crate `router` to new crate `hyperswitch_connectors`
### Have you spent some time checking if this feature request has been raised before?
- [X] I checked and didn't find a similar issue
### Have you read the Contributing Guidelines?
- [X] I have read the [Contributing Guidelines](https://github.com/juspay/hyperswitch/blob/main/docs/CONTRIBUTING.md)
### Are you willing to submit a PR?
Yes, I am willing to submit a PR!
|
diff --git a/Cargo.lock b/Cargo.lock
index 4a37b597d30..30eb871a67f 100644
--- a/Cargo.lock
+++ b/Cargo.lock
@@ -3876,6 +3876,8 @@ dependencies = [
name = "hyperswitch_connectors"
version = "0.1.0"
dependencies = [
+ "actix-http",
+ "actix-web",
"api_models",
"async-trait",
"base64 0.22.0",
@@ -3883,9 +3885,14 @@ dependencies = [
"common_enums",
"common_utils",
"error-stack",
+ "hex",
+ "http 0.2.12",
"hyperswitch_domain_models",
"hyperswitch_interfaces",
"masking",
+ "once_cell",
+ "rand",
+ "regex",
"ring 0.17.8",
"router_env",
"serde",
diff --git a/crates/hyperswitch_connectors/Cargo.toml b/crates/hyperswitch_connectors/Cargo.toml
index 5fb0bd0cc28..2009f60e2e1 100644
--- a/crates/hyperswitch_connectors/Cargo.toml
+++ b/crates/hyperswitch_connectors/Cargo.toml
@@ -10,9 +10,16 @@ frm = ["hyperswitch_domain_models/frm", "hyperswitch_interfaces/frm"]
payouts = ["hyperswitch_domain_models/payouts", "api_models/payouts", "hyperswitch_interfaces/payouts"]
[dependencies]
+actix-http = "3.6.0"
+actix-web = "4.5.1"
async-trait = "0.1.79"
base64 = "0.22.0"
error-stack = "0.4.1"
+hex = "0.4.3"
+http = "0.2.12"
+once_cell = "1.19.0"
+rand = "0.8.5"
+regex = "1.10.4"
ring = "0.17.8"
serde = { version = "1.0.197", features = ["derive"] }
serde_json = "1.0.115"
diff --git a/crates/hyperswitch_connectors/src/connectors.rs b/crates/hyperswitch_connectors/src/connectors.rs
index 8cb44c4546a..88715a36e8a 100644
--- a/crates/hyperswitch_connectors/src/connectors.rs
+++ b/crates/hyperswitch_connectors/src/connectors.rs
@@ -3,13 +3,18 @@ pub mod bitpay;
pub mod fiserv;
pub mod fiservemea;
pub mod fiuu;
+pub mod globepay;
pub mod helcim;
pub mod nexixpay;
pub mod novalnet;
+pub mod powertranz;
pub mod stax;
pub mod taxjar;
+pub mod tsys;
+pub mod worldline;
pub use self::{
bambora::Bambora, bitpay::Bitpay, fiserv::Fiserv, fiservemea::Fiservemea, fiuu::Fiuu,
- helcim::Helcim, nexixpay::Nexixpay, novalnet::Novalnet, stax::Stax, taxjar::Taxjar,
+ globepay::Globepay, helcim::Helcim, nexixpay::Nexixpay, novalnet::Novalnet,
+ powertranz::Powertranz, stax::Stax, taxjar::Taxjar, tsys::Tsys, worldline::Worldline,
};
diff --git a/crates/router/src/connector/globepay.rs b/crates/hyperswitch_connectors/src/connectors/globepay.rs
similarity index 65%
rename from crates/router/src/connector/globepay.rs
rename to crates/hyperswitch_connectors/src/connectors/globepay.rs
index ce9755ddb73..8faf4190e93 100644
--- a/crates/router/src/connector/globepay.rs
+++ b/crates/hyperswitch_connectors/src/connectors/globepay.rs
@@ -2,32 +2,46 @@ pub mod transformers;
use common_utils::{
crypto::{self, GenerateDigest},
- request::RequestContent,
+ errors::CustomResult,
+ ext_traits::BytesExt,
+ request::{Method, Request, RequestBuilder, RequestContent},
types::{AmountConvertor, MinorUnit, MinorUnitForConnector},
};
-use diesel_models::enums;
use error_stack::{report, ResultExt};
use hex::encode;
+use hyperswitch_domain_models::{
+ router_data::{AccessToken, ConnectorAuthType, ErrorResponse, RouterData},
+ router_flow_types::{
+ access_token_auth::AccessTokenAuth,
+ payments::{Authorize, Capture, PSync, PaymentMethodToken, Session, SetupMandate, Void},
+ refunds::{Execute, RSync},
+ },
+ router_request_types::{
+ AccessTokenRequestData, PaymentMethodTokenizationData, PaymentsAuthorizeData,
+ PaymentsCancelData, PaymentsCaptureData, PaymentsSessionData, PaymentsSyncData,
+ RefundsData, SetupMandateRequestData,
+ },
+ router_response_types::{PaymentsResponseData, RefundsResponseData},
+ types::{
+ PaymentsAuthorizeRouterData, PaymentsCaptureRouterData, PaymentsSyncRouterData,
+ RefundSyncRouterData, RefundsRouterData,
+ },
+};
+use hyperswitch_interfaces::{
+ api::{self, ConnectorCommon, ConnectorCommonExt, ConnectorIntegration, ConnectorValidation},
+ configs::Connectors,
+ consts, errors,
+ events::connector_api_logs::ConnectorEvent,
+ types::{PaymentsAuthorizeType, PaymentsSyncType, RefundExecuteType, RefundSyncType, Response},
+ webhooks,
+};
use masking::ExposeInterface;
use rand::distributions::DistString;
use time::OffsetDateTime;
use transformers as globepay;
-use crate::{
- configs::settings,
- connector::utils::convert_amount,
- consts,
- core::errors::{self, CustomResult},
- events::connector_api_logs::ConnectorEvent,
- headers,
- services::{self, request, ConnectorIntegration, ConnectorValidation},
- types::{
- self,
- api::{self, ConnectorCommon, ConnectorCommonExt},
- ErrorResponse, Response,
- },
- utils::BytesExt,
-};
+use crate::{constants::headers, types::ResponseRouterData, utils::convert_amount};
+
#[derive(Clone)]
pub struct Globepay {
amount_converter: &'static (dyn AmountConvertor<Output = MinorUnit> + Sync),
@@ -54,12 +68,8 @@ impl api::RefundExecute for Globepay {}
impl api::RefundSync for Globepay {}
impl api::PaymentToken for Globepay {}
-impl
- ConnectorIntegration<
- api::PaymentMethodToken,
- types::PaymentMethodTokenizationData,
- types::PaymentsResponseData,
- > for Globepay
+impl ConnectorIntegration<PaymentMethodToken, PaymentMethodTokenizationData, PaymentsResponseData>
+ for Globepay
{
// Not Implemented (R)
}
@@ -70,9 +80,9 @@ where
{
fn build_headers(
&self,
- _req: &types::RouterData<Flow, Request, Response>,
- _connectors: &settings::Connectors,
- ) -> CustomResult<Vec<(String, request::Maskable<String>)>, errors::ConnectorError> {
+ _req: &RouterData<Flow, Request, Response>,
+ _connectors: &Connectors,
+ ) -> CustomResult<Vec<(String, masking::Maskable<String>)>, errors::ConnectorError> {
let header = vec![(
headers::CONTENT_TYPE.to_string(),
self.get_content_type().to_string().into(),
@@ -82,7 +92,7 @@ where
}
fn get_globlepay_query_params(
- connector_auth_type: &types::ConnectorAuthType,
+ connector_auth_type: &ConnectorAuthType,
) -> CustomResult<String, errors::ConnectorError> {
let auth_type = globepay::GlobepayAuthType::try_from(connector_auth_type)?;
let time = (OffsetDateTime::now_utc().unix_timestamp_nanos() / 1_000_000).to_string();
@@ -102,7 +112,7 @@ fn get_globlepay_query_params(
}
fn get_partner_code(
- connector_auth_type: &types::ConnectorAuthType,
+ connector_auth_type: &ConnectorAuthType,
) -> CustomResult<String, errors::ConnectorError> {
let auth_type = globepay::GlobepayAuthType::try_from(connector_auth_type)?;
Ok(auth_type.partner_code.expose())
@@ -117,7 +127,7 @@ impl ConnectorCommon for Globepay {
"application/json"
}
- fn base_url<'a>(&self, connectors: &'a settings::Connectors) -> &'a str {
+ fn base_url<'a>(&self, connectors: &'a Connectors) -> &'a str {
connectors.globepay.base_url.as_ref()
}
@@ -147,32 +157,18 @@ impl ConnectorCommon for Globepay {
impl ConnectorValidation for Globepay {}
-impl ConnectorIntegration<api::Session, types::PaymentsSessionData, types::PaymentsResponseData>
- for Globepay
-{
-}
+impl ConnectorIntegration<Session, PaymentsSessionData, PaymentsResponseData> for Globepay {}
-impl ConnectorIntegration<api::AccessTokenAuth, types::AccessTokenRequestData, types::AccessToken>
- for Globepay
-{
-}
+impl ConnectorIntegration<AccessTokenAuth, AccessTokenRequestData, AccessToken> for Globepay {}
-impl
- ConnectorIntegration<
- api::SetupMandate,
- types::SetupMandateRequestData,
- types::PaymentsResponseData,
- > for Globepay
+impl ConnectorIntegration<SetupMandate, SetupMandateRequestData, PaymentsResponseData>
+ for Globepay
{
fn build_request(
&self,
- _req: &types::RouterData<
- api::SetupMandate,
- types::SetupMandateRequestData,
- types::PaymentsResponseData,
- >,
- _connectors: &settings::Connectors,
- ) -> CustomResult<Option<services::Request>, errors::ConnectorError> {
+ _req: &RouterData<SetupMandate, SetupMandateRequestData, PaymentsResponseData>,
+ _connectors: &Connectors,
+ ) -> CustomResult<Option<Request>, errors::ConnectorError> {
Err(
errors::ConnectorError::NotImplemented("Setup Mandate flow for Globepay".to_string())
.into(),
@@ -180,14 +176,12 @@ impl
}
}
-impl ConnectorIntegration<api::Authorize, types::PaymentsAuthorizeData, types::PaymentsResponseData>
- for Globepay
-{
+impl ConnectorIntegration<Authorize, PaymentsAuthorizeData, PaymentsResponseData> for Globepay {
fn get_headers(
&self,
- req: &types::PaymentsAuthorizeRouterData,
- connectors: &settings::Connectors,
- ) -> CustomResult<Vec<(String, request::Maskable<String>)>, errors::ConnectorError> {
+ req: &PaymentsAuthorizeRouterData,
+ connectors: &Connectors,
+ ) -> CustomResult<Vec<(String, masking::Maskable<String>)>, errors::ConnectorError> {
self.build_headers(req, connectors)
}
@@ -197,11 +191,11 @@ impl ConnectorIntegration<api::Authorize, types::PaymentsAuthorizeData, types::P
fn get_url(
&self,
- req: &types::PaymentsAuthorizeRouterData,
- connectors: &settings::Connectors,
+ req: &PaymentsAuthorizeRouterData,
+ connectors: &Connectors,
) -> CustomResult<String, errors::ConnectorError> {
let query_params = get_globlepay_query_params(&req.connector_auth_type)?;
- if req.request.capture_method == Some(enums::CaptureMethod::Automatic) {
+ if req.request.capture_method == Some(common_enums::enums::CaptureMethod::Automatic) {
Ok(format!(
"{}api/v1.0/gateway/partners/{}/orders/{}{query_params}",
self.base_url(connectors),
@@ -219,8 +213,8 @@ impl ConnectorIntegration<api::Authorize, types::PaymentsAuthorizeData, types::P
fn get_request_body(
&self,
- req: &types::PaymentsAuthorizeRouterData,
- _connectors: &settings::Connectors,
+ req: &PaymentsAuthorizeRouterData,
+ _connectors: &Connectors,
) -> CustomResult<RequestContent, errors::ConnectorError> {
let amount = convert_amount(
self.amount_converter,
@@ -235,20 +229,16 @@ impl ConnectorIntegration<api::Authorize, types::PaymentsAuthorizeData, types::P
fn build_request(
&self,
- req: &types::PaymentsAuthorizeRouterData,
- connectors: &settings::Connectors,
- ) -> CustomResult<Option<services::Request>, errors::ConnectorError> {
+ req: &PaymentsAuthorizeRouterData,
+ connectors: &Connectors,
+ ) -> CustomResult<Option<Request>, errors::ConnectorError> {
Ok(Some(
- services::RequestBuilder::new()
- .method(services::Method::Put)
- .url(&types::PaymentsAuthorizeType::get_url(
- self, req, connectors,
- )?)
+ RequestBuilder::new()
+ .method(Method::Put)
+ .url(&PaymentsAuthorizeType::get_url(self, req, connectors)?)
.attach_default_headers()
- .headers(types::PaymentsAuthorizeType::get_headers(
- self, req, connectors,
- )?)
- .set_body(types::PaymentsAuthorizeType::get_request_body(
+ .headers(PaymentsAuthorizeType::get_headers(self, req, connectors)?)
+ .set_body(PaymentsAuthorizeType::get_request_body(
self, req, connectors,
)?)
.build(),
@@ -257,10 +247,10 @@ impl ConnectorIntegration<api::Authorize, types::PaymentsAuthorizeData, types::P
fn handle_response(
&self,
- data: &types::PaymentsAuthorizeRouterData,
+ data: &PaymentsAuthorizeRouterData,
event_builder: Option<&mut ConnectorEvent>,
res: Response,
- ) -> CustomResult<types::PaymentsAuthorizeRouterData, errors::ConnectorError> {
+ ) -> CustomResult<PaymentsAuthorizeRouterData, errors::ConnectorError> {
let response: globepay::GlobepayPaymentsResponse = res
.response
.parse_struct("Globepay PaymentsAuthorizeResponse")
@@ -269,7 +259,7 @@ impl ConnectorIntegration<api::Authorize, types::PaymentsAuthorizeData, types::P
event_builder.map(|i| i.set_response_body(&response));
router_env::logger::info!(connector_response=?response);
- types::RouterData::try_from(types::ResponseRouterData {
+ RouterData::try_from(ResponseRouterData {
response,
data: data.clone(),
http_code: res.status_code,
@@ -285,14 +275,12 @@ impl ConnectorIntegration<api::Authorize, types::PaymentsAuthorizeData, types::P
}
}
-impl ConnectorIntegration<api::PSync, types::PaymentsSyncData, types::PaymentsResponseData>
- for Globepay
-{
+impl ConnectorIntegration<PSync, PaymentsSyncData, PaymentsResponseData> for Globepay {
fn get_headers(
&self,
- req: &types::PaymentsSyncRouterData,
- connectors: &settings::Connectors,
- ) -> CustomResult<Vec<(String, request::Maskable<String>)>, errors::ConnectorError> {
+ req: &PaymentsSyncRouterData,
+ connectors: &Connectors,
+ ) -> CustomResult<Vec<(String, masking::Maskable<String>)>, errors::ConnectorError> {
self.build_headers(req, connectors)
}
@@ -302,8 +290,8 @@ impl ConnectorIntegration<api::PSync, types::PaymentsSyncData, types::PaymentsRe
fn get_url(
&self,
- req: &types::PaymentsSyncRouterData,
- connectors: &settings::Connectors,
+ req: &PaymentsSyncRouterData,
+ connectors: &Connectors,
) -> CustomResult<String, errors::ConnectorError> {
let query_params = get_globlepay_query_params(&req.connector_auth_type)?;
Ok(format!(
@@ -316,25 +304,25 @@ impl ConnectorIntegration<api::PSync, types::PaymentsSyncData, types::PaymentsRe
fn build_request(
&self,
- req: &types::PaymentsSyncRouterData,
- connectors: &settings::Connectors,
- ) -> CustomResult<Option<services::Request>, errors::ConnectorError> {
+ req: &PaymentsSyncRouterData,
+ connectors: &Connectors,
+ ) -> CustomResult<Option<Request>, errors::ConnectorError> {
Ok(Some(
- services::RequestBuilder::new()
- .method(services::Method::Get)
- .url(&types::PaymentsSyncType::get_url(self, req, connectors)?)
+ RequestBuilder::new()
+ .method(Method::Get)
+ .url(&PaymentsSyncType::get_url(self, req, connectors)?)
.attach_default_headers()
- .headers(types::PaymentsSyncType::get_headers(self, req, connectors)?)
+ .headers(PaymentsSyncType::get_headers(self, req, connectors)?)
.build(),
))
}
fn handle_response(
&self,
- data: &types::PaymentsSyncRouterData,
+ data: &PaymentsSyncRouterData,
event_builder: Option<&mut ConnectorEvent>,
res: Response,
- ) -> CustomResult<types::PaymentsSyncRouterData, errors::ConnectorError> {
+ ) -> CustomResult<PaymentsSyncRouterData, errors::ConnectorError> {
let response: globepay::GlobepaySyncResponse = res
.response
.parse_struct("globepay PaymentsSyncResponse")
@@ -343,7 +331,7 @@ impl ConnectorIntegration<api::PSync, types::PaymentsSyncData, types::PaymentsRe
event_builder.map(|i| i.set_response_body(&response));
router_env::logger::info!(connector_response=?response);
- types::RouterData::try_from(types::ResponseRouterData {
+ RouterData::try_from(ResponseRouterData {
response,
data: data.clone(),
http_code: res.status_code,
@@ -359,14 +347,12 @@ impl ConnectorIntegration<api::PSync, types::PaymentsSyncData, types::PaymentsRe
}
}
-impl ConnectorIntegration<api::Capture, types::PaymentsCaptureData, types::PaymentsResponseData>
- for Globepay
-{
+impl ConnectorIntegration<Capture, PaymentsCaptureData, PaymentsResponseData> for Globepay {
fn build_request(
&self,
- _req: &types::PaymentsCaptureRouterData,
- _connectors: &settings::Connectors,
- ) -> CustomResult<Option<services::Request>, errors::ConnectorError> {
+ _req: &PaymentsCaptureRouterData,
+ _connectors: &Connectors,
+ ) -> CustomResult<Option<Request>, errors::ConnectorError> {
Err(errors::ConnectorError::FlowNotSupported {
flow: "Manual Capture".to_owned(),
connector: "Globepay".to_owned(),
@@ -375,19 +361,14 @@ impl ConnectorIntegration<api::Capture, types::PaymentsCaptureData, types::Payme
}
}
-impl ConnectorIntegration<api::Void, types::PaymentsCancelData, types::PaymentsResponseData>
- for Globepay
-{
-}
+impl ConnectorIntegration<Void, PaymentsCancelData, PaymentsResponseData> for Globepay {}
-impl ConnectorIntegration<api::Execute, types::RefundsData, types::RefundsResponseData>
- for Globepay
-{
+impl ConnectorIntegration<Execute, RefundsData, RefundsResponseData> for Globepay {
fn get_headers(
&self,
- req: &types::RefundsRouterData<api::Execute>,
- connectors: &settings::Connectors,
- ) -> CustomResult<Vec<(String, request::Maskable<String>)>, errors::ConnectorError> {
+ req: &RefundsRouterData<Execute>,
+ connectors: &Connectors,
+ ) -> CustomResult<Vec<(String, masking::Maskable<String>)>, errors::ConnectorError> {
self.build_headers(req, connectors)
}
@@ -397,8 +378,8 @@ impl ConnectorIntegration<api::Execute, types::RefundsData, types::RefundsRespon
fn get_url(
&self,
- req: &types::RefundsRouterData<api::Execute>,
- connectors: &settings::Connectors,
+ req: &RefundsRouterData<Execute>,
+ connectors: &Connectors,
) -> CustomResult<String, errors::ConnectorError> {
let query_params = get_globlepay_query_params(&req.connector_auth_type)?;
Ok(format!(
@@ -412,8 +393,8 @@ impl ConnectorIntegration<api::Execute, types::RefundsData, types::RefundsRespon
fn get_request_body(
&self,
- req: &types::RefundsRouterData<api::Execute>,
- _connectors: &settings::Connectors,
+ req: &RefundsRouterData<Execute>,
+ _connectors: &Connectors,
) -> CustomResult<RequestContent, errors::ConnectorError> {
let refund_amount = convert_amount(
self.amount_converter,
@@ -428,30 +409,26 @@ impl ConnectorIntegration<api::Execute, types::RefundsData, types::RefundsRespon
fn build_request(
&self,
- req: &types::RefundsRouterData<api::Execute>,
- connectors: &settings::Connectors,
- ) -> CustomResult<Option<services::Request>, errors::ConnectorError> {
+ req: &RefundsRouterData<Execute>,
+ connectors: &Connectors,
+ ) -> CustomResult<Option<Request>, errors::ConnectorError> {
Ok(Some(
- services::RequestBuilder::new()
- .method(services::Method::Put)
- .url(&types::RefundExecuteType::get_url(self, req, connectors)?)
+ RequestBuilder::new()
+ .method(Method::Put)
+ .url(&RefundExecuteType::get_url(self, req, connectors)?)
.attach_default_headers()
- .headers(types::RefundExecuteType::get_headers(
- self, req, connectors,
- )?)
- .set_body(types::RefundExecuteType::get_request_body(
- self, req, connectors,
- )?)
+ .headers(RefundExecuteType::get_headers(self, req, connectors)?)
+ .set_body(RefundExecuteType::get_request_body(self, req, connectors)?)
.build(),
))
}
fn handle_response(
&self,
- data: &types::RefundsRouterData<api::Execute>,
+ data: &RefundsRouterData<Execute>,
event_builder: Option<&mut ConnectorEvent>,
res: Response,
- ) -> CustomResult<types::RefundsRouterData<api::Execute>, errors::ConnectorError> {
+ ) -> CustomResult<RefundsRouterData<Execute>, errors::ConnectorError> {
let response: globepay::GlobepayRefundResponse = res
.response
.parse_struct("Globalpay RefundResponse")
@@ -460,7 +437,7 @@ impl ConnectorIntegration<api::Execute, types::RefundsData, types::RefundsRespon
event_builder.map(|i| i.set_response_body(&response));
router_env::logger::info!(connector_response=?response);
- types::RouterData::try_from(types::ResponseRouterData {
+ RouterData::try_from(ResponseRouterData {
response,
data: data.clone(),
http_code: res.status_code,
@@ -476,12 +453,12 @@ impl ConnectorIntegration<api::Execute, types::RefundsData, types::RefundsRespon
}
}
-impl ConnectorIntegration<api::RSync, types::RefundsData, types::RefundsResponseData> for Globepay {
+impl ConnectorIntegration<RSync, RefundsData, RefundsResponseData> for Globepay {
fn get_headers(
&self,
- req: &types::RefundSyncRouterData,
- connectors: &settings::Connectors,
- ) -> CustomResult<Vec<(String, request::Maskable<String>)>, errors::ConnectorError> {
+ req: &RefundSyncRouterData,
+ connectors: &Connectors,
+ ) -> CustomResult<Vec<(String, masking::Maskable<String>)>, errors::ConnectorError> {
self.build_headers(req, connectors)
}
@@ -491,8 +468,8 @@ impl ConnectorIntegration<api::RSync, types::RefundsData, types::RefundsResponse
fn get_url(
&self,
- req: &types::RefundSyncRouterData,
- connectors: &settings::Connectors,
+ req: &RefundSyncRouterData,
+ connectors: &Connectors,
) -> CustomResult<String, errors::ConnectorError> {
let query_params = get_globlepay_query_params(&req.connector_auth_type)?;
Ok(format!(
@@ -506,25 +483,25 @@ impl ConnectorIntegration<api::RSync, types::RefundsData, types::RefundsResponse
fn build_request(
&self,
- req: &types::RefundSyncRouterData,
- connectors: &settings::Connectors,
- ) -> CustomResult<Option<services::Request>, errors::ConnectorError> {
+ req: &RefundSyncRouterData,
+ connectors: &Connectors,
+ ) -> CustomResult<Option<Request>, errors::ConnectorError> {
Ok(Some(
- services::RequestBuilder::new()
- .method(services::Method::Get)
- .url(&types::RefundSyncType::get_url(self, req, connectors)?)
+ RequestBuilder::new()
+ .method(Method::Get)
+ .url(&RefundSyncType::get_url(self, req, connectors)?)
.attach_default_headers()
- .headers(types::RefundSyncType::get_headers(self, req, connectors)?)
+ .headers(RefundSyncType::get_headers(self, req, connectors)?)
.build(),
))
}
fn handle_response(
&self,
- data: &types::RefundSyncRouterData,
+ data: &RefundSyncRouterData,
event_builder: Option<&mut ConnectorEvent>,
res: Response,
- ) -> CustomResult<types::RefundSyncRouterData, errors::ConnectorError> {
+ ) -> CustomResult<RefundSyncRouterData, errors::ConnectorError> {
let response: globepay::GlobepayRefundResponse = res
.response
.parse_struct("Globalpay RefundResponse")
@@ -533,7 +510,7 @@ impl ConnectorIntegration<api::RSync, types::RefundsData, types::RefundsResponse
event_builder.map(|i| i.set_response_body(&response));
router_env::logger::info!(connector_response=?response);
- types::RouterData::try_from(types::ResponseRouterData {
+ RouterData::try_from(ResponseRouterData {
response,
data: data.clone(),
http_code: res.status_code,
@@ -550,24 +527,24 @@ impl ConnectorIntegration<api::RSync, types::RefundsData, types::RefundsResponse
}
#[async_trait::async_trait]
-impl api::IncomingWebhook for Globepay {
+impl webhooks::IncomingWebhook for Globepay {
fn get_webhook_object_reference_id(
&self,
- _request: &api::IncomingWebhookRequestDetails<'_>,
- ) -> CustomResult<api::webhooks::ObjectReferenceId, errors::ConnectorError> {
+ _request: &webhooks::IncomingWebhookRequestDetails<'_>,
+ ) -> CustomResult<api_models::webhooks::ObjectReferenceId, errors::ConnectorError> {
Err(report!(errors::ConnectorError::WebhooksNotImplemented))
}
fn get_webhook_event_type(
&self,
- _request: &api::IncomingWebhookRequestDetails<'_>,
- ) -> CustomResult<api::IncomingWebhookEvent, errors::ConnectorError> {
+ _request: &webhooks::IncomingWebhookRequestDetails<'_>,
+ ) -> CustomResult<api_models::webhooks::IncomingWebhookEvent, errors::ConnectorError> {
Err(report!(errors::ConnectorError::WebhooksNotImplemented))
}
fn get_webhook_resource_object(
&self,
- _request: &api::IncomingWebhookRequestDetails<'_>,
+ _request: &webhooks::IncomingWebhookRequestDetails<'_>,
) -> CustomResult<Box<dyn masking::ErasedMaskSerialize>, errors::ConnectorError> {
Err(report!(errors::ConnectorError::WebhooksNotImplemented))
}
diff --git a/crates/router/src/connector/globepay/transformers.rs b/crates/hyperswitch_connectors/src/connectors/globepay/transformers.rs
similarity index 69%
rename from crates/router/src/connector/globepay/transformers.rs
rename to crates/hyperswitch_connectors/src/connectors/globepay/transformers.rs
index 2d5991c7160..4986e8d5f32 100644
--- a/crates/router/src/connector/globepay/transformers.rs
+++ b/crates/hyperswitch_connectors/src/connectors/globepay/transformers.rs
@@ -1,13 +1,20 @@
+use common_enums::enums;
use common_utils::{ext_traits::Encode, types::MinorUnit};
use error_stack::ResultExt;
+use hyperswitch_domain_models::{
+ payment_method_data::{PaymentMethodData, WalletData},
+ router_data::{ConnectorAuthType, ErrorResponse, RouterData},
+ router_request_types::ResponseId,
+ router_response_types::{PaymentsResponseData, RefundsResponseData},
+ types::{self, RefundsRouterData},
+};
+use hyperswitch_interfaces::{consts, errors};
use masking::Secret;
use serde::{Deserialize, Serialize};
use crate::{
- connector::utils::{self, RouterData},
- consts,
- core::errors,
- types::{self, domain, storage::enums},
+ types::{RefundsResponseRouterData, ResponseRouterData},
+ utils::{get_unimplemented_payment_method_error_message, RouterData as _},
};
type Error = error_stack::Report<errors::ConnectorError>;
@@ -47,57 +54,55 @@ impl TryFrom<&GlobepayRouterData<&types::PaymentsAuthorizeRouterData>> for Globe
) -> Result<Self, Self::Error> {
let item = item_data.router_data.clone();
let channel: GlobepayChannel = match &item.request.payment_method_data {
- domain::PaymentMethodData::Wallet(ref wallet_data) => match wallet_data {
- domain::WalletData::AliPayQr(_) => GlobepayChannel::Alipay,
- domain::WalletData::WeChatPayQr(_) => GlobepayChannel::Wechat,
- domain::WalletData::AliPayRedirect(_)
- | domain::WalletData::AliPayHkRedirect(_)
- | domain::WalletData::MomoRedirect(_)
- | domain::WalletData::KakaoPayRedirect(_)
- | domain::WalletData::GoPayRedirect(_)
- | domain::WalletData::GcashRedirect(_)
- | domain::WalletData::ApplePay(_)
- | domain::WalletData::ApplePayRedirect(_)
- | domain::WalletData::ApplePayThirdPartySdk(_)
- | domain::WalletData::DanaRedirect {}
- | domain::WalletData::GooglePay(_)
- | domain::WalletData::GooglePayRedirect(_)
- | domain::WalletData::GooglePayThirdPartySdk(_)
- | domain::WalletData::MbWayRedirect(_)
- | domain::WalletData::MobilePayRedirect(_)
- | domain::WalletData::PaypalRedirect(_)
- | domain::WalletData::PaypalSdk(_)
- | domain::WalletData::SamsungPay(_)
- | domain::WalletData::TwintRedirect {}
- | domain::WalletData::VippsRedirect {}
- | domain::WalletData::TouchNGoRedirect(_)
- | domain::WalletData::WeChatPayRedirect(_)
- | domain::WalletData::CashappQr(_)
- | domain::WalletData::SwishQr(_)
- | domain::WalletData::Mifinity(_) => Err(errors::ConnectorError::NotImplemented(
- utils::get_unimplemented_payment_method_error_message("globepay"),
+ PaymentMethodData::Wallet(ref wallet_data) => match wallet_data {
+ WalletData::AliPayQr(_) => GlobepayChannel::Alipay,
+ WalletData::WeChatPayQr(_) => GlobepayChannel::Wechat,
+ WalletData::AliPayRedirect(_)
+ | WalletData::AliPayHkRedirect(_)
+ | WalletData::MomoRedirect(_)
+ | WalletData::KakaoPayRedirect(_)
+ | WalletData::GoPayRedirect(_)
+ | WalletData::GcashRedirect(_)
+ | WalletData::ApplePay(_)
+ | WalletData::ApplePayRedirect(_)
+ | WalletData::ApplePayThirdPartySdk(_)
+ | WalletData::DanaRedirect {}
+ | WalletData::GooglePay(_)
+ | WalletData::GooglePayRedirect(_)
+ | WalletData::GooglePayThirdPartySdk(_)
+ | WalletData::MbWayRedirect(_)
+ | WalletData::MobilePayRedirect(_)
+ | WalletData::PaypalRedirect(_)
+ | WalletData::PaypalSdk(_)
+ | WalletData::SamsungPay(_)
+ | WalletData::TwintRedirect {}
+ | WalletData::VippsRedirect {}
+ | WalletData::TouchNGoRedirect(_)
+ | WalletData::WeChatPayRedirect(_)
+ | WalletData::CashappQr(_)
+ | WalletData::SwishQr(_)
+ | WalletData::Mifinity(_) => Err(errors::ConnectorError::NotImplemented(
+ get_unimplemented_payment_method_error_message("globepay"),
))?,
},
- domain::PaymentMethodData::Card(_)
- | domain::PaymentMethodData::CardRedirect(_)
- | domain::PaymentMethodData::PayLater(_)
- | domain::PaymentMethodData::BankRedirect(_)
- | domain::PaymentMethodData::BankDebit(_)
- | domain::PaymentMethodData::BankTransfer(_)
- | domain::PaymentMethodData::Crypto(_)
- | domain::PaymentMethodData::MandatePayment
- | domain::PaymentMethodData::Reward
- | domain::PaymentMethodData::RealTimePayment(_)
- | domain::PaymentMethodData::Upi(_)
- | domain::PaymentMethodData::Voucher(_)
- | domain::PaymentMethodData::GiftCard(_)
- | domain::PaymentMethodData::OpenBanking(_)
- | domain::PaymentMethodData::CardToken(_)
- | domain::PaymentMethodData::NetworkToken(_) => {
- Err(errors::ConnectorError::NotImplemented(
- utils::get_unimplemented_payment_method_error_message("globepay"),
- ))?
- }
+ PaymentMethodData::Card(_)
+ | PaymentMethodData::CardRedirect(_)
+ | PaymentMethodData::PayLater(_)
+ | PaymentMethodData::BankRedirect(_)
+ | PaymentMethodData::BankDebit(_)
+ | PaymentMethodData::BankTransfer(_)
+ | PaymentMethodData::Crypto(_)
+ | PaymentMethodData::MandatePayment
+ | PaymentMethodData::Reward
+ | PaymentMethodData::RealTimePayment(_)
+ | PaymentMethodData::Upi(_)
+ | PaymentMethodData::Voucher(_)
+ | PaymentMethodData::GiftCard(_)
+ | PaymentMethodData::OpenBanking(_)
+ | PaymentMethodData::CardToken(_)
+ | PaymentMethodData::NetworkToken(_) => Err(errors::ConnectorError::NotImplemented(
+ get_unimplemented_payment_method_error_message("globepay"),
+ ))?,
};
let description = item.get_description()?;
Ok(Self {
@@ -114,11 +119,11 @@ pub struct GlobepayAuthType {
pub(super) credential_code: Secret<String>,
}
-impl TryFrom<&types::ConnectorAuthType> for GlobepayAuthType {
+impl TryFrom<&ConnectorAuthType> for GlobepayAuthType {
type Error = Error;
- fn try_from(auth_type: &types::ConnectorAuthType) -> Result<Self, Self::Error> {
+ fn try_from(auth_type: &ConnectorAuthType) -> Result<Self, Self::Error> {
match auth_type {
- types::ConnectorAuthType::BodyKey { api_key, key1 } => Ok(Self {
+ ConnectorAuthType::BodyKey { api_key, key1 } => Ok(Self {
partner_code: api_key.to_owned(),
credential_code: key1.to_owned(),
}),
@@ -174,18 +179,12 @@ pub enum GlobepayReturnCode {
OrderNotPaid,
}
-impl<F, T>
- TryFrom<types::ResponseRouterData<F, GlobepayPaymentsResponse, T, types::PaymentsResponseData>>
- for types::RouterData<F, T, types::PaymentsResponseData>
+impl<F, T> TryFrom<ResponseRouterData<F, GlobepayPaymentsResponse, T, PaymentsResponseData>>
+ for RouterData<F, T, PaymentsResponseData>
{
type Error = Error;
fn try_from(
- item: types::ResponseRouterData<
- F,
- GlobepayPaymentsResponse,
- T,
- types::PaymentsResponseData,
- >,
+ item: ResponseRouterData<F, GlobepayPaymentsResponse, T, PaymentsResponseData>,
) -> Result<Self, Self::Error> {
if item.response.return_code == GlobepayReturnCode::Success {
let globepay_metadata = GlobepayConnectorMetadata {
@@ -204,8 +203,8 @@ impl<F, T>
Ok(Self {
status: enums::AttemptStatus::from(globepay_status),
- response: Ok(types::PaymentsResponseData::TransactionResponse {
- resource_id: types::ResponseId::ConnectorTransactionId(
+ response: Ok(PaymentsResponseData::TransactionResponse {
+ resource_id: ResponseId::ConnectorTransactionId(
item.response
.order_id
.ok_or(errors::ConnectorError::ResponseHandlingFailed)?,
@@ -264,13 +263,12 @@ impl From<GlobepayPaymentPsyncStatus> for enums::AttemptStatus {
}
}
-impl<F, T>
- TryFrom<types::ResponseRouterData<F, GlobepaySyncResponse, T, types::PaymentsResponseData>>
- for types::RouterData<F, T, types::PaymentsResponseData>
+impl<F, T> TryFrom<ResponseRouterData<F, GlobepaySyncResponse, T, PaymentsResponseData>>
+ for RouterData<F, T, PaymentsResponseData>
{
type Error = Error;
fn try_from(
- item: types::ResponseRouterData<F, GlobepaySyncResponse, T, types::PaymentsResponseData>,
+ item: ResponseRouterData<F, GlobepaySyncResponse, T, PaymentsResponseData>,
) -> Result<Self, Self::Error> {
if item.response.return_code == GlobepayReturnCode::Success {
let globepay_status = item
@@ -283,8 +281,8 @@ impl<F, T>
.ok_or(errors::ConnectorError::ResponseHandlingFailed)?;
Ok(Self {
status: enums::AttemptStatus::from(globepay_status),
- response: Ok(types::PaymentsResponseData::TransactionResponse {
- resource_id: types::ResponseId::ConnectorTransactionId(globepay_id),
+ response: Ok(PaymentsResponseData::TransactionResponse {
+ resource_id: ResponseId::ConnectorTransactionId(globepay_id),
redirection_data: None,
mandate_reference: None,
connector_metadata: None,
@@ -313,8 +311,8 @@ fn get_error_response(
return_code: GlobepayReturnCode,
return_msg: Option<String>,
status_code: u16,
-) -> types::ErrorResponse {
- types::ErrorResponse {
+) -> ErrorResponse {
+ ErrorResponse {
code: return_code.to_string(),
message: consts::NO_ERROR_MESSAGE.to_string(),
reason: return_msg,
@@ -329,11 +327,9 @@ pub struct GlobepayRefundRequest {
pub fee: MinorUnit,
}
-impl<F> TryFrom<&GlobepayRouterData<&types::RefundsRouterData<F>>> for GlobepayRefundRequest {
+impl<F> TryFrom<&GlobepayRouterData<&RefundsRouterData<F>>> for GlobepayRefundRequest {
type Error = Error;
- fn try_from(
- item: &GlobepayRouterData<&types::RefundsRouterData<F>>,
- ) -> Result<Self, Self::Error> {
+ fn try_from(item: &GlobepayRouterData<&RefundsRouterData<F>>) -> Result<Self, Self::Error> {
Ok(Self { fee: item.amount })
}
}
@@ -368,12 +364,10 @@ pub struct GlobepayRefundResponse {
pub return_msg: Option<String>,
}
-impl<T> TryFrom<types::RefundsResponseRouterData<T, GlobepayRefundResponse>>
- for types::RefundsRouterData<T>
-{
+impl<T> TryFrom<RefundsResponseRouterData<T, GlobepayRefundResponse>> for RefundsRouterData<T> {
type Error = Error;
fn try_from(
- item: types::RefundsResponseRouterData<T, GlobepayRefundResponse>,
+ item: RefundsResponseRouterData<T, GlobepayRefundResponse>,
) -> Result<Self, Self::Error> {
if item.response.return_code == GlobepayReturnCode::Success {
let globepay_refund_id = item
@@ -385,7 +379,7 @@ impl<T> TryFrom<types::RefundsResponseRouterData<T, GlobepayRefundResponse>>
.result_code
.ok_or(errors::ConnectorError::ResponseHandlingFailed)?;
Ok(Self {
- response: Ok(types::RefundsResponseData {
+ response: Ok(RefundsResponseData {
connector_refund_id: globepay_refund_id,
refund_status: enums::RefundStatus::from(globepay_refund_status),
}),
diff --git a/crates/router/src/connector/powertranz.rs b/crates/hyperswitch_connectors/src/connectors/powertranz.rs
similarity index 60%
rename from crates/router/src/connector/powertranz.rs
rename to crates/hyperswitch_connectors/src/connectors/powertranz.rs
index b9daf49fac0..a437d419bc8 100644
--- a/crates/router/src/connector/powertranz.rs
+++ b/crates/hyperswitch_connectors/src/connectors/powertranz.rs
@@ -3,32 +3,50 @@ pub mod transformers;
use std::fmt::Debug;
use api_models::enums::AuthenticationType;
-use common_utils::{ext_traits::ValueExt, request::RequestContent};
-use diesel_models::enums;
+use common_enums::enums;
+use common_utils::{
+ errors::CustomResult,
+ ext_traits::{BytesExt, ValueExt},
+ request::{Method, Request, RequestBuilder, RequestContent},
+};
use error_stack::{report, ResultExt};
-use masking::ExposeInterface;
-use transformers as powertranz;
-
-use super::utils::{
- self as connector_utils, PaymentsAuthorizeRequestData, PaymentsCompleteAuthorizeRequestData,
+use hyperswitch_domain_models::{
+ router_data::{AccessToken, ConnectorAuthType, ErrorResponse, RouterData},
+ router_flow_types::{
+ access_token_auth::AccessTokenAuth,
+ payments::{Authorize, Capture, PSync, PaymentMethodToken, Session, SetupMandate, Void},
+ refunds::{Execute, RSync},
+ CompleteAuthorize,
+ },
+ router_request_types::{
+ AccessTokenRequestData, CompleteAuthorizeData, PaymentMethodTokenizationData,
+ PaymentsAuthorizeData, PaymentsCancelData, PaymentsCaptureData, PaymentsSessionData,
+ PaymentsSyncData, RefundsData, SetupMandateRequestData,
+ },
+ router_response_types::{PaymentsResponseData, RefundsResponseData},
+ types::{
+ PaymentsAuthorizeRouterData, PaymentsCancelRouterData, PaymentsCaptureRouterData,
+ PaymentsCompleteAuthorizeRouterData, RefundsRouterData,
+ },
};
-use crate::{
- configs::settings,
- consts,
- core::errors::{self, CustomResult},
+use hyperswitch_interfaces::{
+ api::{self, ConnectorCommon, ConnectorCommonExt, ConnectorIntegration, ConnectorValidation},
+ configs::Connectors,
+ consts, errors,
events::connector_api_logs::ConnectorEvent,
- headers,
- services::{
- self,
- request::{self, Mask},
- ConnectorIntegration, ConnectorValidation,
- },
types::{
- self,
- api::{self, ConnectorCommon, ConnectorCommonExt},
- ErrorResponse, Response,
+ PaymentsAuthorizeType, PaymentsCaptureType, PaymentsCompleteAuthorizeType,
+ PaymentsVoidType, RefundExecuteType, Response,
},
- utils::BytesExt,
+ webhooks,
+};
+use masking::{ExposeInterface, Mask};
+use transformers as powertranz;
+
+use crate::{
+ constants::headers,
+ types::ResponseRouterData,
+ utils::{self, PaymentsAuthorizeRequestData as _, PaymentsCompleteAuthorizeRequestData as _},
};
#[derive(Debug, Clone)]
@@ -51,12 +69,8 @@ impl api::PaymentToken for Powertranz {}
const POWER_TRANZ_ID: &str = "PowerTranz-PowerTranzId";
const POWER_TRANZ_PASSWORD: &str = "PowerTranz-PowerTranzPassword";
-impl
- ConnectorIntegration<
- api::PaymentMethodToken,
- types::PaymentMethodTokenizationData,
- types::PaymentsResponseData,
- > for Powertranz
+impl ConnectorIntegration<PaymentMethodToken, PaymentMethodTokenizationData, PaymentsResponseData>
+ for Powertranz
{
}
@@ -66,9 +80,9 @@ where
{
fn build_headers(
&self,
- req: &types::RouterData<Flow, Request, Response>,
- _connectors: &settings::Connectors,
- ) -> CustomResult<Vec<(String, request::Maskable<String>)>, errors::ConnectorError> {
+ req: &RouterData<Flow, Request, Response>,
+ _connectors: &Connectors,
+ ) -> CustomResult<Vec<(String, masking::Maskable<String>)>, errors::ConnectorError> {
let mut header = vec![(
headers::CONTENT_TYPE.to_string(),
self.common_get_content_type().to_string().into(),
@@ -88,14 +102,14 @@ impl ConnectorCommon for Powertranz {
"application/json"
}
- fn base_url<'a>(&self, connectors: &'a settings::Connectors) -> &'a str {
+ fn base_url<'a>(&self, connectors: &'a Connectors) -> &'a str {
connectors.powertranz.base_url.as_ref()
}
fn get_auth_header(
&self,
- auth_type: &types::ConnectorAuthType,
- ) -> CustomResult<Vec<(String, request::Maskable<String>)>, errors::ConnectorError> {
+ auth_type: &ConnectorAuthType,
+ ) -> CustomResult<Vec<(String, masking::Maskable<String>)>, errors::ConnectorError> {
let auth = powertranz::PowertranzAuthType::try_from(auth_type)
.change_context(errors::ConnectorError::FailedToObtainAuthType)?;
Ok(vec![
@@ -140,38 +154,24 @@ impl ConnectorValidation for Powertranz {
match capture_method {
enums::CaptureMethod::Automatic | enums::CaptureMethod::Manual => Ok(()),
enums::CaptureMethod::ManualMultiple | enums::CaptureMethod::Scheduled => Err(
- connector_utils::construct_not_supported_error_report(capture_method, self.id()),
+ utils::construct_not_supported_error_report(capture_method, self.id()),
),
}
}
}
-impl ConnectorIntegration<api::Session, types::PaymentsSessionData, types::PaymentsResponseData>
- for Powertranz
-{
-}
+impl ConnectorIntegration<Session, PaymentsSessionData, PaymentsResponseData> for Powertranz {}
-impl ConnectorIntegration<api::AccessTokenAuth, types::AccessTokenRequestData, types::AccessToken>
- for Powertranz
-{
-}
+impl ConnectorIntegration<AccessTokenAuth, AccessTokenRequestData, AccessToken> for Powertranz {}
-impl
- ConnectorIntegration<
- api::SetupMandate,
- types::SetupMandateRequestData,
- types::PaymentsResponseData,
- > for Powertranz
+impl ConnectorIntegration<SetupMandate, SetupMandateRequestData, PaymentsResponseData>
+ for Powertranz
{
fn build_request(
&self,
- _req: &types::RouterData<
- api::SetupMandate,
- types::SetupMandateRequestData,
- types::PaymentsResponseData,
- >,
- _connectors: &settings::Connectors,
- ) -> CustomResult<Option<services::Request>, errors::ConnectorError> {
+ _req: &RouterData<SetupMandate, SetupMandateRequestData, PaymentsResponseData>,
+ _connectors: &Connectors,
+ ) -> CustomResult<Option<Request>, errors::ConnectorError> {
Err(
errors::ConnectorError::NotImplemented("Setup Mandate flow for Powertranz".to_string())
.into(),
@@ -179,14 +179,12 @@ impl
}
}
-impl ConnectorIntegration<api::Authorize, types::PaymentsAuthorizeData, types::PaymentsResponseData>
- for Powertranz
-{
+impl ConnectorIntegration<Authorize, PaymentsAuthorizeData, PaymentsResponseData> for Powertranz {
fn get_headers(
&self,
- req: &types::PaymentsAuthorizeRouterData,
- connectors: &settings::Connectors,
- ) -> CustomResult<Vec<(String, request::Maskable<String>)>, errors::ConnectorError> {
+ req: &PaymentsAuthorizeRouterData,
+ connectors: &Connectors,
+ ) -> CustomResult<Vec<(String, masking::Maskable<String>)>, errors::ConnectorError> {
self.build_headers(req, connectors)
}
@@ -196,8 +194,8 @@ impl ConnectorIntegration<api::Authorize, types::PaymentsAuthorizeData, types::P
fn get_url(
&self,
- req: &types::PaymentsAuthorizeRouterData,
- connectors: &settings::Connectors,
+ req: &PaymentsAuthorizeRouterData,
+ connectors: &Connectors,
) -> CustomResult<String, errors::ConnectorError> {
let mut endpoint = match req.request.is_auto_capture()? {
true => "sale",
@@ -213,8 +211,8 @@ impl ConnectorIntegration<api::Authorize, types::PaymentsAuthorizeData, types::P
fn get_request_body(
&self,
- req: &types::PaymentsAuthorizeRouterData,
- _connectors: &settings::Connectors,
+ req: &PaymentsAuthorizeRouterData,
+ _connectors: &Connectors,
) -> CustomResult<RequestContent, errors::ConnectorError> {
let connector_req = powertranz::PowertranzPaymentsRequest::try_from(req)?;
Ok(RequestContent::Json(Box::new(connector_req)))
@@ -222,20 +220,16 @@ impl ConnectorIntegration<api::Authorize, types::PaymentsAuthorizeData, types::P
fn build_request(
&self,
- req: &types::PaymentsAuthorizeRouterData,
- connectors: &settings::Connectors,
- ) -> CustomResult<Option<services::Request>, errors::ConnectorError> {
+ req: &PaymentsAuthorizeRouterData,
+ connectors: &Connectors,
+ ) -> CustomResult<Option<Request>, errors::ConnectorError> {
Ok(Some(
- services::RequestBuilder::new()
- .method(services::Method::Post)
- .url(&types::PaymentsAuthorizeType::get_url(
- self, req, connectors,
- )?)
+ RequestBuilder::new()
+ .method(Method::Post)
+ .url(&PaymentsAuthorizeType::get_url(self, req, connectors)?)
.attach_default_headers()
- .headers(types::PaymentsAuthorizeType::get_headers(
- self, req, connectors,
- )?)
- .set_body(types::PaymentsAuthorizeType::get_request_body(
+ .headers(PaymentsAuthorizeType::get_headers(self, req, connectors)?)
+ .set_body(PaymentsAuthorizeType::get_request_body(
self, req, connectors,
)?)
.build(),
@@ -244,10 +238,10 @@ impl ConnectorIntegration<api::Authorize, types::PaymentsAuthorizeData, types::P
fn handle_response(
&self,
- data: &types::PaymentsAuthorizeRouterData,
+ data: &PaymentsAuthorizeRouterData,
event_builder: Option<&mut ConnectorEvent>,
res: Response,
- ) -> CustomResult<types::PaymentsAuthorizeRouterData, errors::ConnectorError> {
+ ) -> CustomResult<PaymentsAuthorizeRouterData, errors::ConnectorError> {
let response: powertranz::PowertranzBaseResponse = res
.response
.parse_struct("Powertranz PaymentsAuthorizeResponse")
@@ -256,7 +250,7 @@ impl ConnectorIntegration<api::Authorize, types::PaymentsAuthorizeData, types::P
event_builder.map(|i| i.set_response_body(&response));
router_env::logger::info!(connector_response=?response);
- types::RouterData::try_from(types::ResponseRouterData {
+ RouterData::try_from(ResponseRouterData {
response,
data: data.clone(),
http_code: res.status_code,
@@ -272,18 +266,14 @@ impl ConnectorIntegration<api::Authorize, types::PaymentsAuthorizeData, types::P
}
}
-impl
- ConnectorIntegration<
- api::CompleteAuthorize,
- types::CompleteAuthorizeData,
- types::PaymentsResponseData,
- > for Powertranz
+impl ConnectorIntegration<CompleteAuthorize, CompleteAuthorizeData, PaymentsResponseData>
+ for Powertranz
{
fn get_headers(
&self,
- req: &types::PaymentsCompleteAuthorizeRouterData,
- connectors: &settings::Connectors,
- ) -> CustomResult<Vec<(String, request::Maskable<String>)>, errors::ConnectorError> {
+ req: &PaymentsCompleteAuthorizeRouterData,
+ connectors: &Connectors,
+ ) -> CustomResult<Vec<(String, masking::Maskable<String>)>, errors::ConnectorError> {
self.build_headers(req, connectors)
}
@@ -293,16 +283,16 @@ impl
fn get_url(
&self,
- _req: &types::PaymentsCompleteAuthorizeRouterData,
- connectors: &settings::Connectors,
+ _req: &PaymentsCompleteAuthorizeRouterData,
+ connectors: &Connectors,
) -> CustomResult<String, errors::ConnectorError> {
Ok(format!("{}spi/payment", self.base_url(connectors)))
}
fn get_request_body(
&self,
- req: &types::PaymentsCompleteAuthorizeRouterData,
- _connectors: &settings::Connectors,
+ req: &PaymentsCompleteAuthorizeRouterData,
+ _connectors: &Connectors,
) -> CustomResult<RequestContent, errors::ConnectorError> {
let redirect_payload: powertranz::RedirectResponsePayload = req
.request
@@ -315,20 +305,20 @@ impl
fn build_request(
&self,
- req: &types::PaymentsCompleteAuthorizeRouterData,
- connectors: &settings::Connectors,
- ) -> CustomResult<Option<services::Request>, errors::ConnectorError> {
+ req: &PaymentsCompleteAuthorizeRouterData,
+ connectors: &Connectors,
+ ) -> CustomResult<Option<Request>, errors::ConnectorError> {
Ok(Some(
- services::RequestBuilder::new()
- .method(services::Method::Post)
- .url(&types::PaymentsCompleteAuthorizeType::get_url(
+ RequestBuilder::new()
+ .method(Method::Post)
+ .url(&PaymentsCompleteAuthorizeType::get_url(
self, req, connectors,
)?)
.attach_default_headers()
- .headers(types::PaymentsCompleteAuthorizeType::get_headers(
+ .headers(PaymentsCompleteAuthorizeType::get_headers(
self, req, connectors,
)?)
- .set_body(types::PaymentsCompleteAuthorizeType::get_request_body(
+ .set_body(PaymentsCompleteAuthorizeType::get_request_body(
self, req, connectors,
)?)
.build(),
@@ -337,10 +327,10 @@ impl
fn handle_response(
&self,
- data: &types::PaymentsCompleteAuthorizeRouterData,
+ data: &PaymentsCompleteAuthorizeRouterData,
event_builder: Option<&mut ConnectorEvent>,
res: Response,
- ) -> CustomResult<types::PaymentsCompleteAuthorizeRouterData, errors::ConnectorError> {
+ ) -> CustomResult<PaymentsCompleteAuthorizeRouterData, errors::ConnectorError> {
let response: powertranz::PowertranzBaseResponse = res
.response
.parse_struct("Powertranz PaymentsCompleteAuthorizeResponse")
@@ -349,7 +339,7 @@ impl
event_builder.map(|i| i.set_response_body(&response));
router_env::logger::info!(connector_response=?response);
- types::RouterData::try_from(types::ResponseRouterData {
+ RouterData::try_from(ResponseRouterData {
response,
data: data.clone(),
http_code: res.status_code,
@@ -365,20 +355,16 @@ impl
}
}
-impl ConnectorIntegration<api::PSync, types::PaymentsSyncData, types::PaymentsResponseData>
- for Powertranz
-{
+impl ConnectorIntegration<PSync, PaymentsSyncData, PaymentsResponseData> for Powertranz {
// default implementation of build_request method will be executed
}
-impl ConnectorIntegration<api::Capture, types::PaymentsCaptureData, types::PaymentsResponseData>
- for Powertranz
-{
+impl ConnectorIntegration<Capture, PaymentsCaptureData, PaymentsResponseData> for Powertranz {
fn get_headers(
&self,
- req: &types::PaymentsCaptureRouterData,
- connectors: &settings::Connectors,
- ) -> CustomResult<Vec<(String, request::Maskable<String>)>, errors::ConnectorError> {
+ req: &PaymentsCaptureRouterData,
+ connectors: &Connectors,
+ ) -> CustomResult<Vec<(String, masking::Maskable<String>)>, errors::ConnectorError> {
self.build_headers(req, connectors)
}
@@ -388,16 +374,16 @@ impl ConnectorIntegration<api::Capture, types::PaymentsCaptureData, types::Payme
fn get_url(
&self,
- _req: &types::PaymentsCaptureRouterData,
- connectors: &settings::Connectors,
+ _req: &PaymentsCaptureRouterData,
+ connectors: &Connectors,
) -> CustomResult<String, errors::ConnectorError> {
Ok(format!("{}capture", self.base_url(connectors)))
}
fn get_request_body(
&self,
- req: &types::PaymentsCaptureRouterData,
- _connectors: &settings::Connectors,
+ req: &PaymentsCaptureRouterData,
+ _connectors: &Connectors,
) -> CustomResult<RequestContent, errors::ConnectorError> {
let connector_req = powertranz::PowertranzBaseRequest::try_from(&req.request)?;
Ok(RequestContent::Json(Box::new(connector_req)))
@@ -405,18 +391,16 @@ impl ConnectorIntegration<api::Capture, types::PaymentsCaptureData, types::Payme
fn build_request(
&self,
- req: &types::PaymentsCaptureRouterData,
- connectors: &settings::Connectors,
- ) -> CustomResult<Option<services::Request>, errors::ConnectorError> {
+ req: &PaymentsCaptureRouterData,
+ connectors: &Connectors,
+ ) -> CustomResult<Option<Request>, errors::ConnectorError> {
Ok(Some(
- services::RequestBuilder::new()
- .method(services::Method::Post)
- .url(&types::PaymentsCaptureType::get_url(self, req, connectors)?)
+ RequestBuilder::new()
+ .method(Method::Post)
+ .url(&PaymentsCaptureType::get_url(self, req, connectors)?)
.attach_default_headers()
- .headers(types::PaymentsCaptureType::get_headers(
- self, req, connectors,
- )?)
- .set_body(types::PaymentsCaptureType::get_request_body(
+ .headers(PaymentsCaptureType::get_headers(self, req, connectors)?)
+ .set_body(PaymentsCaptureType::get_request_body(
self, req, connectors,
)?)
.build(),
@@ -425,10 +409,10 @@ impl ConnectorIntegration<api::Capture, types::PaymentsCaptureData, types::Payme
fn handle_response(
&self,
- data: &types::PaymentsCaptureRouterData,
+ data: &PaymentsCaptureRouterData,
event_builder: Option<&mut ConnectorEvent>,
res: Response,
- ) -> CustomResult<types::PaymentsCaptureRouterData, errors::ConnectorError> {
+ ) -> CustomResult<PaymentsCaptureRouterData, errors::ConnectorError> {
let response: powertranz::PowertranzBaseResponse = res
.response
.parse_struct("Powertranz PaymentsCaptureResponse")
@@ -437,7 +421,7 @@ impl ConnectorIntegration<api::Capture, types::PaymentsCaptureData, types::Payme
event_builder.map(|i| i.set_response_body(&response));
router_env::logger::info!(connector_response=?response);
- types::RouterData::try_from(types::ResponseRouterData {
+ RouterData::try_from(ResponseRouterData {
response,
data: data.clone(),
http_code: res.status_code,
@@ -453,29 +437,27 @@ impl ConnectorIntegration<api::Capture, types::PaymentsCaptureData, types::Payme
}
}
-impl ConnectorIntegration<api::Void, types::PaymentsCancelData, types::PaymentsResponseData>
- for Powertranz
-{
+impl ConnectorIntegration<Void, PaymentsCancelData, PaymentsResponseData> for Powertranz {
fn get_headers(
&self,
- req: &types::PaymentsCancelRouterData,
- connectors: &settings::Connectors,
- ) -> CustomResult<Vec<(String, request::Maskable<String>)>, errors::ConnectorError> {
+ req: &PaymentsCancelRouterData,
+ connectors: &Connectors,
+ ) -> CustomResult<Vec<(String, masking::Maskable<String>)>, errors::ConnectorError> {
self.build_headers(req, connectors)
}
fn get_url(
&self,
- _req: &types::RouterData<api::Void, types::PaymentsCancelData, types::PaymentsResponseData>,
- connectors: &settings::Connectors,
+ _req: &RouterData<Void, PaymentsCancelData, PaymentsResponseData>,
+ connectors: &Connectors,
) -> CustomResult<String, errors::ConnectorError> {
Ok(format!("{}void", self.base_url(connectors)))
}
fn get_request_body(
&self,
- req: &types::RouterData<api::Void, types::PaymentsCancelData, types::PaymentsResponseData>,
- _connectors: &settings::Connectors,
+ req: &RouterData<Void, PaymentsCancelData, PaymentsResponseData>,
+ _connectors: &Connectors,
) -> CustomResult<RequestContent, errors::ConnectorError> {
let connector_req = powertranz::PowertranzBaseRequest::try_from(&req.request)?;
Ok(RequestContent::Json(Box::new(connector_req)))
@@ -483,10 +465,10 @@ impl ConnectorIntegration<api::Void, types::PaymentsCancelData, types::PaymentsR
fn handle_response(
&self,
- data: &types::RouterData<api::Void, types::PaymentsCancelData, types::PaymentsResponseData>,
+ data: &RouterData<Void, PaymentsCancelData, PaymentsResponseData>,
event_builder: Option<&mut ConnectorEvent>,
res: Response,
- ) -> CustomResult<types::PaymentsCancelRouterData, errors::ConnectorError> {
+ ) -> CustomResult<PaymentsCancelRouterData, errors::ConnectorError> {
let response: powertranz::PowertranzBaseResponse = res
.response
.parse_struct("powertranz CancelResponse")
@@ -495,7 +477,7 @@ impl ConnectorIntegration<api::Void, types::PaymentsCancelData, types::PaymentsR
event_builder.map(|i| i.set_response_body(&response));
router_env::logger::info!(connector_response=?response);
- types::RouterData::try_from(types::ResponseRouterData {
+ RouterData::try_from(ResponseRouterData {
response,
data: data.clone(),
http_code: res.status_code,
@@ -504,18 +486,16 @@ impl ConnectorIntegration<api::Void, types::PaymentsCancelData, types::PaymentsR
fn build_request(
&self,
- req: &types::RouterData<api::Void, types::PaymentsCancelData, types::PaymentsResponseData>,
- connectors: &settings::Connectors,
- ) -> CustomResult<Option<services::Request>, errors::ConnectorError> {
+ req: &RouterData<Void, PaymentsCancelData, PaymentsResponseData>,
+ connectors: &Connectors,
+ ) -> CustomResult<Option<Request>, errors::ConnectorError> {
Ok(Some(
- services::RequestBuilder::new()
- .method(services::Method::Post)
- .url(&types::PaymentsVoidType::get_url(self, req, connectors)?)
+ RequestBuilder::new()
+ .method(Method::Post)
+ .url(&PaymentsVoidType::get_url(self, req, connectors)?)
.attach_default_headers()
- .headers(types::PaymentsVoidType::get_headers(self, req, connectors)?)
- .set_body(types::PaymentsVoidType::get_request_body(
- self, req, connectors,
- )?)
+ .headers(PaymentsVoidType::get_headers(self, req, connectors)?)
+ .set_body(PaymentsVoidType::get_request_body(self, req, connectors)?)
.build(),
))
}
@@ -529,14 +509,12 @@ impl ConnectorIntegration<api::Void, types::PaymentsCancelData, types::PaymentsR
}
}
-impl ConnectorIntegration<api::Execute, types::RefundsData, types::RefundsResponseData>
- for Powertranz
-{
+impl ConnectorIntegration<Execute, RefundsData, RefundsResponseData> for Powertranz {
fn get_headers(
&self,
- req: &types::RefundsRouterData<api::Execute>,
- connectors: &settings::Connectors,
- ) -> CustomResult<Vec<(String, request::Maskable<String>)>, errors::ConnectorError> {
+ req: &RefundsRouterData<Execute>,
+ connectors: &Connectors,
+ ) -> CustomResult<Vec<(String, masking::Maskable<String>)>, errors::ConnectorError> {
self.build_headers(req, connectors)
}
@@ -546,16 +524,16 @@ impl ConnectorIntegration<api::Execute, types::RefundsData, types::RefundsRespon
fn get_url(
&self,
- _req: &types::RefundsRouterData<api::Execute>,
- connectors: &settings::Connectors,
+ _req: &RefundsRouterData<Execute>,
+ connectors: &Connectors,
) -> CustomResult<String, errors::ConnectorError> {
Ok(format!("{}refund", self.base_url(connectors)))
}
fn get_request_body(
&self,
- req: &types::RefundsRouterData<api::Execute>,
- _connectors: &settings::Connectors,
+ req: &RefundsRouterData<Execute>,
+ _connectors: &Connectors,
) -> CustomResult<RequestContent, errors::ConnectorError> {
let connector_req = powertranz::PowertranzBaseRequest::try_from(req)?;
Ok(RequestContent::Json(Box::new(connector_req)))
@@ -563,29 +541,25 @@ impl ConnectorIntegration<api::Execute, types::RefundsData, types::RefundsRespon
fn build_request(
&self,
- req: &types::RefundsRouterData<api::Execute>,
- connectors: &settings::Connectors,
- ) -> CustomResult<Option<services::Request>, errors::ConnectorError> {
- let request = services::RequestBuilder::new()
- .method(services::Method::Post)
- .url(&types::RefundExecuteType::get_url(self, req, connectors)?)
+ req: &RefundsRouterData<Execute>,
+ connectors: &Connectors,
+ ) -> CustomResult<Option<Request>, errors::ConnectorError> {
+ let request = RequestBuilder::new()
+ .method(Method::Post)
+ .url(&RefundExecuteType::get_url(self, req, connectors)?)
.attach_default_headers()
- .headers(types::RefundExecuteType::get_headers(
- self, req, connectors,
- )?)
- .set_body(types::RefundExecuteType::get_request_body(
- self, req, connectors,
- )?)
+ .headers(RefundExecuteType::get_headers(self, req, connectors)?)
+ .set_body(RefundExecuteType::get_request_body(self, req, connectors)?)
.build();
Ok(Some(request))
}
fn handle_response(
&self,
- data: &types::RefundsRouterData<api::Execute>,
+ data: &RefundsRouterData<Execute>,
event_builder: Option<&mut ConnectorEvent>,
res: Response,
- ) -> CustomResult<types::RefundsRouterData<api::Execute>, errors::ConnectorError> {
+ ) -> CustomResult<RefundsRouterData<Execute>, errors::ConnectorError> {
let response: powertranz::PowertranzBaseResponse = res
.response
.parse_struct("powertranz RefundResponse")
@@ -594,7 +568,7 @@ impl ConnectorIntegration<api::Execute, types::RefundsData, types::RefundsRespon
event_builder.map(|i| i.set_response_body(&response));
router_env::logger::info!(connector_response=?response);
- types::RouterData::try_from(types::ResponseRouterData {
+ RouterData::try_from(ResponseRouterData {
response,
data: data.clone(),
http_code: res.status_code,
@@ -610,31 +584,29 @@ impl ConnectorIntegration<api::Execute, types::RefundsData, types::RefundsRespon
}
}
-impl ConnectorIntegration<api::RSync, types::RefundsData, types::RefundsResponseData>
- for Powertranz
-{
+impl ConnectorIntegration<RSync, RefundsData, RefundsResponseData> for Powertranz {
// default implementation of build_request method will be executed
}
#[async_trait::async_trait]
-impl api::IncomingWebhook for Powertranz {
+impl webhooks::IncomingWebhook for Powertranz {
fn get_webhook_object_reference_id(
&self,
- _request: &api::IncomingWebhookRequestDetails<'_>,
- ) -> CustomResult<api::webhooks::ObjectReferenceId, errors::ConnectorError> {
+ _request: &webhooks::IncomingWebhookRequestDetails<'_>,
+ ) -> CustomResult<api_models::webhooks::ObjectReferenceId, errors::ConnectorError> {
Err(report!(errors::ConnectorError::WebhooksNotImplemented))
}
fn get_webhook_event_type(
&self,
- _request: &api::IncomingWebhookRequestDetails<'_>,
- ) -> CustomResult<api::IncomingWebhookEvent, errors::ConnectorError> {
+ _request: &webhooks::IncomingWebhookRequestDetails<'_>,
+ ) -> CustomResult<api_models::webhooks::IncomingWebhookEvent, errors::ConnectorError> {
Err(report!(errors::ConnectorError::WebhooksNotImplemented))
}
fn get_webhook_resource_object(
&self,
- _request: &api::IncomingWebhookRequestDetails<'_>,
+ _request: &webhooks::IncomingWebhookRequestDetails<'_>,
) -> CustomResult<Box<dyn masking::ErasedMaskSerialize>, errors::ConnectorError> {
Err(report!(errors::ConnectorError::WebhooksNotImplemented))
}
diff --git a/crates/router/src/connector/powertranz/transformers.rs b/crates/hyperswitch_connectors/src/connectors/powertranz/transformers.rs
similarity index 68%
rename from crates/router/src/connector/powertranz/transformers.rs
rename to crates/hyperswitch_connectors/src/connectors/powertranz/transformers.rs
index 97c2994b4c7..5ea64f8b958 100644
--- a/crates/router/src/connector/powertranz/transformers.rs
+++ b/crates/hyperswitch_connectors/src/connectors/powertranz/transformers.rs
@@ -1,15 +1,23 @@
+use common_enums::enums::{self, AuthenticationType, Currency};
use common_utils::pii::IpAddress;
-use diesel_models::enums::RefundStatus;
+use hyperswitch_domain_models::{
+ payment_method_data::{Card, PaymentMethodData},
+ router_data::{ConnectorAuthType, ErrorResponse, RouterData},
+ router_flow_types::refunds::Execute,
+ router_request_types::{
+ BrowserInformation, PaymentsCancelData, PaymentsCaptureData, ResponseId,
+ },
+ router_response_types::{PaymentsResponseData, RefundsResponseData},
+ types::{PaymentsAuthorizeRouterData, RefundsRouterData},
+};
+use hyperswitch_interfaces::{consts, errors};
use masking::{ExposeInterface, Secret};
use serde::{Deserialize, Serialize};
use uuid::Uuid;
use crate::{
- connector::utils::{self, CardData, PaymentsAuthorizeRequestData, RouterData},
- consts,
- core::errors,
- services,
- types::{self, api, domain, storage::enums, transformers::ForeignFrom},
+ types::{RefundsResponseRouterData, ResponseRouterData},
+ utils::{self, CardData, PaymentsAuthorizeRequestData, RouterData as _},
};
const ISO_SUCCESS_CODES: [&str; 7] = ["00", "3D0", "3D1", "HP0", "TK0", "SP4", "FC0"];
@@ -95,44 +103,40 @@ pub struct RedirectResponsePayload {
pub spi_token: Secret<String>,
}
-impl TryFrom<&types::PaymentsAuthorizeRouterData> for PowertranzPaymentsRequest {
+impl TryFrom<&PaymentsAuthorizeRouterData> for PowertranzPaymentsRequest {
type Error = error_stack::Report<errors::ConnectorError>;
- fn try_from(item: &types::PaymentsAuthorizeRouterData) -> Result<Self, Self::Error> {
+ fn try_from(item: &PaymentsAuthorizeRouterData) -> Result<Self, Self::Error> {
let source = match item.request.payment_method_data.clone() {
- domain::PaymentMethodData::Card(card) => {
+ PaymentMethodData::Card(card) => {
let card_holder_name = item.get_optional_billing_full_name();
Source::try_from((&card, card_holder_name))
}
- domain::PaymentMethodData::Wallet(_)
- | domain::PaymentMethodData::CardRedirect(_)
- | domain::PaymentMethodData::PayLater(_)
- | domain::PaymentMethodData::BankRedirect(_)
- | domain::PaymentMethodData::BankDebit(_)
- | domain::PaymentMethodData::BankTransfer(_)
- | domain::PaymentMethodData::Crypto(_)
- | domain::PaymentMethodData::MandatePayment
- | domain::PaymentMethodData::Reward
- | domain::PaymentMethodData::RealTimePayment(_)
- | domain::PaymentMethodData::Upi(_)
- | domain::PaymentMethodData::Voucher(_)
- | domain::PaymentMethodData::GiftCard(_)
- | domain::PaymentMethodData::OpenBanking(_)
- | domain::PaymentMethodData::CardToken(_)
- | domain::PaymentMethodData::NetworkToken(_) => {
- Err(errors::ConnectorError::NotSupported {
- message: utils::SELECTED_PAYMENT_METHOD.to_string(),
- connector: "powertranz",
- }
- .into())
+ PaymentMethodData::Wallet(_)
+ | PaymentMethodData::CardRedirect(_)
+ | PaymentMethodData::PayLater(_)
+ | PaymentMethodData::BankRedirect(_)
+ | PaymentMethodData::BankDebit(_)
+ | PaymentMethodData::BankTransfer(_)
+ | PaymentMethodData::Crypto(_)
+ | PaymentMethodData::MandatePayment
+ | PaymentMethodData::Reward
+ | PaymentMethodData::RealTimePayment(_)
+ | PaymentMethodData::Upi(_)
+ | PaymentMethodData::Voucher(_)
+ | PaymentMethodData::GiftCard(_)
+ | PaymentMethodData::OpenBanking(_)
+ | PaymentMethodData::CardToken(_)
+ | PaymentMethodData::NetworkToken(_) => Err(errors::ConnectorError::NotSupported {
+ message: utils::SELECTED_PAYMENT_METHOD.to_string(),
+ connector: "powertranz",
}
+ .into()),
}?;
// let billing_address = get_address_details(&item.address.billing, &item.request.email);
// let shipping_address = get_address_details(&item.address.shipping, &item.request.email);
let (three_d_secure, extended_data) = match item.auth_type {
- diesel_models::enums::AuthenticationType::ThreeDs => {
- (true, Some(ExtendedData::try_from(item)?))
- }
- diesel_models::enums::AuthenticationType::NoThreeDs => (false, None),
+ AuthenticationType::ThreeDs => (true, Some(ExtendedData::try_from(item)?)),
+ AuthenticationType::NoThreeDs => (false, None),
};
Ok(Self {
transaction_identifier: Uuid::new_v4().to_string(),
@@ -140,8 +144,7 @@ impl TryFrom<&types::PaymentsAuthorizeRouterData> for PowertranzPaymentsRequest
item.request.amount,
item.request.currency,
)?,
- currency_code: diesel_models::enums::Currency::iso_4217(&item.request.currency)
- .to_string(),
+ currency_code: Currency::iso_4217(&item.request.currency).to_string(),
three_d_secure,
source,
order_identifier: item.connector_request_reference_id.clone(),
@@ -152,9 +155,9 @@ impl TryFrom<&types::PaymentsAuthorizeRouterData> for PowertranzPaymentsRequest
}
}
-impl TryFrom<&types::PaymentsAuthorizeRouterData> for ExtendedData {
+impl TryFrom<&PaymentsAuthorizeRouterData> for ExtendedData {
type Error = error_stack::Report<errors::ConnectorError>;
- fn try_from(item: &types::PaymentsAuthorizeRouterData) -> Result<Self, Self::Error> {
+ fn try_from(item: &PaymentsAuthorizeRouterData) -> Result<Self, Self::Error> {
Ok(Self {
three_d_secure: ThreeDSecure {
// Merchants preferred sized of challenge window presented to cardholder.
@@ -167,9 +170,9 @@ impl TryFrom<&types::PaymentsAuthorizeRouterData> for ExtendedData {
}
}
-impl TryFrom<&types::BrowserInformation> for BrowserInfo {
+impl TryFrom<&BrowserInformation> for BrowserInfo {
type Error = error_stack::Report<errors::ConnectorError>;
- fn try_from(item: &types::BrowserInformation) -> Result<Self, Self::Error> {
+ fn try_from(item: &BrowserInformation) -> Result<Self, Self::Error> {
Ok(Self {
java_enabled: item.java_enabled,
javascript_enabled: item.java_script_enabled,
@@ -219,10 +222,10 @@ impl TryFrom<&types::BrowserInformation> for BrowserInfo {
})
}*/
-impl TryFrom<(&domain::Card, Option<Secret<String>>)> for Source {
+impl TryFrom<(&Card, Option<Secret<String>>)> for Source {
type Error = error_stack::Report<errors::ConnectorError>;
fn try_from(
- (card, card_holder_name): (&domain::Card, Option<Secret<String>>),
+ (card, card_holder_name): (&Card, Option<Secret<String>>),
) -> Result<Self, Self::Error> {
let card = PowertranzCard {
cardholder_name: card_holder_name.unwrap_or(Secret::new("".to_string())),
@@ -240,11 +243,11 @@ pub struct PowertranzAuthType {
pub(super) power_tranz_password: Secret<String>,
}
-impl TryFrom<&types::ConnectorAuthType> for PowertranzAuthType {
+impl TryFrom<&ConnectorAuthType> for PowertranzAuthType {
type Error = error_stack::Report<errors::ConnectorError>;
- fn try_from(auth_type: &types::ConnectorAuthType) -> Result<Self, Self::Error> {
+ fn try_from(auth_type: &ConnectorAuthType) -> Result<Self, Self::Error> {
match auth_type {
- types::ConnectorAuthType::BodyKey { api_key, key1 } => Ok(Self {
+ ConnectorAuthType::BodyKey { api_key, key1 } => Ok(Self {
power_tranz_id: key1.to_owned(),
power_tranz_password: api_key.to_owned(),
}),
@@ -268,56 +271,53 @@ pub struct PowertranzBaseResponse {
order_identifier: String,
}
-impl ForeignFrom<(u8, bool, bool)> for enums::AttemptStatus {
- fn foreign_from((transaction_type, approved, is_3ds): (u8, bool, bool)) -> Self {
- match transaction_type {
- // Auth
- 1 => match approved {
- true => Self::Authorized,
- false => match is_3ds {
- true => Self::AuthenticationPending,
- false => Self::Failure,
- },
- },
- // Sale
- 2 => match approved {
- true => Self::Charged,
- false => match is_3ds {
- true => Self::AuthenticationPending,
- false => Self::Failure,
- },
- },
- // Capture
- 3 => match approved {
- true => Self::Charged,
- false => Self::Failure,
+fn get_status((transaction_type, approved, is_3ds): (u8, bool, bool)) -> enums::AttemptStatus {
+ match transaction_type {
+ // Auth
+ 1 => match approved {
+ true => enums::AttemptStatus::Authorized,
+ false => match is_3ds {
+ true => enums::AttemptStatus::AuthenticationPending,
+ false => enums::AttemptStatus::Failure,
},
- // Void
- 4 => match approved {
- true => Self::Voided,
- false => Self::VoidFailed,
+ },
+ // Sale
+ 2 => match approved {
+ true => enums::AttemptStatus::Charged,
+ false => match is_3ds {
+ true => enums::AttemptStatus::AuthenticationPending,
+ false => enums::AttemptStatus::Failure,
},
- // Refund
- 5 => match approved {
- true => Self::AutoRefunded,
- false => Self::Failure,
- },
- // Risk Management
- _ => match approved {
- true => Self::Pending,
- false => Self::Failure,
- },
- }
+ },
+ // Capture
+ 3 => match approved {
+ true => enums::AttemptStatus::Charged,
+ false => enums::AttemptStatus::Failure,
+ },
+ // Void
+ 4 => match approved {
+ true => enums::AttemptStatus::Voided,
+ false => enums::AttemptStatus::VoidFailed,
+ },
+ // Refund
+ 5 => match approved {
+ true => enums::AttemptStatus::AutoRefunded,
+ false => enums::AttemptStatus::Failure,
+ },
+ // Risk Management
+ _ => match approved {
+ true => enums::AttemptStatus::Pending,
+ false => enums::AttemptStatus::Failure,
+ },
}
}
-impl<F, T>
- TryFrom<types::ResponseRouterData<F, PowertranzBaseResponse, T, types::PaymentsResponseData>>
- for types::RouterData<F, T, types::PaymentsResponseData>
+impl<F, T> TryFrom<ResponseRouterData<F, PowertranzBaseResponse, T, PaymentsResponseData>>
+ for RouterData<F, T, PaymentsResponseData>
{
type Error = error_stack::Report<errors::ConnectorError>;
fn try_from(
- item: types::ResponseRouterData<F, PowertranzBaseResponse, T, types::PaymentsResponseData>,
+ item: ResponseRouterData<F, PowertranzBaseResponse, T, PaymentsResponseData>,
) -> Result<Self, Self::Error> {
let error_response = build_error_response(&item.response, item.http_code);
// original_trxn_identifier will be present only in capture and void
@@ -325,15 +325,14 @@ impl<F, T>
.response
.original_trxn_identifier
.unwrap_or(item.response.transaction_identifier.clone());
- let redirection_data =
- item.response
- .redirect_data
- .map(|redirect_data| services::RedirectForm::Html {
- html_data: redirect_data.expose(),
- });
+ let redirection_data = item.response.redirect_data.map(|redirect_data| {
+ hyperswitch_domain_models::router_response_types::RedirectForm::Html {
+ html_data: redirect_data.expose(),
+ }
+ });
let response = error_response.map_or(
- Ok(types::PaymentsResponseData::TransactionResponse {
- resource_id: types::ResponseId::ConnectorTransactionId(connector_transaction_id),
+ Ok(PaymentsResponseData::TransactionResponse {
+ resource_id: ResponseId::ConnectorTransactionId(connector_transaction_id),
redirection_data,
mandate_reference: None,
connector_metadata: None,
@@ -345,7 +344,7 @@ impl<F, T>
Err,
);
Ok(Self {
- status: enums::AttemptStatus::foreign_from((
+ status: get_status((
item.response.transaction_type,
item.response.approved,
is_3ds_payment(item.response.iso_response_code),
@@ -369,9 +368,9 @@ pub struct PowertranzBaseRequest {
refund: Option<bool>,
}
-impl TryFrom<&types::PaymentsCancelData> for PowertranzBaseRequest {
+impl TryFrom<&PaymentsCancelData> for PowertranzBaseRequest {
type Error = error_stack::Report<errors::ConnectorError>;
- fn try_from(item: &types::PaymentsCancelData) -> Result<Self, Self::Error> {
+ fn try_from(item: &PaymentsCancelData) -> Result<Self, Self::Error> {
Ok(Self {
transaction_identifier: item.connector_transaction_id.clone(),
total_amount: None,
@@ -380,9 +379,9 @@ impl TryFrom<&types::PaymentsCancelData> for PowertranzBaseRequest {
}
}
-impl TryFrom<&types::PaymentsCaptureData> for PowertranzBaseRequest {
+impl TryFrom<&PaymentsCaptureData> for PowertranzBaseRequest {
type Error = error_stack::Report<errors::ConnectorError>;
- fn try_from(item: &types::PaymentsCaptureData) -> Result<Self, Self::Error> {
+ fn try_from(item: &PaymentsCaptureData) -> Result<Self, Self::Error> {
let total_amount = Some(utils::to_currency_base_unit_asf64(
item.amount_to_capture,
item.currency,
@@ -395,9 +394,9 @@ impl TryFrom<&types::PaymentsCaptureData> for PowertranzBaseRequest {
}
}
-impl<F> TryFrom<&types::RefundsRouterData<F>> for PowertranzBaseRequest {
+impl<F> TryFrom<&RefundsRouterData<F>> for PowertranzBaseRequest {
type Error = error_stack::Report<errors::ConnectorError>;
- fn try_from(item: &types::RefundsRouterData<F>) -> Result<Self, Self::Error> {
+ fn try_from(item: &RefundsRouterData<F>) -> Result<Self, Self::Error> {
let total_amount = Some(utils::to_currency_base_unit_asf64(
item.request.refund_amount,
item.request.currency,
@@ -410,20 +409,20 @@ impl<F> TryFrom<&types::RefundsRouterData<F>> for PowertranzBaseRequest {
}
}
-impl TryFrom<types::RefundsResponseRouterData<api::Execute, PowertranzBaseResponse>>
- for types::RefundsRouterData<api::Execute>
+impl TryFrom<RefundsResponseRouterData<Execute, PowertranzBaseResponse>>
+ for RefundsRouterData<Execute>
{
type Error = error_stack::Report<errors::ConnectorError>;
fn try_from(
- item: types::RefundsResponseRouterData<api::Execute, PowertranzBaseResponse>,
+ item: RefundsResponseRouterData<Execute, PowertranzBaseResponse>,
) -> Result<Self, Self::Error> {
let error_response = build_error_response(&item.response, item.http_code);
let response = error_response.map_or(
- Ok(types::RefundsResponseData {
+ Ok(RefundsResponseData {
connector_refund_id: item.response.transaction_identifier.to_string(),
refund_status: match item.response.approved {
- true => RefundStatus::Success,
- false => RefundStatus::Failure,
+ true => enums::RefundStatus::Success,
+ false => enums::RefundStatus::Failure,
},
}),
Err,
@@ -435,10 +434,7 @@ impl TryFrom<types::RefundsResponseRouterData<api::Execute, PowertranzBaseRespon
}
}
-fn build_error_response(
- item: &PowertranzBaseResponse,
- status_code: u16,
-) -> Option<types::ErrorResponse> {
+fn build_error_response(item: &PowertranzBaseResponse, status_code: u16) -> Option<ErrorResponse> {
// errors object has highest precedence to get error message and code
let error_response = if item.errors.is_some() {
item.errors.as_ref().map(|errors| {
@@ -446,7 +442,7 @@ fn build_error_response(
let code = first_error.map(|error| error.code.clone());
let message = first_error.map(|error| error.message.clone());
- types::ErrorResponse {
+ ErrorResponse {
status_code,
code: code.unwrap_or_else(|| consts::NO_ERROR_CODE.to_string()),
message: message.unwrap_or_else(|| consts::NO_ERROR_MESSAGE.to_string()),
@@ -463,7 +459,7 @@ fn build_error_response(
})
} else if !ISO_SUCCESS_CODES.contains(&item.iso_response_code.as_str()) {
// Incase error object is not present the error message and code should be propagated based on iso_response_code
- Some(types::ErrorResponse {
+ Some(ErrorResponse {
status_code,
code: item.iso_response_code.clone(),
message: item.response_message.clone(),
diff --git a/crates/router/src/connector/tsys.rs b/crates/hyperswitch_connectors/src/connectors/tsys.rs
similarity index 57%
rename from crates/router/src/connector/tsys.rs
rename to crates/hyperswitch_connectors/src/connectors/tsys.rs
index 9387fbcec1e..ec53a99316f 100644
--- a/crates/router/src/connector/tsys.rs
+++ b/crates/hyperswitch_connectors/src/connectors/tsys.rs
@@ -2,29 +2,45 @@ pub mod transformers;
use std::fmt::Debug;
-use common_utils::request::RequestContent;
-use diesel_models::enums;
+use common_enums::enums;
+use common_utils::{
+ errors::CustomResult,
+ ext_traits::BytesExt,
+ request::{Method, Request, RequestBuilder, RequestContent},
+};
use error_stack::{report, ResultExt};
-use transformers as tsys;
-
-use crate::{
- configs::settings,
- connector::utils as connector_utils,
- core::errors::{self, CustomResult},
- events::connector_api_logs::ConnectorEvent,
- headers,
- services::{
- self,
- request::{self},
- ConnectorIntegration, ConnectorValidation,
+use hyperswitch_domain_models::{
+ router_data::{AccessToken, ErrorResponse, RouterData},
+ router_flow_types::{
+ access_token_auth::AccessTokenAuth,
+ payments::{Authorize, Capture, PSync, PaymentMethodToken, Session, SetupMandate, Void},
+ refunds::{Execute, RSync},
+ },
+ router_request_types::{
+ AccessTokenRequestData, PaymentMethodTokenizationData, PaymentsAuthorizeData,
+ PaymentsCancelData, PaymentsCaptureData, PaymentsSessionData, PaymentsSyncData,
+ RefundsData, SetupMandateRequestData,
},
+ router_response_types::{PaymentsResponseData, RefundsResponseData},
types::{
- self,
- api::{self, ConnectorCommon, ConnectorCommonExt},
- ErrorResponse, Response,
+ PaymentsAuthorizeRouterData, PaymentsCancelRouterData, PaymentsCaptureRouterData,
+ PaymentsSyncRouterData, RefundSyncRouterData, RefundsRouterData,
},
- utils::BytesExt,
};
+use hyperswitch_interfaces::{
+ api::{self, ConnectorCommon, ConnectorCommonExt, ConnectorIntegration, ConnectorValidation},
+ configs::Connectors,
+ errors,
+ events::connector_api_logs::ConnectorEvent,
+ types::{
+ PaymentsAuthorizeType, PaymentsCaptureType, PaymentsSyncType, PaymentsVoidType,
+ RefundExecuteType, RefundSyncType, Response,
+ },
+ webhooks,
+};
+use transformers as tsys;
+
+use crate::{constants::headers, types::ResponseRouterData, utils};
#[derive(Debug, Clone)]
pub struct Tsys;
@@ -42,12 +58,8 @@ impl api::RefundExecute for Tsys {}
impl api::RefundSync for Tsys {}
impl api::PaymentToken for Tsys {}
-impl
- ConnectorIntegration<
- api::PaymentMethodToken,
- types::PaymentMethodTokenizationData,
- types::PaymentsResponseData,
- > for Tsys
+impl ConnectorIntegration<PaymentMethodToken, PaymentMethodTokenizationData, PaymentsResponseData>
+ for Tsys
{
}
@@ -57,9 +69,9 @@ where
{
fn build_headers(
&self,
- _req: &types::RouterData<Flow, Request, Response>,
- _connectors: &settings::Connectors,
- ) -> CustomResult<Vec<(String, request::Maskable<String>)>, errors::ConnectorError> {
+ _req: &RouterData<Flow, Request, Response>,
+ _connectors: &Connectors,
+ ) -> CustomResult<Vec<(String, masking::Maskable<String>)>, errors::ConnectorError> {
let header = vec![(
headers::CONTENT_TYPE.to_string(),
Self::get_content_type(self).to_string().into(),
@@ -77,7 +89,7 @@ impl ConnectorCommon for Tsys {
"application/json"
}
- fn base_url<'a>(&self, connectors: &'a settings::Connectors) -> &'a str {
+ fn base_url<'a>(&self, connectors: &'a Connectors) -> &'a str {
connectors.tsys.base_url.as_ref()
}
}
@@ -92,38 +104,22 @@ impl ConnectorValidation for Tsys {
match capture_method {
enums::CaptureMethod::Automatic | enums::CaptureMethod::Manual => Ok(()),
enums::CaptureMethod::ManualMultiple | enums::CaptureMethod::Scheduled => Err(
- connector_utils::construct_not_supported_error_report(capture_method, self.id()),
+ utils::construct_not_supported_error_report(capture_method, self.id()),
),
}
}
}
-impl ConnectorIntegration<api::Session, types::PaymentsSessionData, types::PaymentsResponseData>
- for Tsys
-{
-}
+impl ConnectorIntegration<Session, PaymentsSessionData, PaymentsResponseData> for Tsys {}
-impl ConnectorIntegration<api::AccessTokenAuth, types::AccessTokenRequestData, types::AccessToken>
- for Tsys
-{
-}
+impl ConnectorIntegration<AccessTokenAuth, AccessTokenRequestData, AccessToken> for Tsys {}
-impl
- ConnectorIntegration<
- api::SetupMandate,
- types::SetupMandateRequestData,
- types::PaymentsResponseData,
- > for Tsys
-{
+impl ConnectorIntegration<SetupMandate, SetupMandateRequestData, PaymentsResponseData> for Tsys {
fn build_request(
&self,
- _req: &types::RouterData<
- api::SetupMandate,
- types::SetupMandateRequestData,
- types::PaymentsResponseData,
- >,
- _connectors: &settings::Connectors,
- ) -> CustomResult<Option<services::Request>, errors::ConnectorError> {
+ _req: &RouterData<SetupMandate, SetupMandateRequestData, PaymentsResponseData>,
+ _connectors: &Connectors,
+ ) -> CustomResult<Option<Request>, errors::ConnectorError> {
Err(
errors::ConnectorError::NotImplemented("Setup Mandate flow for Tsys".to_string())
.into(),
@@ -131,14 +127,12 @@ impl
}
}
-impl ConnectorIntegration<api::Authorize, types::PaymentsAuthorizeData, types::PaymentsResponseData>
- for Tsys
-{
+impl ConnectorIntegration<Authorize, PaymentsAuthorizeData, PaymentsResponseData> for Tsys {
fn get_headers(
&self,
- req: &types::PaymentsAuthorizeRouterData,
- connectors: &settings::Connectors,
- ) -> CustomResult<Vec<(String, request::Maskable<String>)>, errors::ConnectorError> {
+ req: &PaymentsAuthorizeRouterData,
+ connectors: &Connectors,
+ ) -> CustomResult<Vec<(String, masking::Maskable<String>)>, errors::ConnectorError> {
self.build_headers(req, connectors)
}
@@ -148,8 +142,8 @@ impl ConnectorIntegration<api::Authorize, types::PaymentsAuthorizeData, types::P
fn get_url(
&self,
- _req: &types::PaymentsAuthorizeRouterData,
- connectors: &settings::Connectors,
+ _req: &PaymentsAuthorizeRouterData,
+ connectors: &Connectors,
) -> CustomResult<String, errors::ConnectorError> {
Ok(format!(
"{}servlets/transnox_api_server",
@@ -159,8 +153,8 @@ impl ConnectorIntegration<api::Authorize, types::PaymentsAuthorizeData, types::P
fn get_request_body(
&self,
- req: &types::PaymentsAuthorizeRouterData,
- _connectors: &settings::Connectors,
+ req: &PaymentsAuthorizeRouterData,
+ _connectors: &Connectors,
) -> CustomResult<RequestContent, errors::ConnectorError> {
let connector_req = tsys::TsysPaymentsRequest::try_from(req)?;
Ok(RequestContent::Json(Box::new(connector_req)))
@@ -168,20 +162,16 @@ impl ConnectorIntegration<api::Authorize, types::PaymentsAuthorizeData, types::P
fn build_request(
&self,
- req: &types::PaymentsAuthorizeRouterData,
- connectors: &settings::Connectors,
- ) -> CustomResult<Option<services::Request>, errors::ConnectorError> {
+ req: &PaymentsAuthorizeRouterData,
+ connectors: &Connectors,
+ ) -> CustomResult<Option<Request>, errors::ConnectorError> {
Ok(Some(
- services::RequestBuilder::new()
- .method(services::Method::Post)
- .url(&types::PaymentsAuthorizeType::get_url(
- self, req, connectors,
- )?)
+ RequestBuilder::new()
+ .method(Method::Post)
+ .url(&PaymentsAuthorizeType::get_url(self, req, connectors)?)
.attach_default_headers()
- .headers(types::PaymentsAuthorizeType::get_headers(
- self, req, connectors,
- )?)
- .set_body(types::PaymentsAuthorizeType::get_request_body(
+ .headers(PaymentsAuthorizeType::get_headers(self, req, connectors)?)
+ .set_body(PaymentsAuthorizeType::get_request_body(
self, req, connectors,
)?)
.build(),
@@ -190,10 +180,10 @@ impl ConnectorIntegration<api::Authorize, types::PaymentsAuthorizeData, types::P
fn handle_response(
&self,
- data: &types::PaymentsAuthorizeRouterData,
+ data: &PaymentsAuthorizeRouterData,
event_builder: Option<&mut ConnectorEvent>,
res: Response,
- ) -> CustomResult<types::PaymentsAuthorizeRouterData, errors::ConnectorError> {
+ ) -> CustomResult<PaymentsAuthorizeRouterData, errors::ConnectorError> {
let response: tsys::TsysPaymentsResponse = res
.response
.parse_struct("Tsys PaymentsAuthorizeResponse")
@@ -202,7 +192,7 @@ impl ConnectorIntegration<api::Authorize, types::PaymentsAuthorizeData, types::P
event_builder.map(|i| i.set_response_body(&response));
router_env::logger::info!(connector_response=?response);
- types::RouterData::try_from(types::ResponseRouterData {
+ RouterData::try_from(ResponseRouterData {
response,
data: data.clone(),
http_code: res.status_code,
@@ -218,14 +208,12 @@ impl ConnectorIntegration<api::Authorize, types::PaymentsAuthorizeData, types::P
}
}
-impl ConnectorIntegration<api::PSync, types::PaymentsSyncData, types::PaymentsResponseData>
- for Tsys
-{
+impl ConnectorIntegration<PSync, PaymentsSyncData, PaymentsResponseData> for Tsys {
fn get_headers(
&self,
- req: &types::PaymentsSyncRouterData,
- connectors: &settings::Connectors,
- ) -> CustomResult<Vec<(String, request::Maskable<String>)>, errors::ConnectorError> {
+ req: &PaymentsSyncRouterData,
+ connectors: &Connectors,
+ ) -> CustomResult<Vec<(String, masking::Maskable<String>)>, errors::ConnectorError> {
self.build_headers(req, connectors)
}
@@ -235,8 +223,8 @@ impl ConnectorIntegration<api::PSync, types::PaymentsSyncData, types::PaymentsRe
fn get_url(
&self,
- _req: &types::PaymentsSyncRouterData,
- connectors: &settings::Connectors,
+ _req: &PaymentsSyncRouterData,
+ connectors: &Connectors,
) -> CustomResult<String, errors::ConnectorError> {
Ok(format!(
"{}servlets/transnox_api_server",
@@ -246,8 +234,8 @@ impl ConnectorIntegration<api::PSync, types::PaymentsSyncData, types::PaymentsRe
fn get_request_body(
&self,
- req: &types::PaymentsSyncRouterData,
- _connectors: &settings::Connectors,
+ req: &PaymentsSyncRouterData,
+ _connectors: &Connectors,
) -> CustomResult<RequestContent, errors::ConnectorError> {
let connector_req = tsys::TsysSyncRequest::try_from(req)?;
Ok(RequestContent::Json(Box::new(connector_req)))
@@ -255,28 +243,26 @@ impl ConnectorIntegration<api::PSync, types::PaymentsSyncData, types::PaymentsRe
fn build_request(
&self,
- req: &types::PaymentsSyncRouterData,
- connectors: &settings::Connectors,
- ) -> CustomResult<Option<services::Request>, errors::ConnectorError> {
+ req: &PaymentsSyncRouterData,
+ connectors: &Connectors,
+ ) -> CustomResult<Option<Request>, errors::ConnectorError> {
Ok(Some(
- services::RequestBuilder::new()
- .method(services::Method::Post)
- .url(&types::PaymentsSyncType::get_url(self, req, connectors)?)
+ RequestBuilder::new()
+ .method(Method::Post)
+ .url(&PaymentsSyncType::get_url(self, req, connectors)?)
.attach_default_headers()
- .headers(types::PaymentsSyncType::get_headers(self, req, connectors)?)
- .set_body(types::PaymentsSyncType::get_request_body(
- self, req, connectors,
- )?)
+ .headers(PaymentsSyncType::get_headers(self, req, connectors)?)
+ .set_body(PaymentsSyncType::get_request_body(self, req, connectors)?)
.build(),
))
}
fn handle_response(
&self,
- data: &types::PaymentsSyncRouterData,
+ data: &PaymentsSyncRouterData,
event_builder: Option<&mut ConnectorEvent>,
res: Response,
- ) -> CustomResult<types::PaymentsSyncRouterData, errors::ConnectorError> {
+ ) -> CustomResult<PaymentsSyncRouterData, errors::ConnectorError> {
let response: tsys::TsysSyncResponse = res
.response
.parse_struct("tsys PaymentsSyncResponse")
@@ -285,7 +271,7 @@ impl ConnectorIntegration<api::PSync, types::PaymentsSyncData, types::PaymentsRe
event_builder.map(|i| i.set_response_body(&response));
router_env::logger::info!(connector_response=?response);
- types::RouterData::try_from(types::ResponseRouterData {
+ RouterData::try_from(ResponseRouterData {
response,
data: data.clone(),
http_code: res.status_code,
@@ -301,14 +287,12 @@ impl ConnectorIntegration<api::PSync, types::PaymentsSyncData, types::PaymentsRe
}
}
-impl ConnectorIntegration<api::Capture, types::PaymentsCaptureData, types::PaymentsResponseData>
- for Tsys
-{
+impl ConnectorIntegration<Capture, PaymentsCaptureData, PaymentsResponseData> for Tsys {
fn get_headers(
&self,
- req: &types::PaymentsCaptureRouterData,
- connectors: &settings::Connectors,
- ) -> CustomResult<Vec<(String, request::Maskable<String>)>, errors::ConnectorError> {
+ req: &PaymentsCaptureRouterData,
+ connectors: &Connectors,
+ ) -> CustomResult<Vec<(String, masking::Maskable<String>)>, errors::ConnectorError> {
self.build_headers(req, connectors)
}
@@ -318,8 +302,8 @@ impl ConnectorIntegration<api::Capture, types::PaymentsCaptureData, types::Payme
fn get_url(
&self,
- _req: &types::PaymentsCaptureRouterData,
- connectors: &settings::Connectors,
+ _req: &PaymentsCaptureRouterData,
+ connectors: &Connectors,
) -> CustomResult<String, errors::ConnectorError> {
Ok(format!(
"{}servlets/transnox_api_server",
@@ -329,8 +313,8 @@ impl ConnectorIntegration<api::Capture, types::PaymentsCaptureData, types::Payme
fn get_request_body(
&self,
- req: &types::PaymentsCaptureRouterData,
- _connectors: &settings::Connectors,
+ req: &PaymentsCaptureRouterData,
+ _connectors: &Connectors,
) -> CustomResult<RequestContent, errors::ConnectorError> {
let connector_req = tsys::TsysPaymentsCaptureRequest::try_from(req)?;
Ok(RequestContent::Json(Box::new(connector_req)))
@@ -338,18 +322,16 @@ impl ConnectorIntegration<api::Capture, types::PaymentsCaptureData, types::Payme
fn build_request(
&self,
- req: &types::PaymentsCaptureRouterData,
- connectors: &settings::Connectors,
- ) -> CustomResult<Option<services::Request>, errors::ConnectorError> {
+ req: &PaymentsCaptureRouterData,
+ connectors: &Connectors,
+ ) -> CustomResult<Option<Request>, errors::ConnectorError> {
Ok(Some(
- services::RequestBuilder::new()
- .method(services::Method::Post)
- .url(&types::PaymentsCaptureType::get_url(self, req, connectors)?)
+ RequestBuilder::new()
+ .method(Method::Post)
+ .url(&PaymentsCaptureType::get_url(self, req, connectors)?)
.attach_default_headers()
- .headers(types::PaymentsCaptureType::get_headers(
- self, req, connectors,
- )?)
- .set_body(types::PaymentsCaptureType::get_request_body(
+ .headers(PaymentsCaptureType::get_headers(self, req, connectors)?)
+ .set_body(PaymentsCaptureType::get_request_body(
self, req, connectors,
)?)
.build(),
@@ -358,10 +340,10 @@ impl ConnectorIntegration<api::Capture, types::PaymentsCaptureData, types::Payme
fn handle_response(
&self,
- data: &types::PaymentsCaptureRouterData,
+ data: &PaymentsCaptureRouterData,
event_builder: Option<&mut ConnectorEvent>,
res: Response,
- ) -> CustomResult<types::PaymentsCaptureRouterData, errors::ConnectorError> {
+ ) -> CustomResult<PaymentsCaptureRouterData, errors::ConnectorError> {
let response: tsys::TsysPaymentsResponse = res
.response
.parse_struct("Tsys PaymentsCaptureResponse")
@@ -370,7 +352,7 @@ impl ConnectorIntegration<api::Capture, types::PaymentsCaptureData, types::Payme
event_builder.map(|i| i.set_response_body(&response));
router_env::logger::info!(connector_response=?response);
- types::RouterData::try_from(types::ResponseRouterData {
+ RouterData::try_from(ResponseRouterData {
response,
data: data.clone(),
http_code: res.status_code,
@@ -386,14 +368,12 @@ impl ConnectorIntegration<api::Capture, types::PaymentsCaptureData, types::Payme
}
}
-impl ConnectorIntegration<api::Void, types::PaymentsCancelData, types::PaymentsResponseData>
- for Tsys
-{
+impl ConnectorIntegration<Void, PaymentsCancelData, PaymentsResponseData> for Tsys {
fn get_headers(
&self,
- req: &types::PaymentsCancelRouterData,
- connectors: &settings::Connectors,
- ) -> CustomResult<Vec<(String, request::Maskable<String>)>, errors::ConnectorError> {
+ req: &PaymentsCancelRouterData,
+ connectors: &Connectors,
+ ) -> CustomResult<Vec<(String, masking::Maskable<String>)>, errors::ConnectorError> {
self.build_headers(req, connectors)
}
@@ -403,8 +383,8 @@ impl ConnectorIntegration<api::Void, types::PaymentsCancelData, types::PaymentsR
fn get_url(
&self,
- _req: &types::PaymentsCancelRouterData,
- connectors: &settings::Connectors,
+ _req: &PaymentsCancelRouterData,
+ connectors: &Connectors,
) -> CustomResult<String, errors::ConnectorError> {
Ok(format!(
"{}servlets/transnox_api_server",
@@ -413,8 +393,8 @@ impl ConnectorIntegration<api::Void, types::PaymentsCancelData, types::PaymentsR
}
fn get_request_body(
&self,
- req: &types::PaymentsCancelRouterData,
- _connectors: &settings::Connectors,
+ req: &PaymentsCancelRouterData,
+ _connectors: &Connectors,
) -> CustomResult<RequestContent, errors::ConnectorError> {
let connector_req = tsys::TsysPaymentsCancelRequest::try_from(req)?;
Ok(RequestContent::Json(Box::new(connector_req)))
@@ -422,16 +402,14 @@ impl ConnectorIntegration<api::Void, types::PaymentsCancelData, types::PaymentsR
fn build_request(
&self,
- req: &types::PaymentsCancelRouterData,
- connectors: &settings::Connectors,
- ) -> CustomResult<Option<services::Request>, errors::ConnectorError> {
- let request = services::RequestBuilder::new()
- .method(services::Method::Post)
- .url(&types::PaymentsVoidType::get_url(self, req, connectors)?)
- .headers(types::PaymentsVoidType::get_headers(self, req, connectors)?)
- .set_body(types::PaymentsVoidType::get_request_body(
- self, req, connectors,
- )?)
+ req: &PaymentsCancelRouterData,
+ connectors: &Connectors,
+ ) -> CustomResult<Option<Request>, errors::ConnectorError> {
+ let request = RequestBuilder::new()
+ .method(Method::Post)
+ .url(&PaymentsVoidType::get_url(self, req, connectors)?)
+ .headers(PaymentsVoidType::get_headers(self, req, connectors)?)
+ .set_body(PaymentsVoidType::get_request_body(self, req, connectors)?)
.build();
Ok(Some(request))
@@ -439,10 +417,10 @@ impl ConnectorIntegration<api::Void, types::PaymentsCancelData, types::PaymentsR
fn handle_response(
&self,
- data: &types::PaymentsCancelRouterData,
+ data: &PaymentsCancelRouterData,
event_builder: Option<&mut ConnectorEvent>,
res: Response,
- ) -> CustomResult<types::PaymentsCancelRouterData, errors::ConnectorError> {
+ ) -> CustomResult<PaymentsCancelRouterData, errors::ConnectorError> {
let response: tsys::TsysPaymentsResponse = res
.response
.parse_struct("PaymentCancelResponse")
@@ -451,7 +429,7 @@ impl ConnectorIntegration<api::Void, types::PaymentsCancelData, types::PaymentsR
event_builder.map(|i| i.set_response_body(&response));
router_env::logger::info!(connector_response=?response);
- types::RouterData::try_from(types::ResponseRouterData {
+ RouterData::try_from(ResponseRouterData {
response,
data: data.clone(),
http_code: res.status_code,
@@ -466,12 +444,12 @@ impl ConnectorIntegration<api::Void, types::PaymentsCancelData, types::PaymentsR
}
}
-impl ConnectorIntegration<api::Execute, types::RefundsData, types::RefundsResponseData> for Tsys {
+impl ConnectorIntegration<Execute, RefundsData, RefundsResponseData> for Tsys {
fn get_headers(
&self,
- req: &types::RefundsRouterData<api::Execute>,
- connectors: &settings::Connectors,
- ) -> CustomResult<Vec<(String, request::Maskable<String>)>, errors::ConnectorError> {
+ req: &RefundsRouterData<Execute>,
+ connectors: &Connectors,
+ ) -> CustomResult<Vec<(String, masking::Maskable<String>)>, errors::ConnectorError> {
self.build_headers(req, connectors)
}
@@ -481,8 +459,8 @@ impl ConnectorIntegration<api::Execute, types::RefundsData, types::RefundsRespon
fn get_url(
&self,
- _req: &types::RefundsRouterData<api::Execute>,
- connectors: &settings::Connectors,
+ _req: &RefundsRouterData<Execute>,
+ connectors: &Connectors,
) -> CustomResult<String, errors::ConnectorError> {
Ok(format!(
"{}servlets/transnox_api_server",
@@ -492,8 +470,8 @@ impl ConnectorIntegration<api::Execute, types::RefundsData, types::RefundsRespon
fn get_request_body(
&self,
- req: &types::RefundsRouterData<api::Execute>,
- _connectors: &settings::Connectors,
+ req: &RefundsRouterData<Execute>,
+ _connectors: &Connectors,
) -> CustomResult<RequestContent, errors::ConnectorError> {
let connector_req = tsys::TsysRefundRequest::try_from(req)?;
Ok(RequestContent::Json(Box::new(connector_req)))
@@ -501,29 +479,25 @@ impl ConnectorIntegration<api::Execute, types::RefundsData, types::RefundsRespon
fn build_request(
&self,
- req: &types::RefundsRouterData<api::Execute>,
- connectors: &settings::Connectors,
- ) -> CustomResult<Option<services::Request>, errors::ConnectorError> {
- let request = services::RequestBuilder::new()
- .method(services::Method::Post)
- .url(&types::RefundExecuteType::get_url(self, req, connectors)?)
+ req: &RefundsRouterData<Execute>,
+ connectors: &Connectors,
+ ) -> CustomResult<Option<Request>, errors::ConnectorError> {
+ let request = RequestBuilder::new()
+ .method(Method::Post)
+ .url(&RefundExecuteType::get_url(self, req, connectors)?)
.attach_default_headers()
- .headers(types::RefundExecuteType::get_headers(
- self, req, connectors,
- )?)
- .set_body(types::RefundExecuteType::get_request_body(
- self, req, connectors,
- )?)
+ .headers(RefundExecuteType::get_headers(self, req, connectors)?)
+ .set_body(RefundExecuteType::get_request_body(self, req, connectors)?)
.build();
Ok(Some(request))
}
fn handle_response(
&self,
- data: &types::RefundsRouterData<api::Execute>,
+ data: &RefundsRouterData<Execute>,
event_builder: Option<&mut ConnectorEvent>,
res: Response,
- ) -> CustomResult<types::RefundsRouterData<api::Execute>, errors::ConnectorError> {
+ ) -> CustomResult<RefundsRouterData<Execute>, errors::ConnectorError> {
let response: tsys::RefundResponse = res
.response
.parse_struct("tsys RefundResponse")
@@ -532,7 +506,7 @@ impl ConnectorIntegration<api::Execute, types::RefundsData, types::RefundsRespon
event_builder.map(|i| i.set_response_body(&response));
router_env::logger::info!(connector_response=?response);
- types::RouterData::try_from(types::ResponseRouterData {
+ RouterData::try_from(ResponseRouterData {
response,
data: data.clone(),
http_code: res.status_code,
@@ -548,12 +522,12 @@ impl ConnectorIntegration<api::Execute, types::RefundsData, types::RefundsRespon
}
}
-impl ConnectorIntegration<api::RSync, types::RefundsData, types::RefundsResponseData> for Tsys {
+impl ConnectorIntegration<RSync, RefundsData, RefundsResponseData> for Tsys {
fn get_headers(
&self,
- req: &types::RefundSyncRouterData,
- connectors: &settings::Connectors,
- ) -> CustomResult<Vec<(String, request::Maskable<String>)>, errors::ConnectorError> {
+ req: &RefundSyncRouterData,
+ connectors: &Connectors,
+ ) -> CustomResult<Vec<(String, masking::Maskable<String>)>, errors::ConnectorError> {
self.build_headers(req, connectors)
}
@@ -563,8 +537,8 @@ impl ConnectorIntegration<api::RSync, types::RefundsData, types::RefundsResponse
fn get_url(
&self,
- _req: &types::RefundSyncRouterData,
- connectors: &settings::Connectors,
+ _req: &RefundSyncRouterData,
+ connectors: &Connectors,
) -> CustomResult<String, errors::ConnectorError> {
Ok(format!(
"{}servlets/transnox_api_server",
@@ -574,8 +548,8 @@ impl ConnectorIntegration<api::RSync, types::RefundsData, types::RefundsResponse
fn get_request_body(
&self,
- req: &types::RefundSyncRouterData,
- _connectors: &settings::Connectors,
+ req: &RefundSyncRouterData,
+ _connectors: &Connectors,
) -> CustomResult<RequestContent, errors::ConnectorError> {
let connector_req = tsys::TsysSyncRequest::try_from(req)?;
Ok(RequestContent::Json(Box::new(connector_req)))
@@ -583,28 +557,26 @@ impl ConnectorIntegration<api::RSync, types::RefundsData, types::RefundsResponse
fn build_request(
&self,
- req: &types::RefundSyncRouterData,
- connectors: &settings::Connectors,
- ) -> CustomResult<Option<services::Request>, errors::ConnectorError> {
+ req: &RefundSyncRouterData,
+ connectors: &Connectors,
+ ) -> CustomResult<Option<Request>, errors::ConnectorError> {
Ok(Some(
- services::RequestBuilder::new()
- .method(services::Method::Post)
- .url(&types::RefundSyncType::get_url(self, req, connectors)?)
+ RequestBuilder::new()
+ .method(Method::Post)
+ .url(&RefundSyncType::get_url(self, req, connectors)?)
.attach_default_headers()
- .headers(types::RefundSyncType::get_headers(self, req, connectors)?)
- .set_body(types::RefundSyncType::get_request_body(
- self, req, connectors,
- )?)
+ .headers(RefundSyncType::get_headers(self, req, connectors)?)
+ .set_body(RefundSyncType::get_request_body(self, req, connectors)?)
.build(),
))
}
fn handle_response(
&self,
- data: &types::RefundSyncRouterData,
+ data: &RefundSyncRouterData,
event_builder: Option<&mut ConnectorEvent>,
res: Response,
- ) -> CustomResult<types::RefundSyncRouterData, errors::ConnectorError> {
+ ) -> CustomResult<RefundSyncRouterData, errors::ConnectorError> {
let response: tsys::TsysSyncResponse = res
.response
.parse_struct("tsys RefundSyncResponse")
@@ -613,7 +585,7 @@ impl ConnectorIntegration<api::RSync, types::RefundsData, types::RefundsResponse
event_builder.map(|i| i.set_response_body(&response));
router_env::logger::info!(connector_response=?response);
- types::RouterData::try_from(types::ResponseRouterData {
+ RouterData::try_from(ResponseRouterData {
response,
data: data.clone(),
http_code: res.status_code,
@@ -630,24 +602,24 @@ impl ConnectorIntegration<api::RSync, types::RefundsData, types::RefundsResponse
}
#[async_trait::async_trait]
-impl api::IncomingWebhook for Tsys {
+impl webhooks::IncomingWebhook for Tsys {
fn get_webhook_object_reference_id(
&self,
- _request: &api::IncomingWebhookRequestDetails<'_>,
- ) -> CustomResult<api::webhooks::ObjectReferenceId, errors::ConnectorError> {
+ _request: &webhooks::IncomingWebhookRequestDetails<'_>,
+ ) -> CustomResult<api_models::webhooks::ObjectReferenceId, errors::ConnectorError> {
Err(report!(errors::ConnectorError::WebhooksNotImplemented))
}
fn get_webhook_event_type(
&self,
- _request: &api::IncomingWebhookRequestDetails<'_>,
- ) -> CustomResult<api::IncomingWebhookEvent, errors::ConnectorError> {
+ _request: &webhooks::IncomingWebhookRequestDetails<'_>,
+ ) -> CustomResult<api_models::webhooks::IncomingWebhookEvent, errors::ConnectorError> {
Err(report!(errors::ConnectorError::WebhooksNotImplemented))
}
fn get_webhook_resource_object(
&self,
- _request: &api::IncomingWebhookRequestDetails<'_>,
+ _request: &webhooks::IncomingWebhookRequestDetails<'_>,
) -> CustomResult<Box<dyn masking::ErasedMaskSerialize>, errors::ConnectorError> {
Err(report!(errors::ConnectorError::WebhooksNotImplemented))
}
diff --git a/crates/router/src/connector/tsys/transformers.rs b/crates/hyperswitch_connectors/src/connectors/tsys/transformers.rs
similarity index 81%
rename from crates/router/src/connector/tsys/transformers.rs
rename to crates/hyperswitch_connectors/src/connectors/tsys/transformers.rs
index 347a95151d5..8d96058c233 100644
--- a/crates/router/src/connector/tsys/transformers.rs
+++ b/crates/hyperswitch_connectors/src/connectors/tsys/transformers.rs
@@ -1,11 +1,23 @@
+use common_enums::enums;
use error_stack::ResultExt;
+use hyperswitch_domain_models::{
+ payment_method_data::PaymentMethodData,
+ router_data::{self, ConnectorAuthType, RouterData},
+ router_flow_types::refunds::{Execute, RSync},
+ router_request_types::ResponseId,
+ router_response_types::{PaymentsResponseData, RefundsResponseData},
+ types::{
+ self, PaymentsCancelRouterData, PaymentsCaptureRouterData, PaymentsSyncRouterData,
+ RefundSyncRouterData, RefundsRouterData,
+ },
+};
+use hyperswitch_interfaces::errors;
use masking::Secret;
use serde::{Deserialize, Serialize};
use crate::{
- connector::utils::{self, CardData, PaymentsAuthorizeRequestData, RefundsRequestData},
- core::errors,
- types::{self, api, domain, storage::enums},
+ types::{RefundsResponseRouterData, ResponseRouterData},
+ utils::{self, CardData as _, PaymentsAuthorizeRequestData, RefundsRequestData as _},
};
#[derive(Debug, Serialize)]
@@ -38,7 +50,7 @@ impl TryFrom<&types::PaymentsAuthorizeRouterData> for TsysPaymentsRequest {
type Error = error_stack::Report<errors::ConnectorError>;
fn try_from(item: &types::PaymentsAuthorizeRouterData) -> Result<Self, Self::Error> {
match item.request.payment_method_data.clone() {
- domain::PaymentMethodData::Card(ccard) => {
+ PaymentMethodData::Card(ccard) => {
let connector_auth: TsysAuthType =
TsysAuthType::try_from(&item.connector_auth_type)?;
let auth_data: TsysPaymentAuthSaleRequest = TsysPaymentAuthSaleRequest {
@@ -63,26 +75,24 @@ impl TryFrom<&types::PaymentsAuthorizeRouterData> for TsysPaymentsRequest {
Ok(Self::Auth(auth_data))
}
}
- domain::PaymentMethodData::CardRedirect(_)
- | domain::PaymentMethodData::Wallet(_)
- | domain::PaymentMethodData::PayLater(_)
- | domain::PaymentMethodData::BankRedirect(_)
- | domain::PaymentMethodData::BankDebit(_)
- | domain::PaymentMethodData::BankTransfer(_)
- | domain::PaymentMethodData::Crypto(_)
- | domain::PaymentMethodData::MandatePayment
- | domain::PaymentMethodData::Reward
- | domain::PaymentMethodData::RealTimePayment(_)
- | domain::PaymentMethodData::Upi(_)
- | domain::PaymentMethodData::Voucher(_)
- | domain::PaymentMethodData::GiftCard(_)
- | domain::PaymentMethodData::OpenBanking(_)
- | domain::PaymentMethodData::CardToken(_)
- | domain::PaymentMethodData::NetworkToken(_) => {
- Err(errors::ConnectorError::NotImplemented(
- utils::get_unimplemented_payment_method_error_message("tsys"),
- ))?
- }
+ PaymentMethodData::CardRedirect(_)
+ | PaymentMethodData::Wallet(_)
+ | PaymentMethodData::PayLater(_)
+ | PaymentMethodData::BankRedirect(_)
+ | PaymentMethodData::BankDebit(_)
+ | PaymentMethodData::BankTransfer(_)
+ | PaymentMethodData::Crypto(_)
+ | PaymentMethodData::MandatePayment
+ | PaymentMethodData::Reward
+ | PaymentMethodData::RealTimePayment(_)
+ | PaymentMethodData::Upi(_)
+ | PaymentMethodData::Voucher(_)
+ | PaymentMethodData::GiftCard(_)
+ | PaymentMethodData::OpenBanking(_)
+ | PaymentMethodData::CardToken(_)
+ | PaymentMethodData::NetworkToken(_) => Err(errors::ConnectorError::NotImplemented(
+ utils::get_unimplemented_payment_method_error_message("tsys"),
+ ))?,
}
}
}
@@ -94,11 +104,11 @@ pub struct TsysAuthType {
pub(super) developer_id: Secret<String>,
}
-impl TryFrom<&types::ConnectorAuthType> for TsysAuthType {
+impl TryFrom<&ConnectorAuthType> for TsysAuthType {
type Error = error_stack::Report<errors::ConnectorError>;
- fn try_from(auth_type: &types::ConnectorAuthType) -> Result<Self, Self::Error> {
+ fn try_from(auth_type: &ConnectorAuthType) -> Result<Self, Self::Error> {
match auth_type {
- types::ConnectorAuthType::SignatureKey {
+ ConnectorAuthType::SignatureKey {
api_key,
key1,
api_secret,
@@ -199,8 +209,8 @@ pub enum TsysPaymentsResponse {
fn get_error_response(
connector_response: TsysErrorResponse,
status_code: u16,
-) -> types::ErrorResponse {
- types::ErrorResponse {
+) -> router_data::ErrorResponse {
+ router_data::ErrorResponse {
code: connector_response.response_code,
message: connector_response.response_message.clone(),
reason: Some(connector_response.response_message),
@@ -210,11 +220,9 @@ fn get_error_response(
}
}
-fn get_payments_response(connector_response: TsysResponse) -> types::PaymentsResponseData {
- types::PaymentsResponseData::TransactionResponse {
- resource_id: types::ResponseId::ConnectorTransactionId(
- connector_response.transaction_id.clone(),
- ),
+fn get_payments_response(connector_response: TsysResponse) -> PaymentsResponseData {
+ PaymentsResponseData::TransactionResponse {
+ resource_id: ResponseId::ConnectorTransactionId(connector_response.transaction_id.clone()),
redirection_data: None,
mandate_reference: None,
connector_metadata: None,
@@ -227,9 +235,9 @@ fn get_payments_response(connector_response: TsysResponse) -> types::PaymentsRes
fn get_payments_sync_response(
connector_response: &TsysPaymentsSyncResponse,
-) -> types::PaymentsResponseData {
- types::PaymentsResponseData::TransactionResponse {
- resource_id: types::ResponseId::ConnectorTransactionId(
+) -> PaymentsResponseData {
+ PaymentsResponseData::TransactionResponse {
+ resource_id: ResponseId::ConnectorTransactionId(
connector_response
.transaction_details
.transaction_id
@@ -250,13 +258,12 @@ fn get_payments_sync_response(
}
}
-impl<F, T>
- TryFrom<types::ResponseRouterData<F, TsysPaymentsResponse, T, types::PaymentsResponseData>>
- for types::RouterData<F, T, types::PaymentsResponseData>
+impl<F, T> TryFrom<ResponseRouterData<F, TsysPaymentsResponse, T, PaymentsResponseData>>
+ for RouterData<F, T, PaymentsResponseData>
{
type Error = error_stack::Report<errors::ConnectorError>;
fn try_from(
- item: types::ResponseRouterData<F, TsysPaymentsResponse, T, types::PaymentsResponseData>,
+ item: ResponseRouterData<F, TsysPaymentsResponse, T, PaymentsResponseData>,
) -> Result<Self, Self::Error> {
let (response, status) = match item.response {
TsysPaymentsResponse::AuthResponse(resp) => match resp {
@@ -326,9 +333,9 @@ pub struct TsysSyncRequest {
search_transaction: TsysSearchTransactionRequest,
}
-impl TryFrom<&types::PaymentsSyncRouterData> for TsysSyncRequest {
+impl TryFrom<&PaymentsSyncRouterData> for TsysSyncRequest {
type Error = error_stack::Report<errors::ConnectorError>;
- fn try_from(item: &types::PaymentsSyncRouterData) -> Result<Self, Self::Error> {
+ fn try_from(item: &PaymentsSyncRouterData) -> Result<Self, Self::Error> {
let connector_auth: TsysAuthType = TsysAuthType::try_from(&item.connector_auth_type)?;
let search_transaction = TsysSearchTransactionRequest {
device_id: connector_auth.device_id,
@@ -357,12 +364,12 @@ pub struct TsysSyncResponse {
search_transaction_response: SearchResponseTypes,
}
-impl<F, T> TryFrom<types::ResponseRouterData<F, TsysSyncResponse, T, types::PaymentsResponseData>>
- for types::RouterData<F, T, types::PaymentsResponseData>
+impl<F, T> TryFrom<ResponseRouterData<F, TsysSyncResponse, T, PaymentsResponseData>>
+ for RouterData<F, T, PaymentsResponseData>
{
type Error = error_stack::Report<errors::ConnectorError>;
fn try_from(
- item: types::ResponseRouterData<F, TsysSyncResponse, T, types::PaymentsResponseData>,
+ item: ResponseRouterData<F, TsysSyncResponse, T, PaymentsResponseData>,
) -> Result<Self, Self::Error> {
let tsys_search_response = item.response.search_transaction_response;
let (response, status) = match tsys_search_response {
@@ -400,9 +407,9 @@ pub struct TsysCancelRequest {
pub struct TsysPaymentsCancelRequest {
void: TsysCancelRequest,
}
-impl TryFrom<&types::PaymentsCancelRouterData> for TsysPaymentsCancelRequest {
+impl TryFrom<&PaymentsCancelRouterData> for TsysPaymentsCancelRequest {
type Error = error_stack::Report<errors::ConnectorError>;
- fn try_from(item: &types::PaymentsCancelRouterData) -> Result<Self, Self::Error> {
+ fn try_from(item: &PaymentsCancelRouterData) -> Result<Self, Self::Error> {
let connector_auth: TsysAuthType = TsysAuthType::try_from(&item.connector_auth_type)?;
let void = TsysCancelRequest {
device_id: connector_auth.device_id,
@@ -434,9 +441,9 @@ pub struct TsysPaymentsCaptureRequest {
capture: TsysCaptureRequest,
}
-impl TryFrom<&types::PaymentsCaptureRouterData> for TsysPaymentsCaptureRequest {
+impl TryFrom<&PaymentsCaptureRouterData> for TsysPaymentsCaptureRequest {
type Error = error_stack::Report<errors::ConnectorError>;
- fn try_from(item: &types::PaymentsCaptureRouterData) -> Result<Self, Self::Error> {
+ fn try_from(item: &PaymentsCaptureRouterData) -> Result<Self, Self::Error> {
let connector_auth: TsysAuthType = TsysAuthType::try_from(&item.connector_auth_type)?;
let capture = TsysCaptureRequest {
device_id: connector_auth.device_id,
@@ -468,9 +475,9 @@ pub struct TsysRefundRequest {
return_request: TsysReturnRequest,
}
-impl<F> TryFrom<&types::RefundsRouterData<F>> for TsysRefundRequest {
+impl<F> TryFrom<&RefundsRouterData<F>> for TsysRefundRequest {
type Error = error_stack::Report<errors::ConnectorError>;
- fn try_from(item: &types::RefundsRouterData<F>) -> Result<Self, Self::Error> {
+ fn try_from(item: &RefundsRouterData<F>) -> Result<Self, Self::Error> {
let connector_auth: TsysAuthType = TsysAuthType::try_from(&item.connector_auth_type)?;
let return_request = TsysReturnRequest {
device_id: connector_auth.device_id,
@@ -508,16 +515,14 @@ pub struct RefundResponse {
return_response: TsysResponseTypes,
}
-impl TryFrom<types::RefundsResponseRouterData<api::Execute, RefundResponse>>
- for types::RefundsRouterData<api::Execute>
-{
+impl TryFrom<RefundsResponseRouterData<Execute, RefundResponse>> for RefundsRouterData<Execute> {
type Error = error_stack::Report<errors::ConnectorError>;
fn try_from(
- item: types::RefundsResponseRouterData<api::Execute, RefundResponse>,
+ item: RefundsResponseRouterData<Execute, RefundResponse>,
) -> Result<Self, Self::Error> {
let tsys_return_response = item.response.return_response;
let response = match tsys_return_response {
- TsysResponseTypes::SuccessResponse(return_response) => Ok(types::RefundsResponseData {
+ TsysResponseTypes::SuccessResponse(return_response) => Ok(RefundsResponseData {
connector_refund_id: return_response.transaction_id,
refund_status: enums::RefundStatus::from(return_response.status),
}),
@@ -532,9 +537,9 @@ impl TryFrom<types::RefundsResponseRouterData<api::Execute, RefundResponse>>
}
}
-impl TryFrom<&types::RefundSyncRouterData> for TsysSyncRequest {
+impl TryFrom<&RefundSyncRouterData> for TsysSyncRequest {
type Error = error_stack::Report<errors::ConnectorError>;
- fn try_from(item: &types::RefundSyncRouterData) -> Result<Self, Self::Error> {
+ fn try_from(item: &RefundSyncRouterData) -> Result<Self, Self::Error> {
let connector_auth: TsysAuthType = TsysAuthType::try_from(&item.connector_auth_type)?;
let search_transaction = TsysSearchTransactionRequest {
device_id: connector_auth.device_id,
@@ -546,21 +551,17 @@ impl TryFrom<&types::RefundSyncRouterData> for TsysSyncRequest {
}
}
-impl TryFrom<types::RefundsResponseRouterData<api::RSync, TsysSyncResponse>>
- for types::RefundsRouterData<api::RSync>
-{
+impl TryFrom<RefundsResponseRouterData<RSync, TsysSyncResponse>> for RefundsRouterData<RSync> {
type Error = error_stack::Report<errors::ConnectorError>;
fn try_from(
- item: types::RefundsResponseRouterData<api::RSync, TsysSyncResponse>,
+ item: RefundsResponseRouterData<RSync, TsysSyncResponse>,
) -> Result<Self, Self::Error> {
let tsys_search_response = item.response.search_transaction_response;
let response = match tsys_search_response {
- SearchResponseTypes::SuccessResponse(search_response) => {
- Ok(types::RefundsResponseData {
- connector_refund_id: search_response.transaction_details.transaction_id.clone(),
- refund_status: enums::RefundStatus::from(search_response.transaction_details),
- })
- }
+ SearchResponseTypes::SuccessResponse(search_response) => Ok(RefundsResponseData {
+ connector_refund_id: search_response.transaction_details.transaction_id.clone(),
+ refund_status: enums::RefundStatus::from(search_response.transaction_details),
+ }),
SearchResponseTypes::ErrorResponse(connector_response) => {
Err(get_error_response(connector_response, item.http_code))
}
diff --git a/crates/router/src/connector/worldline.rs b/crates/hyperswitch_connectors/src/connectors/worldline.rs
similarity index 65%
rename from crates/router/src/connector/worldline.rs
rename to crates/hyperswitch_connectors/src/connectors/worldline.rs
index 6c8e1a1e951..c5a8466175c 100644
--- a/crates/router/src/connector/worldline.rs
+++ b/crates/hyperswitch_connectors/src/connectors/worldline.rs
@@ -3,32 +3,56 @@ pub mod transformers;
use std::fmt::Debug;
use base64::Engine;
-use common_utils::{ext_traits::ByteSliceExt, request::RequestContent};
-use diesel_models::enums;
+use common_enums::enums;
+use common_utils::{
+ consts, crypto,
+ errors::CustomResult,
+ ext_traits::{ByteSliceExt, OptionExt},
+ request::{Method, Request, RequestBuilder, RequestContent},
+};
use error_stack::ResultExt;
-use masking::{ExposeInterface, PeekInterface};
+use hyperswitch_domain_models::{
+ router_data::{AccessToken, ErrorResponse, RouterData},
+ router_flow_types::{
+ access_token_auth::AccessTokenAuth,
+ payments::{Authorize, Capture, PSync, PaymentMethodToken, Session, SetupMandate, Void},
+ refunds::{Execute, RSync},
+ },
+ router_request_types::{
+ AccessTokenRequestData, PaymentMethodTokenizationData, PaymentsAuthorizeData,
+ PaymentsCancelData, PaymentsCaptureData, PaymentsSessionData, PaymentsSyncData,
+ RefundsData, SetupMandateRequestData,
+ },
+ router_response_types::{PaymentsResponseData, RefundsResponseData},
+ types::{
+ PaymentsAuthorizeRouterData, PaymentsCancelRouterData, PaymentsSyncRouterData,
+ RefundSyncRouterData, RefundsRouterData,
+ },
+};
+use hyperswitch_interfaces::{
+ api::{
+ self, ConnectorCommon, ConnectorCommonExt, ConnectorIntegration, ConnectorValidation,
+ PaymentCapture, PaymentSync,
+ },
+ configs::Connectors,
+ errors,
+ events::connector_api_logs::ConnectorEvent,
+ types::{
+ PaymentsAuthorizeType, PaymentsCaptureType, PaymentsSyncType, PaymentsVoidType,
+ RefundExecuteType, RefundSyncType, Response,
+ },
+ webhooks,
+};
+use masking::{ExposeInterface, Mask, PeekInterface};
use ring::hmac;
+use router_env::logger;
use time::{format_description, OffsetDateTime};
use transformers as worldline;
-use super::utils::{self as connector_utils, RefundsRequestData};
use crate::{
- configs::settings::Connectors,
- consts,
- core::errors::{self, CustomResult},
- events::connector_api_logs::ConnectorEvent,
- headers, logger,
- services::{
- self,
- request::{self, Mask},
- ConnectorIntegration, ConnectorValidation,
- },
- types::{
- self,
- api::{self, ConnectorCommon, ConnectorCommonExt},
- ErrorResponse,
- },
- utils::{crypto, BytesExt, OptionExt},
+ constants::headers,
+ types::ResponseRouterData,
+ utils::{self, RefundsRequestData as _},
};
#[derive(Debug, Clone)]
@@ -38,7 +62,7 @@ impl Worldline {
pub fn generate_authorization_token(
&self,
auth: worldline::WorldlineAuthType,
- http_method: &services::Method,
+ http_method: &Method,
content_type: &str,
date: &str,
endpoint: &str,
@@ -78,9 +102,9 @@ where
{
fn build_headers(
&self,
- req: &types::RouterData<Flow, Request, Response>,
+ req: &RouterData<Flow, Request, Response>,
connectors: &Connectors,
- ) -> CustomResult<Vec<(String, request::Maskable<String>)>, errors::ConnectorError> {
+ ) -> CustomResult<Vec<(String, masking::Maskable<String>)>, errors::ConnectorError> {
let base_url = self.base_url(connectors);
let url = Self::get_url(self, req, connectors)?;
let endpoint = url.replace(base_url, "");
@@ -120,7 +144,7 @@ impl ConnectorCommon for Worldline {
fn build_error_response(
&self,
- res: types::Response,
+ res: Response,
event_builder: Option<&mut ConnectorEvent>,
) -> CustomResult<ErrorResponse, errors::ConnectorError> {
let response: worldline::ErrorResponse = res
@@ -129,17 +153,17 @@ impl ConnectorCommon for Worldline {
.change_context(errors::ConnectorError::ResponseDeserializationFailed)?;
event_builder.map(|i| i.set_error_response_body(&response));
- router_env::logger::info!(connector_response=?response);
+ logger::info!(connector_response=?response);
let error = response.errors.into_iter().next().unwrap_or_default();
Ok(ErrorResponse {
status_code: res.status_code,
code: error
.code
- .unwrap_or_else(|| consts::NO_ERROR_CODE.to_string()),
+ .unwrap_or_else(|| hyperswitch_interfaces::consts::NO_ERROR_CODE.to_string()),
message: error
.message
- .unwrap_or_else(|| consts::NO_ERROR_MESSAGE.to_string()),
+ .unwrap_or_else(|| hyperswitch_interfaces::consts::NO_ERROR_MESSAGE.to_string()),
..Default::default()
})
}
@@ -155,7 +179,7 @@ impl ConnectorValidation for Worldline {
match capture_method {
enums::CaptureMethod::Automatic | enums::CaptureMethod::Manual => Ok(()),
enums::CaptureMethod::ManualMultiple | enums::CaptureMethod::Scheduled => Err(
- connector_utils::construct_not_implemented_error_report(capture_method, self.id()),
+ utils::construct_not_implemented_error_report(capture_method, self.id()),
),
}
}
@@ -163,30 +187,19 @@ impl ConnectorValidation for Worldline {
impl api::ConnectorAccessToken for Worldline {}
-impl ConnectorIntegration<api::AccessTokenAuth, types::AccessTokenRequestData, types::AccessToken>
- for Worldline
-{
-}
+impl ConnectorIntegration<AccessTokenAuth, AccessTokenRequestData, AccessToken> for Worldline {}
impl api::Payment for Worldline {}
impl api::MandateSetup for Worldline {}
-impl
- ConnectorIntegration<
- api::SetupMandate,
- types::SetupMandateRequestData,
- types::PaymentsResponseData,
- > for Worldline
+impl ConnectorIntegration<SetupMandate, SetupMandateRequestData, PaymentsResponseData>
+ for Worldline
{
fn build_request(
&self,
- _req: &types::RouterData<
- api::SetupMandate,
- types::SetupMandateRequestData,
- types::PaymentsResponseData,
- >,
+ _req: &RouterData<SetupMandate, SetupMandateRequestData, PaymentsResponseData>,
_connectors: &Connectors,
- ) -> CustomResult<Option<services::Request>, errors::ConnectorError> {
+ ) -> CustomResult<Option<Request>, errors::ConnectorError> {
Err(
errors::ConnectorError::NotImplemented("Setup Mandate flow for Worldline".to_string())
.into(),
@@ -196,32 +209,26 @@ impl
impl api::PaymentToken for Worldline {}
-impl
- ConnectorIntegration<
- api::PaymentMethodToken,
- types::PaymentMethodTokenizationData,
- types::PaymentsResponseData,
- > for Worldline
+impl ConnectorIntegration<PaymentMethodToken, PaymentMethodTokenizationData, PaymentsResponseData>
+ for Worldline
{
// Not Implemented (R)
}
impl api::PaymentVoid for Worldline {}
-impl ConnectorIntegration<api::Void, types::PaymentsCancelData, types::PaymentsResponseData>
- for Worldline
-{
+impl ConnectorIntegration<Void, PaymentsCancelData, PaymentsResponseData> for Worldline {
fn get_headers(
&self,
- req: &types::RouterData<api::Void, types::PaymentsCancelData, types::PaymentsResponseData>,
+ req: &RouterData<Void, PaymentsCancelData, PaymentsResponseData>,
connectors: &Connectors,
- ) -> CustomResult<Vec<(String, request::Maskable<String>)>, errors::ConnectorError> {
+ ) -> CustomResult<Vec<(String, masking::Maskable<String>)>, errors::ConnectorError> {
self.build_headers(req, connectors)
}
fn get_url(
&self,
- req: &types::PaymentsCancelRouterData,
+ req: &PaymentsCancelRouterData,
connectors: &Connectors,
) -> CustomResult<String, errors::ConnectorError> {
let base_url = self.base_url(connectors);
@@ -236,34 +243,34 @@ impl ConnectorIntegration<api::Void, types::PaymentsCancelData, types::PaymentsR
fn build_request(
&self,
- req: &types::RouterData<api::Void, types::PaymentsCancelData, types::PaymentsResponseData>,
+ req: &RouterData<Void, PaymentsCancelData, PaymentsResponseData>,
connectors: &Connectors,
- ) -> CustomResult<Option<services::Request>, errors::ConnectorError> {
+ ) -> CustomResult<Option<Request>, errors::ConnectorError> {
Ok(Some(
- services::RequestBuilder::new()
- .method(types::PaymentsVoidType::get_http_method(self))
- .url(&types::PaymentsVoidType::get_url(self, req, connectors)?)
+ RequestBuilder::new()
+ .method(PaymentsVoidType::get_http_method(self))
+ .url(&PaymentsVoidType::get_url(self, req, connectors)?)
.attach_default_headers()
- .headers(types::PaymentsVoidType::get_headers(self, req, connectors)?)
+ .headers(PaymentsVoidType::get_headers(self, req, connectors)?)
.build(),
))
}
fn handle_response(
&self,
- data: &types::PaymentsCancelRouterData,
+ data: &PaymentsCancelRouterData,
event_builder: Option<&mut ConnectorEvent>,
- res: types::Response,
- ) -> CustomResult<types::PaymentsCancelRouterData, errors::ConnectorError> {
+ res: Response,
+ ) -> CustomResult<PaymentsCancelRouterData, errors::ConnectorError> {
let response: worldline::PaymentResponse = res
.response
.parse_struct("Worldline PaymentResponse")
.change_context(errors::ConnectorError::ResponseDeserializationFailed)?;
event_builder.map(|i| i.set_response_body(&response));
- router_env::logger::info!(connector_response=?response);
+ logger::info!(connector_response=?response);
- types::RouterData::try_from(types::ResponseRouterData {
+ RouterData::try_from(ResponseRouterData {
response,
data: data.clone(),
http_code: res.status_code,
@@ -273,19 +280,17 @@ impl ConnectorIntegration<api::Void, types::PaymentsCancelData, types::PaymentsR
fn get_error_response(
&self,
- res: types::Response,
+ res: Response,
event_builder: Option<&mut ConnectorEvent>,
) -> CustomResult<ErrorResponse, errors::ConnectorError> {
self.build_error_response(res, event_builder)
}
}
-impl api::PaymentSync for Worldline {}
-impl ConnectorIntegration<api::PSync, types::PaymentsSyncData, types::PaymentsResponseData>
- for Worldline
-{
- fn get_http_method(&self) -> services::Method {
- services::Method::Get
+impl PaymentSync for Worldline {}
+impl ConnectorIntegration<PSync, PaymentsSyncData, PaymentsResponseData> for Worldline {
+ fn get_http_method(&self) -> Method {
+ Method::Get
}
fn get_content_type(&self) -> &'static str {
@@ -294,15 +299,15 @@ impl ConnectorIntegration<api::PSync, types::PaymentsSyncData, types::PaymentsRe
fn get_headers(
&self,
- req: &types::RouterData<api::PSync, types::PaymentsSyncData, types::PaymentsResponseData>,
+ req: &RouterData<PSync, PaymentsSyncData, PaymentsResponseData>,
connectors: &Connectors,
- ) -> CustomResult<Vec<(String, request::Maskable<String>)>, errors::ConnectorError> {
+ ) -> CustomResult<Vec<(String, masking::Maskable<String>)>, errors::ConnectorError> {
self.build_headers(req, connectors)
}
fn get_url(
&self,
- req: &types::PaymentsSyncRouterData,
+ req: &PaymentsSyncRouterData,
connectors: &Connectors,
) -> CustomResult<String, errors::ConnectorError> {
let payment_id = req
@@ -320,22 +325,22 @@ impl ConnectorIntegration<api::PSync, types::PaymentsSyncData, types::PaymentsRe
fn build_request(
&self,
- req: &types::PaymentsSyncRouterData,
+ req: &PaymentsSyncRouterData,
connectors: &Connectors,
- ) -> CustomResult<Option<services::Request>, errors::ConnectorError> {
+ ) -> CustomResult<Option<Request>, errors::ConnectorError> {
Ok(Some(
- services::RequestBuilder::new()
- .method(types::PaymentsSyncType::get_http_method(self))
- .url(&types::PaymentsSyncType::get_url(self, req, connectors)?)
+ RequestBuilder::new()
+ .method(PaymentsSyncType::get_http_method(self))
+ .url(&PaymentsSyncType::get_url(self, req, connectors)?)
.attach_default_headers()
- .headers(types::PaymentsSyncType::get_headers(self, req, connectors)?)
+ .headers(PaymentsSyncType::get_headers(self, req, connectors)?)
.build(),
))
}
fn get_error_response(
&self,
- res: types::Response,
+ res: Response,
event_builder: Option<&mut ConnectorEvent>,
) -> CustomResult<ErrorResponse, errors::ConnectorError> {
self.build_error_response(res, event_builder)
@@ -343,10 +348,10 @@ impl ConnectorIntegration<api::PSync, types::PaymentsSyncData, types::PaymentsRe
fn handle_response(
&self,
- data: &types::PaymentsSyncRouterData,
+ data: &PaymentsSyncRouterData,
event_builder: Option<&mut ConnectorEvent>,
- res: types::Response,
- ) -> CustomResult<types::PaymentsSyncRouterData, errors::ConnectorError> {
+ res: Response,
+ ) -> CustomResult<PaymentsSyncRouterData, errors::ConnectorError> {
logger::debug!(payment_sync_response=?res);
let mut response: worldline::Payment = res
.response
@@ -355,9 +360,9 @@ impl ConnectorIntegration<api::PSync, types::PaymentsSyncData, types::PaymentsRe
response.capture_method = data.request.capture_method.unwrap_or_default();
event_builder.map(|i| i.set_response_body(&response));
- router_env::logger::info!(connector_response=?response);
+ logger::info!(connector_response=?response);
- types::RouterData::try_from(types::ResponseRouterData {
+ RouterData::try_from(ResponseRouterData {
response,
data: data.clone(),
http_code: res.status_code,
@@ -366,29 +371,19 @@ impl ConnectorIntegration<api::PSync, types::PaymentsSyncData, types::PaymentsRe
}
}
-impl api::PaymentCapture for Worldline {}
-impl ConnectorIntegration<api::Capture, types::PaymentsCaptureData, types::PaymentsResponseData>
- for Worldline
-{
+impl PaymentCapture for Worldline {}
+impl ConnectorIntegration<Capture, PaymentsCaptureData, PaymentsResponseData> for Worldline {
fn get_headers(
&self,
- req: &types::RouterData<
- api::Capture,
- types::PaymentsCaptureData,
- types::PaymentsResponseData,
- >,
+ req: &RouterData<Capture, PaymentsCaptureData, PaymentsResponseData>,
connectors: &Connectors,
- ) -> CustomResult<Vec<(String, request::Maskable<String>)>, errors::ConnectorError> {
+ ) -> CustomResult<Vec<(String, masking::Maskable<String>)>, errors::ConnectorError> {
self.build_headers(req, connectors)
}
fn get_url(
&self,
- req: &types::RouterData<
- api::Capture,
- types::PaymentsCaptureData,
- types::PaymentsResponseData,
- >,
+ req: &RouterData<Capture, PaymentsCaptureData, PaymentsResponseData>,
connectors: &Connectors,
) -> CustomResult<String, errors::ConnectorError> {
let payment_id = req.request.connector_transaction_id.clone();
@@ -402,11 +397,7 @@ impl ConnectorIntegration<api::Capture, types::PaymentsCaptureData, types::Payme
fn get_request_body(
&self,
- req: &types::RouterData<
- api::Capture,
- types::PaymentsCaptureData,
- types::PaymentsResponseData,
- >,
+ req: &RouterData<Capture, PaymentsCaptureData, PaymentsResponseData>,
_connectors: &Connectors,
) -> CustomResult<RequestContent, errors::ConnectorError> {
let connector_req = worldline::ApproveRequest::try_from(req)?;
@@ -416,22 +407,16 @@ impl ConnectorIntegration<api::Capture, types::PaymentsCaptureData, types::Payme
fn build_request(
&self,
- req: &types::RouterData<
- api::Capture,
- types::PaymentsCaptureData,
- types::PaymentsResponseData,
- >,
+ req: &RouterData<Capture, PaymentsCaptureData, PaymentsResponseData>,
connectors: &Connectors,
- ) -> CustomResult<Option<services::Request>, errors::ConnectorError> {
+ ) -> CustomResult<Option<Request>, errors::ConnectorError> {
Ok(Some(
- services::RequestBuilder::new()
- .method(types::PaymentsCaptureType::get_http_method(self))
- .url(&types::PaymentsCaptureType::get_url(self, req, connectors)?)
+ RequestBuilder::new()
+ .method(PaymentsCaptureType::get_http_method(self))
+ .url(&PaymentsCaptureType::get_url(self, req, connectors)?)
.attach_default_headers()
- .headers(types::PaymentsCaptureType::get_headers(
- self, req, connectors,
- )?)
- .set_body(types::PaymentsCaptureType::get_request_body(
+ .headers(PaymentsCaptureType::get_headers(self, req, connectors)?)
+ .set_body(PaymentsCaptureType::get_request_body(
self, req, connectors,
)?)
.build(),
@@ -440,21 +425,17 @@ impl ConnectorIntegration<api::Capture, types::PaymentsCaptureData, types::Payme
fn handle_response(
&self,
- data: &types::RouterData<
- api::Capture,
- types::PaymentsCaptureData,
- types::PaymentsResponseData,
- >,
+ data: &RouterData<Capture, PaymentsCaptureData, PaymentsResponseData>,
event_builder: Option<&mut ConnectorEvent>,
- res: types::Response,
+ res: Response,
) -> CustomResult<
- types::RouterData<api::Capture, types::PaymentsCaptureData, types::PaymentsResponseData>,
+ RouterData<Capture, PaymentsCaptureData, PaymentsResponseData>,
errors::ConnectorError,
>
where
- api::Capture: Clone,
- types::PaymentsCaptureData: Clone,
- types::PaymentsResponseData: Clone,
+ Capture: Clone,
+ PaymentsCaptureData: Clone,
+ PaymentsResponseData: Clone,
{
logger::debug!(payment_capture_response=?res);
let mut response: worldline::PaymentResponse = res
@@ -464,9 +445,9 @@ impl ConnectorIntegration<api::Capture, types::PaymentsCaptureData, types::Payme
response.payment.capture_method = enums::CaptureMethod::Manual;
event_builder.map(|i| i.set_response_body(&response));
- router_env::logger::info!(connector_response=?response);
+ logger::info!(connector_response=?response);
- types::RouterData::try_from(types::ResponseRouterData {
+ RouterData::try_from(ResponseRouterData {
response,
data: data.clone(),
http_code: res.status_code,
@@ -476,7 +457,7 @@ impl ConnectorIntegration<api::Capture, types::PaymentsCaptureData, types::Payme
fn get_error_response(
&self,
- res: types::Response,
+ res: Response,
event_builder: Option<&mut ConnectorEvent>,
) -> CustomResult<ErrorResponse, errors::ConnectorError> {
self.build_error_response(res, event_builder)
@@ -485,32 +466,24 @@ impl ConnectorIntegration<api::Capture, types::PaymentsCaptureData, types::Payme
impl api::PaymentSession for Worldline {}
-impl ConnectorIntegration<api::Session, types::PaymentsSessionData, types::PaymentsResponseData>
- for Worldline
-{
+impl ConnectorIntegration<Session, PaymentsSessionData, PaymentsResponseData> for Worldline {
// Not Implemented
}
impl api::PaymentAuthorize for Worldline {}
-impl ConnectorIntegration<api::Authorize, types::PaymentsAuthorizeData, types::PaymentsResponseData>
- for Worldline
-{
+impl ConnectorIntegration<Authorize, PaymentsAuthorizeData, PaymentsResponseData> for Worldline {
fn get_headers(
&self,
- req: &types::RouterData<
- api::Authorize,
- types::PaymentsAuthorizeData,
- types::PaymentsResponseData,
- >,
+ req: &RouterData<Authorize, PaymentsAuthorizeData, PaymentsResponseData>,
connectors: &Connectors,
- ) -> CustomResult<Vec<(String, request::Maskable<String>)>, errors::ConnectorError> {
+ ) -> CustomResult<Vec<(String, masking::Maskable<String>)>, errors::ConnectorError> {
self.build_headers(req, connectors)
}
fn get_url(
&self,
- req: &types::PaymentsAuthorizeRouterData,
+ req: &PaymentsAuthorizeRouterData,
connectors: &Connectors,
) -> CustomResult<String, errors::ConnectorError> {
let base_url = self.base_url(connectors);
@@ -521,7 +494,7 @@ impl ConnectorIntegration<api::Authorize, types::PaymentsAuthorizeData, types::P
fn get_request_body(
&self,
- req: &types::PaymentsAuthorizeRouterData,
+ req: &PaymentsAuthorizeRouterData,
_connectors: &Connectors,
) -> CustomResult<RequestContent, errors::ConnectorError> {
let connector_router_data = worldline::WorldlineRouterData::try_from((
@@ -536,24 +509,16 @@ impl ConnectorIntegration<api::Authorize, types::PaymentsAuthorizeData, types::P
fn build_request(
&self,
- req: &types::RouterData<
- api::Authorize,
- types::PaymentsAuthorizeData,
- types::PaymentsResponseData,
- >,
+ req: &RouterData<Authorize, PaymentsAuthorizeData, PaymentsResponseData>,
connectors: &Connectors,
- ) -> CustomResult<Option<services::Request>, errors::ConnectorError> {
+ ) -> CustomResult<Option<Request>, errors::ConnectorError> {
Ok(Some(
- services::RequestBuilder::new()
- .method(types::PaymentsAuthorizeType::get_http_method(self))
- .url(&types::PaymentsAuthorizeType::get_url(
- self, req, connectors,
- )?)
+ RequestBuilder::new()
+ .method(PaymentsAuthorizeType::get_http_method(self))
+ .url(&PaymentsAuthorizeType::get_url(self, req, connectors)?)
.attach_default_headers()
- .headers(types::PaymentsAuthorizeType::get_headers(
- self, req, connectors,
- )?)
- .set_body(types::PaymentsAuthorizeType::get_request_body(
+ .headers(PaymentsAuthorizeType::get_headers(self, req, connectors)?)
+ .set_body(PaymentsAuthorizeType::get_request_body(
self, req, connectors,
)?)
.build(),
@@ -561,10 +526,10 @@ impl ConnectorIntegration<api::Authorize, types::PaymentsAuthorizeData, types::P
}
fn handle_response(
&self,
- data: &types::PaymentsAuthorizeRouterData,
+ data: &PaymentsAuthorizeRouterData,
event_builder: Option<&mut ConnectorEvent>,
- res: types::Response,
- ) -> CustomResult<types::PaymentsAuthorizeRouterData, errors::ConnectorError> {
+ res: Response,
+ ) -> CustomResult<PaymentsAuthorizeRouterData, errors::ConnectorError> {
logger::debug!(payment_authorize_response=?res);
let mut response: worldline::PaymentResponse = res
.response
@@ -572,8 +537,8 @@ impl ConnectorIntegration<api::Authorize, types::PaymentsAuthorizeData, types::P
.change_context(errors::ConnectorError::ResponseDeserializationFailed)?;
response.payment.capture_method = data.request.capture_method.unwrap_or_default();
event_builder.map(|i| i.set_response_body(&response));
- router_env::logger::info!(connector_response=?response);
- types::RouterData::try_from(types::ResponseRouterData {
+ logger::info!(connector_response=?response);
+ RouterData::try_from(ResponseRouterData {
response,
data: data.clone(),
http_code: res.status_code,
@@ -583,7 +548,7 @@ impl ConnectorIntegration<api::Authorize, types::PaymentsAuthorizeData, types::P
fn get_error_response(
&self,
- res: types::Response,
+ res: Response,
event_builder: Option<&mut ConnectorEvent>,
) -> CustomResult<ErrorResponse, errors::ConnectorError> {
self.build_error_response(res, event_builder)
@@ -594,20 +559,18 @@ impl api::Refund for Worldline {}
impl api::RefundExecute for Worldline {}
impl api::RefundSync for Worldline {}
-impl ConnectorIntegration<api::Execute, types::RefundsData, types::RefundsResponseData>
- for Worldline
-{
+impl ConnectorIntegration<Execute, RefundsData, RefundsResponseData> for Worldline {
fn get_headers(
&self,
- req: &types::RefundsRouterData<api::Execute>,
+ req: &RefundsRouterData<Execute>,
connectors: &Connectors,
- ) -> CustomResult<Vec<(String, request::Maskable<String>)>, errors::ConnectorError> {
+ ) -> CustomResult<Vec<(String, masking::Maskable<String>)>, errors::ConnectorError> {
self.build_headers(req, connectors)
}
fn get_url(
&self,
- req: &types::RefundsRouterData<api::Execute>,
+ req: &RefundsRouterData<Execute>,
connectors: &Connectors,
) -> CustomResult<String, errors::ConnectorError> {
let payment_id = req.request.connector_transaction_id.clone();
@@ -621,7 +584,7 @@ impl ConnectorIntegration<api::Execute, types::RefundsData, types::RefundsRespon
fn get_request_body(
&self,
- req: &types::RefundsRouterData<api::Execute>,
+ req: &RefundsRouterData<Execute>,
_connectors: &Connectors,
) -> CustomResult<RequestContent, errors::ConnectorError> {
let connector_req = worldline::WorldlineRefundRequest::try_from(req)?;
@@ -630,37 +593,33 @@ impl ConnectorIntegration<api::Execute, types::RefundsData, types::RefundsRespon
fn build_request(
&self,
- req: &types::RefundsRouterData<api::Execute>,
+ req: &RefundsRouterData<Execute>,
connectors: &Connectors,
- ) -> CustomResult<Option<services::Request>, errors::ConnectorError> {
- let request = services::RequestBuilder::new()
- .method(types::RefundExecuteType::get_http_method(self))
- .url(&types::RefundExecuteType::get_url(self, req, connectors)?)
+ ) -> CustomResult<Option<Request>, errors::ConnectorError> {
+ let request = RequestBuilder::new()
+ .method(RefundExecuteType::get_http_method(self))
+ .url(&RefundExecuteType::get_url(self, req, connectors)?)
.attach_default_headers()
- .headers(types::RefundExecuteType::get_headers(
- self, req, connectors,
- )?)
- .set_body(types::RefundExecuteType::get_request_body(
- self, req, connectors,
- )?)
+ .headers(RefundExecuteType::get_headers(self, req, connectors)?)
+ .set_body(RefundExecuteType::get_request_body(self, req, connectors)?)
.build();
Ok(Some(request))
}
fn handle_response(
&self,
- data: &types::RefundsRouterData<api::Execute>,
+ data: &RefundsRouterData<Execute>,
event_builder: Option<&mut ConnectorEvent>,
- res: types::Response,
- ) -> CustomResult<types::RefundsRouterData<api::Execute>, errors::ConnectorError> {
+ res: Response,
+ ) -> CustomResult<RefundsRouterData<Execute>, errors::ConnectorError> {
logger::debug!(target: "router::connector::worldline", response=?res);
let response: worldline::RefundResponse = res
.response
.parse_struct("Worldline RefundResponse")
.change_context(errors::ConnectorError::RequestEncodingFailed)?;
event_builder.map(|i| i.set_response_body(&response));
- router_env::logger::info!(connector_response=?response);
- types::RouterData::try_from(types::ResponseRouterData {
+ logger::info!(connector_response=?response);
+ RouterData::try_from(ResponseRouterData {
response,
data: data.clone(),
http_code: res.status_code,
@@ -670,18 +629,16 @@ impl ConnectorIntegration<api::Execute, types::RefundsData, types::RefundsRespon
fn get_error_response(
&self,
- res: types::Response,
+ res: Response,
event_builder: Option<&mut ConnectorEvent>,
) -> CustomResult<ErrorResponse, errors::ConnectorError> {
self.build_error_response(res, event_builder)
}
}
-impl ConnectorIntegration<api::RSync, types::RefundsData, types::RefundsResponseData>
- for Worldline
-{
- fn get_http_method(&self) -> services::Method {
- services::Method::Get
+impl ConnectorIntegration<RSync, RefundsData, RefundsResponseData> for Worldline {
+ fn get_http_method(&self) -> Method {
+ Method::Get
}
fn get_content_type(&self) -> &'static str {
@@ -690,15 +647,15 @@ impl ConnectorIntegration<api::RSync, types::RefundsData, types::RefundsResponse
fn get_headers(
&self,
- req: &types::RefundSyncRouterData,
+ req: &RefundSyncRouterData,
connectors: &Connectors,
- ) -> CustomResult<Vec<(String, request::Maskable<String>)>, errors::ConnectorError> {
+ ) -> CustomResult<Vec<(String, masking::Maskable<String>)>, errors::ConnectorError> {
self.build_headers(req, connectors)
}
fn get_url(
&self,
- req: &types::RefundSyncRouterData,
+ req: &RefundSyncRouterData,
connectors: &Connectors,
) -> CustomResult<String, errors::ConnectorError> {
let refund_id = req.request.get_connector_refund_id()?;
@@ -713,33 +670,33 @@ impl ConnectorIntegration<api::RSync, types::RefundsData, types::RefundsResponse
fn build_request(
&self,
- req: &types::RefundSyncRouterData,
+ req: &RefundSyncRouterData,
connectors: &Connectors,
- ) -> CustomResult<Option<services::Request>, errors::ConnectorError> {
+ ) -> CustomResult<Option<Request>, errors::ConnectorError> {
Ok(Some(
- services::RequestBuilder::new()
- .method(types::RefundSyncType::get_http_method(self))
- .url(&types::RefundSyncType::get_url(self, req, connectors)?)
+ RequestBuilder::new()
+ .method(RefundSyncType::get_http_method(self))
+ .url(&RefundSyncType::get_url(self, req, connectors)?)
.attach_default_headers()
- .headers(types::RefundSyncType::get_headers(self, req, connectors)?)
+ .headers(RefundSyncType::get_headers(self, req, connectors)?)
.build(),
))
}
fn handle_response(
&self,
- data: &types::RefundSyncRouterData,
+ data: &RefundSyncRouterData,
event_builder: Option<&mut ConnectorEvent>,
- res: types::Response,
- ) -> CustomResult<types::RefundSyncRouterData, errors::ConnectorError> {
+ res: Response,
+ ) -> CustomResult<RefundSyncRouterData, errors::ConnectorError> {
logger::debug!(target: "router::connector::worldline", response=?res);
let response: worldline::RefundResponse = res
.response
.parse_struct("Worldline RefundResponse")
.change_context(errors::ConnectorError::ResponseDeserializationFailed)?;
event_builder.map(|i| i.set_response_body(&response));
- router_env::logger::info!(connector_response=?response);
- types::RouterData::try_from(types::ResponseRouterData {
+ logger::info!(connector_response=?response);
+ RouterData::try_from(ResponseRouterData {
response,
data: data.clone(),
http_code: res.status_code,
@@ -749,7 +706,7 @@ impl ConnectorIntegration<api::RSync, types::RefundsData, types::RefundsResponse
fn get_error_response(
&self,
- res: types::Response,
+ res: Response,
event_builder: Option<&mut ConnectorEvent>,
) -> CustomResult<ErrorResponse, errors::ConnectorError> {
self.build_error_response(res, event_builder)
@@ -763,21 +720,20 @@ fn is_endpoint_verification(headers: &actix_web::http::header::HeaderMap) -> boo
}
#[async_trait::async_trait]
-impl api::IncomingWebhook for Worldline {
+impl webhooks::IncomingWebhook for Worldline {
fn get_webhook_source_verification_algorithm(
&self,
- _request: &api::IncomingWebhookRequestDetails<'_>,
+ _request: &webhooks::IncomingWebhookRequestDetails<'_>,
) -> CustomResult<Box<dyn crypto::VerifySignature + Send>, errors::ConnectorError> {
Ok(Box::new(crypto::HmacSha256))
}
fn get_webhook_source_verification_signature(
&self,
- request: &api::IncomingWebhookRequestDetails<'_>,
+ request: &webhooks::IncomingWebhookRequestDetails<'_>,
_connector_webhook_secrets: &api_models::webhooks::ConnectorWebhookSecrets,
) -> CustomResult<Vec<u8>, errors::ConnectorError> {
- let header_value =
- connector_utils::get_header_key_value("X-GCS-Signature", request.headers)?;
+ let header_value = utils::get_header_key_value("X-GCS-Signature", request.headers)?;
let signature = consts::BASE64_ENGINE
.decode(header_value.as_bytes())
.change_context(errors::ConnectorError::WebhookSourceVerificationFailed)?;
@@ -786,7 +742,7 @@ impl api::IncomingWebhook for Worldline {
fn get_webhook_source_verification_message(
&self,
- request: &api::IncomingWebhookRequestDetails<'_>,
+ request: &webhooks::IncomingWebhookRequestDetails<'_>,
_merchant_id: &common_utils::id_type::MerchantId,
_connector_webhook_secrets: &api_models::webhooks::ConnectorWebhookSecrets,
) -> CustomResult<Vec<u8>, errors::ConnectorError> {
@@ -795,7 +751,7 @@ impl api::IncomingWebhook for Worldline {
fn get_webhook_object_reference_id(
&self,
- request: &api::IncomingWebhookRequestDetails<'_>,
+ request: &webhooks::IncomingWebhookRequestDetails<'_>,
) -> CustomResult<api_models::webhooks::ObjectReferenceId, errors::ConnectorError> {
|| -> _ {
Ok::<_, error_stack::Report<common_utils::errors::ParsingError>>(
@@ -816,21 +772,25 @@ impl api::IncomingWebhook for Worldline {
fn get_webhook_event_type(
&self,
- request: &api::IncomingWebhookRequestDetails<'_>,
- ) -> CustomResult<api::IncomingWebhookEvent, errors::ConnectorError> {
+ request: &webhooks::IncomingWebhookRequestDetails<'_>,
+ ) -> CustomResult<api_models::webhooks::IncomingWebhookEvent, errors::ConnectorError> {
if is_endpoint_verification(request.headers) {
- Ok(api::IncomingWebhookEvent::EndpointVerification)
+ Ok(api_models::webhooks::IncomingWebhookEvent::EndpointVerification)
} else {
let details: worldline::WebhookBody = request
.body
.parse_struct("WorldlineWebhookObjectId")
.change_context(errors::ConnectorError::WebhookEventTypeNotFound)?;
let event = match details.event_type {
- worldline::WebhookEvent::Paid => api::IncomingWebhookEvent::PaymentIntentSuccess,
+ worldline::WebhookEvent::Paid => {
+ api_models::webhooks::IncomingWebhookEvent::PaymentIntentSuccess
+ }
worldline::WebhookEvent::Rejected | worldline::WebhookEvent::RejectedCapture => {
- api::IncomingWebhookEvent::PaymentIntentFailure
+ api_models::webhooks::IncomingWebhookEvent::PaymentIntentFailure
+ }
+ worldline::WebhookEvent::Unknown => {
+ api_models::webhooks::IncomingWebhookEvent::EventNotSupported
}
- worldline::WebhookEvent::Unknown => api::IncomingWebhookEvent::EventNotSupported,
};
Ok(event)
}
@@ -838,7 +798,7 @@ impl api::IncomingWebhook for Worldline {
fn get_webhook_resource_object(
&self,
- request: &api::IncomingWebhookRequestDetails<'_>,
+ request: &webhooks::IncomingWebhookRequestDetails<'_>,
) -> CustomResult<Box<dyn masking::ErasedMaskSerialize>, errors::ConnectorError> {
let details = request
.body
@@ -853,18 +813,22 @@ impl api::IncomingWebhook for Worldline {
fn get_webhook_api_response(
&self,
- request: &api::IncomingWebhookRequestDetails<'_>,
- ) -> CustomResult<services::api::ApplicationResponse<serde_json::Value>, errors::ConnectorError>
- {
+ request: &webhooks::IncomingWebhookRequestDetails<'_>,
+ ) -> CustomResult<
+ hyperswitch_domain_models::api::ApplicationResponse<serde_json::Value>,
+ errors::ConnectorError,
+ > {
let verification_header = request.headers.get("x-gcs-webhooks-endpoint-verification");
let response = match verification_header {
- None => services::api::ApplicationResponse::StatusOk,
+ None => hyperswitch_domain_models::api::ApplicationResponse::StatusOk,
Some(header_value) => {
let verification_signature_value = header_value
.to_str()
.change_context(errors::ConnectorError::WebhookResponseEncodingFailed)?
.to_string();
- services::api::ApplicationResponse::TextPlain(verification_signature_value)
+ hyperswitch_domain_models::api::ApplicationResponse::TextPlain(
+ verification_signature_value,
+ )
}
};
Ok(response)
diff --git a/crates/router/src/connector/worldline/transformers.rs b/crates/hyperswitch_connectors/src/connectors/worldline/transformers.rs
similarity index 68%
rename from crates/router/src/connector/worldline/transformers.rs
rename to crates/hyperswitch_connectors/src/connectors/worldline/transformers.rs
index e0278dc4ccb..33c865c3b5f 100644
--- a/crates/router/src/connector/worldline/transformers.rs
+++ b/crates/hyperswitch_connectors/src/connectors/worldline/transformers.rs
@@ -1,21 +1,25 @@
use api_models::payments;
-use common_utils::pii::Email;
+use common_enums::enums::{AttemptStatus, BankNames, CaptureMethod, CountryAlpha2, Currency};
+use common_utils::{pii::Email, request::Method};
+use hyperswitch_domain_models::{
+ payment_method_data::{BankRedirectData, PaymentMethodData},
+ router_data::{ConnectorAuthType, RouterData},
+ router_flow_types::{
+ payments::Authorize,
+ refunds::{Execute, RSync},
+ },
+ router_request_types::{PaymentsAuthorizeData, ResponseId},
+ router_response_types::{PaymentsResponseData, RedirectForm, RefundsResponseData},
+ types::{PaymentsAuthorizeRouterData, PaymentsCaptureRouterData, RefundsRouterData},
+};
+use hyperswitch_interfaces::{api::CurrencyUnit, errors};
use masking::{PeekInterface, Secret};
use serde::{Deserialize, Serialize};
use url::Url;
use crate::{
- connector::utils::{self, CardData, RouterData},
- core::errors,
- services,
- types::{
- self,
- api::{self, enums as api_enums},
- domain,
- storage::enums,
- transformers::ForeignFrom,
- PaymentsAuthorizeData, PaymentsResponseData,
- },
+ types::{RefundsResponseRouterData, ResponseRouterData},
+ utils::{self, CardData, RouterData as RouterDataUtils},
};
#[derive(Default, Debug, Serialize, Eq, PartialEq)]
@@ -60,7 +64,7 @@ pub struct Order {
#[serde(rename_all = "camelCase")]
pub struct BillingAddress {
pub city: Option<String>,
- pub country_code: Option<api_enums::CountryAlpha2>,
+ pub country_code: Option<CountryAlpha2>,
pub house_number: Option<Secret<String>>,
pub state: Option<Secret<String>>,
pub state_code: Option<Secret<String>>,
@@ -95,7 +99,7 @@ pub struct Name {
#[serde(rename_all = "camelCase")]
pub struct Shipping {
pub city: Option<String>,
- pub country_code: Option<api_enums::CountryAlpha2>,
+ pub country_code: Option<CountryAlpha2>,
pub house_number: Option<Secret<String>>,
pub name: Option<Name>,
pub state: Option<Secret<String>>,
@@ -190,10 +194,10 @@ pub struct WorldlineRouterData<T> {
amount: i64,
router_data: T,
}
-impl<T> TryFrom<(&api::CurrencyUnit, enums::Currency, i64, T)> for WorldlineRouterData<T> {
+impl<T> TryFrom<(&CurrencyUnit, Currency, i64, T)> for WorldlineRouterData<T> {
type Error = error_stack::Report<errors::ConnectorError>;
fn try_from(
- (_currency_unit, _currency, amount, item): (&api::CurrencyUnit, enums::Currency, i64, T),
+ (_currency_unit, _currency, amount, item): (&CurrencyUnit, Currency, i64, T),
) -> Result<Self, Self::Error> {
Ok(Self {
amount,
@@ -204,59 +208,48 @@ impl<T> TryFrom<(&api::CurrencyUnit, enums::Currency, i64, T)> for WorldlineRout
impl
TryFrom<
- &WorldlineRouterData<
- &types::RouterData<
- api::payments::Authorize,
- PaymentsAuthorizeData,
- PaymentsResponseData,
- >,
- >,
+ &WorldlineRouterData<&RouterData<Authorize, PaymentsAuthorizeData, PaymentsResponseData>>,
> for PaymentsRequest
{
type Error = error_stack::Report<errors::ConnectorError>;
fn try_from(
item: &WorldlineRouterData<
- &types::RouterData<
- api::payments::Authorize,
- PaymentsAuthorizeData,
- PaymentsResponseData,
- >,
+ &RouterData<Authorize, PaymentsAuthorizeData, PaymentsResponseData>,
>,
) -> Result<Self, Self::Error> {
- let payment_data =
- match &item.router_data.request.payment_method_data {
- domain::PaymentMethodData::Card(card) => {
- let card_holder_name = item.router_data.get_optional_billing_full_name();
- WorldlinePaymentMethod::CardPaymentMethodSpecificInput(Box::new(
- make_card_request(&item.router_data.request, card, card_holder_name)?,
- ))
- }
- domain::PaymentMethodData::BankRedirect(bank_redirect) => {
- WorldlinePaymentMethod::RedirectPaymentMethodSpecificInput(Box::new(
- make_bank_redirect_request(item.router_data, bank_redirect)?,
- ))
- }
- domain::PaymentMethodData::CardRedirect(_)
- | domain::PaymentMethodData::Wallet(_)
- | domain::PaymentMethodData::PayLater(_)
- | domain::PaymentMethodData::BankDebit(_)
- | domain::PaymentMethodData::BankTransfer(_)
- | domain::PaymentMethodData::Crypto(_)
- | domain::PaymentMethodData::MandatePayment
- | domain::PaymentMethodData::Reward
- | domain::PaymentMethodData::RealTimePayment(_)
- | domain::PaymentMethodData::Upi(_)
- | domain::PaymentMethodData::Voucher(_)
- | domain::PaymentMethodData::GiftCard(_)
- | domain::PaymentMethodData::OpenBanking(_)
- | domain::PaymentMethodData::CardToken(_)
- | domain::PaymentMethodData::NetworkToken(_) => {
- Err(errors::ConnectorError::NotImplemented(
- utils::get_unimplemented_payment_method_error_message("worldline"),
- ))?
- }
- };
+ let payment_data = match &item.router_data.request.payment_method_data {
+ PaymentMethodData::Card(card) => {
+ let card_holder_name = item.router_data.get_optional_billing_full_name();
+ WorldlinePaymentMethod::CardPaymentMethodSpecificInput(Box::new(make_card_request(
+ &item.router_data.request,
+ card,
+ card_holder_name,
+ )?))
+ }
+ PaymentMethodData::BankRedirect(bank_redirect) => {
+ WorldlinePaymentMethod::RedirectPaymentMethodSpecificInput(Box::new(
+ make_bank_redirect_request(item.router_data, bank_redirect)?,
+ ))
+ }
+ PaymentMethodData::CardRedirect(_)
+ | PaymentMethodData::Wallet(_)
+ | PaymentMethodData::PayLater(_)
+ | PaymentMethodData::BankDebit(_)
+ | PaymentMethodData::BankTransfer(_)
+ | PaymentMethodData::Crypto(_)
+ | PaymentMethodData::MandatePayment
+ | PaymentMethodData::Reward
+ | PaymentMethodData::RealTimePayment(_)
+ | PaymentMethodData::Upi(_)
+ | PaymentMethodData::Voucher(_)
+ | PaymentMethodData::GiftCard(_)
+ | PaymentMethodData::OpenBanking(_)
+ | PaymentMethodData::CardToken(_)
+ | PaymentMethodData::NetworkToken(_) => Err(errors::ConnectorError::NotImplemented(
+ utils::get_unimplemented_payment_method_error_message("worldline"),
+ ))?,
+ };
let billing_address = item.router_data.get_billing()?;
@@ -309,20 +302,20 @@ impl TryFrom<utils::CardIssuer> for Gateway {
}
}
-impl TryFrom<&common_enums::enums::BankNames> for WorldlineBic {
+impl TryFrom<&BankNames> for WorldlineBic {
type Error = error_stack::Report<errors::ConnectorError>;
- fn try_from(bank: &common_enums::enums::BankNames) -> Result<Self, Self::Error> {
+ fn try_from(bank: &BankNames) -> Result<Self, Self::Error> {
match bank {
- common_enums::enums::BankNames::AbnAmro => Ok(Self::Abnamro),
- common_enums::enums::BankNames::AsnBank => Ok(Self::Asn),
- common_enums::enums::BankNames::Ing => Ok(Self::Ing),
- common_enums::enums::BankNames::Knab => Ok(Self::Knab),
- common_enums::enums::BankNames::Rabobank => Ok(Self::Rabobank),
- common_enums::enums::BankNames::Regiobank => Ok(Self::Regiobank),
- common_enums::enums::BankNames::SnsBank => Ok(Self::Sns),
- common_enums::enums::BankNames::TriodosBank => Ok(Self::Triodos),
- common_enums::enums::BankNames::VanLanschot => Ok(Self::Vanlanschot),
- common_enums::enums::BankNames::FrieslandBank => Ok(Self::Friesland),
+ BankNames::AbnAmro => Ok(Self::Abnamro),
+ BankNames::AsnBank => Ok(Self::Asn),
+ BankNames::Ing => Ok(Self::Ing),
+ BankNames::Knab => Ok(Self::Knab),
+ BankNames::Rabobank => Ok(Self::Rabobank),
+ BankNames::Regiobank => Ok(Self::Regiobank),
+ BankNames::SnsBank => Ok(Self::Sns),
+ BankNames::TriodosBank => Ok(Self::Triodos),
+ BankNames::VanLanschot => Ok(Self::Vanlanschot),
+ BankNames::FrieslandBank => Ok(Self::Friesland),
_ => Err(errors::ConnectorError::FlowNotSupported {
flow: bank.to_string(),
connector: "Worldline".to_string(),
@@ -334,7 +327,7 @@ impl TryFrom<&common_enums::enums::BankNames> for WorldlineBic {
fn make_card_request(
req: &PaymentsAuthorizeData,
- ccard: &domain::Card,
+ ccard: &hyperswitch_domain_models::payment_method_data::Card,
card_holder_name: Option<Secret<String>>,
) -> Result<CardPaymentMethod, error_stack::Report<errors::ConnectorError>> {
let expiry_year = ccard.card_exp_year.peek();
@@ -356,20 +349,20 @@ fn make_card_request(
let payment_product_id = Gateway::try_from(ccard.get_card_issuer()?)? as u16;
let card_payment_method_specific_input = CardPaymentMethod {
card,
- requires_approval: matches!(req.capture_method, Some(enums::CaptureMethod::Manual)),
+ requires_approval: matches!(req.capture_method, Some(CaptureMethod::Manual)),
payment_product_id,
};
Ok(card_payment_method_specific_input)
}
fn make_bank_redirect_request(
- req: &types::PaymentsAuthorizeRouterData,
- bank_redirect: &domain::BankRedirectData,
+ req: &PaymentsAuthorizeRouterData,
+ bank_redirect: &BankRedirectData,
) -> Result<RedirectPaymentMethod, error_stack::Report<errors::ConnectorError>> {
let return_url = req.request.router_return_url.clone();
let redirection_data = RedirectionData { return_url };
let (payment_method_specific_data, payment_product_id) = match bank_redirect {
- domain::BankRedirectData::Giropay {
+ BankRedirectData::Giropay {
bank_account_iban, ..
} => (
{
@@ -382,7 +375,7 @@ fn make_bank_redirect_request(
},
816,
),
- domain::BankRedirectData::Ideal { bank_name, .. } => (
+ BankRedirectData::Ideal { bank_name, .. } => (
{
PaymentMethodSpecificData::PaymentProduct809SpecificInput(Box::new(Ideal {
issuer_id: bank_name
@@ -392,22 +385,22 @@ fn make_bank_redirect_request(
},
809,
),
- domain::BankRedirectData::BancontactCard { .. }
- | domain::BankRedirectData::Bizum {}
- | domain::BankRedirectData::Blik { .. }
- | domain::BankRedirectData::Eps { .. }
- | domain::BankRedirectData::Interac { .. }
- | domain::BankRedirectData::OnlineBankingCzechRepublic { .. }
- | domain::BankRedirectData::OnlineBankingFinland { .. }
- | domain::BankRedirectData::OnlineBankingPoland { .. }
- | domain::BankRedirectData::OnlineBankingSlovakia { .. }
- | domain::BankRedirectData::OpenBankingUk { .. }
- | domain::BankRedirectData::Przelewy24 { .. }
- | domain::BankRedirectData::Sofort { .. }
- | domain::BankRedirectData::Trustly { .. }
- | domain::BankRedirectData::OnlineBankingFpx { .. }
- | domain::BankRedirectData::OnlineBankingThailand { .. }
- | domain::BankRedirectData::LocalBankRedirect {} => {
+ BankRedirectData::BancontactCard { .. }
+ | BankRedirectData::Bizum {}
+ | BankRedirectData::Blik { .. }
+ | BankRedirectData::Eps { .. }
+ | BankRedirectData::Interac { .. }
+ | BankRedirectData::OnlineBankingCzechRepublic { .. }
+ | BankRedirectData::OnlineBankingFinland { .. }
+ | BankRedirectData::OnlineBankingPoland { .. }
+ | BankRedirectData::OnlineBankingSlovakia { .. }
+ | BankRedirectData::OpenBankingUk { .. }
+ | BankRedirectData::Przelewy24 { .. }
+ | BankRedirectData::Sofort { .. }
+ | BankRedirectData::Trustly { .. }
+ | BankRedirectData::OnlineBankingFpx { .. }
+ | BankRedirectData::OnlineBankingThailand { .. }
+ | BankRedirectData::LocalBankRedirect {} => {
return Err(errors::ConnectorError::NotImplemented(
utils::get_unimplemented_payment_method_error_message("worldline"),
)
@@ -493,10 +486,10 @@ pub struct WorldlineAuthType {
pub merchant_account_id: Secret<String>,
}
-impl TryFrom<&types::ConnectorAuthType> for WorldlineAuthType {
+impl TryFrom<&ConnectorAuthType> for WorldlineAuthType {
type Error = error_stack::Report<errors::ConnectorError>;
- fn try_from(auth_type: &types::ConnectorAuthType) -> Result<Self, Self::Error> {
- if let types::ConnectorAuthType::SignatureKey {
+ fn try_from(auth_type: &ConnectorAuthType) -> Result<Self, Self::Error> {
+ if let ConnectorAuthType::SignatureKey {
api_key,
key1,
api_secret,
@@ -530,28 +523,26 @@ pub enum PaymentStatus {
Redirected,
}
-impl ForeignFrom<(PaymentStatus, enums::CaptureMethod)> for enums::AttemptStatus {
- fn foreign_from(item: (PaymentStatus, enums::CaptureMethod)) -> Self {
- let (status, capture_method) = item;
- match status {
- PaymentStatus::Captured
- | PaymentStatus::Paid
- | PaymentStatus::ChargebackNotification => Self::Charged,
- PaymentStatus::Cancelled => Self::Voided,
- PaymentStatus::Rejected => Self::Failure,
- PaymentStatus::RejectedCapture => Self::CaptureFailed,
- PaymentStatus::CaptureRequested => {
- if capture_method == enums::CaptureMethod::Automatic {
- Self::Pending
- } else {
- Self::CaptureInitiated
- }
+fn get_status(item: (PaymentStatus, CaptureMethod)) -> AttemptStatus {
+ let (status, capture_method) = item;
+ match status {
+ PaymentStatus::Captured | PaymentStatus::Paid | PaymentStatus::ChargebackNotification => {
+ AttemptStatus::Charged
+ }
+ PaymentStatus::Cancelled => AttemptStatus::Voided,
+ PaymentStatus::Rejected => AttemptStatus::Failure,
+ PaymentStatus::RejectedCapture => AttemptStatus::CaptureFailed,
+ PaymentStatus::CaptureRequested => {
+ if capture_method == CaptureMethod::Automatic {
+ AttemptStatus::Pending
+ } else {
+ AttemptStatus::CaptureInitiated
}
- PaymentStatus::PendingApproval => Self::Authorized,
- PaymentStatus::Created => Self::Started,
- PaymentStatus::Redirected => Self::AuthenticationPending,
- _ => Self::Pending,
}
+ PaymentStatus::PendingApproval => AttemptStatus::Authorized,
+ PaymentStatus::Created => AttemptStatus::Started,
+ PaymentStatus::Redirected => AttemptStatus::AuthenticationPending,
+ _ => AttemptStatus::Pending,
}
}
@@ -563,23 +554,20 @@ pub struct Payment {
pub id: String,
pub status: PaymentStatus,
#[serde(skip_deserializing)]
- pub capture_method: enums::CaptureMethod,
+ pub capture_method: CaptureMethod,
}
-impl<F, T> TryFrom<types::ResponseRouterData<F, Payment, T, PaymentsResponseData>>
- for types::RouterData<F, T, PaymentsResponseData>
+impl<F, T> TryFrom<ResponseRouterData<F, Payment, T, PaymentsResponseData>>
+ for RouterData<F, T, PaymentsResponseData>
{
type Error = error_stack::Report<errors::ConnectorError>;
fn try_from(
- item: types::ResponseRouterData<F, Payment, T, PaymentsResponseData>,
+ item: ResponseRouterData<F, Payment, T, PaymentsResponseData>,
) -> Result<Self, Self::Error> {
Ok(Self {
- status: enums::AttemptStatus::foreign_from((
- item.response.status,
- item.response.capture_method,
- )),
+ status: get_status((item.response.status, item.response.capture_method)),
response: Ok(PaymentsResponseData::TransactionResponse {
- resource_id: types::ResponseId::ConnectorTransactionId(item.response.id.clone()),
+ resource_id: ResponseId::ConnectorTransactionId(item.response.id.clone()),
redirection_data: None,
mandate_reference: None,
connector_metadata: None,
@@ -612,29 +600,25 @@ pub struct RedirectData {
pub redirect_url: Url,
}
-impl<F, T> TryFrom<types::ResponseRouterData<F, PaymentResponse, T, PaymentsResponseData>>
- for types::RouterData<F, T, PaymentsResponseData>
+impl<F, T> TryFrom<ResponseRouterData<F, PaymentResponse, T, PaymentsResponseData>>
+ for RouterData<F, T, PaymentsResponseData>
{
type Error = error_stack::Report<errors::ConnectorError>;
fn try_from(
- item: types::ResponseRouterData<F, PaymentResponse, T, PaymentsResponseData>,
+ item: ResponseRouterData<F, PaymentResponse, T, PaymentsResponseData>,
) -> Result<Self, Self::Error> {
let redirection_data = item
.response
.merchant_action
.map(|action| action.redirect_data.redirect_url)
- .map(|redirect_url| {
- services::RedirectForm::from((redirect_url, services::Method::Get))
- });
+ .map(|redirect_url| RedirectForm::from((redirect_url, Method::Get)));
Ok(Self {
- status: enums::AttemptStatus::foreign_from((
+ status: get_status((
item.response.payment.status,
item.response.payment.capture_method,
)),
response: Ok(PaymentsResponseData::TransactionResponse {
- resource_id: types::ResponseId::ConnectorTransactionId(
- item.response.payment.id.clone(),
- ),
+ resource_id: ResponseId::ConnectorTransactionId(item.response.payment.id.clone()),
redirection_data,
mandate_reference: None,
connector_metadata: None,
@@ -650,9 +634,9 @@ impl<F, T> TryFrom<types::ResponseRouterData<F, PaymentResponse, T, PaymentsResp
#[derive(Default, Debug, Serialize)]
pub struct ApproveRequest {}
-impl TryFrom<&types::PaymentsCaptureRouterData> for ApproveRequest {
+impl TryFrom<&PaymentsCaptureRouterData> for ApproveRequest {
type Error = error_stack::Report<errors::ConnectorError>;
- fn try_from(_item: &types::PaymentsCaptureRouterData) -> Result<Self, Self::Error> {
+ fn try_from(_item: &PaymentsCaptureRouterData) -> Result<Self, Self::Error> {
Ok(Self {})
}
}
@@ -662,9 +646,9 @@ pub struct WorldlineRefundRequest {
amount_of_money: AmountOfMoney,
}
-impl<F> TryFrom<&types::RefundsRouterData<F>> for WorldlineRefundRequest {
+impl<F> TryFrom<&RefundsRouterData<F>> for WorldlineRefundRequest {
type Error = error_stack::Report<errors::ConnectorError>;
- fn try_from(item: &types::RefundsRouterData<F>) -> Result<Self, Self::Error> {
+ fn try_from(item: &RefundsRouterData<F>) -> Result<Self, Self::Error> {
Ok(Self {
amount_of_money: AmountOfMoney {
amount: item.request.refund_amount,
@@ -685,7 +669,7 @@ pub enum RefundStatus {
Processing,
}
-impl From<RefundStatus> for enums::RefundStatus {
+impl From<RefundStatus> for common_enums::enums::RefundStatus {
fn from(item: RefundStatus) -> Self {
match item {
RefundStatus::Refunded => Self::Success,
@@ -701,16 +685,14 @@ pub struct RefundResponse {
status: RefundStatus,
}
-impl TryFrom<types::RefundsResponseRouterData<api::Execute, RefundResponse>>
- for types::RefundsRouterData<api::Execute>
-{
+impl TryFrom<RefundsResponseRouterData<Execute, RefundResponse>> for RefundsRouterData<Execute> {
type Error = error_stack::Report<errors::ConnectorError>;
fn try_from(
- item: types::RefundsResponseRouterData<api::Execute, RefundResponse>,
+ item: RefundsResponseRouterData<Execute, RefundResponse>,
) -> Result<Self, Self::Error> {
- let refund_status = enums::RefundStatus::from(item.response.status);
+ let refund_status = common_enums::enums::RefundStatus::from(item.response.status);
Ok(Self {
- response: Ok(types::RefundsResponseData {
+ response: Ok(RefundsResponseData {
connector_refund_id: item.response.id.clone(),
refund_status,
}),
@@ -719,16 +701,14 @@ impl TryFrom<types::RefundsResponseRouterData<api::Execute, RefundResponse>>
}
}
-impl TryFrom<types::RefundsResponseRouterData<api::RSync, RefundResponse>>
- for types::RefundsRouterData<api::RSync>
-{
+impl TryFrom<RefundsResponseRouterData<RSync, RefundResponse>> for RefundsRouterData<RSync> {
type Error = error_stack::Report<errors::ConnectorError>;
fn try_from(
- item: types::RefundsResponseRouterData<api::RSync, RefundResponse>,
+ item: RefundsResponseRouterData<RSync, RefundResponse>,
) -> Result<Self, Self::Error> {
- let refund_status = enums::RefundStatus::from(item.response.status);
+ let refund_status = common_enums::enums::RefundStatus::from(item.response.status);
Ok(Self {
- response: Ok(types::RefundsResponseData {
+ response: Ok(RefundsResponseData {
connector_refund_id: item.response.id.clone(),
refund_status,
}),
diff --git a/crates/hyperswitch_connectors/src/constants.rs b/crates/hyperswitch_connectors/src/constants.rs
index 1fd61689307..1427b567c44 100644
--- a/crates/hyperswitch_connectors/src/constants.rs
+++ b/crates/hyperswitch_connectors/src/constants.rs
@@ -4,6 +4,7 @@ pub(crate) mod headers {
pub(crate) const API_TOKEN: &str = "Api-Token";
pub(crate) const AUTHORIZATION: &str = "Authorization";
pub(crate) const CONTENT_TYPE: &str = "Content-Type";
+ pub(crate) const DATE: &str = "Date";
pub(crate) const IDEMPOTENCY_KEY: &str = "Idempotency-Key";
pub(crate) const MESSAGE_SIGNATURE: &str = "Message-Signature";
pub(crate) const TIMESTAMP: &str = "Timestamp";
diff --git a/crates/hyperswitch_connectors/src/default_implementations.rs b/crates/hyperswitch_connectors/src/default_implementations.rs
index 101bb145966..11a071d135e 100644
--- a/crates/hyperswitch_connectors/src/default_implementations.rs
+++ b/crates/hyperswitch_connectors/src/default_implementations.rs
@@ -91,11 +91,15 @@ default_imp_for_authorize_session_token!(
connectors::Fiserv,
connectors::Fiservemea,
connectors::Fiuu,
+ connectors::Globepay,
connectors::Helcim,
connectors::Novalnet,
connectors::Nexixpay,
+ connectors::Powertranz,
connectors::Stax,
- connectors::Taxjar
+ connectors::Taxjar,
+ connectors::Tsys,
+ connectors::Worldline
);
use crate::connectors;
@@ -119,11 +123,14 @@ default_imp_for_complete_authorize!(
connectors::Fiserv,
connectors::Fiservemea,
connectors::Fiuu,
+ connectors::Globepay,
connectors::Helcim,
connectors::Novalnet,
connectors::Nexixpay,
connectors::Stax,
- connectors::Taxjar
+ connectors::Taxjar,
+ connectors::Tsys,
+ connectors::Worldline
);
macro_rules! default_imp_for_incremental_authorization {
@@ -147,11 +154,15 @@ default_imp_for_incremental_authorization!(
connectors::Fiserv,
connectors::Fiservemea,
connectors::Fiuu,
+ connectors::Globepay,
connectors::Helcim,
connectors::Novalnet,
connectors::Nexixpay,
+ connectors::Powertranz,
connectors::Stax,
- connectors::Taxjar
+ connectors::Taxjar,
+ connectors::Tsys,
+ connectors::Worldline
);
macro_rules! default_imp_for_create_customer {
@@ -175,10 +186,14 @@ default_imp_for_create_customer!(
connectors::Fiserv,
connectors::Fiservemea,
connectors::Fiuu,
+ connectors::Globepay,
connectors::Helcim,
connectors::Novalnet,
connectors::Nexixpay,
- connectors::Taxjar
+ connectors::Powertranz,
+ connectors::Taxjar,
+ connectors::Tsys,
+ connectors::Worldline
);
macro_rules! default_imp_for_connector_redirect_response {
@@ -203,11 +218,15 @@ default_imp_for_connector_redirect_response!(
connectors::Fiserv,
connectors::Fiservemea,
connectors::Fiuu,
+ connectors::Globepay,
connectors::Helcim,
connectors::Novalnet,
connectors::Nexixpay,
+ connectors::Powertranz,
connectors::Stax,
- connectors::Taxjar
+ connectors::Taxjar,
+ connectors::Tsys,
+ connectors::Worldline
);
macro_rules! default_imp_for_pre_processing_steps{
@@ -231,11 +250,15 @@ default_imp_for_pre_processing_steps!(
connectors::Fiserv,
connectors::Fiservemea,
connectors::Fiuu,
+ connectors::Globepay,
connectors::Helcim,
connectors::Novalnet,
connectors::Nexixpay,
+ connectors::Powertranz,
connectors::Stax,
- connectors::Taxjar
+ connectors::Taxjar,
+ connectors::Tsys,
+ connectors::Worldline
);
macro_rules! default_imp_for_post_processing_steps{
@@ -259,11 +282,15 @@ default_imp_for_post_processing_steps!(
connectors::Fiserv,
connectors::Fiservemea,
connectors::Fiuu,
+ connectors::Globepay,
connectors::Helcim,
connectors::Novalnet,
connectors::Nexixpay,
+ connectors::Powertranz,
connectors::Stax,
- connectors::Taxjar
+ connectors::Taxjar,
+ connectors::Tsys,
+ connectors::Worldline
);
macro_rules! default_imp_for_approve {
@@ -287,11 +314,15 @@ default_imp_for_approve!(
connectors::Fiserv,
connectors::Fiservemea,
connectors::Fiuu,
+ connectors::Globepay,
connectors::Helcim,
connectors::Novalnet,
connectors::Nexixpay,
+ connectors::Powertranz,
connectors::Stax,
- connectors::Taxjar
+ connectors::Taxjar,
+ connectors::Tsys,
+ connectors::Worldline
);
macro_rules! default_imp_for_reject {
@@ -315,11 +346,15 @@ default_imp_for_reject!(
connectors::Fiserv,
connectors::Fiservemea,
connectors::Fiuu,
+ connectors::Globepay,
connectors::Helcim,
connectors::Novalnet,
connectors::Nexixpay,
+ connectors::Powertranz,
connectors::Stax,
- connectors::Taxjar
+ connectors::Taxjar,
+ connectors::Tsys,
+ connectors::Worldline
);
macro_rules! default_imp_for_webhook_source_verification {
@@ -343,11 +378,15 @@ default_imp_for_webhook_source_verification!(
connectors::Fiserv,
connectors::Fiservemea,
connectors::Fiuu,
+ connectors::Globepay,
connectors::Helcim,
connectors::Novalnet,
connectors::Nexixpay,
+ connectors::Powertranz,
connectors::Stax,
- connectors::Taxjar
+ connectors::Taxjar,
+ connectors::Tsys,
+ connectors::Worldline
);
macro_rules! default_imp_for_accept_dispute {
@@ -372,11 +411,15 @@ default_imp_for_accept_dispute!(
connectors::Fiserv,
connectors::Fiservemea,
connectors::Fiuu,
+ connectors::Globepay,
connectors::Helcim,
connectors::Novalnet,
connectors::Nexixpay,
+ connectors::Powertranz,
connectors::Stax,
- connectors::Taxjar
+ connectors::Taxjar,
+ connectors::Tsys,
+ connectors::Worldline
);
macro_rules! default_imp_for_submit_evidence {
@@ -400,11 +443,15 @@ default_imp_for_submit_evidence!(
connectors::Fiserv,
connectors::Fiservemea,
connectors::Fiuu,
+ connectors::Globepay,
connectors::Helcim,
connectors::Novalnet,
connectors::Nexixpay,
+ connectors::Powertranz,
connectors::Stax,
- connectors::Taxjar
+ connectors::Taxjar,
+ connectors::Tsys,
+ connectors::Worldline
);
macro_rules! default_imp_for_defend_dispute {
@@ -428,11 +475,15 @@ default_imp_for_defend_dispute!(
connectors::Fiserv,
connectors::Fiservemea,
connectors::Fiuu,
+ connectors::Globepay,
connectors::Helcim,
connectors::Novalnet,
connectors::Nexixpay,
+ connectors::Powertranz,
connectors::Stax,
- connectors::Taxjar
+ connectors::Taxjar,
+ connectors::Tsys,
+ connectors::Worldline
);
macro_rules! default_imp_for_file_upload {
@@ -465,11 +516,15 @@ default_imp_for_file_upload!(
connectors::Fiserv,
connectors::Fiservemea,
connectors::Fiuu,
+ connectors::Globepay,
connectors::Helcim,
connectors::Novalnet,
connectors::Nexixpay,
+ connectors::Powertranz,
connectors::Stax,
- connectors::Taxjar
+ connectors::Taxjar,
+ connectors::Tsys,
+ connectors::Worldline
);
#[cfg(feature = "payouts")]
@@ -495,11 +550,15 @@ default_imp_for_payouts_create!(
connectors::Fiserv,
connectors::Fiservemea,
connectors::Fiuu,
+ connectors::Globepay,
connectors::Helcim,
connectors::Novalnet,
connectors::Nexixpay,
+ connectors::Powertranz,
connectors::Stax,
- connectors::Taxjar
+ connectors::Taxjar,
+ connectors::Tsys,
+ connectors::Worldline
);
#[cfg(feature = "payouts")]
@@ -525,11 +584,15 @@ default_imp_for_payouts_retrieve!(
connectors::Fiserv,
connectors::Fiservemea,
connectors::Fiuu,
+ connectors::Globepay,
connectors::Helcim,
connectors::Novalnet,
connectors::Nexixpay,
+ connectors::Powertranz,
connectors::Stax,
- connectors::Taxjar
+ connectors::Taxjar,
+ connectors::Tsys,
+ connectors::Worldline
);
#[cfg(feature = "payouts")]
@@ -555,11 +618,15 @@ default_imp_for_payouts_eligibility!(
connectors::Fiserv,
connectors::Fiservemea,
connectors::Fiuu,
+ connectors::Globepay,
connectors::Helcim,
connectors::Novalnet,
connectors::Nexixpay,
+ connectors::Powertranz,
connectors::Stax,
- connectors::Taxjar
+ connectors::Taxjar,
+ connectors::Tsys,
+ connectors::Worldline
);
#[cfg(feature = "payouts")]
@@ -585,11 +652,15 @@ default_imp_for_payouts_fulfill!(
connectors::Fiserv,
connectors::Fiservemea,
connectors::Fiuu,
+ connectors::Globepay,
connectors::Helcim,
connectors::Novalnet,
connectors::Nexixpay,
+ connectors::Powertranz,
connectors::Stax,
- connectors::Taxjar
+ connectors::Taxjar,
+ connectors::Tsys,
+ connectors::Worldline
);
#[cfg(feature = "payouts")]
@@ -615,11 +686,15 @@ default_imp_for_payouts_cancel!(
connectors::Fiserv,
connectors::Fiservemea,
connectors::Fiuu,
+ connectors::Globepay,
connectors::Helcim,
connectors::Novalnet,
connectors::Nexixpay,
+ connectors::Powertranz,
connectors::Stax,
- connectors::Taxjar
+ connectors::Taxjar,
+ connectors::Tsys,
+ connectors::Worldline
);
#[cfg(feature = "payouts")]
@@ -645,11 +720,15 @@ default_imp_for_payouts_quote!(
connectors::Fiserv,
connectors::Fiservemea,
connectors::Fiuu,
+ connectors::Globepay,
connectors::Helcim,
connectors::Novalnet,
connectors::Nexixpay,
+ connectors::Powertranz,
connectors::Stax,
- connectors::Taxjar
+ connectors::Taxjar,
+ connectors::Tsys,
+ connectors::Worldline
);
#[cfg(feature = "payouts")]
@@ -675,11 +754,15 @@ default_imp_for_payouts_recipient!(
connectors::Fiserv,
connectors::Fiservemea,
connectors::Fiuu,
+ connectors::Globepay,
connectors::Helcim,
connectors::Novalnet,
connectors::Nexixpay,
+ connectors::Powertranz,
connectors::Stax,
- connectors::Taxjar
+ connectors::Taxjar,
+ connectors::Tsys,
+ connectors::Worldline
);
#[cfg(feature = "payouts")]
@@ -705,11 +788,15 @@ default_imp_for_payouts_recipient_account!(
connectors::Fiserv,
connectors::Fiservemea,
connectors::Fiuu,
+ connectors::Globepay,
connectors::Helcim,
connectors::Novalnet,
connectors::Nexixpay,
+ connectors::Powertranz,
connectors::Stax,
- connectors::Taxjar
+ connectors::Taxjar,
+ connectors::Tsys,
+ connectors::Worldline
);
#[cfg(feature = "frm")]
@@ -735,11 +822,15 @@ default_imp_for_frm_sale!(
connectors::Fiserv,
connectors::Fiservemea,
connectors::Fiuu,
+ connectors::Globepay,
connectors::Helcim,
connectors::Novalnet,
connectors::Nexixpay,
+ connectors::Powertranz,
connectors::Stax,
- connectors::Taxjar
+ connectors::Taxjar,
+ connectors::Tsys,
+ connectors::Worldline
);
#[cfg(feature = "frm")]
@@ -765,11 +856,15 @@ default_imp_for_frm_checkout!(
connectors::Fiserv,
connectors::Fiservemea,
connectors::Fiuu,
+ connectors::Globepay,
connectors::Helcim,
connectors::Novalnet,
connectors::Nexixpay,
+ connectors::Powertranz,
connectors::Stax,
- connectors::Taxjar
+ connectors::Taxjar,
+ connectors::Tsys,
+ connectors::Worldline
);
#[cfg(feature = "frm")]
@@ -795,11 +890,15 @@ default_imp_for_frm_transaction!(
connectors::Fiserv,
connectors::Fiservemea,
connectors::Fiuu,
+ connectors::Globepay,
connectors::Helcim,
connectors::Novalnet,
connectors::Nexixpay,
+ connectors::Powertranz,
connectors::Stax,
- connectors::Taxjar
+ connectors::Taxjar,
+ connectors::Tsys,
+ connectors::Worldline
);
#[cfg(feature = "frm")]
@@ -825,11 +924,15 @@ default_imp_for_frm_fulfillment!(
connectors::Fiserv,
connectors::Fiservemea,
connectors::Fiuu,
+ connectors::Globepay,
connectors::Helcim,
connectors::Novalnet,
connectors::Nexixpay,
+ connectors::Powertranz,
connectors::Stax,
- connectors::Taxjar
+ connectors::Taxjar,
+ connectors::Tsys,
+ connectors::Worldline
);
#[cfg(feature = "frm")]
@@ -855,11 +958,15 @@ default_imp_for_frm_record_return!(
connectors::Fiserv,
connectors::Fiservemea,
connectors::Fiuu,
+ connectors::Globepay,
connectors::Helcim,
connectors::Novalnet,
connectors::Nexixpay,
+ connectors::Powertranz,
connectors::Stax,
- connectors::Taxjar
+ connectors::Taxjar,
+ connectors::Tsys,
+ connectors::Worldline
);
macro_rules! default_imp_for_revoking_mandates {
@@ -882,9 +989,13 @@ default_imp_for_revoking_mandates!(
connectors::Fiserv,
connectors::Fiservemea,
connectors::Fiuu,
+ connectors::Globepay,
connectors::Helcim,
connectors::Novalnet,
connectors::Nexixpay,
+ connectors::Powertranz,
connectors::Stax,
- connectors::Taxjar
+ connectors::Taxjar,
+ connectors::Tsys,
+ connectors::Worldline
);
diff --git a/crates/hyperswitch_connectors/src/default_implementations_v2.rs b/crates/hyperswitch_connectors/src/default_implementations_v2.rs
index e3989e38a71..ae7f81ffd30 100644
--- a/crates/hyperswitch_connectors/src/default_implementations_v2.rs
+++ b/crates/hyperswitch_connectors/src/default_implementations_v2.rs
@@ -186,11 +186,15 @@ default_imp_for_new_connector_integration_payment!(
connectors::Fiserv,
connectors::Fiservemea,
connectors::Fiuu,
+ connectors::Globepay,
connectors::Helcim,
connectors::Novalnet,
connectors::Nexixpay,
+ connectors::Powertranz,
connectors::Stax,
- connectors::Taxjar
+ connectors::Taxjar,
+ connectors::Tsys,
+ connectors::Worldline
);
macro_rules! default_imp_for_new_connector_integration_refund {
@@ -215,11 +219,15 @@ default_imp_for_new_connector_integration_refund!(
connectors::Fiserv,
connectors::Fiservemea,
connectors::Fiuu,
+ connectors::Globepay,
connectors::Helcim,
connectors::Novalnet,
connectors::Nexixpay,
+ connectors::Powertranz,
connectors::Stax,
- connectors::Taxjar
+ connectors::Taxjar,
+ connectors::Tsys,
+ connectors::Worldline
);
macro_rules! default_imp_for_new_connector_integration_connector_access_token {
@@ -239,11 +247,15 @@ default_imp_for_new_connector_integration_connector_access_token!(
connectors::Fiserv,
connectors::Fiservemea,
connectors::Fiuu,
+ connectors::Globepay,
connectors::Helcim,
connectors::Novalnet,
connectors::Nexixpay,
+ connectors::Powertranz,
connectors::Stax,
- connectors::Taxjar
+ connectors::Taxjar,
+ connectors::Tsys,
+ connectors::Worldline
);
macro_rules! default_imp_for_new_connector_integration_accept_dispute {
@@ -269,11 +281,15 @@ default_imp_for_new_connector_integration_accept_dispute!(
connectors::Fiserv,
connectors::Fiservemea,
connectors::Fiuu,
+ connectors::Globepay,
connectors::Helcim,
connectors::Novalnet,
connectors::Nexixpay,
+ connectors::Powertranz,
connectors::Stax,
- connectors::Taxjar
+ connectors::Taxjar,
+ connectors::Tsys,
+ connectors::Worldline
);
macro_rules! default_imp_for_new_connector_integration_submit_evidence {
@@ -298,11 +314,15 @@ default_imp_for_new_connector_integration_submit_evidence!(
connectors::Fiserv,
connectors::Fiservemea,
connectors::Fiuu,
+ connectors::Globepay,
connectors::Helcim,
connectors::Novalnet,
connectors::Nexixpay,
+ connectors::Powertranz,
connectors::Stax,
- connectors::Taxjar
+ connectors::Taxjar,
+ connectors::Tsys,
+ connectors::Worldline
);
macro_rules! default_imp_for_new_connector_integration_defend_dispute {
@@ -327,11 +347,15 @@ default_imp_for_new_connector_integration_defend_dispute!(
connectors::Fiserv,
connectors::Fiservemea,
connectors::Fiuu,
+ connectors::Globepay,
connectors::Helcim,
connectors::Novalnet,
connectors::Nexixpay,
+ connectors::Powertranz,
connectors::Stax,
- connectors::Taxjar
+ connectors::Taxjar,
+ connectors::Tsys,
+ connectors::Worldline
);
macro_rules! default_imp_for_new_connector_integration_file_upload {
@@ -366,11 +390,15 @@ default_imp_for_new_connector_integration_file_upload!(
connectors::Fiserv,
connectors::Fiservemea,
connectors::Fiuu,
+ connectors::Globepay,
connectors::Helcim,
connectors::Novalnet,
connectors::Nexixpay,
+ connectors::Powertranz,
connectors::Stax,
- connectors::Taxjar
+ connectors::Taxjar,
+ connectors::Tsys,
+ connectors::Worldline
);
#[cfg(feature = "payouts")]
@@ -397,11 +425,15 @@ default_imp_for_new_connector_integration_payouts_create!(
connectors::Fiserv,
connectors::Fiservemea,
connectors::Fiuu,
+ connectors::Globepay,
connectors::Helcim,
connectors::Novalnet,
connectors::Nexixpay,
+ connectors::Powertranz,
connectors::Stax,
- connectors::Taxjar
+ connectors::Taxjar,
+ connectors::Tsys,
+ connectors::Worldline
);
#[cfg(feature = "payouts")]
@@ -428,11 +460,15 @@ default_imp_for_new_connector_integration_payouts_eligibility!(
connectors::Fiserv,
connectors::Fiservemea,
connectors::Fiuu,
+ connectors::Globepay,
connectors::Helcim,
connectors::Novalnet,
connectors::Nexixpay,
+ connectors::Powertranz,
connectors::Stax,
- connectors::Taxjar
+ connectors::Taxjar,
+ connectors::Tsys,
+ connectors::Worldline
);
#[cfg(feature = "payouts")]
@@ -459,11 +495,15 @@ default_imp_for_new_connector_integration_payouts_fulfill!(
connectors::Fiserv,
connectors::Fiservemea,
connectors::Fiuu,
+ connectors::Globepay,
connectors::Helcim,
connectors::Novalnet,
connectors::Nexixpay,
+ connectors::Powertranz,
connectors::Stax,
- connectors::Taxjar
+ connectors::Taxjar,
+ connectors::Tsys,
+ connectors::Worldline
);
#[cfg(feature = "payouts")]
@@ -490,11 +530,15 @@ default_imp_for_new_connector_integration_payouts_cancel!(
connectors::Fiserv,
connectors::Fiservemea,
connectors::Fiuu,
+ connectors::Globepay,
connectors::Helcim,
connectors::Novalnet,
connectors::Nexixpay,
+ connectors::Powertranz,
connectors::Stax,
- connectors::Taxjar
+ connectors::Taxjar,
+ connectors::Tsys,
+ connectors::Worldline
);
#[cfg(feature = "payouts")]
@@ -521,11 +565,15 @@ default_imp_for_new_connector_integration_payouts_quote!(
connectors::Fiserv,
connectors::Fiservemea,
connectors::Fiuu,
+ connectors::Globepay,
connectors::Helcim,
connectors::Novalnet,
connectors::Nexixpay,
+ connectors::Powertranz,
connectors::Stax,
- connectors::Taxjar
+ connectors::Taxjar,
+ connectors::Tsys,
+ connectors::Worldline
);
#[cfg(feature = "payouts")]
@@ -552,11 +600,15 @@ default_imp_for_new_connector_integration_payouts_recipient!(
connectors::Fiserv,
connectors::Fiservemea,
connectors::Fiuu,
+ connectors::Globepay,
connectors::Helcim,
connectors::Novalnet,
connectors::Nexixpay,
+ connectors::Powertranz,
connectors::Stax,
- connectors::Taxjar
+ connectors::Taxjar,
+ connectors::Tsys,
+ connectors::Worldline
);
#[cfg(feature = "payouts")]
@@ -583,11 +635,15 @@ default_imp_for_new_connector_integration_payouts_sync!(
connectors::Fiserv,
connectors::Fiservemea,
connectors::Fiuu,
+ connectors::Globepay,
connectors::Helcim,
connectors::Novalnet,
connectors::Nexixpay,
+ connectors::Powertranz,
connectors::Stax,
- connectors::Taxjar
+ connectors::Taxjar,
+ connectors::Tsys,
+ connectors::Worldline
);
#[cfg(feature = "payouts")]
@@ -614,11 +670,15 @@ default_imp_for_new_connector_integration_payouts_recipient_account!(
connectors::Fiserv,
connectors::Fiservemea,
connectors::Fiuu,
+ connectors::Globepay,
connectors::Helcim,
connectors::Novalnet,
connectors::Nexixpay,
+ connectors::Powertranz,
connectors::Stax,
- connectors::Taxjar
+ connectors::Taxjar,
+ connectors::Tsys,
+ connectors::Worldline
);
macro_rules! default_imp_for_new_connector_integration_webhook_source_verification {
@@ -643,11 +703,15 @@ default_imp_for_new_connector_integration_webhook_source_verification!(
connectors::Fiserv,
connectors::Fiservemea,
connectors::Fiuu,
+ connectors::Globepay,
connectors::Helcim,
connectors::Novalnet,
connectors::Nexixpay,
+ connectors::Powertranz,
connectors::Stax,
- connectors::Taxjar
+ connectors::Taxjar,
+ connectors::Tsys,
+ connectors::Worldline
);
#[cfg(feature = "frm")]
@@ -674,11 +738,15 @@ default_imp_for_new_connector_integration_frm_sale!(
connectors::Fiserv,
connectors::Fiservemea,
connectors::Fiuu,
+ connectors::Globepay,
connectors::Helcim,
connectors::Novalnet,
connectors::Nexixpay,
+ connectors::Powertranz,
connectors::Stax,
- connectors::Taxjar
+ connectors::Taxjar,
+ connectors::Tsys,
+ connectors::Worldline
);
#[cfg(feature = "frm")]
@@ -705,11 +773,15 @@ default_imp_for_new_connector_integration_frm_checkout!(
connectors::Fiserv,
connectors::Fiservemea,
connectors::Fiuu,
+ connectors::Globepay,
connectors::Helcim,
connectors::Novalnet,
connectors::Nexixpay,
+ connectors::Powertranz,
connectors::Stax,
- connectors::Taxjar
+ connectors::Taxjar,
+ connectors::Tsys,
+ connectors::Worldline
);
#[cfg(feature = "frm")]
@@ -736,11 +808,15 @@ default_imp_for_new_connector_integration_frm_transaction!(
connectors::Fiserv,
connectors::Fiservemea,
connectors::Fiuu,
+ connectors::Globepay,
connectors::Helcim,
connectors::Novalnet,
connectors::Nexixpay,
+ connectors::Powertranz,
connectors::Stax,
- connectors::Taxjar
+ connectors::Taxjar,
+ connectors::Tsys,
+ connectors::Worldline
);
#[cfg(feature = "frm")]
@@ -767,11 +843,15 @@ default_imp_for_new_connector_integration_frm_fulfillment!(
connectors::Fiserv,
connectors::Fiservemea,
connectors::Fiuu,
+ connectors::Globepay,
connectors::Helcim,
connectors::Novalnet,
connectors::Nexixpay,
+ connectors::Powertranz,
connectors::Stax,
- connectors::Taxjar
+ connectors::Taxjar,
+ connectors::Tsys,
+ connectors::Worldline
);
#[cfg(feature = "frm")]
@@ -798,11 +878,15 @@ default_imp_for_new_connector_integration_frm_record_return!(
connectors::Fiserv,
connectors::Fiservemea,
connectors::Fiuu,
+ connectors::Globepay,
connectors::Helcim,
connectors::Novalnet,
connectors::Nexixpay,
+ connectors::Powertranz,
connectors::Stax,
- connectors::Taxjar
+ connectors::Taxjar,
+ connectors::Tsys,
+ connectors::Worldline
);
macro_rules! default_imp_for_new_connector_integration_revoking_mandates {
@@ -826,9 +910,13 @@ default_imp_for_new_connector_integration_revoking_mandates!(
connectors::Fiserv,
connectors::Fiservemea,
connectors::Fiuu,
+ connectors::Globepay,
connectors::Helcim,
connectors::Novalnet,
connectors::Nexixpay,
+ connectors::Powertranz,
connectors::Stax,
- connectors::Taxjar
+ connectors::Taxjar,
+ connectors::Tsys,
+ connectors::Worldline
);
diff --git a/crates/hyperswitch_connectors/src/utils.rs b/crates/hyperswitch_connectors/src/utils.rs
index ebd3ff34704..e5ed9d3e7b4 100644
--- a/crates/hyperswitch_connectors/src/utils.rs
+++ b/crates/hyperswitch_connectors/src/utils.rs
@@ -1,3 +1,5 @@
+use std::collections::HashMap;
+
use api_models::payments::{self, Address, AddressDetails, OrderDetailsWithAmount, PhoneDetails};
use common_enums::{enums, enums::FutureUsage};
use common_utils::{
@@ -7,7 +9,7 @@ use common_utils::{
pii::{self, Email, IpAddress},
types::{AmountConvertor, MinorUnit},
};
-use error_stack::ResultExt;
+use error_stack::{report, ResultExt};
use hyperswitch_domain_models::{
payment_method_data::{Card, PaymentMethodData},
router_data::{PaymentMethodToken, RecurringMandatePaymentData},
@@ -19,6 +21,8 @@ use hyperswitch_domain_models::{
};
use hyperswitch_interfaces::{api, errors};
use masking::{ExposeInterface, PeekInterface, Secret};
+use once_cell::sync::Lazy;
+use regex::Regex;
use serde::Serializer;
type Error = error_stack::Report<errors::ConnectorError>;
@@ -607,8 +611,21 @@ impl<Flow, Request, Response> RouterData
}
}
+#[derive(Debug, Copy, Clone, strum::Display, Eq, Hash, PartialEq)]
+pub enum CardIssuer {
+ AmericanExpress,
+ Master,
+ Maestro,
+ Visa,
+ Discover,
+ DinersClub,
+ JCB,
+ CarteBlanche,
+}
+
pub trait CardData {
fn get_card_expiry_year_2_digit(&self) -> Result<Secret<String>, errors::ConnectorError>;
+ fn get_card_issuer(&self) -> Result<CardIssuer, Error>;
fn get_card_expiry_month_year_2_digit_with_delimiter(
&self,
delimiter: String,
@@ -631,6 +648,9 @@ impl CardData for Card {
.to_string(),
))
}
+ fn get_card_issuer(&self) -> Result<CardIssuer, Error> {
+ get_card_issuer(self.card_number.peek())
+ }
fn get_card_expiry_month_year_2_digit_with_delimiter(
&self,
delimiter: String,
@@ -691,6 +711,45 @@ impl CardData for Card {
}
}
+#[track_caller]
+fn get_card_issuer(card_number: &str) -> Result<CardIssuer, Error> {
+ for (k, v) in CARD_REGEX.iter() {
+ let regex: Regex = v
+ .clone()
+ .change_context(errors::ConnectorError::RequestEncodingFailed)?;
+ if regex.is_match(card_number) {
+ return Ok(*k);
+ }
+ }
+ Err(error_stack::Report::new(
+ errors::ConnectorError::NotImplemented("Card Type".into()),
+ ))
+}
+
+static CARD_REGEX: Lazy<HashMap<CardIssuer, Result<Regex, regex::Error>>> = Lazy::new(|| {
+ let mut map = HashMap::new();
+ // Reference: https://gist.github.com/michaelkeevildown/9096cd3aac9029c4e6e05588448a8841
+ // [#379]: Determine card issuer from card BIN number
+ map.insert(CardIssuer::Master, Regex::new(r"^5[1-5][0-9]{14}$"));
+ map.insert(CardIssuer::AmericanExpress, Regex::new(r"^3[47][0-9]{13}$"));
+ map.insert(CardIssuer::Visa, Regex::new(r"^4[0-9]{12}(?:[0-9]{3})?$"));
+ map.insert(CardIssuer::Discover, Regex::new(r"^65[4-9][0-9]{13}|64[4-9][0-9]{13}|6011[0-9]{12}|(622(?:12[6-9]|1[3-9][0-9]|[2-8][0-9][0-9]|9[01][0-9]|92[0-5])[0-9]{10})$"));
+ map.insert(
+ CardIssuer::Maestro,
+ Regex::new(r"^(5018|5020|5038|5893|6304|6759|6761|6762|6763)[0-9]{8,15}$"),
+ );
+ map.insert(
+ CardIssuer::DinersClub,
+ Regex::new(r"^3(?:0[0-5]|[68][0-9])[0-9]{11}$"),
+ );
+ map.insert(
+ CardIssuer::JCB,
+ Regex::new(r"^(3(?:088|096|112|158|337|5(?:2[89]|[3-8][0-9]))\d{12})$"),
+ );
+ map.insert(CardIssuer::CarteBlanche, Regex::new(r"^389[0-9]{11}$"));
+ map
+});
+
pub trait AddressDetailsData {
fn get_first_name(&self) -> Result<&Secret<String>, Error>;
fn get_last_name(&self) -> Result<&Secret<String>, Error>;
@@ -1215,6 +1274,34 @@ impl BrowserInformationData for BrowserInformation {
}
}
+pub fn get_header_key_value<'a>(
+ key: &str,
+ headers: &'a actix_web::http::header::HeaderMap,
+) -> CustomResult<&'a str, errors::ConnectorError> {
+ get_header_field(headers.get(key))
+}
+
+pub fn get_http_header<'a>(
+ key: &str,
+ headers: &'a http::HeaderMap,
+) -> CustomResult<&'a str, errors::ConnectorError> {
+ get_header_field(headers.get(key))
+}
+
+fn get_header_field(
+ field: Option<&http::HeaderValue>,
+) -> CustomResult<&str, errors::ConnectorError> {
+ field
+ .map(|header_value| {
+ header_value
+ .to_str()
+ .change_context(errors::ConnectorError::WebhookSignatureNotFound)
+ })
+ .ok_or(report!(
+ errors::ConnectorError::WebhookSourceVerificationFailed
+ ))?
+}
+
#[macro_export]
macro_rules! unimplemented_payment_method {
($payment_method:expr, $connector:expr) => {
diff --git a/crates/router/src/connector.rs b/crates/router/src/connector.rs
index f093832db43..e6e7453b033 100644
--- a/crates/router/src/connector.rs
+++ b/crates/router/src/connector.rs
@@ -21,7 +21,6 @@ pub mod dummyconnector;
pub mod ebanx;
pub mod forte;
pub mod globalpay;
-pub mod globepay;
pub mod gocardless;
pub mod gpayments;
pub mod iatapay;
@@ -45,7 +44,6 @@ pub mod paypal;
pub mod payu;
pub mod placetopay;
pub mod plaid;
-pub mod powertranz;
pub mod prophetpay;
pub mod rapyd;
pub mod razorpay;
@@ -56,21 +54,20 @@ pub mod square;
pub mod stripe;
pub mod threedsecureio;
pub mod trustpay;
-pub mod tsys;
pub mod utils;
pub mod volt;
pub mod wellsfargo;
pub mod wellsfargopayout;
pub mod wise;
-pub mod worldline;
pub mod worldpay;
pub mod zen;
pub mod zsl;
pub use hyperswitch_connectors::connectors::{
bambora, bambora::Bambora, bitpay, bitpay::Bitpay, fiserv, fiserv::Fiserv, fiservemea,
- fiservemea::Fiservemea, fiuu, fiuu::Fiuu, helcim, helcim::Helcim, nexixpay, nexixpay::Nexixpay,
- novalnet, novalnet::Novalnet, stax, stax::Stax, taxjar, taxjar::Taxjar,
+ fiservemea::Fiservemea, fiuu, fiuu::Fiuu, globepay, globepay::Globepay, helcim, helcim::Helcim,
+ nexixpay, nexixpay::Nexixpay, novalnet, novalnet::Novalnet, powertranz, powertranz::Powertranz,
+ stax, stax::Stax, taxjar, taxjar::Taxjar, tsys, tsys::Tsys, worldline, worldline::Worldline,
};
#[cfg(feature = "dummy_connector")]
@@ -81,14 +78,13 @@ pub use self::{
billwerk::Billwerk, bluesnap::Bluesnap, boku::Boku, braintree::Braintree,
cashtocode::Cashtocode, checkout::Checkout, coinbase::Coinbase, cryptopay::Cryptopay,
cybersource::Cybersource, datatrans::Datatrans, dlocal::Dlocal, ebanx::Ebanx, forte::Forte,
- globalpay::Globalpay, globepay::Globepay, gocardless::Gocardless, gpayments::Gpayments,
- iatapay::Iatapay, itaubank::Itaubank, klarna::Klarna, mifinity::Mifinity, mollie::Mollie,
+ globalpay::Globalpay, gocardless::Gocardless, gpayments::Gpayments, iatapay::Iatapay,
+ itaubank::Itaubank, klarna::Klarna, mifinity::Mifinity, mollie::Mollie,
multisafepay::Multisafepay, netcetera::Netcetera, nexinets::Nexinets, nmi::Nmi, noon::Noon,
nuvei::Nuvei, opayo::Opayo, opennode::Opennode, paybox::Paybox, payeezy::Payeezy, payme::Payme,
payone::Payone, paypal::Paypal, payu::Payu, placetopay::Placetopay, plaid::Plaid,
- powertranz::Powertranz, prophetpay::Prophetpay, rapyd::Rapyd, razorpay::Razorpay,
- riskified::Riskified, shift4::Shift4, signifyd::Signifyd, square::Square, stripe::Stripe,
- threedsecureio::Threedsecureio, trustpay::Trustpay, tsys::Tsys, volt::Volt,
- wellsfargo::Wellsfargo, wellsfargopayout::Wellsfargopayout, wise::Wise, worldline::Worldline,
- worldpay::Worldpay, zen::Zen, zsl::Zsl,
+ prophetpay::Prophetpay, rapyd::Rapyd, razorpay::Razorpay, riskified::Riskified, shift4::Shift4,
+ signifyd::Signifyd, square::Square, stripe::Stripe, threedsecureio::Threedsecureio,
+ trustpay::Trustpay, volt::Volt, wellsfargo::Wellsfargo, wellsfargopayout::Wellsfargopayout,
+ wise::Wise, worldpay::Worldpay, zen::Zen, zsl::Zsl,
};
diff --git a/crates/router/src/core/payments/connector_integration_v2_impls.rs b/crates/router/src/core/payments/connector_integration_v2_impls.rs
index cd38c087dd2..0a98fdfdb92 100644
--- a/crates/router/src/core/payments/connector_integration_v2_impls.rs
+++ b/crates/router/src/core/payments/connector_integration_v2_impls.rs
@@ -655,7 +655,6 @@ default_imp_for_new_connector_integration_payment!(
connector::Ebanx,
connector::Forte,
connector::Globalpay,
- connector::Globepay,
connector::Gocardless,
connector::Gpayments,
connector::Iatapay,
@@ -678,7 +677,6 @@ default_imp_for_new_connector_integration_payment!(
connector::Paypal,
connector::Payu,
connector::Placetopay,
- connector::Powertranz,
connector::Prophetpay,
connector::Rapyd,
connector::Razorpay,
@@ -689,12 +687,10 @@ default_imp_for_new_connector_integration_payment!(
connector::Shift4,
connector::Trustpay,
connector::Threedsecureio,
- connector::Tsys,
connector::Volt,
connector::Wellsfargo,
connector::Wellsfargopayout,
connector::Wise,
- connector::Worldline,
connector::Worldpay,
connector::Zen,
connector::Zsl,
@@ -739,7 +735,6 @@ default_imp_for_new_connector_integration_refund!(
connector::Ebanx,
connector::Forte,
connector::Globalpay,
- connector::Globepay,
connector::Gocardless,
connector::Gpayments,
connector::Iatapay,
@@ -762,7 +757,6 @@ default_imp_for_new_connector_integration_refund!(
connector::Paypal,
connector::Payu,
connector::Placetopay,
- connector::Powertranz,
connector::Prophetpay,
connector::Rapyd,
connector::Razorpay,
@@ -773,11 +767,9 @@ default_imp_for_new_connector_integration_refund!(
connector::Shift4,
connector::Trustpay,
connector::Threedsecureio,
- connector::Tsys,
connector::Volt,
connector::Wellsfargo,
connector::Wise,
- connector::Worldline,
connector::Worldpay,
connector::Zen,
connector::Zsl,
@@ -817,7 +809,6 @@ default_imp_for_new_connector_integration_connector_access_token!(
connector::Ebanx,
connector::Forte,
connector::Globalpay,
- connector::Globepay,
connector::Gocardless,
connector::Gpayments,
connector::Iatapay,
@@ -840,7 +831,6 @@ default_imp_for_new_connector_integration_connector_access_token!(
connector::Paypal,
connector::Payu,
connector::Placetopay,
- connector::Powertranz,
connector::Prophetpay,
connector::Rapyd,
connector::Razorpay,
@@ -851,11 +841,9 @@ default_imp_for_new_connector_integration_connector_access_token!(
connector::Shift4,
connector::Trustpay,
connector::Threedsecureio,
- connector::Tsys,
connector::Volt,
connector::Wellsfargo,
connector::Wise,
- connector::Worldline,
connector::Worldpay,
connector::Zen,
connector::Zsl,
@@ -917,7 +905,6 @@ default_imp_for_new_connector_integration_accept_dispute!(
connector::Ebanx,
connector::Forte,
connector::Globalpay,
- connector::Globepay,
connector::Gocardless,
connector::Gpayments,
connector::Iatapay,
@@ -940,7 +927,6 @@ default_imp_for_new_connector_integration_accept_dispute!(
connector::Paypal,
connector::Payu,
connector::Placetopay,
- connector::Powertranz,
connector::Prophetpay,
connector::Rapyd,
connector::Razorpay,
@@ -951,11 +937,9 @@ default_imp_for_new_connector_integration_accept_dispute!(
connector::Shift4,
connector::Trustpay,
connector::Threedsecureio,
- connector::Tsys,
connector::Volt,
connector::Wellsfargo,
connector::Wise,
- connector::Worldline,
connector::Worldpay,
connector::Zen,
connector::Zsl,
@@ -999,7 +983,6 @@ default_imp_for_new_connector_integration_defend_dispute!(
connector::Ebanx,
connector::Forte,
connector::Globalpay,
- connector::Globepay,
connector::Gocardless,
connector::Gpayments,
connector::Iatapay,
@@ -1022,7 +1005,6 @@ default_imp_for_new_connector_integration_defend_dispute!(
connector::Paypal,
connector::Payu,
connector::Placetopay,
- connector::Powertranz,
connector::Prophetpay,
connector::Rapyd,
connector::Razorpay,
@@ -1033,11 +1015,9 @@ default_imp_for_new_connector_integration_defend_dispute!(
connector::Shift4,
connector::Trustpay,
connector::Threedsecureio,
- connector::Tsys,
connector::Volt,
connector::Wellsfargo,
connector::Wise,
- connector::Worldline,
connector::Worldpay,
connector::Zen,
connector::Zsl,
@@ -1065,7 +1045,6 @@ default_imp_for_new_connector_integration_submit_evidence!(
connector::Ebanx,
connector::Forte,
connector::Globalpay,
- connector::Globepay,
connector::Gocardless,
connector::Gpayments,
connector::Iatapay,
@@ -1088,7 +1067,6 @@ default_imp_for_new_connector_integration_submit_evidence!(
connector::Paypal,
connector::Payu,
connector::Placetopay,
- connector::Powertranz,
connector::Prophetpay,
connector::Rapyd,
connector::Razorpay,
@@ -1099,11 +1077,9 @@ default_imp_for_new_connector_integration_submit_evidence!(
connector::Shift4,
connector::Trustpay,
connector::Threedsecureio,
- connector::Tsys,
connector::Volt,
connector::Wellsfargo,
connector::Wise,
- connector::Worldline,
connector::Worldpay,
connector::Zen,
connector::Zsl,
@@ -1158,7 +1134,6 @@ default_imp_for_new_connector_integration_file_upload!(
connector::Ebanx,
connector::Forte,
connector::Globalpay,
- connector::Globepay,
connector::Gocardless,
connector::Gpayments,
connector::Iatapay,
@@ -1181,7 +1156,6 @@ default_imp_for_new_connector_integration_file_upload!(
connector::Paypal,
connector::Payu,
connector::Placetopay,
- connector::Powertranz,
connector::Prophetpay,
connector::Rapyd,
connector::Razorpay,
@@ -1192,11 +1166,9 @@ default_imp_for_new_connector_integration_file_upload!(
connector::Shift4,
connector::Trustpay,
connector::Threedsecureio,
- connector::Tsys,
connector::Volt,
connector::Wellsfargo,
connector::Wise,
- connector::Worldline,
connector::Worldpay,
connector::Zen,
connector::Zsl,
@@ -1328,7 +1300,6 @@ default_imp_for_new_connector_integration_payouts_create!(
connector::Ebanx,
connector::Forte,
connector::Globalpay,
- connector::Globepay,
connector::Gocardless,
connector::Gpayments,
connector::Iatapay,
@@ -1351,7 +1322,6 @@ default_imp_for_new_connector_integration_payouts_create!(
connector::Paypal,
connector::Payu,
connector::Placetopay,
- connector::Powertranz,
connector::Prophetpay,
connector::Rapyd,
connector::Razorpay,
@@ -1362,11 +1332,9 @@ default_imp_for_new_connector_integration_payouts_create!(
connector::Shift4,
connector::Trustpay,
connector::Threedsecureio,
- connector::Tsys,
connector::Volt,
connector::Wellsfargo,
connector::Wise,
- connector::Worldline,
connector::Worldpay,
connector::Zen,
connector::Zsl,
@@ -1413,7 +1381,6 @@ default_imp_for_new_connector_integration_payouts_eligibility!(
connector::Ebanx,
connector::Forte,
connector::Globalpay,
- connector::Globepay,
connector::Gocardless,
connector::Gpayments,
connector::Iatapay,
@@ -1436,7 +1403,6 @@ default_imp_for_new_connector_integration_payouts_eligibility!(
connector::Paypal,
connector::Payu,
connector::Placetopay,
- connector::Powertranz,
connector::Prophetpay,
connector::Rapyd,
connector::Razorpay,
@@ -1447,11 +1413,9 @@ default_imp_for_new_connector_integration_payouts_eligibility!(
connector::Shift4,
connector::Trustpay,
connector::Threedsecureio,
- connector::Tsys,
connector::Volt,
connector::Wellsfargo,
connector::Wise,
- connector::Worldline,
connector::Worldpay,
connector::Zen,
connector::Zsl,
@@ -1498,7 +1462,6 @@ default_imp_for_new_connector_integration_payouts_fulfill!(
connector::Ebanx,
connector::Forte,
connector::Globalpay,
- connector::Globepay,
connector::Gocardless,
connector::Gpayments,
connector::Iatapay,
@@ -1521,7 +1484,6 @@ default_imp_for_new_connector_integration_payouts_fulfill!(
connector::Paypal,
connector::Payu,
connector::Placetopay,
- connector::Powertranz,
connector::Prophetpay,
connector::Rapyd,
connector::Razorpay,
@@ -1532,11 +1494,9 @@ default_imp_for_new_connector_integration_payouts_fulfill!(
connector::Shift4,
connector::Trustpay,
connector::Threedsecureio,
- connector::Tsys,
connector::Volt,
connector::Wellsfargo,
connector::Wise,
- connector::Worldline,
connector::Worldpay,
connector::Zen,
connector::Zsl,
@@ -1583,7 +1543,6 @@ default_imp_for_new_connector_integration_payouts_cancel!(
connector::Ebanx,
connector::Forte,
connector::Globalpay,
- connector::Globepay,
connector::Gocardless,
connector::Gpayments,
connector::Iatapay,
@@ -1606,7 +1565,6 @@ default_imp_for_new_connector_integration_payouts_cancel!(
connector::Paypal,
connector::Payu,
connector::Placetopay,
- connector::Powertranz,
connector::Prophetpay,
connector::Rapyd,
connector::Razorpay,
@@ -1617,11 +1575,9 @@ default_imp_for_new_connector_integration_payouts_cancel!(
connector::Shift4,
connector::Trustpay,
connector::Threedsecureio,
- connector::Tsys,
connector::Volt,
connector::Wellsfargo,
connector::Wise,
- connector::Worldline,
connector::Worldpay,
connector::Zen,
connector::Zsl,
@@ -1668,7 +1624,6 @@ default_imp_for_new_connector_integration_payouts_quote!(
connector::Ebanx,
connector::Forte,
connector::Globalpay,
- connector::Globepay,
connector::Gocardless,
connector::Gpayments,
connector::Iatapay,
@@ -1691,7 +1646,6 @@ default_imp_for_new_connector_integration_payouts_quote!(
connector::Paypal,
connector::Payu,
connector::Placetopay,
- connector::Powertranz,
connector::Prophetpay,
connector::Rapyd,
connector::Razorpay,
@@ -1702,11 +1656,9 @@ default_imp_for_new_connector_integration_payouts_quote!(
connector::Shift4,
connector::Trustpay,
connector::Threedsecureio,
- connector::Tsys,
connector::Volt,
connector::Wellsfargo,
connector::Wise,
- connector::Worldline,
connector::Worldpay,
connector::Zen,
connector::Zsl,
@@ -1753,7 +1705,6 @@ default_imp_for_new_connector_integration_payouts_recipient!(
connector::Ebanx,
connector::Forte,
connector::Globalpay,
- connector::Globepay,
connector::Gocardless,
connector::Gpayments,
connector::Iatapay,
@@ -1776,7 +1727,6 @@ default_imp_for_new_connector_integration_payouts_recipient!(
connector::Paypal,
connector::Payu,
connector::Placetopay,
- connector::Powertranz,
connector::Prophetpay,
connector::Rapyd,
connector::Razorpay,
@@ -1787,11 +1737,9 @@ default_imp_for_new_connector_integration_payouts_recipient!(
connector::Shift4,
connector::Trustpay,
connector::Threedsecureio,
- connector::Tsys,
connector::Volt,
connector::Wellsfargo,
connector::Wise,
- connector::Worldline,
connector::Worldpay,
connector::Zen,
connector::Zsl,
@@ -1838,7 +1786,6 @@ default_imp_for_new_connector_integration_payouts_sync!(
connector::Ebanx,
connector::Forte,
connector::Globalpay,
- connector::Globepay,
connector::Gocardless,
connector::Gpayments,
connector::Iatapay,
@@ -1861,7 +1808,6 @@ default_imp_for_new_connector_integration_payouts_sync!(
connector::Paypal,
connector::Payu,
connector::Placetopay,
- connector::Powertranz,
connector::Prophetpay,
connector::Rapyd,
connector::Razorpay,
@@ -1872,11 +1818,9 @@ default_imp_for_new_connector_integration_payouts_sync!(
connector::Shift4,
connector::Threedsecureio,
connector::Trustpay,
- connector::Tsys,
connector::Volt,
connector::Wellsfargo,
connector::Wise,
- connector::Worldline,
connector::Worldpay,
connector::Zen,
connector::Zsl,
@@ -1923,7 +1867,6 @@ default_imp_for_new_connector_integration_payouts_recipient_account!(
connector::Ebanx,
connector::Forte,
connector::Globalpay,
- connector::Globepay,
connector::Gocardless,
connector::Gpayments,
connector::Iatapay,
@@ -1946,7 +1889,6 @@ default_imp_for_new_connector_integration_payouts_recipient_account!(
connector::Paypal,
connector::Payu,
connector::Placetopay,
- connector::Powertranz,
connector::Prophetpay,
connector::Rapyd,
connector::Razorpay,
@@ -1957,11 +1899,9 @@ default_imp_for_new_connector_integration_payouts_recipient_account!(
connector::Shift4,
connector::Trustpay,
connector::Threedsecureio,
- connector::Tsys,
connector::Volt,
connector::Wellsfargo,
connector::Wise,
- connector::Worldline,
connector::Worldpay,
connector::Zen,
connector::Zsl,
@@ -2006,7 +1946,6 @@ default_imp_for_new_connector_integration_webhook_source_verification!(
connector::Ebanx,
connector::Forte,
connector::Globalpay,
- connector::Globepay,
connector::Gocardless,
connector::Gpayments,
connector::Iatapay,
@@ -2029,7 +1968,6 @@ default_imp_for_new_connector_integration_webhook_source_verification!(
connector::Paypal,
connector::Payu,
connector::Placetopay,
- connector::Powertranz,
connector::Prophetpay,
connector::Rapyd,
connector::Razorpay,
@@ -2040,11 +1978,9 @@ default_imp_for_new_connector_integration_webhook_source_verification!(
connector::Shift4,
connector::Trustpay,
connector::Threedsecureio,
- connector::Tsys,
connector::Volt,
connector::Wellsfargo,
connector::Wise,
- connector::Worldline,
connector::Worldpay,
connector::Zen,
connector::Zsl,
@@ -2176,7 +2112,6 @@ default_imp_for_new_connector_integration_frm_sale!(
connector::Ebanx,
connector::Forte,
connector::Globalpay,
- connector::Globepay,
connector::Gocardless,
connector::Gpayments,
connector::Iatapay,
@@ -2199,7 +2134,6 @@ default_imp_for_new_connector_integration_frm_sale!(
connector::Paypal,
connector::Payu,
connector::Placetopay,
- connector::Powertranz,
connector::Prophetpay,
connector::Rapyd,
connector::Razorpay,
@@ -2210,11 +2144,9 @@ default_imp_for_new_connector_integration_frm_sale!(
connector::Shift4,
connector::Trustpay,
connector::Threedsecureio,
- connector::Tsys,
connector::Volt,
connector::Wellsfargo,
connector::Wise,
- connector::Worldline,
connector::Worldpay,
connector::Zen,
connector::Zsl,
@@ -2261,7 +2193,6 @@ default_imp_for_new_connector_integration_frm_checkout!(
connector::Ebanx,
connector::Forte,
connector::Globalpay,
- connector::Globepay,
connector::Gocardless,
connector::Gpayments,
connector::Iatapay,
@@ -2284,7 +2215,6 @@ default_imp_for_new_connector_integration_frm_checkout!(
connector::Paypal,
connector::Payu,
connector::Placetopay,
- connector::Powertranz,
connector::Prophetpay,
connector::Rapyd,
connector::Razorpay,
@@ -2295,11 +2225,9 @@ default_imp_for_new_connector_integration_frm_checkout!(
connector::Shift4,
connector::Trustpay,
connector::Threedsecureio,
- connector::Tsys,
connector::Volt,
connector::Wellsfargo,
connector::Wise,
- connector::Worldline,
connector::Worldpay,
connector::Zen,
connector::Zsl,
@@ -2346,7 +2274,6 @@ default_imp_for_new_connector_integration_frm_transaction!(
connector::Ebanx,
connector::Forte,
connector::Globalpay,
- connector::Globepay,
connector::Gocardless,
connector::Gpayments,
connector::Iatapay,
@@ -2369,7 +2296,6 @@ default_imp_for_new_connector_integration_frm_transaction!(
connector::Paypal,
connector::Payu,
connector::Placetopay,
- connector::Powertranz,
connector::Prophetpay,
connector::Rapyd,
connector::Razorpay,
@@ -2380,11 +2306,9 @@ default_imp_for_new_connector_integration_frm_transaction!(
connector::Shift4,
connector::Trustpay,
connector::Threedsecureio,
- connector::Tsys,
connector::Volt,
connector::Wellsfargo,
connector::Wise,
- connector::Worldline,
connector::Worldpay,
connector::Zen,
connector::Zsl,
@@ -2431,7 +2355,6 @@ default_imp_for_new_connector_integration_frm_fulfillment!(
connector::Ebanx,
connector::Forte,
connector::Globalpay,
- connector::Globepay,
connector::Gocardless,
connector::Gpayments,
connector::Iatapay,
@@ -2454,7 +2377,6 @@ default_imp_for_new_connector_integration_frm_fulfillment!(
connector::Paypal,
connector::Payu,
connector::Placetopay,
- connector::Powertranz,
connector::Prophetpay,
connector::Rapyd,
connector::Razorpay,
@@ -2465,11 +2387,9 @@ default_imp_for_new_connector_integration_frm_fulfillment!(
connector::Shift4,
connector::Trustpay,
connector::Threedsecureio,
- connector::Tsys,
connector::Volt,
connector::Wellsfargo,
connector::Wise,
- connector::Worldline,
connector::Worldpay,
connector::Zen,
connector::Zsl,
@@ -2516,7 +2436,6 @@ default_imp_for_new_connector_integration_frm_record_return!(
connector::Ebanx,
connector::Forte,
connector::Globalpay,
- connector::Globepay,
connector::Gocardless,
connector::Gpayments,
connector::Iatapay,
@@ -2539,7 +2458,6 @@ default_imp_for_new_connector_integration_frm_record_return!(
connector::Paypal,
connector::Payu,
connector::Placetopay,
- connector::Powertranz,
connector::Prophetpay,
connector::Rapyd,
connector::Razorpay,
@@ -2550,11 +2468,9 @@ default_imp_for_new_connector_integration_frm_record_return!(
connector::Shift4,
connector::Trustpay,
connector::Threedsecureio,
- connector::Tsys,
connector::Volt,
connector::Wellsfargo,
connector::Wise,
- connector::Worldline,
connector::Worldpay,
connector::Zen,
connector::Zsl,
@@ -2598,7 +2514,6 @@ default_imp_for_new_connector_integration_revoking_mandates!(
connector::Ebanx,
connector::Forte,
connector::Globalpay,
- connector::Globepay,
connector::Gocardless,
connector::Gpayments,
connector::Iatapay,
@@ -2621,7 +2536,6 @@ default_imp_for_new_connector_integration_revoking_mandates!(
connector::Paypal,
connector::Payu,
connector::Placetopay,
- connector::Powertranz,
connector::Prophetpay,
connector::Rapyd,
connector::Razorpay,
@@ -2632,11 +2546,9 @@ default_imp_for_new_connector_integration_revoking_mandates!(
connector::Shift4,
connector::Trustpay,
connector::Threedsecureio,
- connector::Tsys,
connector::Volt,
connector::Wellsfargo,
connector::Wise,
- connector::Worldline,
connector::Worldpay,
connector::Zen,
connector::Zsl,
diff --git a/crates/router/src/core/payments/flows.rs b/crates/router/src/core/payments/flows.rs
index 6cf07bca148..0650797ce1d 100644
--- a/crates/router/src/core/payments/flows.rs
+++ b/crates/router/src/core/payments/flows.rs
@@ -214,7 +214,6 @@ default_imp_for_complete_authorize!(
connector::Dlocal,
connector::Ebanx,
connector::Forte,
- connector::Globepay,
connector::Gocardless,
connector::Gpayments,
connector::Iatapay,
@@ -241,12 +240,10 @@ default_imp_for_complete_authorize!(
connector::Stripe,
connector::Threedsecureio,
connector::Trustpay,
- connector::Tsys,
connector::Volt,
connector::Wise,
connector::Wellsfargo,
connector::Wellsfargopayout,
- connector::Worldline,
connector::Worldpay,
connector::Zen,
connector::Zsl
@@ -299,7 +296,6 @@ default_imp_for_webhook_source_verification!(
connector::Ebanx,
connector::Forte,
connector::Globalpay,
- connector::Globepay,
connector::Gocardless,
connector::Gpayments,
connector::Iatapay,
@@ -322,7 +318,6 @@ default_imp_for_webhook_source_verification!(
connector::Payu,
connector::Placetopay,
connector::Plaid,
- connector::Powertranz,
connector::Prophetpay,
connector::Rapyd,
connector::Razorpay,
@@ -333,12 +328,10 @@ default_imp_for_webhook_source_verification!(
connector::Stripe,
connector::Threedsecureio,
connector::Trustpay,
- connector::Tsys,
connector::Volt,
connector::Wellsfargo,
connector::Wellsfargopayout,
connector::Wise,
- connector::Worldline,
connector::Worldpay,
connector::Zen,
connector::Zsl
@@ -393,7 +386,6 @@ default_imp_for_create_customer!(
connector::Ebanx,
connector::Forte,
connector::Globalpay,
- connector::Globepay,
connector::Gpayments,
connector::Iatapay,
connector::Itaubank,
@@ -416,7 +408,6 @@ default_imp_for_create_customer!(
connector::Payu,
connector::Placetopay,
connector::Plaid,
- connector::Powertranz,
connector::Prophetpay,
connector::Rapyd,
connector::Razorpay,
@@ -426,12 +417,10 @@ default_imp_for_create_customer!(
connector::Square,
connector::Threedsecureio,
connector::Trustpay,
- connector::Tsys,
connector::Volt,
connector::Wellsfargo,
connector::Wellsfargopayout,
connector::Wise,
- connector::Worldline,
connector::Worldpay,
connector::Zen,
connector::Zsl
@@ -482,7 +471,6 @@ default_imp_for_connector_redirect_response!(
connector::Dlocal,
connector::Ebanx,
connector::Forte,
- connector::Globepay,
connector::Gocardless,
connector::Gpayments,
connector::Iatapay,
@@ -500,7 +488,6 @@ default_imp_for_connector_redirect_response!(
connector::Payu,
connector::Placetopay,
connector::Plaid,
- connector::Powertranz,
connector::Prophetpay,
connector::Rapyd,
connector::Razorpay,
@@ -509,12 +496,10 @@ default_imp_for_connector_redirect_response!(
connector::Signifyd,
connector::Square,
connector::Threedsecureio,
- connector::Tsys,
connector::Volt,
connector::Wellsfargo,
connector::Wellsfargopayout,
connector::Wise,
- connector::Worldline,
connector::Worldpay,
connector::Zsl
);
@@ -656,7 +641,6 @@ default_imp_for_accept_dispute!(
connector::Ebanx,
connector::Forte,
connector::Globalpay,
- connector::Globepay,
connector::Gocardless,
connector::Gpayments,
connector::Iatapay,
@@ -680,7 +664,6 @@ default_imp_for_accept_dispute!(
connector::Payu,
connector::Placetopay,
connector::Plaid,
- connector::Powertranz,
connector::Prophetpay,
connector::Rapyd,
connector::Razorpay,
@@ -691,12 +674,10 @@ default_imp_for_accept_dispute!(
connector::Stripe,
connector::Threedsecureio,
connector::Trustpay,
- connector::Tsys,
connector::Volt,
connector::Wellsfargo,
connector::Wellsfargopayout,
connector::Wise,
- connector::Worldline,
connector::Worldpay,
connector::Zen,
connector::Zsl
@@ -771,7 +752,6 @@ default_imp_for_file_upload!(
connector::Ebanx,
connector::Forte,
connector::Globalpay,
- connector::Globepay,
connector::Gocardless,
connector::Gpayments,
connector::Iatapay,
@@ -794,7 +774,6 @@ default_imp_for_file_upload!(
connector::Payu,
connector::Placetopay,
connector::Plaid,
- connector::Powertranz,
connector::Prophetpay,
connector::Rapyd,
connector::Razorpay,
@@ -804,13 +783,11 @@ default_imp_for_file_upload!(
connector::Square,
connector::Threedsecureio,
connector::Trustpay,
- connector::Tsys,
connector::Volt,
connector::Opennode,
connector::Wellsfargo,
connector::Wellsfargopayout,
connector::Wise,
- connector::Worldline,
connector::Worldpay,
connector::Zen,
connector::Zsl
@@ -863,7 +840,6 @@ default_imp_for_submit_evidence!(
connector::Ebanx,
connector::Forte,
connector::Globalpay,
- connector::Globepay,
connector::Gocardless,
connector::Gpayments,
connector::Iatapay,
@@ -886,7 +862,6 @@ default_imp_for_submit_evidence!(
connector::Payu,
connector::Placetopay,
connector::Plaid,
- connector::Powertranz,
connector::Prophetpay,
connector::Rapyd,
connector::Razorpay,
@@ -896,13 +871,11 @@ default_imp_for_submit_evidence!(
connector::Square,
connector::Threedsecureio,
connector::Trustpay,
- connector::Tsys,
connector::Volt,
connector::Opennode,
connector::Wellsfargo,
connector::Wellsfargopayout,
connector::Wise,
- connector::Worldline,
connector::Worldpay,
connector::Zen,
connector::Zsl
@@ -953,7 +926,6 @@ default_imp_for_defend_dispute!(
connector::Datatrans,
connector::Dlocal,
connector::Ebanx,
- connector::Globepay,
connector::Forte,
connector::Globalpay,
connector::Gocardless,
@@ -978,7 +950,6 @@ default_imp_for_defend_dispute!(
connector::Payu,
connector::Placetopay,
connector::Plaid,
- connector::Powertranz,
connector::Prophetpay,
connector::Rapyd,
connector::Razorpay,
@@ -989,13 +960,11 @@ default_imp_for_defend_dispute!(
connector::Stripe,
connector::Threedsecureio,
connector::Trustpay,
- connector::Tsys,
connector::Volt,
connector::Opennode,
connector::Wellsfargo,
connector::Wellsfargopayout,
connector::Wise,
- connector::Worldline,
connector::Worldpay,
connector::Zen,
connector::Zsl
@@ -1064,7 +1033,6 @@ default_imp_for_pre_processing_steps!(
connector::Itaubank,
connector::Forte,
connector::Globalpay,
- connector::Globepay,
connector::Gpayments,
connector::Klarna,
connector::Mifinity,
@@ -1081,7 +1049,6 @@ default_imp_for_pre_processing_steps!(
connector::Payu,
connector::Placetopay,
connector::Plaid,
- connector::Powertranz,
connector::Prophetpay,
connector::Rapyd,
connector::Razorpay,
@@ -1089,12 +1056,10 @@ default_imp_for_pre_processing_steps!(
connector::Signifyd,
connector::Square,
connector::Threedsecureio,
- connector::Tsys,
connector::Volt,
connector::Wellsfargo,
connector::Wellsfargopayout,
connector::Wise,
- connector::Worldline,
connector::Worldpay,
connector::Zen,
connector::Zsl
@@ -1144,7 +1109,6 @@ default_imp_for_post_processing_steps!(
connector::Itaubank,
connector::Forte,
connector::Globalpay,
- connector::Globepay,
connector::Gpayments,
connector::Klarna,
connector::Mifinity,
@@ -1160,19 +1124,16 @@ default_imp_for_post_processing_steps!(
connector::Payone,
connector::Payu,
connector::Placetopay,
- connector::Powertranz,
connector::Prophetpay,
connector::Rapyd,
connector::Riskified,
connector::Signifyd,
connector::Square,
connector::Threedsecureio,
- connector::Tsys,
connector::Volt,
connector::Wellsfargo,
connector::Wellsfargopayout,
connector::Wise,
- connector::Worldline,
connector::Worldpay,
connector::Zen,
connector::Zsl,
@@ -1308,7 +1269,6 @@ default_imp_for_payouts_create!(
connector::Dlocal,
connector::Forte,
connector::Globalpay,
- connector::Globepay,
connector::Gocardless,
connector::Gpayments,
connector::Iatapay,
@@ -1331,7 +1291,6 @@ default_imp_for_payouts_create!(
connector::Payu,
connector::Placetopay,
connector::Plaid,
- connector::Powertranz,
connector::Prophetpay,
connector::Rapyd,
connector::Razorpay,
@@ -1341,11 +1300,9 @@ default_imp_for_payouts_create!(
connector::Shift4,
connector::Threedsecureio,
connector::Trustpay,
- connector::Tsys,
connector::Volt,
connector::Wellsfargo,
connector::Wellsfargopayout,
- connector::Worldline,
connector::Worldpay,
connector::Zen,
connector::Zsl
@@ -1401,7 +1358,6 @@ default_imp_for_payouts_retrieve!(
connector::Ebanx,
connector::Forte,
connector::Globalpay,
- connector::Globepay,
connector::Gocardless,
connector::Gpayments,
connector::Iatapay,
@@ -1424,7 +1380,6 @@ default_imp_for_payouts_retrieve!(
connector::Payu,
connector::Placetopay,
connector::Plaid,
- connector::Powertranz,
connector::Prophetpay,
connector::Rapyd,
connector::Razorpay,
@@ -1435,12 +1390,10 @@ default_imp_for_payouts_retrieve!(
connector::Shift4,
connector::Threedsecureio,
connector::Trustpay,
- connector::Tsys,
connector::Volt,
connector::Wellsfargo,
connector::Wellsfargopayout,
connector::Wise,
- connector::Worldline,
connector::Worldpay,
connector::Zen,
connector::Zsl
@@ -1497,7 +1450,6 @@ default_imp_for_payouts_eligibility!(
connector::Dlocal,
connector::Forte,
connector::Globalpay,
- connector::Globepay,
connector::Gocardless,
connector::Gpayments,
connector::Iatapay,
@@ -1521,7 +1473,6 @@ default_imp_for_payouts_eligibility!(
connector::Payu,
connector::Placetopay,
connector::Plaid,
- connector::Powertranz,
connector::Prophetpay,
connector::Rapyd,
connector::Razorpay,
@@ -1532,11 +1483,9 @@ default_imp_for_payouts_eligibility!(
connector::Shift4,
connector::Threedsecureio,
connector::Trustpay,
- connector::Tsys,
connector::Volt,
connector::Wellsfargo,
connector::Wellsfargopayout,
- connector::Worldline,
connector::Worldpay,
connector::Zen,
connector::Zsl
@@ -1588,7 +1537,6 @@ default_imp_for_payouts_fulfill!(
connector::Dlocal,
connector::Forte,
connector::Globalpay,
- connector::Globepay,
connector::Gocardless,
connector::Gpayments,
connector::Iatapay,
@@ -1610,7 +1558,6 @@ default_imp_for_payouts_fulfill!(
connector::Payu,
connector::Placetopay,
connector::Plaid,
- connector::Powertranz,
connector::Prophetpay,
connector::Rapyd,
connector::Razorpay,
@@ -1620,11 +1567,9 @@ default_imp_for_payouts_fulfill!(
connector::Shift4,
connector::Threedsecureio,
connector::Trustpay,
- connector::Tsys,
connector::Volt,
connector::Wellsfargo,
connector::Wellsfargopayout,
- connector::Worldline,
connector::Worldpay,
connector::Zen,
connector::Zsl
@@ -1678,7 +1623,6 @@ default_imp_for_payouts_cancel!(
connector::Dlocal,
connector::Forte,
connector::Globalpay,
- connector::Globepay,
connector::Gocardless,
connector::Gpayments,
connector::Iatapay,
@@ -1702,7 +1646,6 @@ default_imp_for_payouts_cancel!(
connector::Payu,
connector::Placetopay,
connector::Plaid,
- connector::Powertranz,
connector::Prophetpay,
connector::Rapyd,
connector::Razorpay,
@@ -1712,11 +1655,9 @@ default_imp_for_payouts_cancel!(
connector::Shift4,
connector::Threedsecureio,
connector::Trustpay,
- connector::Tsys,
connector::Volt,
connector::Wellsfargo,
connector::Wellsfargopayout,
- connector::Worldline,
connector::Worldpay,
connector::Zen,
connector::Zsl
@@ -1771,7 +1712,6 @@ default_imp_for_payouts_quote!(
connector::Dlocal,
connector::Forte,
connector::Globalpay,
- connector::Globepay,
connector::Gocardless,
connector::Gpayments,
connector::Iatapay,
@@ -1795,7 +1735,6 @@ default_imp_for_payouts_quote!(
connector::Payu,
connector::Placetopay,
connector::Plaid,
- connector::Powertranz,
connector::Prophetpay,
connector::Rapyd,
connector::Razorpay,
@@ -1806,11 +1745,9 @@ default_imp_for_payouts_quote!(
connector::Shift4,
connector::Threedsecureio,
connector::Trustpay,
- connector::Tsys,
connector::Volt,
connector::Wellsfargo,
connector::Wellsfargopayout,
- connector::Worldline,
connector::Worldpay,
connector::Zen,
connector::Zsl
@@ -1865,7 +1802,6 @@ default_imp_for_payouts_recipient!(
connector::Dlocal,
connector::Forte,
connector::Globalpay,
- connector::Globepay,
connector::Gocardless,
connector::Gpayments,
connector::Iatapay,
@@ -1889,7 +1825,6 @@ default_imp_for_payouts_recipient!(
connector::Payu,
connector::Placetopay,
connector::Plaid,
- connector::Powertranz,
connector::Prophetpay,
connector::Rapyd,
connector::Razorpay,
@@ -1899,11 +1834,9 @@ default_imp_for_payouts_recipient!(
connector::Shift4,
connector::Threedsecureio,
connector::Trustpay,
- connector::Tsys,
connector::Volt,
connector::Wellsfargo,
connector::Wellsfargopayout,
- connector::Worldline,
connector::Worldpay,
connector::Zen,
connector::Zsl
@@ -1962,7 +1895,6 @@ default_imp_for_payouts_recipient_account!(
connector::Ebanx,
connector::Forte,
connector::Globalpay,
- connector::Globepay,
connector::Gocardless,
connector::Gpayments,
connector::Iatapay,
@@ -1986,7 +1918,6 @@ default_imp_for_payouts_recipient_account!(
connector::Payu,
connector::Placetopay,
connector::Plaid,
- connector::Powertranz,
connector::Prophetpay,
connector::Rapyd,
connector::Razorpay,
@@ -1996,12 +1927,10 @@ default_imp_for_payouts_recipient_account!(
connector::Shift4,
connector::Threedsecureio,
connector::Trustpay,
- connector::Tsys,
connector::Volt,
connector::Wellsfargo,
connector::Wellsfargopayout,
connector::Wise,
- connector::Worldline,
connector::Worldpay,
connector::Zen,
connector::Zsl
@@ -2056,7 +1985,6 @@ default_imp_for_approve!(
connector::Ebanx,
connector::Forte,
connector::Globalpay,
- connector::Globepay,
connector::Gocardless,
connector::Gpayments,
connector::Iatapay,
@@ -2080,7 +2008,6 @@ default_imp_for_approve!(
connector::Payu,
connector::Placetopay,
connector::Plaid,
- connector::Powertranz,
connector::Prophetpay,
connector::Rapyd,
connector::Razorpay,
@@ -2091,12 +2018,10 @@ default_imp_for_approve!(
connector::Shift4,
connector::Threedsecureio,
connector::Trustpay,
- connector::Tsys,
connector::Volt,
connector::Wellsfargo,
connector::Wellsfargopayout,
connector::Wise,
- connector::Worldline,
connector::Worldpay,
connector::Zen,
connector::Zsl
@@ -2151,7 +2076,6 @@ default_imp_for_reject!(
connector::Ebanx,
connector::Forte,
connector::Globalpay,
- connector::Globepay,
connector::Gocardless,
connector::Gpayments,
connector::Iatapay,
@@ -2175,7 +2099,6 @@ default_imp_for_reject!(
connector::Payu,
connector::Placetopay,
connector::Plaid,
- connector::Powertranz,
connector::Prophetpay,
connector::Rapyd,
connector::Razorpay,
@@ -2186,12 +2109,10 @@ default_imp_for_reject!(
connector::Shift4,
connector::Threedsecureio,
connector::Trustpay,
- connector::Tsys,
connector::Volt,
connector::Wellsfargo,
connector::Wellsfargopayout,
connector::Wise,
- connector::Worldline,
connector::Worldpay,
connector::Zen,
connector::Zsl
@@ -2335,7 +2256,6 @@ default_imp_for_frm_sale!(
connector::Ebanx,
connector::Forte,
connector::Globalpay,
- connector::Globepay,
connector::Gocardless,
connector::Gpayments,
connector::Iatapay,
@@ -2359,7 +2279,6 @@ default_imp_for_frm_sale!(
connector::Payu,
connector::Placetopay,
connector::Plaid,
- connector::Powertranz,
connector::Prophetpay,
connector::Rapyd,
connector::Razorpay,
@@ -2368,12 +2287,10 @@ default_imp_for_frm_sale!(
connector::Shift4,
connector::Threedsecureio,
connector::Trustpay,
- connector::Tsys,
connector::Volt,
connector::Wellsfargo,
connector::Wellsfargopayout,
connector::Wise,
- connector::Worldline,
connector::Worldpay,
connector::Zen,
connector::Zsl
@@ -2430,7 +2347,6 @@ default_imp_for_frm_checkout!(
connector::Ebanx,
connector::Forte,
connector::Globalpay,
- connector::Globepay,
connector::Gocardless,
connector::Gpayments,
connector::Iatapay,
@@ -2454,7 +2370,6 @@ default_imp_for_frm_checkout!(
connector::Payu,
connector::Placetopay,
connector::Plaid,
- connector::Powertranz,
connector::Prophetpay,
connector::Rapyd,
connector::Razorpay,
@@ -2463,12 +2378,10 @@ default_imp_for_frm_checkout!(
connector::Shift4,
connector::Threedsecureio,
connector::Trustpay,
- connector::Tsys,
connector::Volt,
connector::Wellsfargo,
connector::Wellsfargopayout,
connector::Wise,
- connector::Worldline,
connector::Worldpay,
connector::Zen,
connector::Zsl
@@ -2525,7 +2438,6 @@ default_imp_for_frm_transaction!(
connector::Ebanx,
connector::Forte,
connector::Globalpay,
- connector::Globepay,
connector::Gocardless,
connector::Gpayments,
connector::Iatapay,
@@ -2549,7 +2461,6 @@ default_imp_for_frm_transaction!(
connector::Payu,
connector::Placetopay,
connector::Plaid,
- connector::Powertranz,
connector::Prophetpay,
connector::Rapyd,
connector::Razorpay,
@@ -2558,12 +2469,10 @@ default_imp_for_frm_transaction!(
connector::Shift4,
connector::Threedsecureio,
connector::Trustpay,
- connector::Tsys,
connector::Volt,
connector::Wellsfargo,
connector::Wellsfargopayout,
connector::Wise,
- connector::Worldline,
connector::Worldpay,
connector::Zen,
connector::Zsl
@@ -2620,7 +2529,6 @@ default_imp_for_frm_fulfillment!(
connector::Ebanx,
connector::Forte,
connector::Globalpay,
- connector::Globepay,
connector::Gocardless,
connector::Gpayments,
connector::Iatapay,
@@ -2644,7 +2552,6 @@ default_imp_for_frm_fulfillment!(
connector::Payu,
connector::Placetopay,
connector::Plaid,
- connector::Powertranz,
connector::Prophetpay,
connector::Rapyd,
connector::Razorpay,
@@ -2653,12 +2560,10 @@ default_imp_for_frm_fulfillment!(
connector::Shift4,
connector::Threedsecureio,
connector::Trustpay,
- connector::Tsys,
connector::Volt,
connector::Wellsfargo,
connector::Wellsfargopayout,
connector::Wise,
- connector::Worldline,
connector::Worldpay,
connector::Zen,
connector::Zsl
@@ -2715,7 +2620,6 @@ default_imp_for_frm_record_return!(
connector::Ebanx,
connector::Forte,
connector::Globalpay,
- connector::Globepay,
connector::Gocardless,
connector::Gpayments,
connector::Iatapay,
@@ -2739,7 +2643,6 @@ default_imp_for_frm_record_return!(
connector::Payu,
connector::Placetopay,
connector::Plaid,
- connector::Powertranz,
connector::Prophetpay,
connector::Rapyd,
connector::Razorpay,
@@ -2748,12 +2651,10 @@ default_imp_for_frm_record_return!(
connector::Shift4,
connector::Threedsecureio,
connector::Trustpay,
- connector::Tsys,
connector::Volt,
connector::Wellsfargo,
connector::Wellsfargopayout,
connector::Wise,
- connector::Worldline,
connector::Worldpay,
connector::Zen,
connector::Zsl
@@ -2807,7 +2708,6 @@ default_imp_for_incremental_authorization!(
connector::Ebanx,
connector::Forte,
connector::Globalpay,
- connector::Globepay,
connector::Gocardless,
connector::Gpayments,
connector::Iatapay,
@@ -2831,7 +2731,6 @@ default_imp_for_incremental_authorization!(
connector::Payu,
connector::Placetopay,
connector::Plaid,
- connector::Powertranz,
connector::Prophetpay,
connector::Rapyd,
connector::Razorpay,
@@ -2842,11 +2741,9 @@ default_imp_for_incremental_authorization!(
connector::Shift4,
connector::Threedsecureio,
connector::Trustpay,
- connector::Tsys,
connector::Volt,
connector::Wellsfargopayout,
connector::Wise,
- connector::Worldline,
connector::Worldpay,
connector::Zen,
connector::Zsl
@@ -2898,7 +2795,6 @@ default_imp_for_revoking_mandates!(
connector::Ebanx,
connector::Forte,
connector::Globalpay,
- connector::Globepay,
connector::Gocardless,
connector::Gpayments,
connector::Iatapay,
@@ -2921,7 +2817,6 @@ default_imp_for_revoking_mandates!(
connector::Payu,
connector::Placetopay,
connector::Plaid,
- connector::Powertranz,
connector::Prophetpay,
connector::Rapyd,
connector::Razorpay,
@@ -2932,10 +2827,8 @@ default_imp_for_revoking_mandates!(
connector::Shift4,
connector::Threedsecureio,
connector::Trustpay,
- connector::Tsys,
connector::Volt,
connector::Wise,
- connector::Worldline,
connector::Worldpay,
connector::Zen,
connector::Zsl
@@ -3148,7 +3041,6 @@ default_imp_for_authorize_session_token!(
connector::Ebanx,
connector::Forte,
connector::Globalpay,
- connector::Globepay,
connector::Gocardless,
connector::Gpayments,
connector::Iatapay,
@@ -3171,7 +3063,6 @@ default_imp_for_authorize_session_token!(
connector::Payu,
connector::Placetopay,
connector::Plaid,
- connector::Powertranz,
connector::Prophetpay,
connector::Rapyd,
connector::Razorpay,
@@ -3181,12 +3072,10 @@ default_imp_for_authorize_session_token!(
connector::Shift4,
connector::Threedsecureio,
connector::Trustpay,
- connector::Tsys,
connector::Volt,
connector::Wellsfargo,
connector::Wellsfargopayout,
connector::Wise,
- connector::Worldline,
connector::Worldpay,
connector::Zen,
connector::Zsl
|
2024-08-30T12:29:57Z
|
## Type of Change
<!-- Put an `x` in the boxes that apply -->
- [ ] Bugfix
- [ ] New feature
- [ ] Enhancement
- [ ] Refactoring
- [ ] Dependency updates
- [ ] Documentation
- [ ] CI/CD
## Description
<!-- Describe your changes in detail -->
### Additional Changes
- [ ] This PR modifies the API contract
- [ ] This PR modifies the database schema
- [ ] This PR modifies application configuration/environment variables
<!--
Provide links to the files with corresponding changes.
Following are the paths where you can find config files:
1. `config`
2. `crates/router/src/configs`
3. `loadtest/config`
-->
## Motivation and Context
<!--
Why is this change required? What problem does it solve?
If it fixes an open issue, please link to the issue here.
If you don't have an issue, we'd recommend starting with one first so the PR
can focus on the implementation (unless it is an obvious bug or documentation fix
that will have little conversation).
-->
https://github.com/juspay/hyperswitch/issues/5759
## How did you test it?
<!--
Did you write an integration/unit/API test to verify the code changes?
Or did you test this change manually (provide relevant screenshots)?
-->
1. Worldline:
Request:
```
curl --location 'http://localhost:8080/payments' \
--header 'Content-Type: application/json' \
--header 'Accept: application/json' \
--header 'api-key: dev_CwqDbNztbMVSQb2nXB765MuZZ42QdqKJ5Bs4XPlC6s0e20sqfhi59GInfhqaRWLL' \
--data '{
"amount": 2980,
"currency": "GBP",
"confirm": true,
"customer_id": "customer123",
"payment_method": "card",
"payment_method_type": "credit",
"payment_method_data": {
"card": {
"card_number": "4567350000427977",
"card_exp_month": "10",
"card_exp_year": "25",
"card_holder_name": "joseph Doe",
"card_cvc": "123"
}
},
"billing": {
"address": {
"country": "US"
},
"phone": {
"number": "8056594427",
"country_code": "+44"
}
}
}'
```
Response:
```
{
"payment_id": "pay_vx9YCgwBjjL6FeFdGz4i",
"merchant_id": "merchant_1725268605",
"status": "processing",
"amount": 2980,
"net_amount": 2980,
"amount_capturable": 0,
"amount_received": null,
"connector": "worldline",
"client_secret": "pay_vx9YCgwBjjL6FeFdGz4i_secret_H5QXqheAQBQqyKasRbVX",
"created": "2024-09-02T09:34:06.186Z",
"currency": "GBP",
"customer_id": "customer123",
"customer": {
"id": "customer123",
"name": "John Doe",
"email": "customer@gmail.com",
"phone": "9999999999",
"phone_country_code": "+1"
},
"description": null,
"refunds": null,
"disputes": null,
"mandate_id": null,
"mandate_data": null,
"setup_future_usage": null,
"off_session": null,
"capture_on": null,
"capture_method": null,
"payment_method": "card",
"payment_method_data": {
"card": {
"last4": "7977",
"card_type": null,
"card_network": null,
"card_issuer": null,
"card_issuing_country": null,
"card_isin": "456735",
"card_extended_bin": null,
"card_exp_month": "10",
"card_exp_year": "25",
"card_holder_name": null,
"payment_checks": null,
"authentication_data": null
},
"billing": null
},
"payment_token": null,
"shipping": null,
"billing": {
"address": {
"city": null,
"country": "US",
"line1": null,
"line2": null,
"line3": null,
"zip": null,
"state": null,
"first_name": null,
"last_name": null
},
"phone": {
"number": "8056594427",
"country_code": "+44"
},
"email": null
},
"order_details": null,
"email": "customer@gmail.com",
"name": "John Doe",
"phone": "9999999999",
"return_url": null,
"authentication_type": "no_three_ds",
"statement_descriptor_name": null,
"statement_descriptor_suffix": null,
"next_action": null,
"cancellation_reason": null,
"error_code": null,
"error_message": null,
"unified_code": null,
"unified_message": null,
"payment_experience": null,
"payment_method_type": "credit",
"connector_label": null,
"business_country": null,
"business_label": "default",
"business_sub_label": null,
"allowed_payment_method_types": null,
"ephemeral_key": {
"customer_id": "customer123",
"created_at": 1725269646,
"expires": 1725273246,
"secret": "epk_a0d661efb5264d76948f0dc2f5ff15d8"
},
"manual_retry_allowed": false,
"connector_transaction_id": "000000113200000161210000100001",
"frm_message": null,
"metadata": null,
"connector_metadata": null,
"feature_metadata": null,
"reference_id": "000000113200000161210000100001",
"payment_link": null,
"profile_id": "pro_W9NsQwrIh7qVDMa4Bktf",
"surcharge_details": null,
"attempt_count": 1,
"merchant_decision": null,
"merchant_connector_id": "mca_m3RwegNJwdLuak50MVPc",
"incremental_authorization_allowed": null,
"authorization_count": null,
"incremental_authorizations": null,
"external_authentication_details": null,
"external_3ds_authentication_attempted": false,
"expires_on": "2024-09-02T09:49:06.186Z",
"fingerprint": null,
"browser_info": null,
"payment_method_id": null,
"payment_method_status": null,
"updated": "2024-09-02T09:34:07.353Z",
"charges": null,
"frm_metadata": null,
"merchant_order_reference_id": null
}
```
2. Globepay:
Request:
```
curl --location 'http://localhost:8080/payments' \
--header 'Content-Type: application/json' \
--header 'Accept: application/json' \
--header 'api-key: dev_njzwR5DqT1Qs2CHNooqmGECzaX1dUZxtJPGhNAPWU5NHFjjqS41YbWytVmsiLEZW' \
--data '{
"amount": 6540,
"currency": "GBP",
"confirm": true,
"capture_method": "automatic",
"customer_id": "customer123",
"payment_method": "wallet",
"payment_method_type": "we_chat_pay",
"payment_method_data": {
"wallet": {
"we_chat_pay_qr": {}
}
},
"description": "Its my first payment request"
}'
```
Response:
```
{
"payment_id": "pay_dwBc0BicdRUttxbtSTS1",
"merchant_id": "merchant_1725270185",
"status": "requires_customer_action",
"amount": 6540,
"net_amount": 6540,
"amount_capturable": 6540,
"amount_received": null,
"connector": "globepay",
"client_secret": "pay_dwBc0BicdRUttxbtSTS1_secret_8461fh9sP2tvSWiDILr7",
"created": "2024-09-02T09:48:25.461Z",
"currency": "GBP",
"customer_id": "customer123",
"customer": {
"id": "customer123",
"name": "John Doe",
"email": "customer@gmail.com",
"phone": "9999999999",
"phone_country_code": "+1"
},
"description": "Its my first payment request",
"refunds": null,
"disputes": null,
"mandate_id": null,
"mandate_data": null,
"setup_future_usage": null,
"off_session": null,
"capture_on": null,
"capture_method": "automatic",
"payment_method": "wallet",
"payment_method_data": {
"wallet": {},
"billing": null
},
"payment_token": null,
"shipping": null,
"billing": null,
"order_details": null,
"email": "customer@gmail.com",
"name": "John Doe",
"phone": "9999999999",
"return_url": null,
"authentication_type": "no_three_ds",
"statement_descriptor_name": null,
"statement_descriptor_suffix": null,
"next_action": {
"type": "qr_code_information",
"image_data_url": "data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAASwAAAEsAQAAAABRBrPYAAACFElEQVR42u2aO5LDIBBERxHH0E31uSlH2JBILNM92GvLrtqULigHMnqJh54vtvqf9WMTm9jEJjYxBewyX3vNW6pn+17MUr1S9t2khflzY/Je1oOvytp29nilhGVL2HSzuE1OZ/Jmtili3DxLaOBIstjuxw1TQORnlcQgcmsKX9vpt7eu9vTFF4bGELiaO799Psa3obFYxZYCd/aH9WvOGhlzg/jPXyNkNQbkWXxHCWsK903ko4UYfHl5FbkG1sIyAbrz9pS9FgZtI/swSjM+345eAMNB0xrGB6ZdT1JS2OXFcEX2wadQ3pm8FgbnLca1hVnsZpDxMa8r/NwXFP8Qua8TlpHCcOheEhv9N8rjW3M3PBY6RzF8RZ2coYT10sL8mZtd5E3hLvJ7wz44xgKD4QvabmnIPBl5LtbC8NsXnnjv6ah2S1JYi1qH+7LH5ObX8OJPIhfAsLmXyEdLzNZQdVQ1jN06+50TOr8Sh05SWPVNei5EHgLw6cSrLwyPMWR1I3hdgS4vygwxjLUx27qt15BvzZ0EFkN+WuDAM01UqxyGGNVduE/VELqVsF43sm/Nj0N/lBwyWB+WsnRE8i0hdRPDEidOoeoDZRVagzeRC2C8vgmGlnlYQxCDLy8cqXHO5qFbEWMCws2y4fSPWzIaH4uLqhoiX+Pm0d6GMONjfy6qMAZ/lhZHksLmX1wmNrGJTUwf+wVePQd56UlWcQAAAABJRU5ErkJggg==",
"display_to_timestamp": null,
"qr_code_url": null
},
"cancellation_reason": null,
"error_code": null,
"error_message": null,
"unified_code": null,
"unified_message": null,
"payment_experience": null,
"payment_method_type": "we_chat_pay",
"connector_label": null,
"business_country": null,
"business_label": "default",
"business_sub_label": null,
"allowed_payment_method_types": null,
"ephemeral_key": {
"customer_id": "customer123",
"created_at": 1725270505,
"expires": 1725274105,
"secret": "epk_8afa80cd997e4be4be43e6221f9b300d"
},
"manual_retry_allowed": null,
"connector_transaction_id": "0000920240902094826388089",
"frm_message": null,
"metadata": null,
"connector_metadata": null,
"feature_metadata": null,
"reference_id": null,
"payment_link": null,
"profile_id": "pro_fsEcq42jh4O69UULhH9o",
"surcharge_details": null,
"attempt_count": 1,
"merchant_decision": null,
"merchant_connector_id": "mca_7iZkoKSF0rPm0B1cKcCg",
"incremental_authorization_allowed": null,
"authorization_count": null,
"incremental_authorizations": null,
"external_authentication_details": null,
"external_3ds_authentication_attempted": false,
"expires_on": "2024-09-02T10:03:25.461Z",
"fingerprint": null,
"browser_info": null,
"payment_method_id": null,
"payment_method_status": null,
"updated": "2024-09-02T09:48:26.385Z",
"charges": null,
"frm_metadata": null,
"merchant_order_reference_id": null
}
```
3. We are unable to test Powertranz and Tsys for now as we do not have working sandbox credentials.
## Checklist
<!-- Put an `x` in the boxes that apply -->
- [x] I formatted the code `cargo +nightly fmt --all`
- [x] I addressed lints thrown by `cargo clippy`
- [x] I reviewed the submitted code
- [ ] I added unit tests for my changes where possible
|
c03587f9c6e8ad444cebac92fd5134fe01c71728
|
|
juspay/hyperswitch
|
juspay__hyperswitch-5756
|
Bug: Interfacing of client and gRPC communications to Dynamo
Building a gRPC Client for communicating with the Dynamo server, once the dynamic routing feature has been enabled.
The dynamic routing feature would be a compile time as well as runtime feature flag ,
for providing the flexibility to enable and disable the dynamic routing during deployment
#### Possible Implementation:
Once dynamic routing has been enabled , we will store the default config in the algorithm column in routing table as the following jsonb:
```
{
"id": "merchant_id",
"params": "card",
"labels": ["stripe","adyen"],
"config": {
"min_aggregates_size": 2,
"default_success_rate": 100.0
}
}
```
gRPC client will be integrated as a dynamic dispatch field of the DynamicRouting trait within the struct SessionState,
which would be under the dynamic_routing feature flag
```
struct SessionState
{
pub grpc: Box<dyn DynamicRouting>
}
```
The DynamicRouting trait would have following functions:
calculate_the_success_rate
update_the_success_rates
```
triat DynamicRouting
{
async fn calculate_success_rate(self,label_input : Vec<T>) -> CalSuccessRateResponse
async fn update_success_rate(self,calculated_success_rate:CalSuccessRateResponse) -> UpdateSuccessRateWindowResponse
}
```
The trait DynamicRouting would be implemented on the the struct SuccessRateCalculator taken from the .proto file
```
impl DynamicRouting for SuccessRateCalculator
{
async fn calculate_success_rate(self,label_input : T) -> CalSuccessRateResponse
{
self.fetch_success_rate(request)
}
async fn update_success_rate(self,calculated_success_rate : CalSuccessRateResponse) -> UpdateSuccessRateWindowResponse
{
self.update_success_rate_window(request)
}
}
```
|
diff --git a/Cargo.lock b/Cargo.lock
index 11036b42dc4..d90c577152d 100644
--- a/Cargo.lock
+++ b/Cargo.lock
@@ -1433,7 +1433,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "3b829e4e32b91e643de6eafe82b1d90675f5874230191a4ffbc1b336dec4d6bf"
dependencies = [
"async-trait",
- "axum-core",
+ "axum-core 0.3.4",
"bitflags 1.3.2",
"bytes 1.7.1",
"futures-util",
@@ -1454,6 +1454,33 @@ dependencies = [
"tower-service",
]
+[[package]]
+name = "axum"
+version = "0.7.5"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "3a6c9af12842a67734c9a2e355436e5d03b22383ed60cf13cd0c18fbfe3dcbcf"
+dependencies = [
+ "async-trait",
+ "axum-core 0.4.3",
+ "bytes 1.7.1",
+ "futures-util",
+ "http 1.1.0",
+ "http-body 1.0.1",
+ "http-body-util",
+ "itoa",
+ "matchit",
+ "memchr",
+ "mime",
+ "percent-encoding",
+ "pin-project-lite",
+ "rustversion",
+ "serde",
+ "sync_wrapper 1.0.1",
+ "tower",
+ "tower-layer",
+ "tower-service",
+]
+
[[package]]
name = "axum-core"
version = "0.3.4"
@@ -1471,6 +1498,26 @@ dependencies = [
"tower-service",
]
+[[package]]
+name = "axum-core"
+version = "0.4.3"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "a15c63fd72d41492dc4f497196f5da1fb04fb7529e631d73630d1b491e47a2e3"
+dependencies = [
+ "async-trait",
+ "bytes 1.7.1",
+ "futures-util",
+ "http 1.1.0",
+ "http-body 1.0.1",
+ "http-body-util",
+ "mime",
+ "pin-project-lite",
+ "rustversion",
+ "sync_wrapper 0.1.2",
+ "tower-layer",
+ "tower-service",
+]
+
[[package]]
name = "backtrace"
version = "0.3.73"
@@ -3064,6 +3111,7 @@ dependencies = [
name = "external_services"
version = "0.1.0"
dependencies = [
+ "api_models",
"async-trait",
"aws-config 0.55.3",
"aws-sdk-kms",
@@ -3081,10 +3129,15 @@ dependencies = [
"hyperswitch_interfaces",
"masking",
"once_cell",
+ "prost 0.13.2",
"router_env",
"serde",
"thiserror",
"tokio 1.40.0",
+ "tonic 0.12.2",
+ "tonic-build",
+ "tonic-reflection",
+ "tonic-types",
"vaultrs",
]
@@ -3160,6 +3213,12 @@ version = "0.2.9"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "28dea519a9695b9977216879a3ebfddf92f1c08c05d984f8996aecd6ecdc811d"
+[[package]]
+name = "fixedbitset"
+version = "0.4.2"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "0ce7134b9999ecaf8bcd65542e436736ef32ddca1b3e06094cb6ec5755203b80"
+
[[package]]
name = "flate2"
version = "1.0.33"
@@ -3854,6 +3913,19 @@ dependencies = [
"tokio-io-timeout",
]
+[[package]]
+name = "hyper-timeout"
+version = "0.5.1"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "3203a961e5c83b6f5498933e78b6b263e208c197b63e9c6c53cc82ffd3f63793"
+dependencies = [
+ "hyper 1.4.1",
+ "hyper-util",
+ "pin-project-lite",
+ "tokio 1.40.0",
+ "tower-service",
+]
+
[[package]]
name = "hyper-tls"
version = "0.5.0"
@@ -4727,6 +4799,12 @@ dependencies = [
"uuid",
]
+[[package]]
+name = "multimap"
+version = "0.10.0"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "defc4c55412d89136f966bbb339008b474350e5e6e78d2714439c386b3137a03"
+
[[package]]
name = "mutually_exclusive_features"
version = "0.0.3"
@@ -5114,10 +5192,10 @@ dependencies = [
"http 0.2.12",
"opentelemetry",
"opentelemetry-proto",
- "prost",
+ "prost 0.11.9",
"thiserror",
"tokio 1.40.0",
- "tonic",
+ "tonic 0.8.3",
]
[[package]]
@@ -5129,8 +5207,8 @@ dependencies = [
"futures 0.3.30",
"futures-util",
"opentelemetry",
- "prost",
- "tonic",
+ "prost 0.11.9",
+ "tonic 0.8.3",
]
[[package]]
@@ -5389,6 +5467,16 @@ dependencies = [
"sha2",
]
+[[package]]
+name = "petgraph"
+version = "0.6.5"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "b4c5cc86750666a3ed20bdaf5ca2a0344f9c67674cae0515bec2da16fbaa47db"
+dependencies = [
+ "fixedbitset",
+ "indexmap 2.5.0",
+]
+
[[package]]
name = "phf"
version = "0.11.2"
@@ -5591,6 +5679,16 @@ dependencies = [
"vcpkg",
]
+[[package]]
+name = "prettyplease"
+version = "0.2.20"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "5f12335488a2f3b0a83b14edad48dca9879ce89b2edd10e80237e4e852dd645e"
+dependencies = [
+ "proc-macro2",
+ "syn 2.0.77",
+]
+
[[package]]
name = "primeorder"
version = "0.13.6"
@@ -5679,7 +5777,38 @@ source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "0b82eaa1d779e9a4bc1c3217db8ffbeabaae1dca241bf70183242128d48681cd"
dependencies = [
"bytes 1.7.1",
- "prost-derive",
+ "prost-derive 0.11.9",
+]
+
+[[package]]
+name = "prost"
+version = "0.13.2"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "3b2ecbe40f08db5c006b5764a2645f7f3f141ce756412ac9e1dd6087e6d32995"
+dependencies = [
+ "bytes 1.7.1",
+ "prost-derive 0.13.2",
+]
+
+[[package]]
+name = "prost-build"
+version = "0.13.2"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "f8650aabb6c35b860610e9cff5dc1af886c9e25073b7b1712a68972af4281302"
+dependencies = [
+ "bytes 1.7.1",
+ "heck 0.5.0",
+ "itertools 0.12.1",
+ "log",
+ "multimap",
+ "once_cell",
+ "petgraph",
+ "prettyplease",
+ "prost 0.13.2",
+ "prost-types",
+ "regex",
+ "syn 2.0.77",
+ "tempfile",
]
[[package]]
@@ -5695,6 +5824,28 @@ dependencies = [
"syn 1.0.109",
]
+[[package]]
+name = "prost-derive"
+version = "0.13.2"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "acf0c195eebb4af52c752bec4f52f645da98b6e92077a04110c7f349477ae5ac"
+dependencies = [
+ "anyhow",
+ "itertools 0.12.1",
+ "proc-macro2",
+ "quote",
+ "syn 2.0.77",
+]
+
+[[package]]
+name = "prost-types"
+version = "0.13.2"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "60caa6738c7369b940c3d49246a8d1749323674c65cb13010134f5c9bad5b519"
+dependencies = [
+ "prost 0.13.2",
+]
+
[[package]]
name = "ptr_meta"
version = "0.1.4"
@@ -8215,7 +8366,7 @@ checksum = "8f219fad3b929bef19b1f86fbc0358d35daed8f2cac972037ac0dc10bbb8d5fb"
dependencies = [
"async-stream",
"async-trait",
- "axum",
+ "axum 0.6.20",
"base64 0.13.1",
"bytes 1.7.1",
"futures-core",
@@ -8224,11 +8375,11 @@ dependencies = [
"http 0.2.12",
"http-body 0.4.6",
"hyper 0.14.30",
- "hyper-timeout",
+ "hyper-timeout 0.4.1",
"percent-encoding",
"pin-project",
- "prost",
- "prost-derive",
+ "prost 0.11.9",
+ "prost-derive 0.11.9",
"tokio 1.40.0",
"tokio-stream",
"tokio-util",
@@ -8239,6 +8390,73 @@ dependencies = [
"tracing-futures",
]
+[[package]]
+name = "tonic"
+version = "0.12.2"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "c6f6ba989e4b2c58ae83d862d3a3e27690b6e3ae630d0deb59f3697f32aa88ad"
+dependencies = [
+ "async-stream",
+ "async-trait",
+ "axum 0.7.5",
+ "base64 0.22.1",
+ "bytes 1.7.1",
+ "h2 0.4.6",
+ "http 1.1.0",
+ "http-body 1.0.1",
+ "http-body-util",
+ "hyper 1.4.1",
+ "hyper-timeout 0.5.1",
+ "hyper-util",
+ "percent-encoding",
+ "pin-project",
+ "prost 0.13.2",
+ "socket2",
+ "tokio 1.40.0",
+ "tokio-stream",
+ "tower",
+ "tower-layer",
+ "tower-service",
+ "tracing",
+]
+
+[[package]]
+name = "tonic-build"
+version = "0.12.2"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "fe4ee8877250136bd7e3d2331632810a4df4ea5e004656990d8d66d2f5ee8a67"
+dependencies = [
+ "prettyplease",
+ "proc-macro2",
+ "prost-build",
+ "quote",
+ "syn 2.0.77",
+]
+
+[[package]]
+name = "tonic-reflection"
+version = "0.12.2"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "7b56b874eedb04f89907573b408eab1e87c1c1dce43aac6ad63742f57faa99ff"
+dependencies = [
+ "prost 0.13.2",
+ "prost-types",
+ "tokio 1.40.0",
+ "tokio-stream",
+ "tonic 0.12.2",
+]
+
+[[package]]
+name = "tonic-types"
+version = "0.12.2"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "9d967793411bc1a5392accf4731114295f0fd122865d22cde46a8584b03402b2"
+dependencies = [
+ "prost 0.13.2",
+ "prost-types",
+ "tonic 0.12.2",
+]
+
[[package]]
name = "totp-rs"
version = "5.6.0"
diff --git a/Dockerfile b/Dockerfile
index 29c1003c115..65ca6370364 100644
--- a/Dockerfile
+++ b/Dockerfile
@@ -4,7 +4,7 @@ ARG EXTRA_FEATURES=""
ARG VERSION_FEATURE_SET="v1"
RUN apt-get update \
- && apt-get install -y libpq-dev libssl-dev pkg-config
+ && apt-get install -y libpq-dev libssl-dev pkg-config protobuf-compiler
# Copying codebase from current dir to /router dir
# and creating a fresh build
diff --git a/crates/api_models/src/routing.rs b/crates/api_models/src/routing.rs
index 5023d30f722..2b551eaebb7 100644
--- a/crates/api_models/src/routing.rs
+++ b/crates/api_models/src/routing.rs
@@ -197,7 +197,9 @@ pub enum RoutableChoiceSerde {
impl std::fmt::Display for RoutableConnectorChoice {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
let base = self.connector.to_string();
-
+ if let Some(mca_id) = &self.merchant_connector_id {
+ return write!(f, "{}:{}", base, mca_id.get_string_repr());
+ }
write!(f, "{}", base)
}
}
@@ -252,6 +254,11 @@ impl From<RoutableConnectorChoice> for RoutableChoiceSerde {
}
}
+#[derive(serde::Serialize, serde::Deserialize, Debug, Clone)]
+pub struct RoutableConnectorChoiceWithStatus {
+ pub routable_connector_choice: RoutableConnectorChoice,
+ pub status: bool,
+}
#[derive(Debug, Copy, Clone, serde::Serialize, serde::Deserialize, strum::Display, ToSchema)]
#[serde(rename_all = "snake_case")]
#[strum(serialize_all = "snake_case")]
@@ -565,7 +572,7 @@ impl Default for SuccessBasedRoutingConfig {
}
}
-#[derive(serde::Serialize, serde::Deserialize, Debug, Clone, ToSchema)]
+#[derive(serde::Serialize, serde::Deserialize, Debug, Clone, ToSchema, strum::Display)]
pub enum SuccessBasedRoutingConfigParams {
PaymentMethod,
PaymentMethodType,
diff --git a/crates/external_services/Cargo.toml b/crates/external_services/Cargo.toml
index 9051c58ea59..a882cdc9f51 100644
--- a/crates/external_services/Cargo.toml
+++ b/crates/external_services/Cargo.toml
@@ -13,6 +13,7 @@ email = ["dep:aws-config"]
aws_s3 = ["dep:aws-config", "dep:aws-sdk-s3"]
hashicorp-vault = ["dep:vaultrs"]
v1 = ["hyperswitch_interfaces/v1"]
+dynamic_routing = ["dep:prost", "dep:tonic", "dep:tonic-reflection", "dep:tonic-types", "dep:api_models", "tokio/macros", "tokio/rt-multi-thread"]
[dependencies]
async-trait = "0.1.79"
@@ -31,14 +32,24 @@ hyper-proxy = "0.9.1"
once_cell = "1.19.0"
serde = { version = "1.0.197", features = ["derive"] }
thiserror = "1.0.58"
-tokio = "1.37.0"
vaultrs = { version = "0.7.2", optional = true }
+prost = { version = "0.13", optional = true }
+tokio = "1.37.0"
+tonic = { version = "0.12.2", optional = true }
+tonic-reflection = { version = "0.12.2", optional = true }
+tonic-types = { version = "0.12.2", optional = true }
+
# First party crates
common_utils = { version = "0.1.0", path = "../common_utils" }
hyperswitch_interfaces = { version = "0.1.0", path = "../hyperswitch_interfaces", default-features = false }
masking = { version = "0.1.0", path = "../masking" }
router_env = { version = "0.1.0", path = "../router_env", features = ["log_extra_implicit_fields", "log_custom_entries_to_extra"] }
+api_models = { version = "0.1.0", path = "../api_models", optional = true }
+
+
+[build-dependencies]
+tonic-build = "0.12"
[lints]
workspace = true
diff --git a/crates/external_services/build.rs b/crates/external_services/build.rs
new file mode 100644
index 00000000000..61e19f308d8
--- /dev/null
+++ b/crates/external_services/build.rs
@@ -0,0 +1,15 @@
+use std::{env, path::PathBuf};
+
+#[allow(clippy::expect_used)]
+fn main() -> Result<(), Box<dyn std::error::Error>> {
+ // Get the directory of the current crate
+ let crate_dir = env::var("CARGO_MANIFEST_DIR")?;
+ let proto_file = PathBuf::from(crate_dir)
+ .join("..")
+ .join("..")
+ .join("proto")
+ .join("success_rate.proto");
+ // Compile the .proto file
+ tonic_build::compile_protos(proto_file).expect("Failed to compile protos ");
+ Ok(())
+}
diff --git a/crates/external_services/src/grpc_client.rs b/crates/external_services/src/grpc_client.rs
new file mode 100644
index 00000000000..5afd3024551
--- /dev/null
+++ b/crates/external_services/src/grpc_client.rs
@@ -0,0 +1,48 @@
+/// Dyanimc Routing Client interface implementation
+#[cfg(feature = "dynamic_routing")]
+pub mod dynamic_routing;
+use std::{fmt::Debug, sync::Arc};
+
+#[cfg(feature = "dynamic_routing")]
+use dynamic_routing::{DynamicRoutingClientConfig, RoutingStrategy};
+use router_env::logger;
+use serde;
+
+/// Struct contains all the gRPC Clients
+#[derive(Debug, Clone)]
+pub struct GrpcClients {
+ /// The routing client
+ #[cfg(feature = "dynamic_routing")]
+ pub dynamic_routing: RoutingStrategy,
+}
+/// Type that contains the configs required to construct a gRPC client with its respective services.
+#[derive(Debug, Clone, serde::Deserialize, serde::Serialize, Default)]
+pub struct GrpcClientSettings {
+ #[cfg(feature = "dynamic_routing")]
+ /// Configs for Dynamic Routing Client
+ pub dynamic_routing_client: DynamicRoutingClientConfig,
+}
+
+impl GrpcClientSettings {
+ /// # Panics
+ ///
+ /// This function will panic if it fails to establish a connection with the gRPC server.
+ /// This function will be called at service startup.
+ #[allow(clippy::expect_used)]
+ pub async fn get_grpc_client_interface(&self) -> Arc<GrpcClients> {
+ #[cfg(feature = "dynamic_routing")]
+ let dynamic_routing_connection = self
+ .dynamic_routing_client
+ .clone()
+ .get_dynamic_routing_connection()
+ .await
+ .expect("Failed to establish a connection with the Dynamic Routing Server");
+
+ logger::info!("Connection established with gRPC Server");
+
+ Arc::new(GrpcClients {
+ #[cfg(feature = "dynamic_routing")]
+ dynamic_routing: dynamic_routing_connection,
+ })
+ }
+}
diff --git a/crates/external_services/src/grpc_client/dynamic_routing.rs b/crates/external_services/src/grpc_client/dynamic_routing.rs
new file mode 100644
index 00000000000..17bd43ca3a8
--- /dev/null
+++ b/crates/external_services/src/grpc_client/dynamic_routing.rs
@@ -0,0 +1,265 @@
+use std::fmt::Debug;
+
+use api_models::routing::{
+ CurrentBlockThreshold, RoutableConnectorChoice, RoutableConnectorChoiceWithStatus,
+ SuccessBasedRoutingConfig, SuccessBasedRoutingConfigBody,
+};
+use common_utils::{errors::CustomResult, ext_traits::OptionExt, transformers::ForeignTryFrom};
+use error_stack::ResultExt;
+use serde;
+use success_rate::{
+ success_rate_calculator_client::SuccessRateCalculatorClient, CalSuccessRateConfig,
+ CalSuccessRateRequest, CalSuccessRateResponse,
+ CurrentBlockThreshold as DynamicCurrentThreshold, LabelWithStatus,
+ UpdateSuccessRateWindowConfig, UpdateSuccessRateWindowRequest, UpdateSuccessRateWindowResponse,
+};
+use tonic::transport::Channel;
+#[allow(
+ missing_docs,
+ unused_qualifications,
+ clippy::unwrap_used,
+ clippy::as_conversions
+)]
+pub mod success_rate {
+ tonic::include_proto!("success_rate");
+}
+/// Result type for Dynamic Routing
+pub type DynamicRoutingResult<T> = CustomResult<T, DynamicRoutingError>;
+
+/// Dynamic Routing Errors
+#[derive(Debug, Clone, thiserror::Error)]
+pub enum DynamicRoutingError {
+ /// The required input is missing
+ #[error("Missing Required Field : {field} for building the Dynamic Routing Request")]
+ MissingRequiredField {
+ /// The required field name
+ field: String,
+ },
+ /// Error from Dynamic Routing Server
+ #[error("Error from Dynamic Routing Server : {0}")]
+ SuccessRateBasedRoutingFailure(String),
+}
+
+/// Type that consists of all the services provided by the client
+#[derive(Debug, Clone)]
+pub struct RoutingStrategy {
+ /// success rate service for Dynamic Routing
+ pub success_rate_client: Option<SuccessRateCalculatorClient<Channel>>,
+}
+
+/// Contains the Dynamic Routing Client Config
+#[derive(Debug, Clone, serde::Deserialize, serde::Serialize, Default)]
+#[serde(untagged)]
+pub enum DynamicRoutingClientConfig {
+ /// If the dynamic routing client config has been enabled
+ Enabled {
+ /// The host for the client
+ host: String,
+ /// The port of the client
+ port: u16,
+ },
+ #[default]
+ /// If the dynamic routing client config has been disabled
+ Disabled,
+}
+
+impl DynamicRoutingClientConfig {
+ /// establish connection with the server
+ pub async fn get_dynamic_routing_connection(
+ self,
+ ) -> Result<RoutingStrategy, Box<dyn std::error::Error>> {
+ let success_rate_client = match self {
+ Self::Enabled { host, port } => {
+ let uri = format!("http://{}:{}", host, port);
+ let channel = tonic::transport::Endpoint::new(uri)?.connect().await?;
+ Some(SuccessRateCalculatorClient::new(channel))
+ }
+ Self::Disabled => None,
+ };
+ Ok(RoutingStrategy {
+ success_rate_client,
+ })
+ }
+}
+
+/// The trait Success Based Dynamic Routing would have the functions required to support the calculation and updation window
+#[async_trait::async_trait]
+pub trait SuccessBasedDynamicRouting: dyn_clone::DynClone + Send + Sync {
+ /// To calculate the success rate for the list of chosen connectors
+ async fn calculate_success_rate(
+ &self,
+ id: String,
+ success_rate_based_config: SuccessBasedRoutingConfig,
+ label_input: Vec<RoutableConnectorChoice>,
+ ) -> DynamicRoutingResult<CalSuccessRateResponse>;
+ /// To update the success rate with the given label
+ async fn update_success_rate(
+ &self,
+ id: String,
+ success_rate_based_config: SuccessBasedRoutingConfig,
+ response: Vec<RoutableConnectorChoiceWithStatus>,
+ ) -> DynamicRoutingResult<UpdateSuccessRateWindowResponse>;
+}
+
+#[async_trait::async_trait]
+impl SuccessBasedDynamicRouting for SuccessRateCalculatorClient<Channel> {
+ async fn calculate_success_rate(
+ &self,
+ id: String,
+ success_rate_based_config: SuccessBasedRoutingConfig,
+ label_input: Vec<RoutableConnectorChoice>,
+ ) -> DynamicRoutingResult<CalSuccessRateResponse> {
+ let params = success_rate_based_config
+ .params
+ .map(|vec| {
+ vec.into_iter().fold(String::new(), |mut acc_vec, params| {
+ if !acc_vec.is_empty() {
+ acc_vec.push(':')
+ }
+ acc_vec.push_str(params.to_string().as_str());
+ acc_vec
+ })
+ })
+ .get_required_value("params")
+ .change_context(DynamicRoutingError::MissingRequiredField {
+ field: "params".to_string(),
+ })?;
+
+ let labels = label_input
+ .into_iter()
+ .map(|conn_choice| conn_choice.to_string())
+ .collect::<Vec<_>>();
+
+ let config = success_rate_based_config
+ .config
+ .map(ForeignTryFrom::foreign_try_from)
+ .transpose()?;
+
+ let request = tonic::Request::new(CalSuccessRateRequest {
+ id,
+ params,
+ labels,
+ config,
+ });
+
+ let mut client = self.clone();
+
+ let response = client
+ .fetch_success_rate(request)
+ .await
+ .change_context(DynamicRoutingError::SuccessRateBasedRoutingFailure(
+ "Failed to fetch the success rate".to_string(),
+ ))?
+ .into_inner();
+
+ Ok(response)
+ }
+
+ async fn update_success_rate(
+ &self,
+ id: String,
+ success_rate_based_config: SuccessBasedRoutingConfig,
+ label_input: Vec<RoutableConnectorChoiceWithStatus>,
+ ) -> DynamicRoutingResult<UpdateSuccessRateWindowResponse> {
+ let config = success_rate_based_config
+ .config
+ .map(ForeignTryFrom::foreign_try_from)
+ .transpose()?;
+
+ let labels_with_status = label_input
+ .into_iter()
+ .map(|conn_choice| LabelWithStatus {
+ label: conn_choice.routable_connector_choice.to_string(),
+ status: conn_choice.status,
+ })
+ .collect();
+
+ let params = success_rate_based_config
+ .params
+ .map(|vec| {
+ vec.into_iter().fold(String::new(), |mut acc_vec, params| {
+ if !acc_vec.is_empty() {
+ acc_vec.push(':')
+ }
+ acc_vec.push_str(params.to_string().as_str());
+ acc_vec
+ })
+ })
+ .get_required_value("params")
+ .change_context(DynamicRoutingError::MissingRequiredField {
+ field: "params".to_string(),
+ })?;
+
+ let request = tonic::Request::new(UpdateSuccessRateWindowRequest {
+ id,
+ params,
+ labels_with_status,
+ config,
+ });
+
+ let mut client = self.clone();
+
+ let response = client
+ .update_success_rate_window(request)
+ .await
+ .change_context(DynamicRoutingError::SuccessRateBasedRoutingFailure(
+ "Failed to update the success rate window".to_string(),
+ ))?
+ .into_inner();
+
+ Ok(response)
+ }
+}
+
+impl ForeignTryFrom<CurrentBlockThreshold> for DynamicCurrentThreshold {
+ type Error = error_stack::Report<DynamicRoutingError>;
+ fn foreign_try_from(current_threshold: CurrentBlockThreshold) -> Result<Self, Self::Error> {
+ Ok(Self {
+ duration_in_mins: current_threshold.duration_in_mins,
+ max_total_count: current_threshold
+ .max_total_count
+ .get_required_value("max_total_count")
+ .change_context(DynamicRoutingError::MissingRequiredField {
+ field: "max_total_count".to_string(),
+ })?,
+ })
+ }
+}
+
+impl ForeignTryFrom<SuccessBasedRoutingConfigBody> for UpdateSuccessRateWindowConfig {
+ type Error = error_stack::Report<DynamicRoutingError>;
+ fn foreign_try_from(config: SuccessBasedRoutingConfigBody) -> Result<Self, Self::Error> {
+ Ok(Self {
+ max_aggregates_size: config
+ .max_aggregates_size
+ .get_required_value("max_aggregate_size")
+ .change_context(DynamicRoutingError::MissingRequiredField {
+ field: "max_aggregates_size".to_string(),
+ })?,
+ current_block_threshold: config
+ .current_block_threshold
+ .map(ForeignTryFrom::foreign_try_from)
+ .transpose()?,
+ })
+ }
+}
+
+impl ForeignTryFrom<SuccessBasedRoutingConfigBody> for CalSuccessRateConfig {
+ type Error = error_stack::Report<DynamicRoutingError>;
+ fn foreign_try_from(config: SuccessBasedRoutingConfigBody) -> Result<Self, Self::Error> {
+ Ok(Self {
+ min_aggregates_size: config
+ .min_aggregates_size
+ .get_required_value("min_aggregate_size")
+ .change_context(DynamicRoutingError::MissingRequiredField {
+ field: "min_aggregates_size".to_string(),
+ })?,
+ default_success_rate: config
+ .default_success_rate
+ .get_required_value("default_success_rate")
+ .change_context(DynamicRoutingError::MissingRequiredField {
+ field: "default_success_rate".to_string(),
+ })?,
+ })
+ }
+}
diff --git a/crates/external_services/src/lib.rs b/crates/external_services/src/lib.rs
index f4bcd91e343..4570a5e5960 100644
--- a/crates/external_services/src/lib.rs
+++ b/crates/external_services/src/lib.rs
@@ -14,6 +14,9 @@ pub mod hashicorp_vault;
pub mod no_encryption;
+/// Building grpc clients to communicate with the server
+pub mod grpc_client;
+
pub mod managers;
/// Crate specific constants
diff --git a/crates/hyperswitch_interfaces/src/api.rs b/crates/hyperswitch_interfaces/src/api.rs
index 0b4545a33d7..7205865f24a 100644
--- a/crates/hyperswitch_interfaces/src/api.rs
+++ b/crates/hyperswitch_interfaces/src/api.rs
@@ -16,7 +16,6 @@ pub mod payouts;
pub mod payouts_v2;
pub mod refunds;
pub mod refunds_v2;
-
use common_enums::enums::{CallConnectorAction, CaptureMethod, PaymentAction, PaymentMethodType};
use common_utils::{
errors::CustomResult,
diff --git a/crates/router/Cargo.toml b/crates/router/Cargo.toml
index bae6243d2e6..442561c2ca3 100644
--- a/crates/router/Cargo.toml
+++ b/crates/router/Cargo.toml
@@ -38,6 +38,7 @@ v1 = ["common_default", "api_models/v1", "diesel_models/v1", "hyperswitch_domain
customer_v2 = ["api_models/customer_v2", "diesel_models/customer_v2", "hyperswitch_domain_models/customer_v2", "storage_impl/customer_v2"]
payment_v2 = ["api_models/payment_v2", "diesel_models/payment_v2", "hyperswitch_domain_models/payment_v2", "storage_impl/payment_v2"]
payment_methods_v2 = ["api_models/payment_methods_v2", "diesel_models/payment_methods_v2", "hyperswitch_domain_models/payment_methods_v2", "storage_impl/payment_methods_v2", "common_utils/payment_methods_v2"]
+dynamic_routing = ["external_services/dynamic_routing"]
# Partial Auth
# The feature reduces the overhead of the router authenticating the merchant for every request, and trusts on `x-merchant-id` header to be present in the request.
diff --git a/crates/router/src/configs/secrets_transformers.rs b/crates/router/src/configs/secrets_transformers.rs
index 9b0bfbb40b2..604dce5047c 100644
--- a/crates/router/src/configs/secrets_transformers.rs
+++ b/crates/router/src/configs/secrets_transformers.rs
@@ -497,6 +497,7 @@ pub(crate) async fn fetch_raw_secrets(
user_auth_methods,
decision: conf.decision,
locker_based_open_banking_connectors: conf.locker_based_open_banking_connectors,
+ grpc_client: conf.grpc_client,
recipient_emails: conf.recipient_emails,
network_tokenization_supported_card_networks: conf
.network_tokenization_supported_card_networks,
diff --git a/crates/router/src/configs/settings.rs b/crates/router/src/configs/settings.rs
index 78ff709cc02..7d6dfd26eae 100644
--- a/crates/router/src/configs/settings.rs
+++ b/crates/router/src/configs/settings.rs
@@ -13,6 +13,7 @@ use error_stack::ResultExt;
use external_services::email::EmailSettings;
use external_services::{
file_storage::FileStorageConfig,
+ grpc_client::GrpcClientSettings,
managers::{
encryption_management::EncryptionManagementConfig,
secrets_management::SecretsManagementConfig,
@@ -120,6 +121,7 @@ pub struct Settings<S: SecretState> {
pub user_auth_methods: SecretStateContainer<UserAuthMethodSettings, S>,
pub decision: Option<DecisionConfig>,
pub locker_based_open_banking_connectors: LockerBasedRecipientConnectorList,
+ pub grpc_client: GrpcClientSettings,
pub recipient_emails: RecipientMails,
pub network_tokenization_supported_card_networks: NetworkTokenizationSupportedCardNetworks,
pub network_tokenization_service: Option<SecretStateContainer<NetworkTokenizationService, S>>,
diff --git a/crates/router/src/core/payments.rs b/crates/router/src/core/payments.rs
index 0af5bf6037a..30d619efedc 100644
--- a/crates/router/src/core/payments.rs
+++ b/crates/router/src/core/payments.rs
@@ -11,7 +11,6 @@ pub mod routing;
pub mod tokenization;
pub mod transformers;
pub mod types;
-
#[cfg(feature = "olap")]
use std::collections::HashMap;
use std::{
@@ -160,7 +159,6 @@ where
&header_payload,
)
.await?;
-
utils::validate_profile_id_from_auth_layer(
profile_id_from_auth_layer,
&payment_data.get_payment_intent().clone(),
@@ -4427,6 +4425,7 @@ where
)
.await
.change_context(errors::ApiErrorResponse::InternalServerError)?;
+
let connectors = routing::perform_eligibility_analysis_with_fallback(
&state.clone(),
key_store,
diff --git a/crates/router/src/routes/admin.rs b/crates/router/src/routes/admin.rs
index a68f648e178..8ba214f94b9 100644
--- a/crates/router/src/routes/admin.rs
+++ b/crates/router/src/routes/admin.rs
@@ -361,7 +361,7 @@ pub async fn connector_retrieve(
})
.into_inner();
- api::server_wrap(
+ Box::pin(api::server_wrap(
flow,
state,
&req,
@@ -384,7 +384,7 @@ pub async fn connector_retrieve(
req.headers(),
),
api_locking::LockAction::NotApplicable,
- )
+ ))
.await
}
/// Merchant Connector - Retrieve
diff --git a/crates/router/src/routes/api_keys.rs b/crates/router/src/routes/api_keys.rs
index 71632cc5749..a00e740b3e6 100644
--- a/crates/router/src/routes/api_keys.rs
+++ b/crates/router/src/routes/api_keys.rs
@@ -166,7 +166,7 @@ pub async fn api_key_update(
payload.key_id = key_id;
payload.merchant_id.clone_from(&merchant_id);
- api::server_wrap(
+ Box::pin(api::server_wrap(
flow,
state,
&req,
@@ -182,7 +182,7 @@ pub async fn api_key_update(
req.headers(),
),
api_locking::LockAction::NotApplicable,
- )
+ ))
.await
}
diff --git a/crates/router/src/routes/app.rs b/crates/router/src/routes/app.rs
index aad5acbbade..034b3784f40 100644
--- a/crates/router/src/routes/app.rs
+++ b/crates/router/src/routes/app.rs
@@ -9,7 +9,7 @@ use common_enums::TransactionType;
use common_utils::crypto::Blake3;
#[cfg(feature = "email")]
use external_services::email::{ses::AwsSes, EmailService};
-use external_services::file_storage::FileStorageInterface;
+use external_services::{file_storage::FileStorageInterface, grpc_client::GrpcClients};
use hyperswitch_interfaces::{
encryption_interface::EncryptionManagementInterface,
secrets_interface::secret_state::{RawSecret, SecuredSecret},
@@ -105,6 +105,7 @@ pub struct SessionState {
pub tenant: Tenant,
#[cfg(feature = "olap")]
pub opensearch_client: Arc<OpenSearchClient>,
+ pub grpc_client: Arc<GrpcClients>,
}
impl scheduler::SchedulerSessionState for SessionState {
fn get_db(&self) -> Box<dyn SchedulerInterface> {
@@ -202,6 +203,7 @@ pub struct AppState {
pub request_id: Option<RequestId>,
pub file_storage_client: Arc<dyn FileStorageInterface>,
pub encryption_client: Arc<dyn EncryptionManagementInterface>,
+ pub grpc_client: Arc<GrpcClients>,
}
impl scheduler::SchedulerAppState for AppState {
fn get_tenants(&self) -> Vec<String> {
@@ -351,6 +353,8 @@ impl AppState {
let file_storage_client = conf.file_storage.get_file_storage_client().await;
+ let grpc_client = conf.grpc_client.get_grpc_client_interface().await;
+
Self {
flow_name: String::from("default"),
stores,
@@ -367,6 +371,7 @@ impl AppState {
request_id: None,
file_storage_client,
encryption_client,
+ grpc_client,
}
})
.await
@@ -447,6 +452,7 @@ impl AppState {
email_client: Arc::clone(&self.email_client),
#[cfg(feature = "olap")]
opensearch_client: Arc::clone(&self.opensearch_client),
+ grpc_client: Arc::clone(&self.grpc_client),
})
}
}
diff --git a/crates/router/src/routes/dummy_connector.rs b/crates/router/src/routes/dummy_connector.rs
index 26c32776d72..e376bcd7f9e 100644
--- a/crates/router/src/routes/dummy_connector.rs
+++ b/crates/router/src/routes/dummy_connector.rs
@@ -46,7 +46,7 @@ pub async fn dummy_connector_complete_payment(
attempt_id,
confirm: json_payload.confirm,
};
- api::server_wrap(
+ Box::pin(api::server_wrap(
flow,
state,
&req,
@@ -54,7 +54,7 @@ pub async fn dummy_connector_complete_payment(
|state, _: (), req, _| core::payment_complete(state, req),
&auth::NoAuth,
api_locking::LockAction::NotApplicable,
- )
+ ))
.await
}
#[instrument(skip_all, fields(flow = ?types::Flow::DummyPaymentCreate))]
@@ -65,7 +65,7 @@ pub async fn dummy_connector_payment(
) -> impl actix_web::Responder {
let payload = json_payload.into_inner();
let flow = types::Flow::DummyPaymentCreate;
- api::server_wrap(
+ Box::pin(api::server_wrap(
flow,
state,
&req,
@@ -73,7 +73,7 @@ pub async fn dummy_connector_payment(
|state, _: (), req, _| core::payment(state, req),
&auth::NoAuth,
api_locking::LockAction::NotApplicable,
- )
+ ))
.await
}
#[instrument(skip_all, fields(flow = ?types::Flow::DummyPaymentRetrieve))]
diff --git a/crates/router/src/routes/routing.rs b/crates/router/src/routes/routing.rs
index 86ad2078f6c..70da80c6756 100644
--- a/crates/router/src/routes/routing.rs
+++ b/crates/router/src/routes/routing.rs
@@ -612,7 +612,7 @@ pub async fn retrieve_surcharge_decision_manager_config(
req: HttpRequest,
) -> impl Responder {
let flow = Flow::DecisionManagerRetrieveConfig;
- oss_api::server_wrap(
+ Box::pin(oss_api::server_wrap(
flow,
state,
&req,
@@ -638,7 +638,7 @@ pub async fn retrieve_surcharge_decision_manager_config(
minimum_entity_level: EntityType::Merchant,
},
api_locking::LockAction::NotApplicable,
- )
+ ))
.await
}
@@ -727,7 +727,7 @@ pub async fn retrieve_decision_manager_config(
req: HttpRequest,
) -> impl Responder {
let flow = Flow::DecisionManagerRetrieveConfig;
- oss_api::server_wrap(
+ Box::pin(oss_api::server_wrap(
flow,
state,
&req,
@@ -750,7 +750,7 @@ pub async fn retrieve_decision_manager_config(
minimum_entity_level: EntityType::Merchant,
},
api_locking::LockAction::NotApplicable,
- )
+ ))
.await
}
diff --git a/docker-compose-development.yml b/docker-compose-development.yml
index ebccb114048..cf12982a9bd 100644
--- a/docker-compose-development.yml
+++ b/docker-compose-development.yml
@@ -60,7 +60,9 @@ services:
### Application services
hyperswitch-server:
image: rust:latest
- command: cargo run --bin router -- -f ./config/docker_compose.toml
+ command: |
+ apt-get install -y protobuf-compiler && \
+ cargo run --bin router -- -f ./config/docker_compose.toml
working_dir: /app
ports:
- "8080:8080"
diff --git a/migrations/2024-09-05-160455_add_new_col_is_dynamic_routing_algorithm_in_business_profile/up.sql b/migrations/2024-09-05-160455_add_new_col_is_dynamic_routing_algorithm_in_business_profile/up.sql
index 2482fc9f591..c7a53898129 100644
--- a/migrations/2024-09-05-160455_add_new_col_is_dynamic_routing_algorithm_in_business_profile/up.sql
+++ b/migrations/2024-09-05-160455_add_new_col_is_dynamic_routing_algorithm_in_business_profile/up.sql
@@ -1,3 +1,5 @@
-- Your SQL goes here
-ALTER TABLE business_profile
-ADD COLUMN dynamic_routing_algorithm JSON DEFAULT NULL;
+ALTER TABLE
+ business_profile
+ADD
+ COLUMN dynamic_routing_algorithm JSON DEFAULT NULL;
\ No newline at end of file
diff --git a/proto/success_rate.proto b/proto/success_rate.proto
new file mode 100644
index 00000000000..8018f6d5fe4
--- /dev/null
+++ b/proto/success_rate.proto
@@ -0,0 +1,57 @@
+syntax = "proto3";
+package success_rate;
+
+ service SuccessRateCalculator {
+ rpc FetchSuccessRate (CalSuccessRateRequest) returns (CalSuccessRateResponse);
+
+ rpc UpdateSuccessRateWindow (UpdateSuccessRateWindowRequest) returns (UpdateSuccessRateWindowResponse);
+ }
+
+ // API-1 types
+ message CalSuccessRateRequest {
+ string id = 1;
+ string params = 2;
+ repeated string labels = 3;
+ CalSuccessRateConfig config = 4;
+ }
+
+ message CalSuccessRateConfig {
+ uint32 min_aggregates_size = 1;
+ double default_success_rate = 2;
+ }
+
+ message CalSuccessRateResponse {
+ repeated LabelWithScore labels_with_score = 1;
+ }
+
+ message LabelWithScore {
+ double score = 1;
+ string label = 2;
+ }
+
+ // API-2 types
+ message UpdateSuccessRateWindowRequest {
+ string id = 1;
+ string params = 2;
+ repeated LabelWithStatus labels_with_status = 3;
+ UpdateSuccessRateWindowConfig config = 4;
+ }
+
+ message LabelWithStatus {
+ string label = 1;
+ bool status = 2;
+ }
+
+ message UpdateSuccessRateWindowConfig {
+ uint32 max_aggregates_size = 1;
+ CurrentBlockThreshold current_block_threshold = 2;
+ }
+
+ message CurrentBlockThreshold {
+ optional uint64 duration_in_mins = 1;
+ uint64 max_total_count = 2;
+ }
+
+ message UpdateSuccessRateWindowResponse {
+ string message = 1;
+ }
\ No newline at end of file
|
2024-09-09T05:27:48Z
|
## Type of Change
<!-- Put an `x` in the boxes that apply -->
- [ ] Bugfix
- [ ] New feature
- [ ] Enhancement
- [ ] Refactoring
- [ ] Dependency updates
- [ ] Documentation
- [ ] CI/CD
## Description
Feature Description:
Building a Grpc Client for communicating with the Dynamo server, once the dynamic routing feature has been enabled.
The dynamic routing feature would be a compile time as well as runtime feature flag ,
for providing the flexibility to enable and disable the dynamic routing during deployment
Possible Implementation:
Once dynamic routing has been enabled , we will store the default config in the algorithm column in routing table as the following jsonb:
```
{
"id": "merchant_id",
"params": "card",
"labels": ["stripe","adyen"],
"config": {
"min_aggregates_size": 2,
"default_success_rate": 100.0
}
}
```
gRPC client will be integrated as a struct of GrpcClientInterface within the struct SessionState,
```
struct SessionState
{
grpc: GrpcClientInterface
}
```
The gRPcClientInterface would be a struct which would have Dynamic Routing as its field and similarly any other future gRPC Client would be one of its fields
```
struct gRPcClientInterface
{
pub dynamic_routing: DynamicRouting
}
```
The DynamicRouting struct would have all the fields that would be there as its services channel
```
struct DynamicRouting
{
pub success_based_client : SuccessBasedClient<Channel>
}
```
The SuccessBasedClient would be a trait would have following functions:
calculate_the_success_rate
update_the_success_rates
```
triat SuccessBasedClient
{
type CalCulatedRespons;
type UpadationResponse;
async fn calculate_success_rate(self,label_input : Vec<T>) -> CalCulatedRespons
async fn update_success_rate(self,calculated_success_rate:CalCulatedRespons) -> UpadationResponse
}
```
The SuccessBasedClient would be implemented on client that would be a SuccessBasedClient<Channel>
```
impl SuccessBasedClient for SuccessBasedClient<Channel>
{
async fn calculate_success_rate(self,label_input : T) -> CalSuccessRateResponse
{
self.fetch_success_rate(request)
}
async fn update_success_rate(self,calculated_success_rate : CalSuccessRateResponse) -> UpdateSuccessRateWindowResponse
{
self.update_success_rate_window(request)
}
}
```
### Additional Changes
- [ ] This PR modifies the API contract
- [ ] This PR modifies the database schema
- [ ] This PR modifies application configuration/environment variables
<!--
Provide links to the files with corresponding changes.
Following are the paths where you can find config files:
1. `config`
2. `crates/router/src/configs`
3. `loadtest/config`
-->
## Motivation and Context
<!--
Why is this change required? What problem does it solve?
If it fixes an open issue, please link to the issue here.
If you don't have an issue, we'd recommend starting with one first so the PR
can focus on the implementation (unless it is an obvious bug or documentation fix
that will have little conversation).
-->
## How did you test it?
- This cannot be tested on sbx, yet
I have tested it locally
- Started the gRPC Server
- Established the connection with the Client <-> Server
- Sent Request the gRPC Server
<img width="1711" alt="Screenshot 2024-09-17 at 7 29 17 PM" src="https://github.com/user-attachments/assets/60fb8ccf-2c4d-48d5-bcfe-f7f3018a915c">
- Response from the server
<img width="1296" alt="Screenshot 2024-09-17 at 7 30 27 PM" src="https://github.com/user-attachments/assets/5de3594b-4701-42a2-9840-a2c14a7db104">
## Checklist
<!-- Put an `x` in the boxes that apply -->
- [ ] I formatted the code `cargo +nightly fmt --all`
- [ ] I addressed lints thrown by `cargo clippy`
- [ ] I reviewed the submitted code
- [ ] I added unit tests for my changes where possible
|
be902ffa5328d32efe70c40c36f86d8fbfa01c79
|
|
juspay/hyperswitch
|
juspay__hyperswitch-5742
|
Bug: [REFACTOR] add domain type for routing id
add domain type for routing id
|
diff --git a/crates/api_models/src/routing.rs b/crates/api_models/src/routing.rs
index f9bcf3901b9..1416e985523 100644
--- a/crates/api_models/src/routing.rs
+++ b/crates/api_models/src/routing.rs
@@ -89,7 +89,8 @@ pub enum LinkedRoutingConfigRetrieveResponse {
#[derive(Debug, Clone, serde::Serialize, serde::Deserialize, ToSchema)]
/// Routing Algorithm specific to merchants
pub struct MerchantRoutingAlgorithm {
- pub id: String,
+ #[schema(value_type = String)]
+ pub id: common_utils::id_type::RoutingId,
#[schema(value_type = String)]
pub profile_id: common_utils::id_type::ProfileId,
pub name: String,
@@ -422,14 +423,14 @@ impl RoutingAlgorithm {
#[derive(Debug, Default, Clone, serde::Serialize, serde::Deserialize)]
pub struct RoutingAlgorithmRef {
- pub algorithm_id: Option<String>,
+ pub algorithm_id: Option<common_utils::id_type::RoutingId>,
pub timestamp: i64,
pub config_algo_id: Option<String>,
pub surcharge_config_algo_id: Option<String>,
}
impl RoutingAlgorithmRef {
- pub fn update_algorithm_id(&mut self, new_id: String) {
+ pub fn update_algorithm_id(&mut self, new_id: common_utils::id_type::RoutingId) {
self.algorithm_id = Some(new_id);
self.timestamp = common_utils::date_time::now_unix_timestamp();
}
@@ -456,7 +457,8 @@ impl RoutingAlgorithmRef {
#[derive(Debug, Clone, serde::Serialize, serde::Deserialize, ToSchema)]
pub struct RoutingDictionaryRecord {
- pub id: String,
+ #[schema(value_type = String)]
+ pub id: common_utils::id_type::RoutingId,
#[schema(value_type = String)]
pub profile_id: common_utils::id_type::ProfileId,
pub name: String,
@@ -484,7 +486,8 @@ pub enum RoutingKind {
#[derive(serde::Serialize, serde::Deserialize, Debug, Clone, ToSchema)]
pub struct RoutingAlgorithmId {
- pub routing_algorithm_id: String,
+ #[schema(value_type = String)]
+ pub routing_algorithm_id: common_utils::id_type::RoutingId,
}
#[derive(Debug, Clone, serde::Serialize, serde::Deserialize)]
diff --git a/crates/common_utils/src/id_type.rs b/crates/common_utils/src/id_type.rs
index b6de37fab4f..5182c821d0f 100644
--- a/crates/common_utils/src/id_type.rs
+++ b/crates/common_utils/src/id_type.rs
@@ -8,6 +8,7 @@ mod merchant;
mod merchant_connector_account;
mod organization;
mod profile;
+mod routing;
mod global_id;
@@ -23,6 +24,7 @@ pub use merchant::MerchantId;
pub use merchant_connector_account::MerchantConnectorAccountId;
pub use organization::OrganizationId;
pub use profile::ProfileId;
+pub use routing::RoutingId;
use serde::{Deserialize, Serialize};
use thiserror::Error;
diff --git a/crates/common_utils/src/id_type/routing.rs b/crates/common_utils/src/id_type/routing.rs
new file mode 100644
index 00000000000..cb6597174a2
--- /dev/null
+++ b/crates/common_utils/src/id_type/routing.rs
@@ -0,0 +1,21 @@
+crate::id_type!(
+ RoutingId,
+ " A type for routing_id that can be used for routing ids"
+);
+
+crate::impl_id_type_methods!(RoutingId, "routing_id");
+
+// This is to display the `RoutingId` as RoutingId(abcd)
+crate::impl_debug_id_type!(RoutingId);
+crate::impl_try_from_cow_str_id_type!(RoutingId, "routing_id");
+
+crate::impl_generate_id_id_type!(RoutingId, "routing");
+crate::impl_serializable_secret_id_type!(RoutingId);
+crate::impl_queryable_id_type!(RoutingId);
+crate::impl_to_sql_from_sql_id_type!(RoutingId);
+
+impl crate::events::ApiEventMetric for RoutingId {
+ fn get_api_event_type(&self) -> Option<crate::events::ApiEventsType> {
+ Some(crate::events::ApiEventsType::Routing)
+ }
+}
diff --git a/crates/common_utils/src/lib.rs b/crates/common_utils/src/lib.rs
index f51ed6eab05..3bf3db11ba3 100644
--- a/crates/common_utils/src/lib.rs
+++ b/crates/common_utils/src/lib.rs
@@ -233,6 +233,12 @@ pub fn generate_profile_id_of_default_length() -> id_type::ProfileId {
id_type::ProfileId::generate()
}
+/// Generate a routing id with default length, with prefix as `routing`
+pub fn generate_routing_id_of_default_length() -> id_type::RoutingId {
+ use id_type::GenerateId;
+
+ id_type::RoutingId::generate()
+}
/// Generate a merchant_connector_account id with default length, with prefix as `mca`
pub fn generate_merchant_connector_account_id_of_default_length(
) -> id_type::MerchantConnectorAccountId {
diff --git a/crates/diesel_models/src/business_profile.rs b/crates/diesel_models/src/business_profile.rs
index 5a4f4fa0b49..2096779262e 100644
--- a/crates/diesel_models/src/business_profile.rs
+++ b/crates/diesel_models/src/business_profile.rs
@@ -269,11 +269,11 @@ pub struct BusinessProfile {
pub outgoing_webhook_custom_http_headers: Option<Encryption>,
pub always_collect_billing_details_from_wallet_connector: Option<bool>,
pub always_collect_shipping_details_from_wallet_connector: Option<bool>,
- pub routing_algorithm_id: Option<String>,
+ pub routing_algorithm_id: Option<common_utils::id_type::RoutingId>,
pub order_fulfillment_time: Option<i64>,
pub order_fulfillment_time_origin: Option<common_enums::OrderFulfillmentTimeOrigin>,
pub frm_routing_algorithm_id: Option<String>,
- pub payout_routing_algorithm_id: Option<String>,
+ pub payout_routing_algorithm_id: Option<common_utils::id_type::RoutingId>,
pub default_fallback_routing: Option<pii::SecretSerdeValue>,
pub tax_connector_id: Option<String>,
pub is_tax_connector_enabled: Option<bool>,
@@ -310,11 +310,11 @@ pub struct BusinessProfileNew {
pub outgoing_webhook_custom_http_headers: Option<Encryption>,
pub always_collect_billing_details_from_wallet_connector: Option<bool>,
pub always_collect_shipping_details_from_wallet_connector: Option<bool>,
- pub routing_algorithm_id: Option<String>,
+ pub routing_algorithm_id: Option<common_utils::id_type::RoutingId>,
pub order_fulfillment_time: Option<i64>,
pub order_fulfillment_time_origin: Option<common_enums::OrderFulfillmentTimeOrigin>,
pub frm_routing_algorithm_id: Option<String>,
- pub payout_routing_algorithm_id: Option<String>,
+ pub payout_routing_algorithm_id: Option<common_utils::id_type::RoutingId>,
pub default_fallback_routing: Option<pii::SecretSerdeValue>,
pub tax_connector_id: Option<String>,
pub is_tax_connector_enabled: Option<bool>,
@@ -348,11 +348,11 @@ pub struct BusinessProfileUpdateInternal {
pub outgoing_webhook_custom_http_headers: Option<Encryption>,
pub always_collect_billing_details_from_wallet_connector: Option<bool>,
pub always_collect_shipping_details_from_wallet_connector: Option<bool>,
- pub routing_algorithm_id: Option<String>,
+ pub routing_algorithm_id: Option<common_utils::id_type::RoutingId>,
pub order_fulfillment_time: Option<i64>,
pub order_fulfillment_time_origin: Option<common_enums::OrderFulfillmentTimeOrigin>,
pub frm_routing_algorithm_id: Option<String>,
- pub payout_routing_algorithm_id: Option<String>,
+ pub payout_routing_algorithm_id: Option<common_utils::id_type::RoutingId>,
pub default_fallback_routing: Option<pii::SecretSerdeValue>,
pub tax_connector_id: Option<String>,
pub is_tax_connector_enabled: Option<bool>,
diff --git a/crates/diesel_models/src/query/routing_algorithm.rs b/crates/diesel_models/src/query/routing_algorithm.rs
index f0fc75430e8..c4d56736aa2 100644
--- a/crates/diesel_models/src/query/routing_algorithm.rs
+++ b/crates/diesel_models/src/query/routing_algorithm.rs
@@ -19,7 +19,7 @@ impl RoutingAlgorithm {
pub async fn find_by_algorithm_id_merchant_id(
conn: &PgPooledConn,
- algorithm_id: &str,
+ algorithm_id: &common_utils::id_type::RoutingId,
merchant_id: &common_utils::id_type::MerchantId,
) -> StorageResult<Self> {
generics::generic_find_one::<<Self as HasTable>::Table, _, _>(
@@ -33,7 +33,7 @@ impl RoutingAlgorithm {
pub async fn find_by_algorithm_id_profile_id(
conn: &PgPooledConn,
- algorithm_id: &str,
+ algorithm_id: &common_utils::id_type::RoutingId,
profile_id: &common_utils::id_type::ProfileId,
) -> StorageResult<Self> {
generics::generic_find_one::<<Self as HasTable>::Table, _, _>(
@@ -47,7 +47,7 @@ impl RoutingAlgorithm {
pub async fn find_metadata_by_algorithm_id_profile_id(
conn: &PgPooledConn,
- algorithm_id: &str,
+ algorithm_id: &common_utils::id_type::RoutingId,
profile_id: &common_utils::id_type::ProfileId,
) -> StorageResult<RoutingProfileMetadata> {
Self::table()
@@ -69,7 +69,7 @@ impl RoutingAlgorithm {
.limit(1)
.load_async::<(
common_utils::id_type::ProfileId,
- String,
+ common_utils::id_type::RoutingId,
String,
Option<String>,
enums::RoutingAlgorithmKind,
@@ -128,7 +128,7 @@ impl RoutingAlgorithm {
.limit(limit)
.offset(offset)
.load_async::<(
- String,
+ common_utils::id_type::RoutingId,
common_utils::id_type::ProfileId,
String,
Option<String>,
@@ -189,7 +189,7 @@ impl RoutingAlgorithm {
.order(dsl::modified_at.desc())
.load_async::<(
common_utils::id_type::ProfileId,
- String,
+ common_utils::id_type::RoutingId,
String,
Option<String>,
enums::RoutingAlgorithmKind,
@@ -251,7 +251,7 @@ impl RoutingAlgorithm {
.order(dsl::modified_at.desc())
.load_async::<(
common_utils::id_type::ProfileId,
- String,
+ common_utils::id_type::RoutingId,
String,
Option<String>,
enums::RoutingAlgorithmKind,
diff --git a/crates/diesel_models/src/routing_algorithm.rs b/crates/diesel_models/src/routing_algorithm.rs
index 6be0be3d5e4..5f5a0560811 100644
--- a/crates/diesel_models/src/routing_algorithm.rs
+++ b/crates/diesel_models/src/routing_algorithm.rs
@@ -1,3 +1,4 @@
+use common_utils::id_type;
use diesel::{Identifiable, Insertable, Queryable, Selectable};
use serde::{Deserialize, Serialize};
@@ -6,9 +7,9 @@ use crate::{enums, schema::routing_algorithm};
#[derive(Clone, Debug, Identifiable, Insertable, Queryable, Selectable, Serialize, Deserialize)]
#[diesel(table_name = routing_algorithm, primary_key(algorithm_id), check_for_backend(diesel::pg::Pg))]
pub struct RoutingAlgorithm {
- pub algorithm_id: String,
- pub profile_id: common_utils::id_type::ProfileId,
- pub merchant_id: common_utils::id_type::MerchantId,
+ pub algorithm_id: id_type::RoutingId,
+ pub profile_id: id_type::ProfileId,
+ pub merchant_id: id_type::MerchantId,
pub name: String,
pub description: Option<String>,
pub kind: enums::RoutingAlgorithmKind,
@@ -19,7 +20,7 @@ pub struct RoutingAlgorithm {
}
pub struct RoutingAlgorithmMetadata {
- pub algorithm_id: String,
+ pub algorithm_id: id_type::RoutingId,
pub name: String,
pub description: Option<String>,
pub kind: enums::RoutingAlgorithmKind,
@@ -29,8 +30,8 @@ pub struct RoutingAlgorithmMetadata {
}
pub struct RoutingProfileMetadata {
- pub profile_id: common_utils::id_type::ProfileId,
- pub algorithm_id: String,
+ pub profile_id: id_type::ProfileId,
+ pub algorithm_id: id_type::RoutingId,
pub name: String,
pub description: Option<String>,
pub kind: enums::RoutingAlgorithmKind,
diff --git a/crates/hyperswitch_domain_models/src/business_profile.rs b/crates/hyperswitch_domain_models/src/business_profile.rs
index 9a6edc50e73..4f9c562a565 100644
--- a/crates/hyperswitch_domain_models/src/business_profile.rs
+++ b/crates/hyperswitch_domain_models/src/business_profile.rs
@@ -479,11 +479,11 @@ pub struct BusinessProfile {
pub outgoing_webhook_custom_http_headers: OptionalEncryptableValue,
pub always_collect_billing_details_from_wallet_connector: Option<bool>,
pub always_collect_shipping_details_from_wallet_connector: Option<bool>,
- pub routing_algorithm_id: Option<String>,
+ pub routing_algorithm_id: Option<common_utils::id_type::RoutingId>,
pub order_fulfillment_time: Option<i64>,
pub order_fulfillment_time_origin: Option<common_enums::OrderFulfillmentTimeOrigin>,
pub frm_routing_algorithm_id: Option<String>,
- pub payout_routing_algorithm_id: Option<String>,
+ pub payout_routing_algorithm_id: Option<common_utils::id_type::RoutingId>,
pub default_fallback_routing: Option<pii::SecretSerdeValue>,
pub tax_connector_id: Option<String>,
pub is_tax_connector_enabled: bool,
@@ -536,8 +536,8 @@ pub struct BusinessProfileGeneralUpdate {
pub enum BusinessProfileUpdate {
Update(Box<BusinessProfileGeneralUpdate>),
RoutingAlgorithmUpdate {
- routing_algorithm_id: Option<String>,
- payout_routing_algorithm_id: Option<String>,
+ routing_algorithm_id: Option<common_utils::id_type::RoutingId>,
+ payout_routing_algorithm_id: Option<common_utils::id_type::RoutingId>,
},
DefaultRoutingFallbackUpdate {
default_fallback_routing: Option<pii::SecretSerdeValue>,
diff --git a/crates/router/src/core/admin.rs b/crates/router/src/core/admin.rs
index cb95feee9e9..eeaf1ddc02e 100644
--- a/crates/router/src/core/admin.rs
+++ b/crates/router/src/core/admin.rs
@@ -4128,7 +4128,7 @@ impl BusinessProfileWrapper {
db: &dyn StorageInterface,
key_manager_state: &KeyManagerState,
merchant_key_store: &domain::MerchantKeyStore,
- algorithm_id: String,
+ algorithm_id: common_utils::id_type::RoutingId,
transaction_type: &storage::enums::TransactionType,
) -> RouterResult<()> {
let routing_cache_key = self.clone().get_routing_config_cache_key();
@@ -4169,7 +4169,7 @@ impl BusinessProfileWrapper {
pub fn get_routing_algorithm_id<'a, F>(
&'a self,
transaction_data: &'a routing::TransactionData<'_, F>,
- ) -> Option<String>
+ ) -> Option<id_type::RoutingId>
where
F: Send + Clone,
{
diff --git a/crates/router/src/core/payments/routing.rs b/crates/router/src/core/payments/routing.rs
index 6f1912d7c65..1c8a58662f1 100644
--- a/crates/router/src/core/payments/routing.rs
+++ b/crates/router/src/core/payments/routing.rs
@@ -114,7 +114,7 @@ impl Default for MerchantAccountRoutingAlgorithm {
#[derive(Debug, serde::Serialize, serde::Deserialize)]
#[serde(untagged)]
enum MerchantAccountRoutingAlgorithm {
- V1(Option<String>),
+ V1(Option<common_utils::id_type::RoutingId>),
}
#[cfg(feature = "payouts")]
@@ -289,7 +289,7 @@ where
pub async fn perform_static_routing_v1<F: Clone>(
state: &SessionState,
merchant_id: &common_utils::id_type::MerchantId,
- algorithm_id: Option<String>,
+ algorithm_id: Option<common_utils::id_type::RoutingId>,
business_profile: &domain::BusinessProfile,
transaction_data: &routing::TransactionData<'_, F>,
) -> RoutingResult<Vec<routing_types::RoutableConnectorChoice>> {
@@ -352,7 +352,7 @@ pub async fn perform_static_routing_v1<F: Clone>(
async fn ensure_algorithm_cached_v1(
state: &SessionState,
merchant_id: &common_utils::id_type::MerchantId,
- algorithm_id: &str,
+ algorithm_id: &common_utils::id_type::RoutingId,
profile_id: common_utils::id_type::ProfileId,
transaction_type: &api_enums::TransactionType,
) -> RoutingResult<Arc<CachedAlgorithm>> {
@@ -437,7 +437,7 @@ fn execute_dsl_and_get_connector_v1(
pub async fn refresh_routing_cache_v1(
state: &SessionState,
key: String,
- algorithm_id: &str,
+ algorithm_id: &common_utils::id_type::RoutingId,
profile_id: common_utils::id_type::ProfileId,
) -> RoutingResult<Arc<CachedAlgorithm>> {
let algorithm = {
diff --git a/crates/router/src/core/routing.rs b/crates/router/src/core/routing.rs
index d5a3a96d155..b0cc088b0ff 100644
--- a/crates/router/src/core/routing.rs
+++ b/crates/router/src/core/routing.rs
@@ -14,8 +14,12 @@ use super::payments;
use super::payouts;
#[cfg(all(any(feature = "v1", feature = "v2"), not(feature = "routing_v2")))]
use crate::utils::ValueExt;
+#[cfg(all(feature = "v2", feature = "routing_v2"))]
+use crate::{
+ core::{admin, errors::RouterResult},
+ db::StorageInterface,
+};
use crate::{
- consts,
core::{
errors::{self, RouterResponse, StorageErrorExt},
metrics, utils as core_utils,
@@ -28,11 +32,6 @@ use crate::{
},
utils::{self, OptionExt},
};
-#[cfg(all(feature = "v2", feature = "routing_v2"))]
-use crate::{
- core::{admin, errors::RouterResult},
- db::StorageInterface,
-};
pub enum TransactionData<'a, F>
where
F: Clone,
@@ -53,10 +52,7 @@ impl RoutingAlgorithmUpdate {
profile_id: common_utils::id_type::ProfileId,
transaction_type: &enums::TransactionType,
) -> Self {
- let algorithm_id = common_utils::generate_id(
- consts::ROUTING_CONFIG_ID_LENGTH,
- &format!("routing_{}", merchant_id.get_string_repr()),
- );
+ let algorithm_id = common_utils::generate_routing_id_of_default_length();
let timestamp = common_utils::date_time::now();
let algo = RoutingAlgorithm {
algorithm_id,
@@ -74,7 +70,7 @@ impl RoutingAlgorithmUpdate {
}
pub async fn fetch_routing_algo(
merchant_id: &common_utils::id_type::MerchantId,
- algorithm_id: &str,
+ algorithm_id: &common_utils::id_type::RoutingId,
db: &dyn StorageInterface,
) -> RouterResult<Self> {
let routing_algo = db
@@ -215,10 +211,7 @@ pub async fn create_routing_algorithm_under_profile(
})
.attach_printable("Algorithm of config not given")?;
- let algorithm_id = common_utils::generate_id(
- consts::ROUTING_CONFIG_ID_LENGTH,
- &format!("routing_{}", merchant_account.get_id().get_string_repr()),
- );
+ let algorithm_id = common_utils::generate_routing_id_of_default_length();
let profile_id = request
.profile_id
@@ -280,7 +273,7 @@ pub async fn link_routing_config_under_profile(
merchant_account: domain::MerchantAccount,
key_store: domain::MerchantKeyStore,
profile_id: common_utils::id_type::ProfileId,
- algorithm_id: String,
+ algorithm_id: common_utils::id_type::RoutingId,
transaction_type: &enums::TransactionType,
) -> RouterResponse<routing_types::RoutingDictionaryRecord> {
metrics::ROUTING_LINK_CONFIG.add(&metrics::CONTEXT, 1, &[]);
@@ -352,7 +345,7 @@ pub async fn link_routing_config(
state: SessionState,
merchant_account: domain::MerchantAccount,
key_store: domain::MerchantKeyStore,
- algorithm_id: String,
+ algorithm_id: common_utils::id_type::RoutingId,
transaction_type: &enums::TransactionType,
) -> RouterResponse<routing_types::RoutingDictionaryRecord> {
metrics::ROUTING_LINK_CONFIG.add(&metrics::CONTEXT, 1, &[]);
@@ -428,7 +421,7 @@ pub async fn retrieve_routing_algorithm_from_algorithm_id(
state: SessionState,
merchant_account: domain::MerchantAccount,
key_store: domain::MerchantKeyStore,
- algorithm_id: String,
+ algorithm_id: common_utils::id_type::RoutingId,
) -> RouterResponse<routing_types::MerchantRoutingAlgorithm> {
metrics::ROUTING_RETRIEVE_CONFIG.add(&metrics::CONTEXT, 1, &[]);
let db = state.store.as_ref();
@@ -461,7 +454,7 @@ pub async fn retrieve_routing_algorithm_from_algorithm_id(
state: SessionState,
merchant_account: domain::MerchantAccount,
key_store: domain::MerchantKeyStore,
- algorithm_id: String,
+ algorithm_id: common_utils::id_type::RoutingId,
) -> RouterResponse<routing_types::MerchantRoutingAlgorithm> {
metrics::ROUTING_RETRIEVE_CONFIG.add(&metrics::CONTEXT, 1, &[]);
let db = state.store.as_ref();
diff --git a/crates/router/src/db/kafka_store.rs b/crates/router/src/db/kafka_store.rs
index 403b79a0377..e3c9b1b85b0 100644
--- a/crates/router/src/db/kafka_store.rs
+++ b/crates/router/src/db/kafka_store.rs
@@ -2494,7 +2494,7 @@ impl RoutingAlgorithmInterface for KafkaStore {
async fn find_routing_algorithm_by_profile_id_algorithm_id(
&self,
profile_id: &id_type::ProfileId,
- algorithm_id: &str,
+ algorithm_id: &id_type::RoutingId,
) -> CustomResult<storage::RoutingAlgorithm, errors::StorageError> {
self.diesel_store
.find_routing_algorithm_by_profile_id_algorithm_id(profile_id, algorithm_id)
@@ -2503,7 +2503,7 @@ impl RoutingAlgorithmInterface for KafkaStore {
async fn find_routing_algorithm_by_algorithm_id_merchant_id(
&self,
- algorithm_id: &str,
+ algorithm_id: &id_type::RoutingId,
merchant_id: &id_type::MerchantId,
) -> CustomResult<storage::RoutingAlgorithm, errors::StorageError> {
self.diesel_store
@@ -2513,7 +2513,7 @@ impl RoutingAlgorithmInterface for KafkaStore {
async fn find_routing_algorithm_metadata_by_algorithm_id_profile_id(
&self,
- algorithm_id: &str,
+ algorithm_id: &id_type::RoutingId,
profile_id: &id_type::ProfileId,
) -> CustomResult<storage::RoutingProfileMetadata, errors::StorageError> {
self.diesel_store
diff --git a/crates/router/src/db/routing_algorithm.rs b/crates/router/src/db/routing_algorithm.rs
index 5672777bfa2..3849b9272e0 100644
--- a/crates/router/src/db/routing_algorithm.rs
+++ b/crates/router/src/db/routing_algorithm.rs
@@ -21,18 +21,18 @@ pub trait RoutingAlgorithmInterface {
async fn find_routing_algorithm_by_profile_id_algorithm_id(
&self,
profile_id: &common_utils::id_type::ProfileId,
- algorithm_id: &str,
+ algorithm_id: &common_utils::id_type::RoutingId,
) -> StorageResult<routing_storage::RoutingAlgorithm>;
async fn find_routing_algorithm_by_algorithm_id_merchant_id(
&self,
- algorithm_id: &str,
+ algorithm_id: &common_utils::id_type::RoutingId,
merchant_id: &common_utils::id_type::MerchantId,
) -> StorageResult<routing_storage::RoutingAlgorithm>;
async fn find_routing_algorithm_metadata_by_algorithm_id_profile_id(
&self,
- algorithm_id: &str,
+ algorithm_id: &common_utils::id_type::RoutingId,
profile_id: &common_utils::id_type::ProfileId,
) -> StorageResult<routing_storage::RoutingProfileMetadata>;
@@ -77,7 +77,7 @@ impl RoutingAlgorithmInterface for Store {
async fn find_routing_algorithm_by_profile_id_algorithm_id(
&self,
profile_id: &common_utils::id_type::ProfileId,
- algorithm_id: &str,
+ algorithm_id: &common_utils::id_type::RoutingId,
) -> StorageResult<routing_storage::RoutingAlgorithm> {
let conn = connection::pg_connection_write(self).await?;
routing_storage::RoutingAlgorithm::find_by_algorithm_id_profile_id(
@@ -92,7 +92,7 @@ impl RoutingAlgorithmInterface for Store {
#[instrument(skip_all)]
async fn find_routing_algorithm_by_algorithm_id_merchant_id(
&self,
- algorithm_id: &str,
+ algorithm_id: &common_utils::id_type::RoutingId,
merchant_id: &common_utils::id_type::MerchantId,
) -> StorageResult<routing_storage::RoutingAlgorithm> {
let conn = connection::pg_connection_write(self).await?;
@@ -108,7 +108,7 @@ impl RoutingAlgorithmInterface for Store {
#[instrument(skip_all)]
async fn find_routing_algorithm_metadata_by_algorithm_id_profile_id(
&self,
- algorithm_id: &str,
+ algorithm_id: &common_utils::id_type::RoutingId,
profile_id: &common_utils::id_type::ProfileId,
) -> StorageResult<routing_storage::RoutingProfileMetadata> {
let conn = connection::pg_connection_write(self).await?;
@@ -186,14 +186,14 @@ impl RoutingAlgorithmInterface for MockDb {
async fn find_routing_algorithm_by_profile_id_algorithm_id(
&self,
_profile_id: &common_utils::id_type::ProfileId,
- _algorithm_id: &str,
+ _algorithm_id: &common_utils::id_type::RoutingId,
) -> StorageResult<routing_storage::RoutingAlgorithm> {
Err(errors::StorageError::MockDbError)?
}
async fn find_routing_algorithm_by_algorithm_id_merchant_id(
&self,
- _algorithm_id: &str,
+ _algorithm_id: &common_utils::id_type::RoutingId,
_merchant_id: &common_utils::id_type::MerchantId,
) -> StorageResult<routing_storage::RoutingAlgorithm> {
Err(errors::StorageError::MockDbError)?
@@ -201,7 +201,7 @@ impl RoutingAlgorithmInterface for MockDb {
async fn find_routing_algorithm_metadata_by_algorithm_id_profile_id(
&self,
- _algorithm_id: &str,
+ _algorithm_id: &common_utils::id_type::RoutingId,
_profile_id: &common_utils::id_type::ProfileId,
) -> StorageResult<routing_storage::RoutingProfileMetadata> {
Err(errors::StorageError::MockDbError)?
diff --git a/crates/router/src/routes/routing.rs b/crates/router/src/routes/routing.rs
index ecce0f96198..aefc91f759c 100644
--- a/crates/router/src/routes/routing.rs
+++ b/crates/router/src/routes/routing.rs
@@ -60,7 +60,7 @@ pub async fn routing_create_config(
pub async fn routing_link_config(
state: web::Data<AppState>,
req: HttpRequest,
- path: web::Path<String>,
+ path: web::Path<common_utils::id_type::RoutingId>,
transaction_type: &enums::TransactionType,
) -> impl Responder {
let flow = Flow::RoutingLinkConfig;
@@ -139,7 +139,7 @@ pub async fn routing_link_config(
pub async fn routing_retrieve_config(
state: web::Data<AppState>,
req: HttpRequest,
- path: web::Path<String>,
+ path: web::Path<common_utils::id_type::RoutingId>,
) -> impl Responder {
let algorithm_id = path.into_inner();
let flow = Flow::RoutingRetrieveConfig;
|
2024-08-28T11:10:22Z
|
## Type of Change
<!-- Put an `x` in the boxes that apply -->
- [ ] Bugfix
- [ ] New feature
- [ ] Enhancement
- [ ] Refactoring
- [ ] Dependency updates
- [ ] Documentation
- [ ] CI/CD
## Description
add domain type for Routing id
### Additional Changes
- [ ] This PR modifies the API contract
- [ ] This PR modifies the database schema
- [ ] This PR modifies application configuration/environment variables
<!--
Provide links to the files with corresponding changes.
Following are the paths where you can find config files:
1. `config`
2. `crates/router/src/configs`
3. `loadtest/config`
-->
## Motivation and Context
<!--
Why is this change required? What problem does it solve?
If it fixes an open issue, please link to the issue here.
If you don't have an issue, we'd recommend starting with one first so the PR
can focus on the implementation (unless it is an obvious bug or documentation fix
that will have little conversation).
-->
## How did you test it?
Tested Manually
Create, Update & Retrieve of outing and subsequent flows like payments sanity
## Checklist
<!-- Put an `x` in the boxes that apply -->
- [ ] I formatted the code `cargo +nightly fmt --all`
- [ ] I addressed lints thrown by `cargo clippy`
- [ ] I reviewed the submitted code
- [ ] I added unit tests for my changes where possible
|
32dd3f97ad094344d8bfe95f7cdcb5cff891990f
|
|
juspay/hyperswitch
|
juspay__hyperswitch-5755
|
Bug: Creation of Toggle and Configs for DynamicRouting & DynamicRoutingMetrics
### Toggle for Dynamic Routing:
There should be a 2 way toggle of the switch:
1. For Success-Based routing(whole integration in core that will affect payments).
2. For only enabling metrics of Success-Based routing (This can be used in future to show users the metrics first and then accordingly the core integration can be enabled).
-> Route 1: Something like GET `/routing/dynamic_routing/enable` or `/routing/dynamic_routing_metrics/enable`.
-> Once Toggled a default config should be created and stored in Routing table to be sent to Dynamo.
-> Add a Boolean value in BusinessProfile table `is_dynamic_routing_enabled`.
-> The code should be under feature flag.
-> Route 2: Update Route (UPDATE `/routing/dynamic_routing/config`) to update the config for users with AdminApiKey auth.
|
diff --git a/api-reference-v2/openapi_spec.json b/api-reference-v2/openapi_spec.json
index 3c2c811766b..8e6e58865fc 100644
--- a/api-reference-v2/openapi_spec.json
+++ b/api-reference-v2/openapi_spec.json
@@ -17247,7 +17247,8 @@
"single",
"priority",
"volume_split",
- "advanced"
+ "advanced",
+ "dynamic"
]
},
"RoutingConfigRequest": {
diff --git a/crates/api_models/src/admin.rs b/crates/api_models/src/admin.rs
index 2b185d202e1..be3e26b2639 100644
--- a/crates/api_models/src/admin.rs
+++ b/crates/api_models/src/admin.rs
@@ -2356,6 +2356,10 @@ pub struct BusinessProfileUpdate {
/// Indicates if tax_calculator connector is enabled or not.
/// If set to `true` tax_connector_id will be checked.
pub is_tax_connector_enabled: Option<bool>,
+
+ /// Indicates if dynamic routing is enabled or not.
+ #[serde(default)]
+ pub dynamic_routing_algorithm: Option<serde_json::Value>,
}
#[cfg(feature = "v2")]
diff --git a/crates/api_models/src/events/routing.rs b/crates/api_models/src/events/routing.rs
index 9cfcafc8733..ffa5e008f0a 100644
--- a/crates/api_models/src/events/routing.rs
+++ b/crates/api_models/src/events/routing.rs
@@ -4,7 +4,9 @@ use crate::routing::{
LinkedRoutingConfigRetrieveResponse, MerchantRoutingAlgorithm, ProfileDefaultRoutingConfig,
RoutingAlgorithmId, RoutingConfigRequest, RoutingDictionaryRecord, RoutingKind,
RoutingLinkWrapper, RoutingPayloadWrapper, RoutingRetrieveLinkQuery,
- RoutingRetrieveLinkQueryWrapper, RoutingRetrieveQuery,
+ RoutingRetrieveLinkQueryWrapper, RoutingRetrieveQuery, SuccessBasedRoutingConfig,
+ SuccessBasedRoutingPayloadWrapper, SuccessBasedRoutingUpdateConfigQuery,
+ ToggleSuccessBasedRoutingQuery, ToggleSuccessBasedRoutingWrapper,
};
impl ApiEventMetric for RoutingKind {
@@ -76,3 +78,33 @@ impl ApiEventMetric for RoutingRetrieveLinkQueryWrapper {
Some(ApiEventsType::Routing)
}
}
+
+impl ApiEventMetric for ToggleSuccessBasedRoutingQuery {
+ fn get_api_event_type(&self) -> Option<ApiEventsType> {
+ Some(ApiEventsType::Routing)
+ }
+}
+
+impl ApiEventMetric for SuccessBasedRoutingConfig {
+ fn get_api_event_type(&self) -> Option<ApiEventsType> {
+ Some(ApiEventsType::Routing)
+ }
+}
+
+impl ApiEventMetric for SuccessBasedRoutingPayloadWrapper {
+ fn get_api_event_type(&self) -> Option<ApiEventsType> {
+ Some(ApiEventsType::Routing)
+ }
+}
+
+impl ApiEventMetric for ToggleSuccessBasedRoutingWrapper {
+ fn get_api_event_type(&self) -> Option<ApiEventsType> {
+ Some(ApiEventsType::Routing)
+ }
+}
+
+impl ApiEventMetric for SuccessBasedRoutingUpdateConfigQuery {
+ fn get_api_event_type(&self) -> Option<ApiEventsType> {
+ Some(ApiEventsType::Routing)
+ }
+}
diff --git a/crates/api_models/src/routing.rs b/crates/api_models/src/routing.rs
index bec917b06c8..5023d30f722 100644
--- a/crates/api_models/src/routing.rs
+++ b/crates/api_models/src/routing.rs
@@ -260,6 +260,7 @@ pub enum RoutingAlgorithmKind {
Priority,
VolumeSplit,
Advanced,
+ Dynamic,
}
#[derive(Debug, Clone, serde::Serialize, serde::Deserialize)]
@@ -495,3 +496,138 @@ pub struct RoutingLinkWrapper {
pub profile_id: common_utils::id_type::ProfileId,
pub algorithm_id: RoutingAlgorithmId,
}
+
+#[derive(Debug, Default, Clone, serde::Serialize, serde::Deserialize)]
+pub struct DynamicAlgorithmWithTimestamp<T> {
+ pub algorithm_id: Option<T>,
+ pub timestamp: i64,
+}
+
+#[derive(Debug, Default, Clone, serde::Serialize, serde::Deserialize)]
+pub struct DynamicRoutingAlgorithmRef {
+ pub success_based_algorithm:
+ Option<DynamicAlgorithmWithTimestamp<common_utils::id_type::RoutingId>>,
+}
+
+impl DynamicRoutingAlgorithmRef {
+ pub fn update_algorithm_id(&mut self, new_id: common_utils::id_type::RoutingId) {
+ self.success_based_algorithm = Some(DynamicAlgorithmWithTimestamp {
+ algorithm_id: Some(new_id),
+ timestamp: common_utils::date_time::now_unix_timestamp(),
+ })
+ }
+}
+
+#[derive(Debug, Clone, serde::Serialize, serde::Deserialize, ToSchema)]
+pub struct ToggleSuccessBasedRoutingQuery {
+ pub status: bool,
+}
+
+#[derive(Debug, Clone, serde::Serialize, serde::Deserialize, ToSchema)]
+pub struct SuccessBasedRoutingUpdateConfigQuery {
+ #[schema(value_type = String)]
+ pub algorithm_id: common_utils::id_type::RoutingId,
+ #[schema(value_type = String)]
+ pub profile_id: common_utils::id_type::ProfileId,
+}
+
+#[derive(Clone, Debug, serde::Deserialize, serde::Serialize)]
+pub struct ToggleSuccessBasedRoutingWrapper {
+ pub profile_id: common_utils::id_type::ProfileId,
+ pub status: bool,
+}
+
+#[derive(Clone, Debug, serde::Deserialize, serde::Serialize, ToSchema)]
+pub struct ToggleSuccessBasedRoutingPath {
+ #[schema(value_type = String)]
+ pub profile_id: common_utils::id_type::ProfileId,
+}
+#[derive(serde::Serialize, serde::Deserialize, Debug, Clone, ToSchema)]
+pub struct SuccessBasedRoutingConfig {
+ pub params: Option<Vec<SuccessBasedRoutingConfigParams>>,
+ pub config: Option<SuccessBasedRoutingConfigBody>,
+}
+
+impl Default for SuccessBasedRoutingConfig {
+ fn default() -> Self {
+ Self {
+ params: Some(vec![SuccessBasedRoutingConfigParams::PaymentMethod]),
+ config: Some(SuccessBasedRoutingConfigBody {
+ min_aggregates_size: Some(2),
+ default_success_rate: Some(100.0),
+ max_aggregates_size: Some(3),
+ current_block_threshold: Some(CurrentBlockThreshold {
+ duration_in_mins: Some(5),
+ max_total_count: Some(2),
+ }),
+ }),
+ }
+ }
+}
+
+#[derive(serde::Serialize, serde::Deserialize, Debug, Clone, ToSchema)]
+pub enum SuccessBasedRoutingConfigParams {
+ PaymentMethod,
+ PaymentMethodType,
+ Currency,
+ AuthenticationType,
+}
+
+#[derive(serde::Serialize, serde::Deserialize, Debug, Clone, ToSchema)]
+pub struct SuccessBasedRoutingConfigBody {
+ pub min_aggregates_size: Option<u32>,
+ pub default_success_rate: Option<f64>,
+ pub max_aggregates_size: Option<u32>,
+ pub current_block_threshold: Option<CurrentBlockThreshold>,
+}
+
+#[derive(serde::Serialize, serde::Deserialize, Debug, Clone, ToSchema)]
+pub struct CurrentBlockThreshold {
+ pub duration_in_mins: Option<u64>,
+ pub max_total_count: Option<u64>,
+}
+
+#[derive(Debug, Clone, serde::Serialize, serde::Deserialize)]
+pub struct SuccessBasedRoutingPayloadWrapper {
+ pub updated_config: SuccessBasedRoutingConfig,
+ pub algorithm_id: common_utils::id_type::RoutingId,
+ pub profile_id: common_utils::id_type::ProfileId,
+}
+
+impl SuccessBasedRoutingConfig {
+ pub fn update(&mut self, new: Self) {
+ if let Some(params) = new.params {
+ self.params = Some(params)
+ }
+ if let Some(new_config) = new.config {
+ self.config.as_mut().map(|config| config.update(new_config));
+ }
+ }
+}
+
+impl SuccessBasedRoutingConfigBody {
+ pub fn update(&mut self, new: Self) {
+ if let Some(min_aggregates_size) = new.min_aggregates_size {
+ self.min_aggregates_size = Some(min_aggregates_size)
+ }
+ if let Some(default_success_rate) = new.default_success_rate {
+ self.default_success_rate = Some(default_success_rate)
+ }
+ if let Some(max_aggregates_size) = new.max_aggregates_size {
+ self.max_aggregates_size = Some(max_aggregates_size)
+ }
+ if let Some(current_block_threshold) = new.current_block_threshold {
+ self.current_block_threshold
+ .as_mut()
+ .map(|threshold| threshold.update(current_block_threshold));
+ }
+ }
+}
+
+impl CurrentBlockThreshold {
+ pub fn update(&mut self, new: Self) {
+ if let Some(max_total_count) = new.max_total_count {
+ self.max_total_count = Some(max_total_count)
+ }
+ }
+}
diff --git a/crates/diesel_models/src/business_profile.rs b/crates/diesel_models/src/business_profile.rs
index 029add42ced..a72263b96a8 100644
--- a/crates/diesel_models/src/business_profile.rs
+++ b/crates/diesel_models/src/business_profile.rs
@@ -53,6 +53,7 @@ pub struct BusinessProfile {
pub tax_connector_id: Option<common_utils::id_type::MerchantConnectorAccountId>,
pub is_tax_connector_enabled: Option<bool>,
pub version: common_enums::ApiVersion,
+ pub dynamic_routing_algorithm: Option<serde_json::Value>,
}
#[cfg(feature = "v1")]
@@ -129,6 +130,7 @@ pub struct BusinessProfileUpdateInternal {
pub always_collect_shipping_details_from_wallet_connector: Option<bool>,
pub tax_connector_id: Option<common_utils::id_type::MerchantConnectorAccountId>,
pub is_tax_connector_enabled: Option<bool>,
+ pub dynamic_routing_algorithm: Option<serde_json::Value>,
}
#[cfg(feature = "v1")]
@@ -164,6 +166,7 @@ impl BusinessProfileUpdateInternal {
always_collect_shipping_details_from_wallet_connector,
tax_connector_id,
is_tax_connector_enabled,
+ dynamic_routing_algorithm,
} = self;
BusinessProfile {
profile_id: source.profile_id,
@@ -217,6 +220,8 @@ impl BusinessProfileUpdateInternal {
tax_connector_id: tax_connector_id.or(source.tax_connector_id),
is_tax_connector_enabled: is_tax_connector_enabled.or(source.is_tax_connector_enabled),
version: source.version,
+ dynamic_routing_algorithm: dynamic_routing_algorithm
+ .or(source.dynamic_routing_algorithm),
}
}
}
@@ -266,6 +271,7 @@ pub struct BusinessProfile {
pub default_fallback_routing: Option<pii::SecretSerdeValue>,
pub id: common_utils::id_type::ProfileId,
pub version: common_enums::ApiVersion,
+ pub dynamic_routing_algorithm: Option<serde_json::Value>,
}
impl BusinessProfile {
@@ -452,6 +458,7 @@ impl BusinessProfileUpdateInternal {
.or(source.payout_routing_algorithm_id),
default_fallback_routing: default_fallback_routing.or(source.default_fallback_routing),
version: source.version,
+ dynamic_routing_algorithm: None,
}
}
}
@@ -502,6 +509,7 @@ impl From<BusinessProfileNew> for BusinessProfile {
payout_routing_algorithm_id: new.payout_routing_algorithm_id,
default_fallback_routing: new.default_fallback_routing,
version: new.version,
+ dynamic_routing_algorithm: None,
}
}
}
diff --git a/crates/diesel_models/src/enums.rs b/crates/diesel_models/src/enums.rs
index 8f9469c0288..68809d8d2fa 100644
--- a/crates/diesel_models/src/enums.rs
+++ b/crates/diesel_models/src/enums.rs
@@ -50,6 +50,7 @@ pub enum RoutingAlgorithmKind {
Priority,
VolumeSplit,
Advanced,
+ Dynamic,
}
#[derive(
diff --git a/crates/diesel_models/src/schema.rs b/crates/diesel_models/src/schema.rs
index 8e6c72eb5ba..1487616f458 100644
--- a/crates/diesel_models/src/schema.rs
+++ b/crates/diesel_models/src/schema.rs
@@ -209,6 +209,7 @@ diesel::table! {
tax_connector_id -> Nullable<Varchar>,
is_tax_connector_enabled -> Nullable<Bool>,
version -> ApiVersion,
+ dynamic_routing_algorithm -> Nullable<Json>,
}
}
diff --git a/crates/diesel_models/src/schema_v2.rs b/crates/diesel_models/src/schema_v2.rs
index 2deaa3d4ee4..818e7ecf01e 100644
--- a/crates/diesel_models/src/schema_v2.rs
+++ b/crates/diesel_models/src/schema_v2.rs
@@ -216,6 +216,7 @@ diesel::table! {
#[max_length = 64]
id -> Varchar,
version -> ApiVersion,
+ dynamic_routing_algorithm -> Nullable<Json>,
}
}
diff --git a/crates/hyperswitch_domain_models/src/business_profile.rs b/crates/hyperswitch_domain_models/src/business_profile.rs
index c6b76680d48..b13d79175c2 100644
--- a/crates/hyperswitch_domain_models/src/business_profile.rs
+++ b/crates/hyperswitch_domain_models/src/business_profile.rs
@@ -54,6 +54,7 @@ pub struct BusinessProfile {
pub tax_connector_id: Option<common_utils::id_type::MerchantConnectorAccountId>,
pub is_tax_connector_enabled: bool,
pub version: common_enums::ApiVersion,
+ pub dynamic_routing_algorithm: Option<serde_json::Value>,
}
#[cfg(feature = "v1")]
@@ -90,6 +91,7 @@ pub struct BusinessProfileSetter {
pub always_collect_shipping_details_from_wallet_connector: Option<bool>,
pub tax_connector_id: Option<common_utils::id_type::MerchantConnectorAccountId>,
pub is_tax_connector_enabled: bool,
+ pub dynamic_routing_algorithm: Option<serde_json::Value>,
}
#[cfg(feature = "v1")]
@@ -133,6 +135,7 @@ impl From<BusinessProfileSetter> for BusinessProfile {
tax_connector_id: value.tax_connector_id,
is_tax_connector_enabled: value.is_tax_connector_enabled,
version: consts::API_VERSION,
+ dynamic_routing_algorithm: value.dynamic_routing_algorithm,
}
}
}
@@ -178,6 +181,7 @@ pub struct BusinessProfileGeneralUpdate {
pub always_collect_shipping_details_from_wallet_connector: Option<bool>,
pub tax_connector_id: Option<common_utils::id_type::MerchantConnectorAccountId>,
pub is_tax_connector_enabled: Option<bool>,
+ pub dynamic_routing_algorithm: Option<serde_json::Value>,
}
#[cfg(feature = "v1")]
@@ -188,6 +192,9 @@ pub enum BusinessProfileUpdate {
routing_algorithm: Option<serde_json::Value>,
payout_routing_algorithm: Option<serde_json::Value>,
},
+ DynamicRoutingAlgorithmUpdate {
+ dynamic_routing_algorithm: Option<serde_json::Value>,
+ },
ExtendedCardInfoUpdate {
is_extended_card_info_enabled: Option<bool>,
},
@@ -230,6 +237,7 @@ impl From<BusinessProfileUpdate> for BusinessProfileUpdateInternal {
always_collect_shipping_details_from_wallet_connector,
tax_connector_id,
is_tax_connector_enabled,
+ dynamic_routing_algorithm,
} = *update;
Self {
@@ -263,6 +271,7 @@ impl From<BusinessProfileUpdate> for BusinessProfileUpdateInternal {
always_collect_shipping_details_from_wallet_connector,
tax_connector_id,
is_tax_connector_enabled,
+ dynamic_routing_algorithm,
}
}
BusinessProfileUpdate::RoutingAlgorithmUpdate {
@@ -298,6 +307,41 @@ impl From<BusinessProfileUpdate> for BusinessProfileUpdateInternal {
always_collect_shipping_details_from_wallet_connector: None,
tax_connector_id: None,
is_tax_connector_enabled: None,
+ dynamic_routing_algorithm: None,
+ },
+ BusinessProfileUpdate::DynamicRoutingAlgorithmUpdate {
+ dynamic_routing_algorithm,
+ } => Self {
+ profile_name: None,
+ modified_at: now,
+ return_url: None,
+ enable_payment_response_hash: None,
+ payment_response_hash_key: None,
+ redirect_to_merchant_with_http_post: None,
+ webhook_details: None,
+ metadata: None,
+ routing_algorithm: None,
+ intent_fulfillment_time: None,
+ frm_routing_algorithm: None,
+ payout_routing_algorithm: None,
+ is_recon_enabled: None,
+ applepay_verified_domains: None,
+ payment_link_config: None,
+ session_expiry: None,
+ authentication_connector_details: None,
+ payout_link_config: None,
+ is_extended_card_info_enabled: None,
+ extended_card_info_config: None,
+ is_connector_agnostic_mit_enabled: None,
+ use_billing_as_payment_method_billing: None,
+ collect_shipping_details_from_wallet_connector: None,
+ collect_billing_details_from_wallet_connector: None,
+ outgoing_webhook_custom_http_headers: None,
+ always_collect_billing_details_from_wallet_connector: None,
+ always_collect_shipping_details_from_wallet_connector: None,
+ tax_connector_id: None,
+ is_tax_connector_enabled: None,
+ dynamic_routing_algorithm,
},
BusinessProfileUpdate::ExtendedCardInfoUpdate {
is_extended_card_info_enabled,
@@ -331,6 +375,7 @@ impl From<BusinessProfileUpdate> for BusinessProfileUpdateInternal {
always_collect_shipping_details_from_wallet_connector: None,
tax_connector_id: None,
is_tax_connector_enabled: None,
+ dynamic_routing_algorithm: None,
},
BusinessProfileUpdate::ConnectorAgnosticMitUpdate {
is_connector_agnostic_mit_enabled,
@@ -364,6 +409,7 @@ impl From<BusinessProfileUpdate> for BusinessProfileUpdateInternal {
always_collect_shipping_details_from_wallet_connector: None,
tax_connector_id: None,
is_tax_connector_enabled: None,
+ dynamic_routing_algorithm: None,
},
}
}
@@ -416,6 +462,7 @@ impl super::behaviour::Conversion for BusinessProfile {
tax_connector_id: self.tax_connector_id,
is_tax_connector_enabled: Some(self.is_tax_connector_enabled),
version: self.version,
+ dynamic_routing_algorithm: self.dynamic_routing_algorithm,
})
}
@@ -480,6 +527,7 @@ impl super::behaviour::Conversion for BusinessProfile {
tax_connector_id: item.tax_connector_id,
is_tax_connector_enabled: item.is_tax_connector_enabled.unwrap_or(false),
version: item.version,
+ dynamic_routing_algorithm: item.dynamic_routing_algorithm,
})
}
.await
@@ -984,6 +1032,7 @@ impl super::behaviour::Conversion for BusinessProfile {
tax_connector_id: self.tax_connector_id,
is_tax_connector_enabled: Some(self.is_tax_connector_enabled),
version: self.version,
+ dynamic_routing_algorithm: None,
})
}
diff --git a/crates/openapi/src/openapi.rs b/crates/openapi/src/openapi.rs
index 2926f47af9e..6c911fc9bbe 100644
--- a/crates/openapi/src/openapi.rs
+++ b/crates/openapi/src/openapi.rs
@@ -158,6 +158,8 @@ Never share your secret api keys. Keep them guarded and secure.
routes::routing::routing_retrieve_linked_config,
routes::routing::routing_retrieve_default_config_for_profiles,
routes::routing::routing_update_default_config_for_profile,
+ routes::routing::toggle_success_based_routing,
+ routes::routing::success_based_routing_update_configs,
// Routes for blocklist
routes::blocklist::remove_entry_from_blocklist,
@@ -543,6 +545,13 @@ Never share your secret api keys. Keep them guarded and secure.
api_models::routing::StraightThroughAlgorithm,
api_models::routing::ConnectorVolumeSplit,
api_models::routing::ConnectorSelection,
+ api_models::routing::ToggleSuccessBasedRoutingQuery,
+ api_models::routing::SuccessBasedRoutingConfig,
+ api_models::routing::SuccessBasedRoutingConfigParams,
+ api_models::routing::SuccessBasedRoutingConfigBody,
+ api_models::routing::CurrentBlockThreshold,
+ api_models::routing::SuccessBasedRoutingUpdateConfigQuery,
+ api_models::routing::ToggleSuccessBasedRoutingPath,
api_models::routing::ast::RoutableChoiceKind,
api_models::enums::RoutableConnectors,
api_models::routing::ast::ProgramConnectorSelection,
diff --git a/crates/openapi/src/routes/routing.rs b/crates/openapi/src/routes/routing.rs
index 5e1e3f60c62..009708d860d 100644
--- a/crates/openapi/src/routes/routing.rs
+++ b/crates/openapi/src/routes/routing.rs
@@ -255,3 +255,56 @@ pub async fn routing_retrieve_default_config_for_profiles() {}
security(("api_key" = []), ("jwt_key" = []))
)]
pub async fn routing_update_default_config_for_profile() {}
+
+#[cfg(feature = "v1")]
+/// Routing - Toggle success based dynamic routing for profile
+///
+/// Create a success based dynamic routing algorithm
+#[utoipa::path(
+ post,
+ path = "/account/:account_id/business_profile/:profile_id/dynamic_routing/success_based/toggle",
+ params(
+ ("account_id" = String, Path, description = "Merchant id"),
+ ("profile_id" = String, Path, description = "Profile id under which Dynamic routing needs to be toggled"),
+ ("status" = bool, Query, description = "Boolean value for mentioning the expected state of dynamic routing"),
+ ),
+ responses(
+ (status = 200, description = "Routing Algorithm created", body = RoutingDictionaryRecord),
+ (status = 400, description = "Request body is malformed"),
+ (status = 500, description = "Internal server error"),
+ (status = 404, description = "Resource missing"),
+ (status = 422, description = "Unprocessable request"),
+ (status = 403, description = "Forbidden"),
+ ),
+ tag = "Routing",
+ operation_id = "Toggle success based dynamic routing algprithm",
+ security(("api_key" = []), ("jwt_key" = []))
+)]
+pub async fn toggle_success_based_routing() {}
+
+#[cfg(feature = "v1")]
+/// Routing - Update config for success based dynamic routing
+///
+/// Update config for success based dynamic routing
+#[utoipa::path(
+ patch,
+ path = "/account/:account_id/business_profile/:profile_id/dynamic_routing/success_based/config/:algorithm_id",
+ request_body = SuccessBasedRoutingConfig,
+ params(
+ ("account_id" = String, Path, description = "Merchant id"),
+ ("profile_id" = String, Path, description = "The unique identifier for a profile"),
+ ("algorithm_id" = String, Path, description = "The unique identifier for routing algorithm"),
+ ),
+ responses(
+ (status = 200, description = "Routing Algorithm updated", body = RoutingDictionaryRecord),
+ (status = 400, description = "Request body is malformed"),
+ (status = 500, description = "Internal server error"),
+ (status = 404, description = "Resource missing"),
+ (status = 422, description = "Unprocessable request"),
+ (status = 403, description = "Forbidden"),
+ ),
+ tag = "Routing",
+ operation_id = "Update configs for success based dynamic routing algorithm",
+ security(("admin_api_key" = []))
+)]
+pub async fn success_based_routing_update_configs() {}
diff --git a/crates/router/src/core/admin.rs b/crates/router/src/core/admin.rs
index c0cb446b38f..eb357d80ad1 100644
--- a/crates/router/src/core/admin.rs
+++ b/crates/router/src/core/admin.rs
@@ -3471,6 +3471,7 @@ impl BusinessProfileCreateBridge for api::BusinessProfileCreate {
.always_collect_billing_details_from_wallet_connector,
always_collect_shipping_details_from_wallet_connector: self
.always_collect_shipping_details_from_wallet_connector,
+ dynamic_routing_algorithm: None,
},
))
}
@@ -3818,6 +3819,7 @@ impl BusinessProfileUpdateBridge for api::BusinessProfileUpdate {
.always_collect_shipping_details_from_wallet_connector,
tax_connector_id: self.tax_connector_id,
is_tax_connector_enabled: self.is_tax_connector_enabled,
+ dynamic_routing_algorithm: self.dynamic_routing_algorithm,
},
)))
}
diff --git a/crates/router/src/core/payments/operations/payment_confirm.rs b/crates/router/src/core/payments/operations/payment_confirm.rs
index df2f8746e11..35cc811af65 100644
--- a/crates/router/src/core/payments/operations/payment_confirm.rs
+++ b/crates/router/src/core/payments/operations/payment_confirm.rs
@@ -922,12 +922,12 @@ impl<F: Clone + Send> Domain<F, api::PaymentsRequest, PaymentData<F>> for Paymen
Some(helpers::PaymentExternalAuthenticationFlow::PostAuthenticationFlow {
authentication_id,
}) => {
- let authentication = authentication::perform_post_authentication(
+ let authentication = Box::pin(authentication::perform_post_authentication(
state,
key_store,
business_profile.clone(),
authentication_id.clone(),
- )
+ ))
.await?;
//If authentication is not successful, skip the payment connector flows and mark the payment as failure
if authentication.authentication_status
diff --git a/crates/router/src/core/routing.rs b/crates/router/src/core/routing.rs
index fd58a2c571a..2ce75065673 100644
--- a/crates/router/src/core/routing.rs
+++ b/crates/router/src/core/routing.rs
@@ -2,12 +2,13 @@ pub mod helpers;
pub mod transformers;
use api_models::{
- enums, mandates as mandates_api,
+ enums, mandates as mandates_api, routing,
routing::{self as routing_types, RoutingRetrieveQuery},
};
use diesel_models::routing_algorithm::RoutingAlgorithm;
use error_stack::ResultExt;
use hyperswitch_domain_models::{mandates, payment_address};
+use router_env::metrics::add_attributes;
use rustc_hash::FxHashSet;
#[cfg(feature = "payouts")]
@@ -411,42 +412,89 @@ pub async fn link_routing_config(
core_utils::validate_profile_id_from_auth_layer(authentication_profile_id, &business_profile)?;
- let mut routing_ref: routing_types::RoutingAlgorithmRef = business_profile
- .routing_algorithm
- .clone()
- .map(|val| val.parse_value("RoutingAlgorithmRef"))
- .transpose()
- .change_context(errors::ApiErrorResponse::InternalServerError)
- .attach_printable("unable to deserialize routing algorithm ref from merchant account")?
- .unwrap_or_default();
-
- utils::when(routing_algorithm.algorithm_for != *transaction_type, || {
- Err(errors::ApiErrorResponse::PreconditionFailed {
- message: format!(
- "Cannot use {}'s routing algorithm for {} operation",
- routing_algorithm.algorithm_for, transaction_type
- ),
- })
- })?;
+ match routing_algorithm.kind {
+ diesel_models::enums::RoutingAlgorithmKind::Dynamic => {
+ let mut dynamic_routing_ref: routing_types::DynamicRoutingAlgorithmRef =
+ business_profile
+ .dynamic_routing_algorithm
+ .clone()
+ .map(|val| val.parse_value("DynamicRoutingAlgorithmRef"))
+ .transpose()
+ .change_context(errors::ApiErrorResponse::InternalServerError)
+ .attach_printable(
+ "unable to deserialize Dynamic routing algorithm ref from business profile",
+ )?
+ .unwrap_or_default();
+
+ utils::when(
+ matches!(
+ dynamic_routing_ref.success_based_algorithm,
+ Some(routing_types::DynamicAlgorithmWithTimestamp {
+ algorithm_id: Some(ref id),
+ timestamp: _
+ }) if id == &algorithm_id
+ ),
+ || {
+ Err(errors::ApiErrorResponse::PreconditionFailed {
+ message: "Algorithm is already active".to_string(),
+ })
+ },
+ )?;
- utils::when(
- routing_ref.algorithm_id == Some(algorithm_id.clone()),
- || {
- Err(errors::ApiErrorResponse::PreconditionFailed {
- message: "Algorithm is already active".to_string(),
- })
- },
- )?;
- routing_ref.update_algorithm_id(algorithm_id);
- helpers::update_business_profile_active_algorithm_ref(
- db,
- key_manager_state,
- &key_store,
- business_profile,
- routing_ref,
- transaction_type,
- )
- .await?;
+ dynamic_routing_ref.update_algorithm_id(algorithm_id);
+ helpers::update_business_profile_active_dynamic_algorithm_ref(
+ db,
+ key_manager_state,
+ &key_store,
+ business_profile,
+ dynamic_routing_ref,
+ )
+ .await?;
+ }
+ diesel_models::enums::RoutingAlgorithmKind::Single
+ | diesel_models::enums::RoutingAlgorithmKind::Priority
+ | diesel_models::enums::RoutingAlgorithmKind::Advanced
+ | diesel_models::enums::RoutingAlgorithmKind::VolumeSplit => {
+ let mut routing_ref: routing_types::RoutingAlgorithmRef = business_profile
+ .routing_algorithm
+ .clone()
+ .map(|val| val.parse_value("RoutingAlgorithmRef"))
+ .transpose()
+ .change_context(errors::ApiErrorResponse::InternalServerError)
+ .attach_printable(
+ "unable to deserialize routing algorithm ref from business profile",
+ )?
+ .unwrap_or_default();
+
+ utils::when(routing_algorithm.algorithm_for != *transaction_type, || {
+ Err(errors::ApiErrorResponse::PreconditionFailed {
+ message: format!(
+ "Cannot use {}'s routing algorithm for {} operation",
+ routing_algorithm.algorithm_for, transaction_type
+ ),
+ })
+ })?;
+
+ utils::when(
+ routing_ref.algorithm_id == Some(algorithm_id.clone()),
+ || {
+ Err(errors::ApiErrorResponse::PreconditionFailed {
+ message: "Algorithm is already active".to_string(),
+ })
+ },
+ )?;
+ routing_ref.update_algorithm_id(algorithm_id);
+ helpers::update_business_profile_active_algorithm_ref(
+ db,
+ key_manager_state,
+ &key_store,
+ business_profile,
+ routing_ref,
+ transaction_type,
+ )
+ .await?;
+ }
+ };
metrics::ROUTING_LINK_CONFIG_SUCCESS_RESPONSE.add(&metrics::CONTEXT, 1, &[]);
Ok(service_api::ApplicationResponse::Json(
@@ -1111,3 +1159,192 @@ pub async fn update_default_routing_config_for_profile(
},
))
}
+
+#[cfg(feature = "v1")]
+pub async fn toggle_success_based_routing(
+ state: SessionState,
+ merchant_account: domain::MerchantAccount,
+ key_store: domain::MerchantKeyStore,
+ status: bool,
+ profile_id: common_utils::id_type::ProfileId,
+) -> RouterResponse<routing_types::RoutingDictionaryRecord> {
+ metrics::ROUTING_CREATE_REQUEST_RECEIVED.add(
+ &metrics::CONTEXT,
+ 1,
+ &add_attributes([("profile_id", profile_id.get_string_repr().to_owned())]),
+ );
+ let db = state.store.as_ref();
+ let key_manager_state = &(&state).into();
+
+ let business_profile: domain::BusinessProfile = core_utils::validate_and_get_business_profile(
+ db,
+ key_manager_state,
+ &key_store,
+ Some(&profile_id),
+ merchant_account.get_id(),
+ )
+ .await?
+ .get_required_value("BusinessProfile")
+ .change_context(errors::ApiErrorResponse::BusinessProfileNotFound {
+ id: profile_id.get_string_repr().to_owned(),
+ })?;
+
+ let mut success_based_dynamic_routing_algo_ref: routing_types::DynamicRoutingAlgorithmRef =
+ business_profile
+ .dynamic_routing_algorithm
+ .clone()
+ .map(|val| val.parse_value("DynamicRoutingAlgorithmRef"))
+ .transpose()
+ .change_context(errors::ApiErrorResponse::InternalServerError)
+ .attach_printable(
+ "unable to deserialize dynamic routing algorithm ref from business profile",
+ )?
+ .unwrap_or_default();
+
+ if status {
+ let default_success_based_routing_config = routing::SuccessBasedRoutingConfig::default();
+ let algorithm_id = common_utils::generate_routing_id_of_default_length();
+ let timestamp = common_utils::date_time::now();
+ let algo = RoutingAlgorithm {
+ algorithm_id: algorithm_id.clone(),
+ profile_id: business_profile.get_id().to_owned(),
+ merchant_id: merchant_account.get_id().to_owned(),
+ name: "Dynamic routing algorithm".to_string(),
+ description: None,
+ kind: diesel_models::enums::RoutingAlgorithmKind::Dynamic,
+ algorithm_data: serde_json::json!(default_success_based_routing_config),
+ created_at: timestamp,
+ modified_at: timestamp,
+ algorithm_for: common_enums::TransactionType::Payment,
+ };
+
+ let record = db
+ .insert_routing_algorithm(algo)
+ .await
+ .change_context(errors::ApiErrorResponse::InternalServerError)
+ .attach_printable("Unable to insert record in routing algorithm table")?;
+
+ success_based_dynamic_routing_algo_ref.update_algorithm_id(algorithm_id);
+ helpers::update_business_profile_active_dynamic_algorithm_ref(
+ db,
+ key_manager_state,
+ &key_store,
+ business_profile,
+ success_based_dynamic_routing_algo_ref,
+ )
+ .await?;
+
+ let new_record = record.foreign_into();
+
+ metrics::ROUTING_CREATE_SUCCESS_RESPONSE.add(
+ &metrics::CONTEXT,
+ 1,
+ &add_attributes([("profile_id", profile_id.get_string_repr().to_owned())]),
+ );
+ Ok(service_api::ApplicationResponse::Json(new_record))
+ } else {
+ let timestamp = common_utils::date_time::now_unix_timestamp();
+ match success_based_dynamic_routing_algo_ref.success_based_algorithm {
+ Some(algorithm_ref) => {
+ if let Some(algorithm_id) = algorithm_ref.algorithm_id {
+ let dynamic_routing_algorithm = routing_types::DynamicRoutingAlgorithmRef {
+ success_based_algorithm: Some(
+ routing_types::DynamicAlgorithmWithTimestamp {
+ algorithm_id: None,
+ timestamp,
+ },
+ ),
+ };
+
+ let record = db
+ .find_routing_algorithm_by_profile_id_algorithm_id(
+ business_profile.get_id(),
+ &algorithm_id,
+ )
+ .await
+ .to_not_found_response(errors::ApiErrorResponse::ResourceIdNotFound)?;
+ let response = record.foreign_into();
+ helpers::update_business_profile_active_dynamic_algorithm_ref(
+ db,
+ key_manager_state,
+ &key_store,
+ business_profile,
+ dynamic_routing_algorithm,
+ )
+ .await?;
+
+ metrics::ROUTING_UNLINK_CONFIG_SUCCESS_RESPONSE.add(
+ &metrics::CONTEXT,
+ 1,
+ &add_attributes([("profile_id", profile_id.get_string_repr().to_owned())]),
+ );
+
+ Ok(service_api::ApplicationResponse::Json(response))
+ } else {
+ Err(errors::ApiErrorResponse::PreconditionFailed {
+ message: "Algorithm is already inactive".to_string(),
+ })?
+ }
+ }
+ None => Err(errors::ApiErrorResponse::PreconditionFailed {
+ message: "Algorithm is already inactive".to_string(),
+ })?,
+ }
+ }
+}
+
+#[cfg(feature = "v1")]
+pub async fn success_based_routing_update_configs(
+ state: SessionState,
+ request: routing_types::SuccessBasedRoutingConfig,
+ algorithm_id: common_utils::id_type::RoutingId,
+ profile_id: common_utils::id_type::ProfileId,
+) -> RouterResponse<routing_types::RoutingDictionaryRecord> {
+ metrics::ROUTING_UPDATE_CONFIG_FOR_PROFILE.add(
+ &metrics::CONTEXT,
+ 1,
+ &add_attributes([("profile_id", profile_id.get_string_repr().to_owned())]),
+ );
+ let db = state.store.as_ref();
+ let dynamic_routing_algo_to_update = db
+ .find_routing_algorithm_by_profile_id_algorithm_id(&profile_id, &algorithm_id)
+ .await
+ .to_not_found_response(errors::ApiErrorResponse::ResourceIdNotFound)?;
+
+ let mut config_to_update: routing::SuccessBasedRoutingConfig = dynamic_routing_algo_to_update
+ .algorithm_data
+ .parse_value::<routing::SuccessBasedRoutingConfig>("SuccessBasedRoutingConfig")
+ .change_context(errors::ApiErrorResponse::InternalServerError)
+ .attach_printable("unable to deserialize algorithm data from routing table into SuccessBasedRoutingConfig")?;
+
+ config_to_update.update(request);
+
+ let algorithm_id = common_utils::generate_routing_id_of_default_length();
+ let timestamp = common_utils::date_time::now();
+ let algo = RoutingAlgorithm {
+ algorithm_id,
+ profile_id: dynamic_routing_algo_to_update.profile_id,
+ merchant_id: dynamic_routing_algo_to_update.merchant_id,
+ name: dynamic_routing_algo_to_update.name,
+ description: dynamic_routing_algo_to_update.description,
+ kind: dynamic_routing_algo_to_update.kind,
+ algorithm_data: serde_json::json!(config_to_update),
+ created_at: timestamp,
+ modified_at: timestamp,
+ algorithm_for: dynamic_routing_algo_to_update.algorithm_for,
+ };
+ let record = db
+ .insert_routing_algorithm(algo)
+ .await
+ .change_context(errors::ApiErrorResponse::InternalServerError)
+ .attach_printable("Unable to insert record in routing algorithm table")?;
+
+ let new_record = record.foreign_into();
+
+ metrics::ROUTING_UPDATE_CONFIG_FOR_PROFILE_SUCCESS_RESPONSE.add(
+ &metrics::CONTEXT,
+ 1,
+ &add_attributes([("profile_id", profile_id.get_string_repr().to_owned())]),
+ );
+ Ok(service_api::ApplicationResponse::Json(new_record))
+}
diff --git a/crates/router/src/core/routing/helpers.rs b/crates/router/src/core/routing/helpers.rs
index bd4107a48d0..f818dc05f5b 100644
--- a/crates/router/src/core/routing/helpers.rs
+++ b/crates/router/src/core/routing/helpers.rs
@@ -236,6 +236,33 @@ pub async fn update_business_profile_active_algorithm_ref(
Ok(())
}
+#[cfg(feature = "v1")]
+pub async fn update_business_profile_active_dynamic_algorithm_ref(
+ db: &dyn StorageInterface,
+ key_manager_state: &KeyManagerState,
+ merchant_key_store: &domain::MerchantKeyStore,
+ current_business_profile: domain::BusinessProfile,
+ dynamic_routing_algorithm: routing_types::DynamicRoutingAlgorithmRef,
+) -> RouterResult<()> {
+ let ref_val = dynamic_routing_algorithm
+ .encode_to_value()
+ .change_context(errors::ApiErrorResponse::InternalServerError)
+ .attach_printable("Failed to convert dynamic routing ref to value")?;
+ let business_profile_update = domain::BusinessProfileUpdate::DynamicRoutingAlgorithmUpdate {
+ dynamic_routing_algorithm: Some(ref_val),
+ };
+ db.update_business_profile_by_profile_id(
+ key_manager_state,
+ merchant_key_store,
+ current_business_profile,
+ business_profile_update,
+ )
+ .await
+ .change_context(errors::ApiErrorResponse::InternalServerError)
+ .attach_printable("Failed to update dynamic routing algorithm ref in business profile")?;
+ Ok(())
+}
+
#[cfg(feature = "v2")]
#[derive(Clone, Debug)]
pub struct RoutingAlgorithmHelpers<'h> {
diff --git a/crates/router/src/core/routing/transformers.rs b/crates/router/src/core/routing/transformers.rs
index 6bffde12a9b..652422086b7 100644
--- a/crates/router/src/core/routing/transformers.rs
+++ b/crates/router/src/core/routing/transformers.rs
@@ -72,6 +72,7 @@ impl ForeignFrom<storage_enums::RoutingAlgorithmKind> for RoutingAlgorithmKind {
storage_enums::RoutingAlgorithmKind::Priority => Self::Priority,
storage_enums::RoutingAlgorithmKind::VolumeSplit => Self::VolumeSplit,
storage_enums::RoutingAlgorithmKind::Advanced => Self::Advanced,
+ storage_enums::RoutingAlgorithmKind::Dynamic => Self::Dynamic,
}
}
}
@@ -83,6 +84,7 @@ impl ForeignFrom<RoutingAlgorithmKind> for storage_enums::RoutingAlgorithmKind {
RoutingAlgorithmKind::Priority => Self::Priority,
RoutingAlgorithmKind::VolumeSplit => Self::VolumeSplit,
RoutingAlgorithmKind::Advanced => Self::Advanced,
+ RoutingAlgorithmKind::Dynamic => Self::Dynamic,
}
}
}
diff --git a/crates/router/src/routes/app.rs b/crates/router/src/routes/app.rs
index 210ded9c25d..0c6e6762854 100644
--- a/crates/router/src/routes/app.rs
+++ b/crates/router/src/routes/app.rs
@@ -1614,6 +1614,23 @@ impl BusinessProfile {
)
.service(
web::scope("/{profile_id}")
+ .service(
+ web::scope("/dynamic_routing").service(
+ web::scope("/success_based")
+ .service(
+ web::resource("/toggle").route(
+ web::post().to(routing::toggle_success_based_routing),
+ ),
+ )
+ .service(web::resource("/config/{algorithm_id}").route(
+ web::patch().to(|state, req, path, payload| {
+ routing::success_based_routing_update_configs(
+ state, req, path, payload,
+ )
+ }),
+ )),
+ ),
+ )
.service(
web::resource("")
.route(web::get().to(business_profile_retrieve))
diff --git a/crates/router/src/routes/lock_utils.rs b/crates/router/src/routes/lock_utils.rs
index 13148801aa9..9593e0344c9 100644
--- a/crates/router/src/routes/lock_utils.rs
+++ b/crates/router/src/routes/lock_utils.rs
@@ -65,6 +65,8 @@ impl From<Flow> for ApiIdentifier {
| Flow::RoutingDeleteConfig
| Flow::DecisionManagerDeleteConfig
| Flow::DecisionManagerRetrieveConfig
+ | Flow::ToggleDynamicRouting
+ | Flow::UpdateDynamicRoutingConfigs
| Flow::DecisionManagerUpsertConfig => Self::Routing,
Flow::RetrieveForexFlow => Self::Forex,
diff --git a/crates/router/src/routes/routing.rs b/crates/router/src/routes/routing.rs
index b1831068991..5870b5ba77d 100644
--- a/crates/router/src/routes/routing.rs
+++ b/crates/router/src/routes/routing.rs
@@ -977,3 +977,88 @@ pub async fn routing_update_default_config_for_profile(
))
.await
}
+
+#[cfg(all(feature = "olap", feature = "v1"))]
+#[instrument(skip_all)]
+pub async fn toggle_success_based_routing(
+ state: web::Data<AppState>,
+ req: HttpRequest,
+ query: web::Query<api_models::routing::ToggleSuccessBasedRoutingQuery>,
+ path: web::Path<routing_types::ToggleSuccessBasedRoutingPath>,
+) -> impl Responder {
+ let flow = Flow::ToggleDynamicRouting;
+ let wrapper = routing_types::ToggleSuccessBasedRoutingWrapper {
+ status: query.into_inner().status,
+ profile_id: path.into_inner().profile_id,
+ };
+ Box::pin(oss_api::server_wrap(
+ flow,
+ state,
+ &req,
+ wrapper.clone(),
+ |state,
+ auth: auth::AuthenticationData,
+ wrapper: routing_types::ToggleSuccessBasedRoutingWrapper,
+ _| {
+ routing::toggle_success_based_routing(
+ state,
+ auth.merchant_account,
+ auth.key_store,
+ wrapper.status,
+ wrapper.profile_id,
+ )
+ },
+ #[cfg(not(feature = "release"))]
+ auth::auth_type(
+ &auth::HeaderAuth(auth::ApiKeyAuth),
+ &auth::JWTAuthProfileFromRoute {
+ profile_id: wrapper.profile_id,
+ required_permission: Permission::RoutingWrite,
+ minimum_entity_level: EntityType::Merchant,
+ },
+ req.headers(),
+ ),
+ #[cfg(feature = "release")]
+ &auth::JWTAuthProfileFromRoute {
+ profile_id: wrapper.profile_id,
+ required_permission: Permission::RoutingWrite,
+ minimum_entity_level: EntityType::Merchant,
+ },
+ api_locking::LockAction::NotApplicable,
+ ))
+ .await
+}
+
+#[cfg(all(feature = "olap", feature = "v1"))]
+#[instrument(skip_all)]
+pub async fn success_based_routing_update_configs(
+ state: web::Data<AppState>,
+ req: HttpRequest,
+ path: web::Path<routing_types::SuccessBasedRoutingUpdateConfigQuery>,
+ json_payload: web::Json<routing_types::SuccessBasedRoutingConfig>,
+) -> impl Responder {
+ let flow = Flow::UpdateDynamicRoutingConfigs;
+ let routing_payload_wrapper = routing_types::SuccessBasedRoutingPayloadWrapper {
+ updated_config: json_payload.into_inner(),
+ algorithm_id: path.clone().algorithm_id,
+ profile_id: path.clone().profile_id,
+ };
+ Box::pin(oss_api::server_wrap(
+ flow,
+ state,
+ &req,
+ routing_payload_wrapper,
+ |state, _, wrapper: routing_types::SuccessBasedRoutingPayloadWrapper, _| async {
+ Box::pin(routing::success_based_routing_update_configs(
+ state,
+ wrapper.updated_config,
+ wrapper.algorithm_id,
+ wrapper.profile_id,
+ ))
+ .await
+ },
+ &auth::AdminApiAuth,
+ api_locking::LockAction::NotApplicable,
+ ))
+ .await
+}
diff --git a/crates/router/src/types/api/admin.rs b/crates/router/src/types/api/admin.rs
index 3d915f838ee..9d90ef530ae 100644
--- a/crates/router/src/types/api/admin.rs
+++ b/crates/router/src/types/api/admin.rs
@@ -347,6 +347,7 @@ pub async fn create_business_profile_from_merchant_account(
.map(Into::into),
tax_connector_id: request.tax_connector_id,
is_tax_connector_enabled: request.is_tax_connector_enabled,
+ dynamic_routing_algorithm: None,
},
))
}
diff --git a/crates/router_env/src/logger/types.rs b/crates/router_env/src/logger/types.rs
index 79ab704fbbe..329fe5e55fc 100644
--- a/crates/router_env/src/logger/types.rs
+++ b/crates/router_env/src/logger/types.rs
@@ -242,6 +242,10 @@ pub enum Flow {
RoutingUpdateDefaultConfig,
/// Routing delete config
RoutingDeleteConfig,
+ /// Toggle dynamic routing
+ ToggleDynamicRouting,
+ /// Update dynamic routing config
+ UpdateDynamicRoutingConfigs,
/// Add record to blocklist
AddToBlocklist,
/// Delete record from blocklist
diff --git a/migrations/2024-09-05-155712_add_new_variant_in_routing_algorithm_kind_type/down.sql b/migrations/2024-09-05-155712_add_new_variant_in_routing_algorithm_kind_type/down.sql
new file mode 100644
index 00000000000..9ca7ff5389e
--- /dev/null
+++ b/migrations/2024-09-05-155712_add_new_variant_in_routing_algorithm_kind_type/down.sql
@@ -0,0 +1,6 @@
+-- This file should undo anything in `up.sql`
+DELETE FROM pg_enum
+WHERE enumlabel = 'dynamic'
+AND enumtypid = (
+ SELECT oid FROM pg_type WHERE typname = 'RoutingAlgorithmKind'
+);
diff --git a/migrations/2024-09-05-155712_add_new_variant_in_routing_algorithm_kind_type/up.sql b/migrations/2024-09-05-155712_add_new_variant_in_routing_algorithm_kind_type/up.sql
new file mode 100644
index 00000000000..ebe6188c7db
--- /dev/null
+++ b/migrations/2024-09-05-155712_add_new_variant_in_routing_algorithm_kind_type/up.sql
@@ -0,0 +1,2 @@
+-- Your SQL goes here
+ALTER TYPE "RoutingAlgorithmKind" ADD VALUE 'dynamic';
diff --git a/migrations/2024-09-05-160455_add_new_col_is_dynamic_routing_algorithm_in_business_profile/down.sql b/migrations/2024-09-05-160455_add_new_col_is_dynamic_routing_algorithm_in_business_profile/down.sql
new file mode 100644
index 00000000000..61c22e45eae
--- /dev/null
+++ b/migrations/2024-09-05-160455_add_new_col_is_dynamic_routing_algorithm_in_business_profile/down.sql
@@ -0,0 +1,3 @@
+-- This file should undo anything in `up.sql`
+ALTER TABLE business_profile
+DROP COLUMN dynamic_routing_algorithm;
diff --git a/migrations/2024-09-05-160455_add_new_col_is_dynamic_routing_algorithm_in_business_profile/up.sql b/migrations/2024-09-05-160455_add_new_col_is_dynamic_routing_algorithm_in_business_profile/up.sql
new file mode 100644
index 00000000000..2482fc9f591
--- /dev/null
+++ b/migrations/2024-09-05-160455_add_new_col_is_dynamic_routing_algorithm_in_business_profile/up.sql
@@ -0,0 +1,3 @@
+-- Your SQL goes here
+ALTER TABLE business_profile
+ADD COLUMN dynamic_routing_algorithm JSON DEFAULT NULL;
|
2024-09-06T15:35:56Z
|
## Type of Change
<!-- Put an `x` in the boxes that apply -->
- [ ] Bugfix
- [x] New feature
- [ ] Enhancement
- [ ] Refactoring
- [ ] Dependency updates
- [ ] Documentation
- [ ] CI/CD
## Description
<!-- Describe your changes in detail -->
### Toggle Success based dynamic routing
This PR will toggle success based dynamic routing for a profile, and the flow looks something like this:
1. A default config will be created for the profile, which will look something like this.
```
api_models::routing::SuccessBasedRoutingConfig {
params: Some(vec![SuccessBasedRoutingConfigParams::PaymentMethod]),
config: Some(SuccessBasedRoutingConfigBody {
min_aggregates_size: Some(2),
default_success_rate: Some(100.0),
max_aggregates_size: Some(3),
current_block_threshold: Some(CurrentBlockThreshold {
duration_in_mins: Some(5),
max_total_count: Some(2),
}),
}),
};
```
2. `is_dynamic_routing_enabled` will be set to true in the business profile table and the routing algo id will be set.
The curls will be something like this:
1. Toggle(enable) Dynamic Routing.
```
curl --location --request POST 'http://localhost:8080/account/merchant_1726160910/business_profile/pro_7Oo0CzTQoOwE5HfwKf6v/dynamic_routing/success_based/toggle?status=true' \
--header 'api-key: xxxxxx'
```
### Update success based dynamic routing configs
This route will update the default configs for success based dynamic routing for a particular profile. Basically it will create a new routing rule and assign the id in business_profile.
The authentication is `admin_api_key`
```
curl --location --request PATCH 'http://localhost:8080/account/merchant_1726160910/business_profile/pro_7Oo0CzTQoOwE5HfwKf6v/dynamic_routing/success_based/config/routing_LYmOkYZuaVkL6ZEXaAjA' \
--header 'Content-Type: application/json' \
--header 'api-key: test_admin' \
--data '{
"params": [
"Currency"
],
"config": {
"min_aggregates_size": 1,
"current_block_threshold": {
"max_total_count": 22
}
}
}'
```
### Additional Changes
- [x] This PR modifies the API contract
- [x] This PR modifies the database schema
- [ ] This PR modifies application configuration/environment variables
<!--
Provide links to the files with corresponding changes.
Following are the paths where you can find config files:
1. `config`
4. `crates/router/src/configs`
5. `loadtest/config`
-->
## Motivation and Context
<!--
Why is this change required? What problem does it solve?
If it fixes an open issue, please link to the issue here.
If you don't have an issue, we'd recommend starting with one first so the PR
can focus on the implementation (unless it is an obvious bug or documentation fix
that will have little conversation).
-->
Baby steps for Dynamic Routing
## How did you test it?
1. Request:
```
curl --location --request POST 'http://localhost:8080/account/merchant_1726160910/business_profile/pro_7Oo0CzTQoOwE5HfwKf6v/dynamic_routing/success_based/toggle?status=false' \
--header 'api-key:xxxxx'
```
Response:
```
{
"id": "routing_sSePmUaucfVIcaSeZPK4",
"profile_id": "pro_ejL5TRsd1mjCulBMXFIR",
"name": "Dynamic routing algorithm",
"kind": "dynamic",
"description": "",
"created_at": 1725635764,
"modified_at": 1725635764,
"algorithm_for": "payment"
}
```
Things to check for:
-> Check the BusinessProfile table for the `profile_id` and then whether the `dynamic_routing_algorithm` is present with the routing algo id we got in the response.
-> Toggle off the above curl by sending the `status` flag as `false` and then check the `step 1.` field for dynamic routing id to only have `timestamp` and no `routing_algorithm_Id`.
2. Request:
```
curl --location --request PATCH 'http://localhost:8080/account/merchant_1726160910/business_profile/pro_7Oo0CzTQoOwE5HfwKf6v/dynamic_routing/success_based/config/routing_LYmOkYZuaVkL6ZEXaAjA' \
--header 'Content-Type: application/json' \
--header 'api-key: test_admin' \
--data '{
"params": [
"Currency"
],
"config": {
"min_aggregates_size": 1,
"current_block_threshold": {
"max_total_count": 22
}
}
}'
```
Response:
```
{
"id": "routing_LYmOkYZuaVkL6ZEXaAjA",
"profile_id": "pro_ejL5TRsd1mjCulBMXFIR",
"name": "Dynamic routing algorithm",
"kind": "dynamic",
"description": "",
"created_at": 1725635764,
"modified_at": 1725635764,
"algorithm_for": "payment"
}
```
Things to check for:
-> Check the `RoutingAlgorithm` table for the `routing_algo_id`. Have a look for the fields above which we are updating like
`"max_total_count": 22` should be present.
## Checklist
<!-- Put an `x` in the boxes that apply -->
- [x] I formatted the code `cargo +nightly fmt --all`
- [x] I addressed lints thrown by `cargo clippy`
- [x] I reviewed the submitted code
- [ ] I added unit tests for my changes where possible
|
246fdc84064367885596b33f5e0e66af78a97a3c
|
|
juspay/hyperswitch
|
juspay__hyperswitch-5762
|
Bug: refactor(users): Add V2 user_roles data support
In V2 user_roles data, merchant_id will be null for org level users.
Currently in the BE, we throw 500 if merchant_id is not found in user_role.
So, we should fix this case and get merchant_id from db using org_id if merchant_id is not present in the user_role.
|
diff --git a/crates/api_models/src/events/user.rs b/crates/api_models/src/events/user.rs
index 590179c052c..8d1ae60b325 100644
--- a/crates/api_models/src/events/user.rs
+++ b/crates/api_models/src/events/user.rs
@@ -16,11 +16,11 @@ use crate::user::{
GetSsoAuthUrlRequest, GetUserAuthenticationMethodsRequest, GetUserDetailsResponse,
GetUserRoleDetailsRequest, GetUserRoleDetailsResponse, InviteUserRequest, ListUsersResponse,
ReInviteUserRequest, RecoveryCodes, ResetPasswordRequest, RotatePasswordRequest,
- SendVerifyEmailRequest, SignInResponse, SignUpRequest, SignUpWithMerchantIdRequest,
- SsoSignInRequest, SwitchMerchantRequest, SwitchOrganizationRequest, SwitchProfileRequest,
- TokenOrPayloadResponse, TokenResponse, TwoFactorAuthStatusResponse,
- UpdateUserAccountDetailsRequest, UpdateUserAuthenticationMethodRequest, UserFromEmailRequest,
- UserMerchantCreate, VerifyEmailRequest, VerifyRecoveryCodeRequest, VerifyTotpRequest,
+ SendVerifyEmailRequest, SignUpRequest, SignUpWithMerchantIdRequest, SsoSignInRequest,
+ SwitchMerchantRequest, SwitchOrganizationRequest, SwitchProfileRequest, TokenResponse,
+ TwoFactorAuthStatusResponse, UpdateUserAccountDetailsRequest,
+ UpdateUserAuthenticationMethodRequest, UserFromEmailRequest, UserMerchantCreate,
+ VerifyEmailRequest, VerifyRecoveryCodeRequest, VerifyTotpRequest,
};
impl ApiEventMetric for DashboardEntryResponse {
@@ -40,12 +40,6 @@ impl ApiEventMetric for VerifyTokenResponse {
}
}
-impl<T> ApiEventMetric for TokenOrPayloadResponse<T> {
- fn get_api_event_type(&self) -> Option<ApiEventsType> {
- Some(ApiEventsType::Miscellaneous)
- }
-}
-
common_utils::impl_api_event_type!(
Miscellaneous,
(
@@ -72,7 +66,6 @@ common_utils::impl_api_event_type!(
VerifyEmailRequest,
SendVerifyEmailRequest,
AcceptInviteFromEmailRequest,
- SignInResponse,
UpdateUserAccountDetailsRequest,
GetUserDetailsResponse,
GetUserRoleDetailsRequest,
diff --git a/crates/api_models/src/events/user_role.rs b/crates/api_models/src/events/user_role.rs
index 5b5da0ec50a..f88c318477a 100644
--- a/crates/api_models/src/events/user_role.rs
+++ b/crates/api_models/src/events/user_role.rs
@@ -2,9 +2,8 @@ use common_utils::events::{ApiEventMetric, ApiEventsType};
use crate::user_role::{
role::{
- CreateRoleRequest, GetRoleFromTokenResponse, GetRoleRequest, ListRolesResponse,
- RoleInfoResponse, RoleInfoWithGroupsResponse, RoleInfoWithPermissionsResponse,
- UpdateRoleRequest,
+ CreateRoleRequest, GetRoleRequest, ListRolesResponse, RoleInfoWithGroupsResponse,
+ RoleInfoWithPermissionsResponse, UpdateRoleRequest,
},
AcceptInvitationRequest, AuthorizationInfoResponse, DeleteUserRoleRequest,
MerchantSelectRequest, UpdateUserRoleRequest,
@@ -23,8 +22,6 @@ common_utils::impl_api_event_type!(
CreateRoleRequest,
UpdateRoleRequest,
ListRolesResponse,
- RoleInfoResponse,
- GetRoleFromTokenResponse,
RoleInfoWithGroupsResponse
)
);
diff --git a/crates/api_models/src/user.rs b/crates/api_models/src/user.rs
index 97d0c63fdf1..abc09c8bbee 100644
--- a/crates/api_models/src/user.rs
+++ b/crates/api_models/src/user.rs
@@ -23,8 +23,6 @@ pub struct SignUpRequest {
pub password: Secret<String>,
}
-pub type SignUpResponse = DashboardEntryResponse;
-
#[derive(serde::Serialize, Debug, Clone)]
pub struct DashboardEntryResponse {
pub token: Secret<String>,
@@ -40,22 +38,6 @@ pub struct DashboardEntryResponse {
pub type SignInRequest = SignUpRequest;
-#[derive(Debug, serde::Serialize)]
-#[serde(tag = "flow_type", rename_all = "snake_case")]
-pub enum SignInResponse {
- MerchantSelect(MerchantSelectResponse),
- DashboardEntry(DashboardEntryResponse),
-}
-
-#[derive(Debug, serde::Serialize)]
-pub struct MerchantSelectResponse {
- pub token: Secret<String>,
- pub name: Secret<String>,
- pub email: pii::Email,
- pub verification_days_left: Option<i64>,
- pub merchants: Vec<UserMerchantAccount>,
-}
-
#[derive(serde::Deserialize, Debug, Clone, serde::Serialize)]
pub struct ConnectAccountRequest {
pub email: pii::Email,
@@ -202,8 +184,6 @@ pub struct VerifyEmailRequest {
pub token: Secret<String>,
}
-pub type VerifyEmailResponse = SignInResponse;
-
#[derive(serde::Deserialize, Debug, serde::Serialize)]
pub struct SendVerifyEmailRequest {
pub email: pii::Email,
@@ -232,11 +212,6 @@ pub struct UpdateUserAccountDetailsRequest {
pub preferred_merchant_id: Option<id_type::MerchantId>,
}
-#[derive(Debug, serde::Deserialize, serde::Serialize)]
-pub struct TokenOnlyQueryParam {
- pub token_only: Option<bool>,
-}
-
#[derive(Debug, serde::Deserialize, serde::Serialize)]
pub struct SkipTwoFactorAuthQueryParam {
pub skip_two_factor_auth: Option<bool>,
@@ -254,12 +229,6 @@ pub struct TwoFactorAuthStatusResponse {
pub recovery_code: bool,
}
-#[derive(Debug, serde::Serialize)]
-#[serde(untagged)]
-pub enum TokenOrPayloadResponse<T> {
- Token(TokenResponse),
- Payload(T),
-}
#[derive(Debug, serde::Deserialize, serde::Serialize)]
pub struct UserFromEmailRequest {
pub token: Secret<String>,
diff --git a/crates/api_models/src/user_role.rs b/crates/api_models/src/user_role.rs
index c9f222cb7be..ed6911016b1 100644
--- a/crates/api_models/src/user_role.rs
+++ b/crates/api_models/src/user_role.rs
@@ -121,9 +121,8 @@ pub enum UserStatus {
#[derive(Debug, serde::Deserialize, serde::Serialize)]
pub struct MerchantSelectRequest {
pub merchant_ids: Vec<common_utils::id_type::MerchantId>,
- // TODO: Remove this once the token only api is being used
- pub need_dashboard_entry_response: Option<bool>,
}
+
#[derive(Debug, serde::Deserialize, serde::Serialize)]
pub struct AcceptInvitationRequest {
pub merchant_ids: Vec<common_utils::id_type::MerchantId>,
diff --git a/crates/api_models/src/user_role/role.rs b/crates/api_models/src/user_role/role.rs
index 73b25c84af5..acbad9152ae 100644
--- a/crates/api_models/src/user_role/role.rs
+++ b/crates/api_models/src/user_role/role.rs
@@ -1,4 +1,5 @@
-use common_enums::{EntityType, PermissionGroup, RoleScope};
+pub use common_enums::PermissionGroup;
+use common_enums::{EntityType, RoleScope};
use super::Permission;
@@ -17,26 +18,7 @@ pub struct UpdateRoleRequest {
}
#[derive(Debug, serde::Serialize)]
-pub struct ListRolesResponse(pub Vec<RoleInfoResponse>);
-
-#[derive(Debug, serde::Deserialize)]
-pub struct GetGroupsQueryParam {
- pub groups: Option<bool>,
-}
-
-#[derive(Debug, serde::Serialize)]
-#[serde(untagged)]
-pub enum GetRoleFromTokenResponse {
- Permissions(Vec<Permission>),
- Groups(Vec<PermissionGroup>),
-}
-
-#[derive(Debug, serde::Serialize)]
-#[serde(untagged)]
-pub enum RoleInfoResponse {
- Permissions(RoleInfoWithPermissionsResponse),
- Groups(RoleInfoWithGroupsResponse),
-}
+pub struct ListRolesResponse(pub Vec<RoleInfoWithGroupsResponse>);
#[derive(Debug, serde::Serialize)]
pub struct RoleInfoWithPermissionsResponse {
diff --git a/crates/router/src/core/user.rs b/crates/router/src/core/user.rs
index ace8c3babc6..93a557d5688 100644
--- a/crates/router/src/core/user.rs
+++ b/crates/router/src/core/user.rs
@@ -121,42 +121,10 @@ pub async fn get_user_details(
))
}
-pub async fn signup(
- state: SessionState,
- request: user_api::SignUpRequest,
-) -> UserResponse<user_api::TokenOrPayloadResponse<user_api::SignUpResponse>> {
- let new_user = domain::NewUser::try_from(request)?;
- new_user
- .get_new_merchant()
- .get_new_organization()
- .insert_org_in_db(state.clone())
- .await?;
- let user_from_db = new_user
- .insert_user_and_merchant_in_db(state.clone())
- .await?;
- let user_role = new_user
- .insert_org_level_user_role_in_db(
- state.clone(),
- common_utils::consts::ROLE_ID_ORGANIZATION_ADMIN.to_string(),
- UserStatus::Active,
- None,
- )
- .await?;
- utils::user_role::set_role_permissions_in_cache_by_user_role(&state, &user_role).await;
-
- let token =
- utils::user::generate_jwt_auth_token_without_profile(&state, &user_from_db, &user_role)
- .await?;
- let response =
- utils::user::get_dashboard_entry_response(&state, user_from_db, user_role, token.clone())?;
-
- auth::cookies::set_cookie_response(user_api::TokenOrPayloadResponse::Payload(response), token)
-}
-
pub async fn signup_token_only_flow(
state: SessionState,
request: user_api::SignUpRequest,
-) -> UserResponse<user_api::TokenOrPayloadResponse<user_api::SignUpResponse>> {
+) -> UserResponse<user_api::TokenResponse> {
let new_user = domain::NewUser::try_from(request)?;
new_user
.get_new_merchant()
@@ -182,61 +150,17 @@ pub async fn signup_token_only_flow(
.get_token_with_user_role(&state, &user_role)
.await?;
- let response = user_api::TokenOrPayloadResponse::Token(user_api::TokenResponse {
+ let response = user_api::TokenResponse {
token: token.clone(),
token_type: next_flow.get_flow().into(),
- });
+ };
auth::cookies::set_cookie_response(response, token)
}
-pub async fn signin(
- state: SessionState,
- request: user_api::SignInRequest,
-) -> UserResponse<user_api::TokenOrPayloadResponse<user_api::SignInResponse>> {
- let user_from_db: domain::UserFromStorage = state
- .global_store
- .find_user_by_email(&request.email)
- .await
- .map_err(|e| {
- if e.current_context().is_db_not_found() {
- e.change_context(UserErrors::InvalidCredentials)
- } else {
- e.change_context(UserErrors::InternalServerError)
- }
- })?
- .into();
-
- user_from_db.compare_password(&request.password)?;
-
- let signin_strategy =
- if let Some(preferred_merchant_id) = user_from_db.get_preferred_merchant_id() {
- let preferred_role = user_from_db
- .get_role_from_db_by_merchant_id(&state, &preferred_merchant_id)
- .await
- .to_not_found_response(UserErrors::InternalServerError)
- .attach_printable("User role with preferred_merchant_id not found")?;
- domain::SignInWithRoleStrategyType::SingleRole(domain::SignInWithSingleRoleStrategy {
- user: user_from_db,
- user_role: Box::new(preferred_role),
- })
- } else {
- let user_roles = user_from_db.get_roles_from_db(&state).await?;
- domain::SignInWithRoleStrategyType::decide_signin_strategy_by_user_roles(
- user_from_db,
- user_roles,
- )
- .await?
- };
-
- let response = signin_strategy.get_signin_response(&state).await?;
- let token = utils::user::get_token_from_signin_response(&response);
- auth::cookies::set_cookie_response(user_api::TokenOrPayloadResponse::Payload(response), token)
-}
-
pub async fn signin_token_only_flow(
state: SessionState,
request: user_api::SignInRequest,
-) -> UserResponse<user_api::TokenOrPayloadResponse<user_api::SignInResponse>> {
+) -> UserResponse<user_api::TokenResponse> {
let user_from_db: domain::UserFromStorage = state
.global_store
.find_user_by_email(&request.email)
@@ -251,10 +175,10 @@ pub async fn signin_token_only_flow(
let token = next_flow.get_token(&state).await?;
- let response = user_api::TokenOrPayloadResponse::Token(user_api::TokenResponse {
+ let response = user_api::TokenResponse {
token: token.clone(),
token_type: next_flow.get_flow().into(),
- });
+ };
auth::cookies::set_cookie_response(response, token)
}
@@ -573,105 +497,11 @@ pub async fn reset_password_token_only_flow(
auth::cookies::remove_cookie_response()
}
-#[cfg(feature = "email")]
-pub async fn reset_password(
- state: SessionState,
- request: user_api::ResetPasswordRequest,
-) -> UserResponse<()> {
- let token = request.token.expose();
- let email_token = auth::decode_jwt::<email_types::EmailToken>(&token, &state)
- .await
- .change_context(UserErrors::LinkInvalid)?;
-
- auth::blacklist::check_email_token_in_blacklist(&state, &token).await?;
-
- let password = domain::UserPassword::new(request.password)?;
- let hash_password = utils::user::password::generate_password_hash(password.get_secret())?;
-
- let user = state
- .global_store
- .update_user_by_email(
- &email_token
- .get_email()
- .change_context(UserErrors::InternalServerError)?,
- storage_user::UserUpdate::PasswordUpdate {
- password: hash_password,
- },
- )
- .await
- .change_context(UserErrors::InternalServerError)?;
-
- if let Some(inviter_merchant_id) = email_token.get_merchant_id() {
- let key_manager_state = &(&state).into();
-
- let key_store = state
- .store
- .get_merchant_key_store_by_merchant_id(
- key_manager_state,
- inviter_merchant_id,
- &state.store.get_master_key().to_vec().into(),
- )
- .await
- .change_context(UserErrors::InternalServerError)
- .attach_printable("merchant_key_store not found")?;
-
- let merchant_account = state
- .store
- .find_merchant_account_by_merchant_id(
- key_manager_state,
- inviter_merchant_id,
- &key_store,
- )
- .await
- .change_context(UserErrors::InternalServerError)
- .attach_printable("merchant_account not found")?;
-
- let (update_v1_result, update_v2_result) =
- utils::user_role::update_v1_and_v2_user_roles_in_db(
- &state,
- user.user_id.clone().as_str(),
- &merchant_account.organization_id,
- inviter_merchant_id,
- None,
- UserRoleUpdate::UpdateStatus {
- status: UserStatus::Active,
- modified_by: user.user_id.clone(),
- },
- )
- .await;
-
- if update_v1_result
- .as_ref()
- .is_err_and(|err| !err.current_context().is_db_not_found())
- || update_v2_result
- .as_ref()
- .is_err_and(|err| !err.current_context().is_db_not_found())
- {
- return Err(report!(UserErrors::InternalServerError));
- }
-
- if update_v1_result.is_err() && update_v2_result.is_err() {
- return Err(report!(UserErrors::InvalidRoleOperation))
- .attach_printable("User not found in the organization")?;
- }
- }
-
- let _ = auth::blacklist::insert_email_token_in_blacklist(&state, &token)
- .await
- .map_err(|error| logger::error!(?error));
- let _ = auth::blacklist::insert_user_in_blacklist(&state, &user.user_id)
- .await
- .map_err(|error| logger::error!(?error));
-
- auth::cookies::remove_cookie_response()
-}
-
pub async fn invite_multiple_user(
state: SessionState,
user_from_token: auth::UserFromToken,
requests: Vec<user_api::InviteUserRequest>,
req_state: ReqState,
- is_token_only: Option<bool>,
auth_id: Option<String>,
) -> UserResponse<Vec<InviteMultipleUserResponse>> {
if requests.len() > 10 {
@@ -680,16 +510,7 @@ pub async fn invite_multiple_user(
}
let responses = futures::future::join_all(requests.iter().map(|request| async {
- match handle_invitation(
- &state,
- &user_from_token,
- request,
- &req_state,
- is_token_only,
- &auth_id,
- )
- .await
- {
+ match handle_invitation(&state, &user_from_token, request, &req_state, &auth_id).await {
Ok(response) => response,
Err(error) => InviteMultipleUserResponse {
email: request.email.clone(),
@@ -709,7 +530,6 @@ async fn handle_invitation(
user_from_token: &auth::UserFromToken,
request: &user_api::InviteUserRequest,
req_state: &ReqState,
- is_token_only: Option<bool>,
auth_id: &Option<String>,
) -> UserResult<InviteMultipleUserResponse> {
let inviter_user = user_from_token.get_user_from_db(state).await?;
@@ -756,15 +576,8 @@ async fn handle_invitation(
.err()
.unwrap_or(false)
{
- handle_new_user_invitation(
- state,
- user_from_token,
- request,
- req_state.clone(),
- is_token_only,
- auth_id,
- )
- .await
+ handle_new_user_invitation(state, user_from_token, request, req_state.clone(), auth_id)
+ .await
} else {
Err(UserErrors::InternalServerError.into())
}
@@ -877,7 +690,6 @@ async fn handle_new_user_invitation(
user_from_token: &auth::UserFromToken,
request: &user_api::InviteUserRequest,
req_state: ReqState,
- is_token_only: Option<bool>,
auth_id: &Option<String>,
) -> UserResult<InviteMultipleUserResponse> {
let new_user = domain::NewUser::try_from((request.clone(), user_from_token.clone()))?;
@@ -912,8 +724,6 @@ async fn handle_new_user_invitation(
.await?;
let is_email_sent;
- // TODO: Adding this to avoid clippy lints, remove this once the token only flow is being used
- let _ = is_token_only;
#[cfg(feature = "email")]
{
@@ -921,8 +731,7 @@ async fn handle_new_user_invitation(
// Will be adding actual usage for this variable later
let _ = req_state.clone();
let invitee_email = domain::UserEmail::from_pii_email(request.email.clone())?;
- let email_contents: Box<dyn EmailData + Send + 'static> = if let Some(true) = is_token_only
- {
+ let email_contents: Box<dyn EmailData + Send + 'static> =
Box::new(email_types::InviteRegisteredUser {
recipient_email: invitee_email,
user_name: domain::UserName::new(new_user.get_name())?,
@@ -930,17 +739,7 @@ async fn handle_new_user_invitation(
subject: "You have been invited to join Hyperswitch Community!",
merchant_id: user_from_token.merchant_id.clone(),
auth_id: auth_id.clone(),
- })
- } else {
- Box::new(email_types::InviteUser {
- recipient_email: invitee_email,
- user_name: domain::UserName::new(new_user.get_name())?,
- settings: state.conf.clone(),
- subject: "You have been invited to join Hyperswitch Community!",
- merchant_id: user_from_token.merchant_id.clone(),
- auth_id: auth_id.clone(),
- })
- };
+ });
let send_email_result = state
.email_client
.compose_and_send_email(email_contents, state.conf.proxy.https_url.as_ref())
@@ -1047,115 +846,12 @@ pub async fn resend_invite(
Ok(ApplicationResponse::StatusOk)
}
-#[cfg(feature = "email")]
-pub async fn accept_invite_from_email(
- state: SessionState,
- request: user_api::AcceptInviteFromEmailRequest,
-) -> UserResponse<user_api::DashboardEntryResponse> {
- let token = request.token.expose();
-
- let email_token = auth::decode_jwt::<email_types::EmailToken>(&token, &state)
- .await
- .change_context(UserErrors::LinkInvalid)?;
-
- auth::blacklist::check_email_token_in_blacklist(&state, &token).await?;
-
- let user: domain::UserFromStorage = state
- .global_store
- .find_user_by_email(
- &email_token
- .get_email()
- .change_context(UserErrors::InternalServerError)?,
- )
- .await
- .change_context(UserErrors::InternalServerError)?
- .into();
-
- let merchant_id = email_token
- .get_merchant_id()
- .ok_or(UserErrors::InternalServerError)?;
-
- let key_manager_state = &(&state).into();
-
- let key_store = state
- .store
- .get_merchant_key_store_by_merchant_id(
- key_manager_state,
- merchant_id,
- &state.store.get_master_key().to_vec().into(),
- )
- .await
- .change_context(UserErrors::InternalServerError)
- .attach_printable("merchant_key_store not found")?;
-
- let merchant_account = state
- .store
- .find_merchant_account_by_merchant_id(key_manager_state, merchant_id, &key_store)
- .await
- .change_context(UserErrors::InternalServerError)
- .attach_printable("merchant_account not found")?;
-
- let (update_v1_result, update_v2_result) = utils::user_role::update_v1_and_v2_user_roles_in_db(
- &state,
- user.get_user_id(),
- &merchant_account.organization_id,
- merchant_id,
- None,
- UserRoleUpdate::UpdateStatus {
- status: UserStatus::Active,
- modified_by: user.get_user_id().to_string(),
- },
- )
- .await;
-
- if update_v1_result
- .as_ref()
- .is_err_and(|err| !err.current_context().is_db_not_found())
- || update_v2_result
- .as_ref()
- .is_err_and(|err| !err.current_context().is_db_not_found())
- {
- return Err(report!(UserErrors::InternalServerError));
- }
-
- if update_v1_result.is_err() && update_v2_result.is_err() {
- return Err(report!(UserErrors::InvalidRoleOperation))
- .attach_printable("User not found in the organization")?;
- }
-
- let _ = auth::blacklist::insert_email_token_in_blacklist(&state, &token)
- .await
- .map_err(|error| logger::error!(?error));
-
- let user_from_db: domain::UserFromStorage = state
- .global_store
- .update_user_by_user_id(user.get_user_id(), storage_user::UserUpdate::VerifyUser)
- .await
- .change_context(UserErrors::InternalServerError)?
- .into();
-
- let user_role = user_from_db
- .get_preferred_or_active_user_role_from_db(&state)
- .await
- .change_context(UserErrors::InternalServerError)?;
-
- let token =
- utils::user::generate_jwt_auth_token_without_profile(&state, &user_from_db, &user_role)
- .await?;
- utils::user_role::set_role_permissions_in_cache_by_user_role(&state, &user_role).await;
-
- let response =
- utils::user::get_dashboard_entry_response(&state, user_from_db, user_role, token.clone())?;
-
- auth::cookies::set_cookie_response(response, token)
-}
-
#[cfg(feature = "email")]
pub async fn accept_invite_from_email_token_only_flow(
state: SessionState,
user_token: auth::UserFromSinglePurposeToken,
request: user_api::AcceptInviteFromEmailRequest,
-) -> UserResponse<user_api::TokenOrPayloadResponse<user_api::DashboardEntryResponse>> {
+) -> UserResponse<user_api::TokenResponse> {
let token = request.token.expose();
let email_token = auth::decode_jwt::<email_types::EmailToken>(&token, &state)
@@ -1261,10 +957,10 @@ pub async fn accept_invite_from_email_token_only_flow(
.get_token_with_user_role(&state, &user_role)
.await?;
- let response = user_api::TokenOrPayloadResponse::Token(user_api::TokenResponse {
+ let response = user_api::TokenResponse {
token: token.clone(),
token_type: next_flow.get_flow().into(),
- });
+ };
auth::cookies::set_cookie_response(response, token)
}
@@ -1503,7 +1199,7 @@ pub async fn list_merchants_for_user(
.await
.change_context(UserErrors::InternalServerError)?;
- let merchant_accounts = state
+ let merchant_accounts_map = state
.store
.list_multiple_merchant_accounts(
&(&state).into(),
@@ -1517,17 +1213,62 @@ pub async fn list_merchants_for_user(
.collect::<Result<Vec<_>, _>>()?,
)
.await
- .change_context(UserErrors::InternalServerError)?;
+ .change_context(UserErrors::InternalServerError)?
+ .into_iter()
+ .map(|merchant_account| (merchant_account.get_id().clone(), merchant_account))
+ .collect::<HashMap<_, _>>();
- let roles =
- utils::user_role::get_multiple_role_info_for_user_roles(&state, &user_roles).await?;
+ let roles_map = futures::future::try_join_all(user_roles.iter().map(|user_role| async {
+ let Some(merchant_id) = &user_role.merchant_id else {
+ return Err(report!(UserErrors::InternalServerError))
+ .attach_printable("merchant_id not found for user_role");
+ };
+ let Some(org_id) = &user_role.org_id else {
+ return Err(report!(UserErrors::InternalServerError)
+ .attach_printable("org_id not found in user_role"));
+ };
+ roles::RoleInfo::from_role_id(&state, &user_role.role_id, merchant_id, org_id)
+ .await
+ .change_context(UserErrors::InternalServerError)
+ .attach_printable("Unable to find role info for user role")
+ }))
+ .await?
+ .into_iter()
+ .map(|role_info| (role_info.get_role_id().to_owned(), role_info))
+ .collect::<HashMap<_, _>>();
Ok(ApplicationResponse::Json(
- utils::user::get_multiple_merchant_details_with_status(
- user_roles,
- merchant_accounts,
- roles,
- )?,
+ user_roles
+ .into_iter()
+ .map(|user_role| {
+ let Some(merchant_id) = &user_role.merchant_id else {
+ return Err(report!(UserErrors::InternalServerError))
+ .attach_printable("merchant_id not found for user_role");
+ };
+ let Some(org_id) = &user_role.org_id else {
+ return Err(report!(UserErrors::InternalServerError)
+ .attach_printable("org_id not found in user_role"));
+ };
+ let merchant_account = merchant_accounts_map
+ .get(merchant_id)
+ .ok_or(UserErrors::InternalServerError)
+ .attach_printable("Merchant account for user role doesn't exist")?;
+
+ let role_info = roles_map
+ .get(&user_role.role_id)
+ .ok_or(UserErrors::InternalServerError)
+ .attach_printable("Role info for user role doesn't exist")?;
+
+ Ok(user_api::UserMerchantAccount {
+ merchant_id: merchant_id.to_owned(),
+ merchant_name: merchant_account.merchant_name.clone(),
+ is_active: user_role.status == UserStatus::Active,
+ role_id: user_role.role_id,
+ role_name: role_info.get_role_name().to_string(),
+ org_id: org_id.to_owned(),
+ })
+ })
+ .collect::<Result<Vec<_>, _>>()?,
))
}
@@ -1650,71 +1391,12 @@ pub async fn list_users_for_merchant_account(
)))
}
-#[cfg(feature = "email")]
-pub async fn verify_email(
- state: SessionState,
- req: user_api::VerifyEmailRequest,
-) -> UserResponse<user_api::SignInResponse> {
- let token = req.token.clone().expose();
- let email_token = auth::decode_jwt::<email_types::EmailToken>(&token, &state)
- .await
- .change_context(UserErrors::LinkInvalid)?;
-
- auth::blacklist::check_email_token_in_blacklist(&state, &token).await?;
-
- let user = state
- .global_store
- .find_user_by_email(
- &email_token
- .get_email()
- .change_context(UserErrors::InternalServerError)?,
- )
- .await
- .change_context(UserErrors::InternalServerError)?;
-
- let user = state
- .global_store
- .update_user_by_user_id(user.user_id.as_str(), storage_user::UserUpdate::VerifyUser)
- .await
- .change_context(UserErrors::InternalServerError)?;
-
- let user_from_db: domain::UserFromStorage = user.into();
-
- let signin_strategy =
- if let Some(preferred_merchant_id) = user_from_db.get_preferred_merchant_id() {
- let preferred_role = user_from_db
- .get_role_from_db_by_merchant_id(&state, &preferred_merchant_id)
- .await
- .change_context(UserErrors::InternalServerError)
- .attach_printable("User role with preferred_merchant_id not found")?;
- domain::SignInWithRoleStrategyType::SingleRole(domain::SignInWithSingleRoleStrategy {
- user: user_from_db,
- user_role: Box::new(preferred_role),
- })
- } else {
- let user_roles = user_from_db.get_roles_from_db(&state).await?;
- domain::SignInWithRoleStrategyType::decide_signin_strategy_by_user_roles(
- user_from_db,
- user_roles,
- )
- .await?
- };
-
- let _ = auth::blacklist::insert_email_token_in_blacklist(&state, &token)
- .await
- .map_err(|error| logger::error!(?error));
-
- let response = signin_strategy.get_signin_response(&state).await?;
- let token = utils::user::get_token_from_signin_response(&response);
- auth::cookies::set_cookie_response(response, token)
-}
-
#[cfg(feature = "email")]
pub async fn verify_email_token_only_flow(
state: SessionState,
user_token: auth::UserFromSinglePurposeToken,
req: user_api::VerifyEmailRequest,
-) -> UserResponse<user_api::TokenOrPayloadResponse<user_api::SignInResponse>> {
+) -> UserResponse<user_api::TokenResponse> {
let token = req.token.clone().expose();
let email_token = auth::decode_jwt::<email_types::EmailToken>(&token, &state)
.await
@@ -1754,10 +1436,10 @@ pub async fn verify_email_token_only_flow(
let next_flow = current_flow.next(user_from_db, &state).await?;
let token = next_flow.get_token(&state).await?;
- let response = user_api::TokenOrPayloadResponse::Token(user_api::TokenResponse {
+ let response = user_api::TokenResponse {
token: token.clone(),
token_type: next_flow.get_flow().into(),
- });
+ };
auth::cookies::set_cookie_response(response, token)
}
@@ -2839,24 +2521,7 @@ pub async fn switch_org_for_user(
))?
.to_owned();
- let merchant_id = if let Some(merchant_id) = &user_role.merchant_id {
- merchant_id.clone()
- } else {
- state
- .store
- .list_merchant_accounts_by_organization_id(
- key_manager_state,
- request.org_id.get_string_repr(),
- )
- .await
- .change_context(UserErrors::InternalServerError)
- .attach_printable("Failed to list merchant accounts by organization_id")?
- .first()
- .ok_or(UserErrors::InternalServerError)
- .attach_printable("No merchant account found for the given organization_id")?
- .get_id()
- .clone()
- };
+ let merchant_id = utils::user_role::get_single_merchant_id(&state, &user_role).await?;
let profile_id = if let Some(profile_id) = &user_role.profile_id {
profile_id.clone()
diff --git a/crates/router/src/core/user_role.rs b/crates/router/src/core/user_role.rs
index 971b34b0667..4204e91678d 100644
--- a/crates/router/src/core/user_role.rs
+++ b/crates/router/src/core/user_role.rs
@@ -24,20 +24,6 @@ pub mod role;
use common_enums::{EntityType, PermissionGroup};
use strum::IntoEnumIterator;
-// TODO: To be deprecated once groups are stable
-pub async fn get_authorization_info_with_modules(
- _state: SessionState,
-) -> UserResponse<user_role_api::AuthorizationInfoResponse> {
- Ok(ApplicationResponse::Json(
- user_role_api::AuthorizationInfoResponse(
- info::get_module_authorization_info()
- .into_iter()
- .map(|module_info| user_role_api::AuthorizationInfo::Module(module_info.into()))
- .collect(),
- ),
- ))
-}
-
pub async fn get_authorization_info_with_groups(
_state: SessionState,
) -> UserResponse<user_role_api::AuthorizationInfoResponse> {
@@ -50,6 +36,7 @@ pub async fn get_authorization_info_with_groups(
),
))
}
+
pub async fn get_authorization_info_with_group_tag(
) -> UserResponse<user_role_api::AuthorizationInfoResponse> {
static GROUPS_WITH_PARENT_TAGS: Lazy<Vec<user_role_api::ParentInfo>> = Lazy::new(|| {
@@ -309,85 +296,11 @@ pub async fn accept_invitation(
Ok(ApplicationResponse::StatusOk)
}
-pub async fn merchant_select(
- state: SessionState,
- user_token: auth::UserFromSinglePurposeToken,
- req: user_role_api::MerchantSelectRequest,
-) -> UserResponse<user_api::TokenOrPayloadResponse<user_api::DashboardEntryResponse>> {
- let merchant_accounts = state
- .store
- .list_multiple_merchant_accounts(&(&state).into(), req.merchant_ids)
- .await
- .change_context(UserErrors::InternalServerError)?;
-
- let update_result =
- futures::future::join_all(merchant_accounts.iter().map(|merchant_account| async {
- let (update_v1_result, update_v2_result) =
- utils::user_role::update_v1_and_v2_user_roles_in_db(
- &state,
- user_token.user_id.as_str(),
- &merchant_account.organization_id,
- merchant_account.get_id(),
- None,
- UserRoleUpdate::UpdateStatus {
- status: UserStatus::Active,
- modified_by: user_token.user_id.clone(),
- },
- )
- .await;
-
- if update_v1_result.is_err_and(|err| !err.current_context().is_db_not_found())
- || update_v2_result.is_err_and(|err| !err.current_context().is_db_not_found())
- {
- Err(report!(UserErrors::InternalServerError))
- } else {
- Ok(())
- }
- }))
- .await;
-
- if update_result.iter().all(Result::is_err) {
- return Err(UserErrors::MerchantIdNotFound.into());
- }
-
- if let Some(true) = req.need_dashboard_entry_response {
- let user_from_db: domain::UserFromStorage = state
- .global_store
- .find_user_by_id(user_token.user_id.as_str())
- .await
- .change_context(UserErrors::InternalServerError)?
- .into();
-
- let user_role = user_from_db
- .get_preferred_or_active_user_role_from_db(&state)
- .await
- .change_context(UserErrors::InternalServerError)?;
-
- utils::user_role::set_role_permissions_in_cache_by_user_role(&state, &user_role).await;
-
- let token =
- utils::user::generate_jwt_auth_token_without_profile(&state, &user_from_db, &user_role)
- .await?;
- let response = utils::user::get_dashboard_entry_response(
- &state,
- user_from_db,
- user_role,
- token.clone(),
- )?;
- return auth::cookies::set_cookie_response(
- user_api::TokenOrPayloadResponse::Payload(response),
- token,
- );
- }
-
- Ok(ApplicationResponse::StatusOk)
-}
-
pub async fn merchant_select_token_only_flow(
state: SessionState,
user_token: auth::UserFromSinglePurposeToken,
req: user_role_api::MerchantSelectRequest,
-) -> UserResponse<user_api::TokenOrPayloadResponse<user_api::DashboardEntryResponse>> {
+) -> UserResponse<user_api::TokenResponse> {
let merchant_accounts = state
.store
.list_multiple_merchant_accounts(&(&state).into(), req.merchant_ids)
@@ -444,10 +357,10 @@ pub async fn merchant_select_token_only_flow(
.get_token_with_user_role(&state, &user_role)
.await?;
- let response = user_api::TokenOrPayloadResponse::Token(user_api::TokenResponse {
+ let response = user_api::TokenResponse {
token: token.clone(),
token_type: next_flow.get_flow().into(),
- });
+ };
auth::cookies::set_cookie_response(response, token)
}
diff --git a/crates/router/src/core/user_role/role.rs b/crates/router/src/core/user_role/role.rs
index d79b3136422..7a2c7020512 100644
--- a/crates/router/src/core/user_role/role.rs
+++ b/crates/router/src/core/user_role/role.rs
@@ -16,30 +16,10 @@ use crate::{
utils,
};
-pub async fn get_role_from_token_with_permissions(
- state: SessionState,
- user_from_token: UserFromToken,
-) -> UserResponse<role_api::GetRoleFromTokenResponse> {
- let role_info = user_from_token
- .get_role_info_from_db(&state)
- .await
- .attach_printable("Invalid role_id in JWT")?;
-
- let permissions = role_info
- .get_permissions_set()
- .into_iter()
- .map(Into::into)
- .collect();
-
- Ok(ApplicationResponse::Json(
- role_api::GetRoleFromTokenResponse::Permissions(permissions),
- ))
-}
-
pub async fn get_role_from_token_with_groups(
state: SessionState,
user_from_token: UserFromToken,
-) -> UserResponse<role_api::GetRoleFromTokenResponse> {
+) -> UserResponse<Vec<role_api::PermissionGroup>> {
let role_info = user_from_token
.get_role_info_from_db(&state)
.await
@@ -47,9 +27,7 @@ pub async fn get_role_from_token_with_groups(
let permissions = role_info.get_permission_groups().to_vec();
- Ok(ApplicationResponse::Json(
- role_api::GetRoleFromTokenResponse::Groups(permissions),
- ))
+ Ok(ApplicationResponse::Json(permissions))
}
pub async fn create_role(
@@ -105,56 +83,6 @@ pub async fn create_role(
))
}
-// TODO: To be deprecated once groups are stable
-pub async fn list_invitable_roles_with_permissions(
- state: SessionState,
- user_from_token: UserFromToken,
-) -> UserResponse<role_api::ListRolesResponse> {
- let predefined_roles_map = PREDEFINED_ROLES
- .iter()
- .filter(|(_, role_info)| role_info.is_invitable())
- .map(|(role_id, role_info)| {
- role_api::RoleInfoResponse::Permissions(role_api::RoleInfoWithPermissionsResponse {
- permissions: role_info
- .get_permissions_set()
- .into_iter()
- .map(Into::into)
- .collect(),
- role_id: role_id.to_string(),
- role_name: role_info.get_role_name().to_string(),
- role_scope: role_info.get_scope(),
- })
- });
-
- let custom_roles_map = state
- .store
- .list_all_roles(&user_from_token.merchant_id, &user_from_token.org_id)
- .await
- .change_context(UserErrors::InternalServerError)?
- .into_iter()
- .filter_map(|role| {
- let role_info = roles::RoleInfo::from(role);
- role_info
- .is_invitable()
- .then_some(role_api::RoleInfoResponse::Permissions(
- role_api::RoleInfoWithPermissionsResponse {
- permissions: role_info
- .get_permissions_set()
- .into_iter()
- .map(Into::into)
- .collect(),
- role_id: role_info.get_role_id().to_string(),
- role_name: role_info.get_role_name().to_string(),
- role_scope: role_info.get_scope(),
- },
- ))
- });
-
- Ok(ApplicationResponse::Json(role_api::ListRolesResponse(
- predefined_roles_map.chain(custom_roles_map).collect(),
- )))
-}
-
pub async fn list_invitable_roles_with_groups(
state: SessionState,
user_from_token: UserFromToken,
@@ -162,14 +90,14 @@ pub async fn list_invitable_roles_with_groups(
let predefined_roles_map = PREDEFINED_ROLES
.iter()
.filter(|(_, role_info)| role_info.is_invitable())
- .map(|(role_id, role_info)| {
- role_api::RoleInfoResponse::Groups(role_api::RoleInfoWithGroupsResponse {
+ .map(
+ |(role_id, role_info)| role_api::RoleInfoWithGroupsResponse {
groups: role_info.get_permission_groups().to_vec(),
role_id: role_id.to_string(),
role_name: role_info.get_role_name().to_string(),
role_scope: role_info.get_scope(),
- })
- });
+ },
+ );
let custom_roles_map = state
.store
@@ -181,14 +109,12 @@ pub async fn list_invitable_roles_with_groups(
let role_info = roles::RoleInfo::from(role);
role_info
.is_invitable()
- .then_some(role_api::RoleInfoResponse::Groups(
- role_api::RoleInfoWithGroupsResponse {
- groups: role_info.get_permission_groups().to_vec(),
- role_id: role_info.get_role_id().to_string(),
- role_name: role_info.get_role_name().to_string(),
- role_scope: role_info.get_scope(),
- },
- ))
+ .then_some(role_api::RoleInfoWithGroupsResponse {
+ groups: role_info.get_permission_groups().to_vec(),
+ role_id: role_info.get_role_id().to_string(),
+ role_name: role_info.get_role_name().to_string(),
+ role_scope: role_info.get_scope(),
+ })
});
Ok(ApplicationResponse::Json(role_api::ListRolesResponse(
@@ -196,46 +122,11 @@ pub async fn list_invitable_roles_with_groups(
)))
}
-// TODO: To be deprecated once groups are stable
-pub async fn get_role_with_permissions(
- state: SessionState,
- user_from_token: UserFromToken,
- role: role_api::GetRoleRequest,
-) -> UserResponse<role_api::RoleInfoResponse> {
- let role_info = roles::RoleInfo::from_role_id(
- &state,
- &role.role_id,
- &user_from_token.merchant_id,
- &user_from_token.org_id,
- )
- .await
- .to_not_found_response(UserErrors::InvalidRoleId)?;
-
- if role_info.is_internal() {
- return Err(UserErrors::InvalidRoleId.into());
- }
-
- let permissions = role_info
- .get_permissions_set()
- .into_iter()
- .map(Into::into)
- .collect();
-
- Ok(ApplicationResponse::Json(
- role_api::RoleInfoResponse::Permissions(role_api::RoleInfoWithPermissionsResponse {
- permissions,
- role_id: role.role_id,
- role_name: role_info.get_role_name().to_string(),
- role_scope: role_info.get_scope(),
- }),
- ))
-}
-
pub async fn get_role_with_groups(
state: SessionState,
user_from_token: UserFromToken,
role: role_api::GetRoleRequest,
-) -> UserResponse<role_api::RoleInfoResponse> {
+) -> UserResponse<role_api::RoleInfoWithGroupsResponse> {
let role_info = roles::RoleInfo::from_role_id(
&state,
&role.role_id,
@@ -250,12 +141,12 @@ pub async fn get_role_with_groups(
}
Ok(ApplicationResponse::Json(
- role_api::RoleInfoResponse::Groups(role_api::RoleInfoWithGroupsResponse {
+ role_api::RoleInfoWithGroupsResponse {
groups: role_info.get_permission_groups().to_vec(),
role_id: role.role_id,
role_name: role_info.get_role_name().to_string(),
role_scope: role_info.get_scope(),
- }),
+ },
))
}
diff --git a/crates/router/src/db/user_role.rs b/crates/router/src/db/user_role.rs
index 57090632725..eadd1ef4a5b 100644
--- a/crates/router/src/db/user_role.rs
+++ b/crates/router/src/db/user_role.rs
@@ -357,11 +357,7 @@ impl UserRoleInterface for MockDb {
for user_role in user_roles.iter() {
let Some(user_role_merchant_id) = &user_role.merchant_id else {
- return Err(errors::StorageError::DatabaseError(
- report!(errors::DatabaseError::Others)
- .attach_printable("merchant_id not found for user_role"),
- )
- .into());
+ continue;
};
if user_role.user_id == user_id
&& user_role_merchant_id == merchant_id
diff --git a/crates/router/src/routes/app.rs b/crates/router/src/routes/app.rs
index 8201380cc29..42f46e39d2e 100644
--- a/crates/router/src/routes/app.rs
+++ b/crates/router/src/routes/app.rs
@@ -1681,6 +1681,7 @@ impl User {
route = route
.service(web::resource("").route(web::get().to(get_user_details)))
+ .service(web::resource("/signin").route(web::post().to(user_signin)))
.service(web::resource("/v2/signin").route(web::post().to(user_signin)))
// signin/signup with sso using openidconnect
.service(web::resource("/oidc").route(web::post().to(sso_sign)))
@@ -1796,6 +1797,7 @@ impl User {
web::resource("/signup_with_merchant_id")
.route(web::post().to(user_signup_with_merchant_id)),
)
+ .service(web::resource("/verify_email").route(web::post().to(verify_email)))
.service(web::resource("/v2/verify_email").route(web::post().to(verify_email)))
.service(
web::resource("/verify_email_request")
diff --git a/crates/router/src/routes/user.rs b/crates/router/src/routes/user.rs
index c52c5d1321c..1d5e3d601b6 100644
--- a/crates/router/src/routes/user.rs
+++ b/crates/router/src/routes/user.rs
@@ -62,22 +62,16 @@ pub async fn user_signup(
state: web::Data<AppState>,
http_req: HttpRequest,
json_payload: web::Json<user_api::SignUpRequest>,
- query: web::Query<user_api::TokenOnlyQueryParam>,
) -> HttpResponse {
let flow = Flow::UserSignUp;
let req_payload = json_payload.into_inner();
- let is_token_only = query.into_inner().token_only;
Box::pin(api::server_wrap(
flow.clone(),
state,
&http_req,
req_payload.clone(),
|state, _: (), req_body, _| async move {
- if let Some(true) = is_token_only {
- user_core::signup_token_only_flow(state, req_body).await
- } else {
- user_core::signup(state, req_body).await
- }
+ user_core::signup_token_only_flow(state, req_body).await
},
&auth::NoAuth,
api_locking::LockAction::NotApplicable,
@@ -89,22 +83,16 @@ pub async fn user_signin(
state: web::Data<AppState>,
http_req: HttpRequest,
json_payload: web::Json<user_api::SignInRequest>,
- query: web::Query<user_api::TokenOnlyQueryParam>,
) -> HttpResponse {
let flow = Flow::UserSignIn;
let req_payload = json_payload.into_inner();
- let is_token_only = query.into_inner().token_only;
Box::pin(api::server_wrap(
flow.clone(),
state,
&http_req,
req_payload.clone(),
|state, _: (), req_body, _| async move {
- if let Some(true) = is_token_only {
- user_core::signin_token_only_flow(state, req_body).await
- } else {
- user_core::signin(state, req_body).await
- }
+ user_core::signin_token_only_flow(state, req_body).await
},
&auth::NoAuth,
api_locking::LockAction::NotApplicable,
@@ -409,46 +397,27 @@ pub async fn reset_password(
state: web::Data<AppState>,
req: HttpRequest,
payload: web::Json<user_api::ResetPasswordRequest>,
- query: web::Query<user_api::TokenOnlyQueryParam>,
) -> HttpResponse {
let flow = Flow::ResetPassword;
- let is_token_only = query.into_inner().token_only;
- if let Some(true) = is_token_only {
- 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
- } else {
- Box::pin(api::server_wrap(
- flow,
- state.clone(),
- &req,
- payload.into_inner(),
- |state, _: (), payload, _| user_core::reset_password(state, payload),
- &auth::NoAuth,
- api_locking::LockAction::NotApplicable,
- ))
- .await
- }
+ 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>>,
- token_only_query_param: web::Query<user_api::TokenOnlyQueryParam>,
auth_id_query_param: web::Query<user_api::AuthIdQueryParam>,
) -> HttpResponse {
let flow = Flow::InviteMultipleUser;
- let is_token_only = token_only_query_param.into_inner().token_only;
let auth_id = auth_id_query_param.into_inner().auth_id;
Box::pin(api::server_wrap(
flow,
@@ -456,14 +425,7 @@ pub async fn invite_multiple_user(
&req,
payload.into_inner(),
|state, user, payload, req_state| {
- user_core::invite_multiple_user(
- state,
- user,
- payload,
- req_state,
- is_token_only,
- auth_id.clone(),
- )
+ user_core::invite_multiple_user(state, user, payload, req_state, auth_id.clone())
},
&auth::JWTAuth(Permission::UsersWrite),
api_locking::LockAction::NotApplicable,
@@ -499,37 +461,20 @@ pub async fn accept_invite_from_email(
state: web::Data<AppState>,
req: HttpRequest,
payload: web::Json<user_api::AcceptInviteFromEmailRequest>,
- query: web::Query<user_api::TokenOnlyQueryParam>,
) -> HttpResponse {
let flow = Flow::AcceptInviteFromEmail;
- let is_token_only = query.into_inner().token_only;
- if let Some(true) = is_token_only {
- 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)
- },
- &auth::SinglePurposeJWTAuth(TokenPurpose::AcceptInvitationFromEmail),
- api_locking::LockAction::NotApplicable,
- ))
- .await
- } else {
- Box::pin(api::server_wrap(
- flow,
- state.clone(),
- &req,
- payload.into_inner(),
- |state, _: (), request_payload, _| {
- user_core::accept_invite_from_email(state, request_payload)
- },
- &auth::NoAuth,
- api_locking::LockAction::NotApplicable,
- ))
- .await
- }
+ 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)
+ },
+ &auth::SinglePurposeJWTAuth(TokenPurpose::AcceptInvitationFromEmail),
+ api_locking::LockAction::NotApplicable,
+ ))
+ .await
}
#[cfg(feature = "email")]
@@ -537,35 +482,20 @@ pub async fn verify_email(
state: web::Data<AppState>,
http_req: HttpRequest,
json_payload: web::Json<user_api::VerifyEmailRequest>,
- query: web::Query<user_api::TokenOnlyQueryParam>,
) -> HttpResponse {
let flow = Flow::VerifyEmail;
- let is_token_only = query.into_inner().token_only;
- if let Some(true) = is_token_only {
- 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
- } else {
- Box::pin(api::server_wrap(
- flow.clone(),
- state,
- &http_req,
- json_payload.into_inner(),
- |state, _: (), req_payload, _| user_core::verify_email(state, req_payload),
- &auth::NoAuth,
- api_locking::LockAction::NotApplicable,
- ))
- .await
- }
+ 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")]
diff --git a/crates/router/src/routes/user_role.rs b/crates/router/src/routes/user_role.rs
index a730321e190..5f1e4301d45 100644
--- a/crates/router/src/routes/user_role.rs
+++ b/crates/router/src/routes/user_role.rs
@@ -1,8 +1,5 @@
use actix_web::{web, HttpRequest, HttpResponse};
-use api_models::{
- user as user_api,
- user_role::{self as user_role_api, role as role_api},
-};
+use api_models::user_role::{self as user_role_api, role as role_api};
use common_enums::TokenPurpose;
use router_env::Flow;
@@ -22,22 +19,15 @@ use crate::{
pub async fn get_authorization_info(
state: web::Data<AppState>,
http_req: HttpRequest,
- query: web::Query<role_api::GetGroupsQueryParam>,
) -> HttpResponse {
let flow = Flow::GetAuthorizationInfo;
- let respond_with_groups = query.into_inner().groups.unwrap_or(false);
Box::pin(api::server_wrap(
flow,
state.clone(),
&http_req,
(),
|state, _: (), _, _| async move {
- // TODO: Permissions to be deprecated once groups are stable
- if respond_with_groups {
- user_role_core::get_authorization_info_with_groups(state).await
- } else {
- user_role_core::get_authorization_info_with_modules(state).await
- }
+ user_role_core::get_authorization_info_with_groups(state).await
},
&auth::JWTAuth(Permission::UsersRead),
api_locking::LockAction::NotApplicable,
@@ -45,13 +35,8 @@ pub async fn get_authorization_info(
.await
}
-pub async fn get_role_from_token(
- state: web::Data<AppState>,
- req: HttpRequest,
- query: web::Query<role_api::GetGroupsQueryParam>,
-) -> HttpResponse {
+pub async fn get_role_from_token(state: web::Data<AppState>, req: HttpRequest) -> HttpResponse {
let flow = Flow::GetRoleFromToken;
- let respond_with_groups = query.into_inner().groups.unwrap_or(false);
Box::pin(api::server_wrap(
flow,
@@ -59,12 +44,7 @@ pub async fn get_role_from_token(
&req,
(),
|state, user, _, _| async move {
- // TODO: Permissions to be deprecated once groups are stable
- if respond_with_groups {
- role_core::get_role_from_token_with_groups(state, user).await
- } else {
- role_core::get_role_from_token_with_permissions(state, user).await
- }
+ role_core::get_role_from_token_with_groups(state, user).await
},
&auth::DashboardNoPermissionAuth,
api_locking::LockAction::NotApplicable,
@@ -90,25 +70,15 @@ pub async fn create_role(
.await
}
-pub async fn list_all_roles(
- state: web::Data<AppState>,
- req: HttpRequest,
- query: web::Query<role_api::GetGroupsQueryParam>,
-) -> HttpResponse {
+pub async fn list_all_roles(state: web::Data<AppState>, req: HttpRequest) -> HttpResponse {
let flow = Flow::ListRoles;
- let respond_with_groups = query.into_inner().groups.unwrap_or(false);
Box::pin(api::server_wrap(
flow,
state.clone(),
&req,
(),
|state, user, _, _| async move {
- // TODO: Permissions to be deprecated once groups are stable
- if respond_with_groups {
- role_core::list_invitable_roles_with_groups(state, user).await
- } else {
- role_core::list_invitable_roles_with_permissions(state, user).await
- }
+ role_core::list_invitable_roles_with_groups(state, user).await
},
&auth::JWTAuth(Permission::UsersRead),
api_locking::LockAction::NotApplicable,
@@ -120,25 +90,18 @@ pub async fn get_role(
state: web::Data<AppState>,
req: HttpRequest,
path: web::Path<String>,
- query: web::Query<role_api::GetGroupsQueryParam>,
) -> HttpResponse {
let flow = Flow::GetRole;
let request_payload = user_role_api::role::GetRoleRequest {
role_id: path.into_inner(),
};
- let respond_with_groups = query.into_inner().groups.unwrap_or(false);
Box::pin(api::server_wrap(
flow,
state.clone(),
&req,
request_payload,
|state, user, payload, _| async move {
- // TODO: Permissions to be deprecated once groups are stable
- if respond_with_groups {
- role_core::get_role_with_groups(state, user, payload).await
- } else {
- role_core::get_role_with_permissions(state, user, payload).await
- }
+ role_core::get_role_with_groups(state, user, payload).await
},
&auth::JWTAuth(Permission::UsersRead),
api_locking::LockAction::NotApplicable,
@@ -209,22 +172,16 @@ pub async fn merchant_select(
state: web::Data<AppState>,
req: HttpRequest,
json_payload: web::Json<user_role_api::MerchantSelectRequest>,
- query: web::Query<user_api::TokenOnlyQueryParam>,
) -> HttpResponse {
let flow = Flow::MerchantSelect;
let payload = json_payload.into_inner();
- let is_token_only = query.into_inner().token_only;
Box::pin(api::server_wrap(
flow,
state.clone(),
&req,
payload,
|state, user, req_body, _| async move {
- if let Some(true) = is_token_only {
- user_role_core::merchant_select_token_only_flow(state, user, req_body).await
- } else {
- user_role_core::merchant_select(state, user, req_body).await
- }
+ user_role_core::merchant_select_token_only_flow(state, user, req_body).await
},
&auth::SinglePurposeJWTAuth(TokenPurpose::AcceptInvite),
api_locking::LockAction::NotApplicable,
diff --git a/crates/router/src/services/authorization/predefined_permissions.rs b/crates/router/src/services/authorization/predefined_permissions.rs
deleted file mode 100644
index 50f9a7196b8..00000000000
--- a/crates/router/src/services/authorization/predefined_permissions.rs
+++ /dev/null
@@ -1,346 +0,0 @@
-use std::collections::HashMap;
-
-#[cfg(feature = "olap")]
-use error_stack::ResultExt;
-use once_cell::sync::Lazy;
-
-use super::permissions::Permission;
-use crate::consts;
-#[cfg(feature = "olap")]
-use crate::core::errors::{UserErrors, UserResult};
-
-#[allow(dead_code)]
-pub struct RoleInfo {
- permissions: Vec<Permission>,
- name: Option<&'static str>,
- is_invitable: bool,
- is_deletable: bool,
- is_updatable: bool,
-}
-
-impl RoleInfo {
- pub fn get_permissions(&self) -> &Vec<Permission> {
- &self.permissions
- }
-
- pub fn get_name(&self) -> Option<&'static str> {
- self.name
- }
-
- pub fn is_invitable(&self) -> bool {
- self.is_invitable
- }
-}
-
-pub static PREDEFINED_PERMISSIONS: Lazy<HashMap<&'static str, RoleInfo>> = Lazy::new(|| {
- let mut roles = HashMap::new();
- roles.insert(
- consts::user_role::ROLE_ID_INTERNAL_ADMIN,
- RoleInfo {
- permissions: vec![
- Permission::PaymentRead,
- Permission::PaymentWrite,
- Permission::RefundRead,
- Permission::RefundWrite,
- Permission::ApiKeyRead,
- Permission::ApiKeyWrite,
- Permission::MerchantAccountRead,
- Permission::MerchantAccountWrite,
- Permission::MerchantConnectorAccountRead,
- Permission::MerchantConnectorAccountWrite,
- Permission::RoutingRead,
- Permission::RoutingWrite,
- Permission::ThreeDsDecisionManagerWrite,
- Permission::ThreeDsDecisionManagerRead,
- Permission::SurchargeDecisionManagerWrite,
- Permission::SurchargeDecisionManagerRead,
- Permission::DisputeRead,
- Permission::DisputeWrite,
- Permission::MandateRead,
- Permission::MandateWrite,
- Permission::CustomerRead,
- Permission::CustomerWrite,
- Permission::Analytics,
- Permission::UsersRead,
- Permission::UsersWrite,
- Permission::MerchantAccountCreate,
- Permission::PayoutRead,
- Permission::PayoutWrite,
- ],
- name: None,
- is_invitable: false,
- is_deletable: false,
- is_updatable: false,
- },
- );
- roles.insert(
- consts::user_role::ROLE_ID_INTERNAL_VIEW_ONLY_USER,
- RoleInfo {
- permissions: vec![
- Permission::PaymentRead,
- Permission::RefundRead,
- Permission::ApiKeyRead,
- Permission::MerchantAccountRead,
- Permission::MerchantConnectorAccountRead,
- Permission::RoutingRead,
- Permission::ThreeDsDecisionManagerRead,
- Permission::SurchargeDecisionManagerRead,
- Permission::Analytics,
- Permission::DisputeRead,
- Permission::MandateRead,
- Permission::CustomerRead,
- Permission::UsersRead,
- Permission::PayoutRead,
- ],
- name: None,
- is_invitable: false,
- is_deletable: false,
- is_updatable: false,
- },
- );
-
- roles.insert(
- consts::user_role::ROLE_ID_ORGANIZATION_ADMIN,
- RoleInfo {
- permissions: vec![
- Permission::PaymentRead,
- Permission::PaymentWrite,
- Permission::RefundRead,
- Permission::RefundWrite,
- Permission::ApiKeyRead,
- Permission::ApiKeyWrite,
- Permission::MerchantAccountRead,
- Permission::MerchantAccountWrite,
- Permission::MerchantConnectorAccountRead,
- Permission::MerchantConnectorAccountWrite,
- Permission::RoutingRead,
- Permission::RoutingWrite,
- Permission::ThreeDsDecisionManagerWrite,
- Permission::ThreeDsDecisionManagerRead,
- Permission::SurchargeDecisionManagerWrite,
- Permission::SurchargeDecisionManagerRead,
- Permission::DisputeRead,
- Permission::DisputeWrite,
- Permission::MandateRead,
- Permission::MandateWrite,
- Permission::CustomerRead,
- Permission::CustomerWrite,
- Permission::Analytics,
- Permission::UsersRead,
- Permission::UsersWrite,
- Permission::MerchantAccountCreate,
- Permission::PayoutRead,
- Permission::PayoutWrite,
- ],
- name: Some("Organization Admin"),
- is_invitable: false,
- is_deletable: false,
- is_updatable: false,
- },
- );
-
- // MERCHANT ROLES
- roles.insert(
- consts::user_role::ROLE_ID_MERCHANT_ADMIN,
- RoleInfo {
- permissions: vec![
- Permission::PaymentRead,
- Permission::PaymentWrite,
- Permission::RefundRead,
- Permission::RefundWrite,
- Permission::ApiKeyRead,
- Permission::ApiKeyWrite,
- Permission::MerchantAccountRead,
- Permission::MerchantAccountWrite,
- Permission::MerchantConnectorAccountRead,
- Permission::MerchantConnectorAccountWrite,
- Permission::RoutingRead,
- Permission::RoutingWrite,
- Permission::ThreeDsDecisionManagerWrite,
- Permission::ThreeDsDecisionManagerRead,
- Permission::SurchargeDecisionManagerWrite,
- Permission::SurchargeDecisionManagerRead,
- Permission::DisputeRead,
- Permission::DisputeWrite,
- Permission::MandateRead,
- Permission::MandateWrite,
- Permission::CustomerRead,
- Permission::CustomerWrite,
- Permission::Analytics,
- Permission::UsersRead,
- Permission::UsersWrite,
- Permission::PayoutRead,
- Permission::PayoutWrite,
- ],
- name: Some("Admin"),
- is_invitable: true,
- is_deletable: true,
- is_updatable: true,
- },
- );
- roles.insert(
- consts::user_role::ROLE_ID_MERCHANT_VIEW_ONLY,
- RoleInfo {
- permissions: vec![
- Permission::PaymentRead,
- Permission::RefundRead,
- Permission::ApiKeyRead,
- Permission::MerchantAccountRead,
- Permission::MerchantConnectorAccountRead,
- Permission::RoutingRead,
- Permission::ThreeDsDecisionManagerRead,
- Permission::SurchargeDecisionManagerRead,
- Permission::DisputeRead,
- Permission::MandateRead,
- Permission::CustomerRead,
- Permission::Analytics,
- Permission::UsersRead,
- Permission::PayoutRead,
- ],
- name: Some("View Only"),
- is_invitable: true,
- is_deletable: true,
- is_updatable: true,
- },
- );
- roles.insert(
- consts::user_role::ROLE_ID_MERCHANT_IAM_ADMIN,
- RoleInfo {
- permissions: vec![
- Permission::PaymentRead,
- Permission::RefundRead,
- Permission::ApiKeyRead,
- Permission::MerchantAccountRead,
- Permission::MerchantConnectorAccountRead,
- Permission::RoutingRead,
- Permission::ThreeDsDecisionManagerRead,
- Permission::SurchargeDecisionManagerRead,
- Permission::DisputeRead,
- Permission::MandateRead,
- Permission::CustomerRead,
- Permission::Analytics,
- Permission::UsersRead,
- Permission::UsersWrite,
- Permission::PayoutRead,
- ],
- name: Some("IAM"),
- is_invitable: true,
- is_deletable: true,
- is_updatable: true,
- },
- );
- roles.insert(
- consts::user_role::ROLE_ID_MERCHANT_DEVELOPER,
- RoleInfo {
- permissions: vec![
- Permission::PaymentRead,
- Permission::RefundRead,
- Permission::ApiKeyRead,
- Permission::ApiKeyWrite,
- Permission::MerchantAccountRead,
- Permission::MerchantConnectorAccountRead,
- Permission::RoutingRead,
- Permission::ThreeDsDecisionManagerRead,
- Permission::SurchargeDecisionManagerRead,
- Permission::DisputeRead,
- Permission::MandateRead,
- Permission::CustomerRead,
- Permission::Analytics,
- Permission::UsersRead,
- Permission::PayoutRead,
- ],
- name: Some("Developer"),
- is_invitable: true,
- is_deletable: true,
- is_updatable: true,
- },
- );
- roles.insert(
- consts::user_role::ROLE_ID_MERCHANT_OPERATOR,
- RoleInfo {
- permissions: vec![
- Permission::PaymentRead,
- Permission::PaymentWrite,
- Permission::RefundRead,
- Permission::RefundWrite,
- Permission::ApiKeyRead,
- Permission::MerchantAccountRead,
- Permission::MerchantConnectorAccountRead,
- Permission::MerchantConnectorAccountWrite,
- Permission::RoutingRead,
- Permission::RoutingWrite,
- Permission::ThreeDsDecisionManagerRead,
- Permission::ThreeDsDecisionManagerWrite,
- Permission::SurchargeDecisionManagerRead,
- Permission::SurchargeDecisionManagerWrite,
- Permission::DisputeRead,
- Permission::MandateRead,
- Permission::CustomerRead,
- Permission::Analytics,
- Permission::UsersRead,
- Permission::PayoutRead,
- Permission::PayoutWrite,
- ],
- name: Some("Operator"),
- is_invitable: true,
- is_deletable: true,
- is_updatable: true,
- },
- );
- roles.insert(
- consts::user_role::ROLE_ID_MERCHANT_CUSTOMER_SUPPORT,
- RoleInfo {
- permissions: vec![
- Permission::PaymentRead,
- Permission::RefundRead,
- Permission::RefundWrite,
- Permission::DisputeRead,
- Permission::DisputeWrite,
- Permission::MerchantAccountRead,
- Permission::MerchantConnectorAccountRead,
- Permission::MandateRead,
- Permission::CustomerRead,
- Permission::Analytics,
- Permission::PayoutRead,
- ],
- name: Some("Customer Support"),
- is_invitable: true,
- is_deletable: true,
- is_updatable: true,
- },
- );
- roles
-});
-
-pub fn get_role_name_from_id(role_id: &str) -> Option<&'static str> {
- PREDEFINED_PERMISSIONS
- .get(role_id)
- .and_then(|role_info| role_info.name)
-}
-
-#[cfg(feature = "olap")]
-pub fn is_role_invitable(role_id: &str) -> UserResult<bool> {
- PREDEFINED_PERMISSIONS
- .get(role_id)
- .map(|role_info| role_info.is_invitable)
- .ok_or(UserErrors::InvalidRoleId.into())
- .attach_printable(format!("role_id = {} doesn't exist", role_id))
-}
-
-#[cfg(feature = "olap")]
-pub fn is_role_deletable(role_id: &str) -> UserResult<bool> {
- PREDEFINED_PERMISSIONS
- .get(role_id)
- .map(|role_info| role_info.is_deletable)
- .ok_or(UserErrors::InvalidRoleId.into())
- .attach_printable(format!("role_id = {} doesn't exist", role_id))
-}
-
-#[cfg(feature = "olap")]
-pub fn is_role_updatable(role_id: &str) -> UserResult<bool> {
- PREDEFINED_PERMISSIONS
- .get(role_id)
- .map(|role_info| role_info.is_updatable)
- .ok_or(UserErrors::InvalidRoleId.into())
- .attach_printable(format!("role_id = {} doesn't exist", role_id))
-}
diff --git a/crates/router/src/types/domain/user.rs b/crates/router/src/types/domain/user.rs
index 42cb71458d5..58a0a68df51 100644
--- a/crates/router/src/types/domain/user.rs
+++ b/crates/router/src/types/domain/user.rs
@@ -3,7 +3,7 @@ use std::{collections::HashSet, ops, str::FromStr};
use api_models::{
admin as admin_api, organization as api_org, user as user_api, user_role as user_role_api,
};
-use common_enums::{EntityType, TokenPurpose};
+use common_enums::EntityType;
use common_utils::{
crypto::Encryptable, errors::CustomResult, id_type, new_type::MerchantName, pii, type_name,
types::keymanager::Identifier,
@@ -32,13 +32,9 @@ use crate::{
},
db::{user_role::InsertUserRolePayload, GlobalStorageInterface},
routes::SessionState,
- services::{
- self,
- authentication::{self as auth, UserFromToken},
- authorization::info,
- },
+ services::{self, authentication::UserFromToken, authorization::info},
types::transformers::ForeignFrom,
- utils::{self, user::password},
+ utils::user::password,
};
pub mod dashboard_metadata;
@@ -1115,130 +1111,6 @@ impl From<info::PermissionModule> for user_role_api::PermissionModule {
}
}
-pub enum SignInWithRoleStrategyType {
- SingleRole(SignInWithSingleRoleStrategy),
- MultipleRoles(SignInWithMultipleRolesStrategy),
-}
-
-impl SignInWithRoleStrategyType {
- pub async fn decide_signin_strategy_by_user_roles(
- user: UserFromStorage,
- user_roles: Vec<UserRole>,
- ) -> UserResult<Self> {
- if user_roles.is_empty() {
- return Err(UserErrors::InternalServerError.into());
- }
-
- if let Some(user_role) = user_roles
- .iter()
- .find(|role| role.status == UserStatus::Active)
- {
- Ok(Self::SingleRole(SignInWithSingleRoleStrategy {
- user,
- user_role: Box::new(user_role.clone()),
- }))
- } else {
- Ok(Self::MultipleRoles(SignInWithMultipleRolesStrategy {
- user,
- user_roles,
- }))
- }
- }
-
- pub async fn get_signin_response(
- self,
- state: &SessionState,
- ) -> UserResult<user_api::SignInResponse> {
- match self {
- Self::SingleRole(strategy) => strategy.get_signin_response(state).await,
- Self::MultipleRoles(strategy) => strategy.get_signin_response(state).await,
- }
- }
-}
-
-pub struct SignInWithSingleRoleStrategy {
- pub user: UserFromStorage,
- pub user_role: Box<UserRole>,
-}
-
-impl SignInWithSingleRoleStrategy {
- async fn get_signin_response(
- self,
- state: &SessionState,
- ) -> UserResult<user_api::SignInResponse> {
- let token = utils::user::generate_jwt_auth_token_without_profile(
- state,
- &self.user,
- &self.user_role,
- )
- .await?;
- utils::user_role::set_role_permissions_in_cache_by_user_role(state, &self.user_role).await;
-
- let dashboard_entry_response =
- utils::user::get_dashboard_entry_response(state, self.user, *self.user_role, token)?;
-
- Ok(user_api::SignInResponse::DashboardEntry(
- dashboard_entry_response,
- ))
- }
-}
-
-pub struct SignInWithMultipleRolesStrategy {
- pub user: UserFromStorage,
- pub user_roles: Vec<UserRole>,
-}
-
-impl SignInWithMultipleRolesStrategy {
- async fn get_signin_response(
- self,
- state: &SessionState,
- ) -> UserResult<user_api::SignInResponse> {
- let merchant_accounts = state
- .store
- .list_multiple_merchant_accounts(
- &state.into(),
- self.user_roles
- .iter()
- .map(|role| {
- role.merchant_id
- .clone()
- .ok_or(UserErrors::InternalServerError)
- })
- .collect::<Result<Vec<_>, _>>()?,
- )
- .await
- .change_context(UserErrors::InternalServerError)?;
-
- let roles =
- utils::user_role::get_multiple_role_info_for_user_roles(state, &self.user_roles)
- .await?;
-
- let merchant_details = utils::user::get_multiple_merchant_details_with_status(
- self.user_roles,
- merchant_accounts,
- roles,
- )?;
-
- Ok(user_api::SignInResponse::MerchantSelect(
- user_api::MerchantSelectResponse {
- name: self.user.get_name(),
- email: self.user.get_email(),
- token: auth::SinglePurposeToken::new_token(
- self.user.get_user_id().to_string(),
- TokenPurpose::AcceptInvite,
- Origin::SignIn,
- &state.conf,
- vec![],
- )
- .await?
- .into(),
- merchants: merchant_details,
- verification_days_left: utils::user::get_verification_days_left(state, &self.user)?,
- },
- ))
- }
-}
-
impl ForeignFrom<UserStatus> for user_role_api::UserStatus {
fn foreign_from(value: UserStatus) -> Self {
match value {
diff --git a/crates/router/src/types/domain/user/decision_manager.rs b/crates/router/src/types/domain/user/decision_manager.rs
index 92f1d4ba5ba..4206b16df6d 100644
--- a/crates/router/src/types/domain/user/decision_manager.rs
+++ b/crates/router/src/types/domain/user/decision_manager.rs
@@ -1,6 +1,6 @@
use common_enums::TokenPurpose;
use diesel_models::{enums::UserStatus, user_role::UserRole};
-use error_stack::report;
+use error_stack::{report, ResultExt};
use masking::Secret;
use super::UserFromStorage;
@@ -109,16 +109,14 @@ impl JWTFlow {
) -> UserResult<Secret<String>> {
auth::AuthToken::new_token(
next_flow.user.get_user_id().to_string(),
- user_role
- .merchant_id
- .clone()
- .ok_or(report!(UserErrors::InternalServerError))?,
+ utils::user_role::get_single_merchant_id(state, user_role).await?,
user_role.role_id.clone(),
&state.conf,
user_role
.org_id
.clone()
- .ok_or(report!(UserErrors::InternalServerError))?,
+ .ok_or(report!(UserErrors::InternalServerError))
+ .attach_printable("org_id not found")?,
None,
)
.await
diff --git a/crates/router/src/utils/user.rs b/crates/router/src/utils/user.rs
index b2170e7294a..a1bd6972dab 100644
--- a/crates/router/src/utils/user.rs
+++ b/crates/router/src/utils/user.rs
@@ -1,11 +1,11 @@
-use std::{collections::HashMap, sync::Arc};
+use std::sync::Arc;
use api_models::user as user_api;
use common_enums::UserAuthType;
use common_utils::{
encryption::Encryption, errors::CustomResult, id_type, type_name, types::keymanager::Identifier,
};
-use diesel_models::{enums::UserStatus, user_role::UserRole};
+use diesel_models::user_role::UserRole;
use error_stack::{report, ResultExt};
use masking::{ExposeInterface, Secret};
use redis_interface::RedisConnectionPool;
@@ -128,28 +128,6 @@ pub async fn generate_jwt_auth_token_with_attributes(
Ok(Secret::new(token))
}
-pub fn get_dashboard_entry_response(
- state: &SessionState,
- user: UserFromStorage,
- user_role: UserRole,
- token: Secret<String>,
-) -> UserResult<user_api::DashboardEntryResponse> {
- let verification_days_left = get_verification_days_left(state, &user)?;
-
- Ok(user_api::DashboardEntryResponse {
- merchant_id: user_role.merchant_id.ok_or(
- report!(UserErrors::InternalServerError)
- .attach_printable("merchant_id not found for user_role"),
- )?,
- token,
- name: user.get_name(),
- email: user.get_email(),
- user_id: user.get_user_id().to_string(),
- verification_days_left,
- user_role: user_role.role_id,
- })
-}
-
#[allow(unused_variables)]
pub fn get_verification_days_left(
state: &SessionState,
@@ -161,54 +139,6 @@ pub fn get_verification_days_left(
return Ok(None);
}
-pub fn get_multiple_merchant_details_with_status(
- user_roles: Vec<UserRole>,
- merchant_accounts: Vec<MerchantAccount>,
- roles: Vec<RoleInfo>,
-) -> UserResult<Vec<user_api::UserMerchantAccount>> {
- let merchant_account_map = merchant_accounts
- .into_iter()
- .map(|merchant_account| (merchant_account.get_id().clone(), merchant_account))
- .collect::<HashMap<_, _>>();
-
- let role_map = roles
- .into_iter()
- .map(|role_info| (role_info.get_role_id().to_string(), role_info))
- .collect::<HashMap<_, _>>();
-
- user_roles
- .into_iter()
- .map(|user_role| {
- let Some(merchant_id) = &user_role.merchant_id else {
- return Err(report!(UserErrors::InternalServerError))
- .attach_printable("merchant_id not found for user_role");
- };
- let Some(org_id) = &user_role.org_id else {
- return Err(report!(UserErrors::InternalServerError)
- .attach_printable("org_id not found in user_role"));
- };
- let merchant_account = merchant_account_map
- .get(merchant_id)
- .ok_or(UserErrors::InternalServerError)
- .attach_printable("Merchant account for user role doesn't exist")?;
-
- let role_info = role_map
- .get(&user_role.role_id)
- .ok_or(UserErrors::InternalServerError)
- .attach_printable("Role info for user role doesn't exist")?;
-
- Ok(user_api::UserMerchantAccount {
- merchant_id: merchant_id.to_owned(),
- merchant_name: merchant_account.merchant_name.clone(),
- is_active: user_role.status == UserStatus::Active,
- role_id: user_role.role_id,
- role_name: role_info.get_role_name().to_string(),
- org_id: org_id.to_owned(),
- })
- })
- .collect()
-}
-
pub async fn get_user_from_db_by_email(
state: &SessionState,
email: domain::UserEmail,
@@ -220,13 +150,6 @@ pub async fn get_user_from_db_by_email(
.map(UserFromStorage::from)
}
-pub fn get_token_from_signin_response(resp: &user_api::SignInResponse) -> Secret<String> {
- match resp {
- user_api::SignInResponse::DashboardEntry(data) => data.token.clone(),
- user_api::SignInResponse::MerchantSelect(data) => data.token.clone(),
- }
-}
-
pub fn get_redis_connection(state: &SessionState) -> UserResult<Arc<RedisConnectionPool>> {
state
.store
diff --git a/crates/router/src/utils/user_role.rs b/crates/router/src/utils/user_role.rs
index 1791b5308b4..dbe3ed6d585 100644
--- a/crates/router/src/utils/user_role.rs
+++ b/crates/router/src/utils/user_role.rs
@@ -1,7 +1,7 @@
use std::collections::HashSet;
use api_models::user_role as user_role_api;
-use common_enums::PermissionGroup;
+use common_enums::{EntityType, PermissionGroup};
use common_utils::id_type;
use diesel_models::{
enums::UserRoleVersion,
@@ -13,7 +13,7 @@ use storage_impl::errors::StorageError;
use crate::{
consts,
- core::errors::{StorageErrorExt, UserErrors, UserResult},
+ core::errors::{UserErrors, UserResult},
routes::SessionState,
services::authorization::{self as authz, permissions::Permission, roles},
types::domain,
@@ -167,28 +167,6 @@ pub async fn set_role_permissions_in_cache_if_required(
.attach_printable("Error setting permissions in redis")
}
-pub async fn get_multiple_role_info_for_user_roles(
- state: &SessionState,
- user_roles: &[UserRole],
-) -> UserResult<Vec<roles::RoleInfo>> {
- futures::future::try_join_all(user_roles.iter().map(|user_role| async {
- let Some(merchant_id) = &user_role.merchant_id else {
- return Err(report!(UserErrors::InternalServerError))
- .attach_printable("merchant_id not found for user_role");
- };
- let Some(org_id) = &user_role.org_id else {
- return Err(report!(UserErrors::InternalServerError)
- .attach_printable("org_id not found in user_role"));
- };
- let role = roles::RoleInfo::from_role_id(state, &user_role.role_id, merchant_id, org_id)
- .await
- .to_not_found_response(UserErrors::InternalServerError)
- .attach_printable("Role for user role doesn't exist")?;
- Ok::<_, Report<UserErrors>>(role)
- }))
- .await
-}
-
pub async fn update_v1_and_v2_user_roles_in_db(
state: &SessionState,
user_id: &str,
@@ -234,3 +212,38 @@ pub async fn update_v1_and_v2_user_roles_in_db(
(updated_v1_role, updated_v2_role)
}
+
+pub async fn get_single_merchant_id(
+ state: &SessionState,
+ user_role: &UserRole,
+) -> UserResult<id_type::MerchantId> {
+ match user_role.entity_type {
+ Some(EntityType::Organization) => Ok(state
+ .store
+ .list_merchant_accounts_by_organization_id(
+ &state.into(),
+ user_role
+ .org_id
+ .as_ref()
+ .ok_or(UserErrors::InternalServerError)
+ .attach_printable("org_id not found")?
+ .get_string_repr(),
+ )
+ .await
+ .change_context(UserErrors::InternalServerError)
+ .attach_printable("Failed to get merchant list for org")?
+ .first()
+ .ok_or(UserErrors::InternalServerError)
+ .attach_printable("No merchants found for org_id")?
+ .get_id()
+ .clone()),
+ Some(EntityType::Merchant)
+ | Some(EntityType::Internal)
+ | Some(EntityType::Profile)
+ | None => user_role
+ .merchant_id
+ .clone()
+ .ok_or(UserErrors::InternalServerError)
+ .attach_printable("merchant_id not found"),
+ }
+}
diff --git a/postman/collection-dir/users/Flow Testcases/Sign In/.meta.json b/postman/collection-dir/users/Flow Testcases/Sign In/.meta.json
index 84ed2cb9494..75badf2502c 100644
--- a/postman/collection-dir/users/Flow Testcases/Sign In/.meta.json
+++ b/postman/collection-dir/users/Flow Testcases/Sign In/.meta.json
@@ -2,7 +2,7 @@
"childrenOrder": [
"Signin",
"Signin Wrong",
- "Signin Token Only",
- "Signin Token Only Wrong"
+ "Signin V2 - To be deprecated",
+ "Signin V2 Wrong"
]
}
diff --git a/postman/collection-dir/users/Flow Testcases/Sign In/Signin Token Only Wrong/.event.meta.json b/postman/collection-dir/users/Flow Testcases/Sign In/Signin V2 - To be deprecated/.event.meta.json
similarity index 100%
rename from postman/collection-dir/users/Flow Testcases/Sign In/Signin Token Only Wrong/.event.meta.json
rename to postman/collection-dir/users/Flow Testcases/Sign In/Signin V2 - To be deprecated/.event.meta.json
diff --git a/postman/collection-dir/users/Flow Testcases/Sign In/Signin Token Only/event.test.js b/postman/collection-dir/users/Flow Testcases/Sign In/Signin V2 - To be deprecated/event.test.js
similarity index 61%
rename from postman/collection-dir/users/Flow Testcases/Sign In/Signin Token Only/event.test.js
rename to postman/collection-dir/users/Flow Testcases/Sign In/Signin V2 - To be deprecated/event.test.js
index 9105ce122cb..c8d654d21e9 100644
--- a/postman/collection-dir/users/Flow Testcases/Sign In/Signin Token Only/event.test.js
+++ b/postman/collection-dir/users/Flow Testcases/Sign In/Signin V2 - To be deprecated/event.test.js
@@ -1,24 +1,24 @@
console.log("[LOG]::x-request-id - " + pm.response.headers.get("x-request-id"));
// Validate status 2xx
-pm.test("[POST]::user/v2/signin?token_only=true - Status code is 2xx", function () {
+pm.test("[POST]::user/v2/signin - Status code is 2xx", function () {
pm.response.to.be.success;
});
// Validate if response header has matching content-type
-pm.test("[POST]::user/v2/signin?token_only=true - Content-Type is application/json", function () {
+pm.test("[POST]::user/v2/signin - Content-Type is application/json", function () {
pm.expect(pm.response.headers.get("Content-Type")).to.include(
"application/json",
);
});
// Validate if response has JSON Body
-pm.test("[POST]::user/v2/signin?token_only=true - Response has JSON Body", function () {
+pm.test("[POST]::user/v2/signin - Response has JSON Body", function () {
pm.response.to.have.jsonBody();
});
// Validate specific JSON response content
-pm.test("[POST]::user/v2/signin?token_only=true - Response contains token", function () {
+pm.test("[POST]::user/v2/signin - Response contains token", function () {
var jsonData = pm.response.json();
pm.expect(jsonData).to.have.property("token");
pm.expect(jsonData.token).to.be.a("string").and.to.not.be.empty;
diff --git a/postman/collection-dir/users/Flow Testcases/Sign In/Signin Token Only/request.json b/postman/collection-dir/users/Flow Testcases/Sign In/Signin V2 - To be deprecated/request.json
similarity index 75%
rename from postman/collection-dir/users/Flow Testcases/Sign In/Signin Token Only/request.json
rename to postman/collection-dir/users/Flow Testcases/Sign In/Signin V2 - To be deprecated/request.json
index 62028501a50..1d23f6e9652 100644
--- a/postman/collection-dir/users/Flow Testcases/Sign In/Signin Token Only/request.json
+++ b/postman/collection-dir/users/Flow Testcases/Sign In/Signin V2 - To be deprecated/request.json
@@ -18,7 +18,7 @@
}
},
"url": {
- "raw": "{{baseUrl}}/user/v2/signin?token_only=true",
+ "raw": "{{baseUrl}}/user/v2/signin",
"host": [
"{{baseUrl}}"
],
@@ -26,12 +26,6 @@
"user",
"v2",
"signin"
- ],
- "query": [
- {
- "key": "token_only",
- "value": "true"
- }
]
}
}
diff --git a/postman/collection-dir/users/Flow Testcases/Sign In/Signin Token Only Wrong/response.json b/postman/collection-dir/users/Flow Testcases/Sign In/Signin V2 - To be deprecated/response.json
similarity index 100%
rename from postman/collection-dir/users/Flow Testcases/Sign In/Signin Token Only Wrong/response.json
rename to postman/collection-dir/users/Flow Testcases/Sign In/Signin V2 - To be deprecated/response.json
diff --git a/postman/collection-dir/users/Flow Testcases/Sign In/Signin Token Only/.event.meta.json b/postman/collection-dir/users/Flow Testcases/Sign In/Signin V2 Wrong/.event.meta.json
similarity index 100%
rename from postman/collection-dir/users/Flow Testcases/Sign In/Signin Token Only/.event.meta.json
rename to postman/collection-dir/users/Flow Testcases/Sign In/Signin V2 Wrong/.event.meta.json
diff --git a/postman/collection-dir/users/Flow Testcases/Sign In/Signin Token Only Wrong/event.test.js b/postman/collection-dir/users/Flow Testcases/Sign In/Signin V2 Wrong/event.test.js
similarity index 57%
rename from postman/collection-dir/users/Flow Testcases/Sign In/Signin Token Only Wrong/event.test.js
rename to postman/collection-dir/users/Flow Testcases/Sign In/Signin V2 Wrong/event.test.js
index a9297538452..3cc82ebb013 100644
--- a/postman/collection-dir/users/Flow Testcases/Sign In/Signin Token Only Wrong/event.test.js
+++ b/postman/collection-dir/users/Flow Testcases/Sign In/Signin V2 Wrong/event.test.js
@@ -1,18 +1,18 @@
console.log("[LOG]::x-request-id - " + pm.response.headers.get("x-request-id"));
// Validate status 4xx
-pm.test("[POST]::/user/v2/signin?token_only=true - Status code is 401", function () {
+pm.test("[POST]::/user/v2/signin - Status code is 401", function () {
pm.response.to.have.status(401);
});
// Validate if response header has matching content-type
-pm.test("[POST]::user/v2/signin?token_only=true - Content-Type is application/json", function () {
+pm.test("[POST]::user/v2/signin - Content-Type is application/json", function () {
pm.expect(pm.response.headers.get("Content-Type")).to.include(
"application/json",
);
});
// Validate if response has JSON Body
-pm.test("[POST]::user/v2/signin?token_only=true - Response has JSON Body", function () {
+pm.test("[POST]::user/v2/signin - Response has JSON Body", function () {
pm.response.to.have.jsonBody();
});
\ No newline at end of file
diff --git a/postman/collection-dir/users/Flow Testcases/Sign In/Signin Token Only Wrong/request.json b/postman/collection-dir/users/Flow Testcases/Sign In/Signin V2 Wrong/request.json
similarity index 75%
rename from postman/collection-dir/users/Flow Testcases/Sign In/Signin Token Only Wrong/request.json
rename to postman/collection-dir/users/Flow Testcases/Sign In/Signin V2 Wrong/request.json
index 7fee4c465c8..775b0972d57 100644
--- a/postman/collection-dir/users/Flow Testcases/Sign In/Signin Token Only Wrong/request.json
+++ b/postman/collection-dir/users/Flow Testcases/Sign In/Signin V2 Wrong/request.json
@@ -18,7 +18,7 @@
}
},
"url": {
- "raw": "{{baseUrl}}/user/v2/signin?token_only=true",
+ "raw": "{{baseUrl}}/user/v2/signin",
"host": [
"{{baseUrl}}"
],
@@ -26,12 +26,6 @@
"user",
"v2",
"signin"
- ],
- "query": [
- {
- "key": "token_only",
- "value": "true"
- }
]
}
}
diff --git a/postman/collection-dir/users/Flow Testcases/Sign In/Signin Token Only/response.json b/postman/collection-dir/users/Flow Testcases/Sign In/Signin V2 Wrong/response.json
similarity index 100%
rename from postman/collection-dir/users/Flow Testcases/Sign In/Signin Token Only/response.json
rename to postman/collection-dir/users/Flow Testcases/Sign In/Signin V2 Wrong/response.json
diff --git a/postman/collection-dir/users/Flow Testcases/Sign In/Signin Wrong/event.test.js b/postman/collection-dir/users/Flow Testcases/Sign In/Signin Wrong/event.test.js
index 6cb6b69ba6c..bd346bc0cb3 100644
--- a/postman/collection-dir/users/Flow Testcases/Sign In/Signin Wrong/event.test.js
+++ b/postman/collection-dir/users/Flow Testcases/Sign In/Signin Wrong/event.test.js
@@ -1,18 +1,18 @@
console.log("[LOG]::x-request-id - " + pm.response.headers.get("x-request-id"));
// Validate status code is 4xx Bad Request
-pm.test("[POST]::/user/v2/signin - Status code is 401", function () {
+pm.test("[POST]::/user/signin - Status code is 401", function () {
pm.response.to.have.status(401);
});
// Validate if response header has matching content-type
-pm.test("[POST]::/user/v2/signin - Content-Type is application/json", function () {
+pm.test("[POST]::/user/signin - Content-Type is application/json", function () {
pm.expect(pm.response.headers.get("Content-Type")).to.include(
"application/json",
);
});
// Validate if response has JSON Body
-pm.test("[POST]::/user/v2/signin - Response has JSON Body", function () {
+pm.test("[POST]::/user/signin - Response has JSON Body", function () {
pm.response.to.have.jsonBody();
});
\ No newline at end of file
diff --git a/postman/collection-dir/users/Flow Testcases/Sign In/Signin Wrong/request.json b/postman/collection-dir/users/Flow Testcases/Sign In/Signin Wrong/request.json
index 775b0972d57..0cd97ee6de1 100644
--- a/postman/collection-dir/users/Flow Testcases/Sign In/Signin Wrong/request.json
+++ b/postman/collection-dir/users/Flow Testcases/Sign In/Signin Wrong/request.json
@@ -18,13 +18,12 @@
}
},
"url": {
- "raw": "{{baseUrl}}/user/v2/signin",
+ "raw": "{{baseUrl}}/user/signin",
"host": [
"{{baseUrl}}"
],
"path": [
"user",
- "v2",
"signin"
]
}
diff --git a/postman/collection-dir/users/Flow Testcases/Sign In/Signin/event.test.js b/postman/collection-dir/users/Flow Testcases/Sign In/Signin/event.test.js
index 4724ff5981f..23dc84eb8a9 100644
--- a/postman/collection-dir/users/Flow Testcases/Sign In/Signin/event.test.js
+++ b/postman/collection-dir/users/Flow Testcases/Sign In/Signin/event.test.js
@@ -1,24 +1,24 @@
console.log("[LOG]::x-request-id - " + pm.response.headers.get("x-request-id"));
// Validate status 2xx
-pm.test("[POST]::/user/v2/signin - Status code is 2xx", function () {
+pm.test("[POST]::/user/signin - Status code is 2xx", function () {
pm.response.to.be.success;
});
// Validate if response header has matching content-type
-pm.test("[POST]::/user/v2/signin - Content-Type is application/json", function () {
+pm.test("[POST]::/user/signin - Content-Type is application/json", function () {
pm.expect(pm.response.headers.get("Content-Type")).to.include(
"application/json",
);
});
// Validate if response has JSON Body
-pm.test("[POST]::/user/v2/signin - Response has JSON Body", function () {
+pm.test("[POST]::/user/signin - Response has JSON Body", function () {
pm.response.to.have.jsonBody();
});
// Validate specific JSON response content
-pm.test("[POST]::/user/v2/signin - Response contains token", function () {
+pm.test("[POST]::/user/signin - Response contains token", function () {
var jsonData = pm.response.json();
pm.expect(jsonData).to.have.property("token");
pm.expect(jsonData.token).to.be.a("string").and.to.not.be.empty;
diff --git a/postman/collection-dir/users/Flow Testcases/Sign In/Signin/request.json b/postman/collection-dir/users/Flow Testcases/Sign In/Signin/request.json
index 1d23f6e9652..17f0eccff36 100644
--- a/postman/collection-dir/users/Flow Testcases/Sign In/Signin/request.json
+++ b/postman/collection-dir/users/Flow Testcases/Sign In/Signin/request.json
@@ -18,13 +18,12 @@
}
},
"url": {
- "raw": "{{baseUrl}}/user/v2/signin",
+ "raw": "{{baseUrl}}/user/signin",
"host": [
"{{baseUrl}}"
],
"path": [
"user",
- "v2",
"signin"
]
}
diff --git a/postman/collection-json/users.postman_collection.json b/postman/collection-json/users.postman_collection.json
index 142eaf3b232..ac6ee2f8cb0 100644
--- a/postman/collection-json/users.postman_collection.json
+++ b/postman/collection-json/users.postman_collection.json
@@ -1,567 +1,553 @@
{
- "event": [
- {
- "listen": "prerequest",
- "script": {
- "exec": [
- ""
- ],
- "type": "text/javascript"
- }
- },
- {
- "listen": "test",
- "script": {
- "exec": [
- ""
- ],
- "type": "text/javascript"
- }
- }
- ],
- "item": [
- {
- "name": "Health check",
- "item": [
- {
- "name": "New Request",
- "event": [
- {
- "listen": "test",
- "script": {
- "exec": [
- "// Validate status 2xx",
- "pm.test(\"[POST]::/health - Status code is 2xx\", function () {",
- " pm.response.to.be.success;",
- "});",
- ""
- ],
- "type": "text/javascript"
- }
- }
- ],
- "request": {
- "method": "GET",
- "header": [],
- "url": {
- "raw": "{{baseUrl}}/health",
- "host": [
- "{{baseUrl}}"
- ],
- "path": [
- "health"
- ]
- }
- },
- "response": []
- }
- ]
- },
- {
- "name": "Flow Testcases",
- "item": [
- {
- "name": "Sign Up",
- "item": [
- {
- "name": "Connect Account",
- "event": [
- {
- "listen": "test",
- "script": {
- "exec": [
- "console.log(\"[LOG]::x-request-id - \" + pm.response.headers.get(\"x-request-id\"));",
- "",
- "// Validate status 2xx",
- "pm.test(\"[POST]::/user/connect_account - Status code is 2xx\", function () {",
- " pm.response.to.be.success;",
- "});",
- "",
- "// Validate if response header has matching content-type",
- "pm.test(\"[POST]::/user/connect_account - Content-Type is application/json\", function () {",
- " pm.expect(pm.response.headers.get(\"Content-Type\")).to.include(",
- " \"application/json\",",
- " );",
- "});",
- "",
- "// Validate if response has JSON Body",
- "pm.test(\"[POST]::/user/connect_account - Response has JSON Body\", function () {",
- " pm.response.to.have.jsonBody();",
- "});",
- "",
- "// Validate specific JSON response content",
- "pm.test(\"[POST]::/user/connect_account - Response contains is_email_sent\", function () {",
- " var jsonData = pm.response.json();",
- " pm.expect(jsonData).to.have.property(\"is_email_sent\");",
- " pm.expect(jsonData.is_email_sent).to.be.true;",
- "});",
- "",
- ""
- ],
- "type": "text/javascript"
- }
- },
- {
- "listen": "prerequest",
- "script": {
- "exec": [
- "",
- "var baseEmail = pm.environment.get('user_base_email_for_signup');",
- "var emailDomain = pm.environment.get(\"user_domain_for_signup\");",
- "",
- "// Generate a unique email address",
- "var uniqueEmail = baseEmail + new Date().getTime() + emailDomain;",
- "// Set the unique email address as an environment variable",
- "pm.environment.set('unique_email', uniqueEmail);",
- ""
- ],
- "type": "text/javascript"
- }
- }
- ],
- "request": {
- "method": "POST",
- "header": [
- {
- "key": "Content-Type",
- "value": "application/json"
- },
- {
- "key": "Cookie",
- "value": "Cookie_1=value"
- }
- ],
- "body": {
- "mode": "raw",
- "raw": "{\"email\":\"{{unique_email}}\"}"
- },
- "url": {
- "raw": "{{baseUrl}}/user/connect_account",
- "host": [
- "{{baseUrl}}"
- ],
- "path": [
- "user",
- "connect_account"
- ]
- }
- },
- "response": []
- }
- ]
- },
- {
- "name": "Sign In",
- "item": [
- {
- "name": "Signin",
- "event": [
- {
- "listen": "test",
- "script": {
- "exec": [
- "console.log(\"[LOG]::x-request-id - \" + pm.response.headers.get(\"x-request-id\"));",
- "",
- "// Validate status 2xx",
- "pm.test(\"[POST]::/user/v2/signin - Status code is 2xx\", function () {",
- " pm.response.to.be.success;",
- "});",
- "",
- "// Validate if response header has matching content-type",
- "pm.test(\"[POST]::/user/v2/signin - Content-Type is application/json\", function () {",
- " pm.expect(pm.response.headers.get(\"Content-Type\")).to.include(",
- " \"application/json\",",
- " );",
- "});",
- "",
- "// Validate if response has JSON Body",
- "pm.test(\"[POST]::/user/v2/signin - Response has JSON Body\", function () {",
- " pm.response.to.have.jsonBody();",
- "});",
- "",
- "// Validate specific JSON response content",
- "pm.test(\"[POST]::/user/v2/signin - Response contains token\", function () {",
- " var jsonData = pm.response.json();",
- " pm.expect(jsonData).to.have.property(\"token\");",
- " pm.expect(jsonData.token).to.be.a(\"string\").and.to.not.be.empty;",
- "});"
- ],
- "type": "text/javascript"
- }
- },
- {
- "listen": "prerequest",
- "script": {
- "exec": [
- ""
- ],
- "type": "text/javascript"
- }
- }
- ],
- "request": {
- "method": "POST",
- "header": [
- {
- "key": "Content-Type",
- "value": "application/json"
- },
- {
- "key": "Cookie",
- "value": "Cookie_1=value"
- }
- ],
- "body": {
- "mode": "raw",
- "raw": "{\"email\":\"{{user_email}}\",\"password\":\"{{user_password}}\"}"
- },
- "url": {
- "raw": "{{baseUrl}}/user/v2/signin",
- "host": [
- "{{baseUrl}}"
- ],
- "path": [
- "user",
- "v2",
- "signin"
- ]
- }
- },
- "response": []
- },
- {
- "name": "Signin Wrong",
- "event": [
- {
- "listen": "test",
- "script": {
- "exec": [
- "console.log(\"[LOG]::x-request-id - \" + pm.response.headers.get(\"x-request-id\"));",
- "",
- "// Validate status code is 4xx Bad Request",
- "pm.test(\"[POST]::/user/v2/signin - Status code is 401\", function () {",
- " pm.response.to.have.status(401);",
- "});",
- "",
- "// Validate if response header has matching content-type",
- "pm.test(\"[POST]::/user/v2/signin - Content-Type is application/json\", function () {",
- " pm.expect(pm.response.headers.get(\"Content-Type\")).to.include(",
- " \"application/json\",",
- " );",
- "});",
- "",
- "// Validate if response has JSON Body",
- "pm.test(\"[POST]::/user/v2/signin - Response has JSON Body\", function () {",
- " pm.response.to.have.jsonBody();",
- "});"
- ],
- "type": "text/javascript"
- }
- }
- ],
- "request": {
- "method": "POST",
- "header": [
- {
- "key": "Content-Type",
- "value": "application/json"
- },
- {
- "key": "Cookie",
- "value": "Cookie_1=value"
- }
- ],
- "body": {
- "mode": "raw",
- "raw": "{\"email\":\"{{user_email}}\",\"password\":\"{{wrong_password}}\"}"
- },
- "url": {
- "raw": "{{baseUrl}}/user/v2/signin",
- "host": [
- "{{baseUrl}}"
- ],
- "path": [
- "user",
- "v2",
- "signin"
- ]
- }
- },
- "response": []
- },
- {
- "name": "Signin Token Only",
- "event": [
- {
- "listen": "test",
- "script": {
- "exec": [
- "console.log(\"[LOG]::x-request-id - \" + pm.response.headers.get(\"x-request-id\"));",
- "",
- "// Validate status 2xx",
- "pm.test(\"[POST]::user/v2/signin?token_only=true - Status code is 2xx\", function () {",
- " pm.response.to.be.success;",
- "});",
- "",
- "// Validate if response header has matching content-type",
- "pm.test(\"[POST]::user/v2/signin?token_only=true - Content-Type is application/json\", function () {",
- " pm.expect(pm.response.headers.get(\"Content-Type\")).to.include(",
- " \"application/json\",",
- " );",
- "});",
- "",
- "// Validate if response has JSON Body",
- "pm.test(\"[POST]::user/v2/signin?token_only=true - Response has JSON Body\", function () {",
- " pm.response.to.have.jsonBody();",
- "});",
- "",
- "// Validate specific JSON response content",
- "pm.test(\"[POST]::user/v2/signin?token_only=true - Response contains token\", function () {",
- " var jsonData = pm.response.json();",
- " pm.expect(jsonData).to.have.property(\"token\");",
- " pm.expect(jsonData.token).to.be.a(\"string\").and.to.not.be.empty;",
- "});"
- ],
- "type": "text/javascript"
- }
- }
- ],
- "request": {
- "method": "POST",
- "header": [
- {
- "key": "Content-Type",
- "value": "application/json"
- },
- {
- "key": "Cookie",
- "value": "Cookie_1=value"
- }
- ],
- "body": {
- "mode": "raw",
- "raw": "{\"email\":\"{{user_email}}\",\"password\":\"{{user_password}}\"}"
- },
- "url": {
- "raw": "{{baseUrl}}/user/v2/signin?token_only=true",
- "host": [
- "{{baseUrl}}"
- ],
- "path": [
- "user",
- "v2",
- "signin"
- ],
- "query": [
- {
- "key": "token_only",
- "value": "true"
- }
- ]
- }
- },
- "response": []
- },
- {
- "name": "Signin Token Only Wrong",
- "event": [
- {
- "listen": "test",
- "script": {
- "exec": [
- "console.log(\"[LOG]::x-request-id - \" + pm.response.headers.get(\"x-request-id\"));",
- "",
- "// Validate status 4xx",
- "pm.test(\"[POST]::/user/v2/signin?token_only=true - Status code is 401\", function () {",
- " pm.response.to.have.status(401);",
- "});",
- "",
- "// Validate if response header has matching content-type",
- "pm.test(\"[POST]::user/v2/signin?token_only=true - Content-Type is application/json\", function () {",
- " pm.expect(pm.response.headers.get(\"Content-Type\")).to.include(",
- " \"application/json\",",
- " );",
- "});",
- "",
- "// Validate if response has JSON Body",
- "pm.test(\"[POST]::user/v2/signin?token_only=true - Response has JSON Body\", function () {",
- " pm.response.to.have.jsonBody();",
- "});"
- ],
- "type": "text/javascript"
- }
- }
- ],
- "request": {
- "method": "POST",
- "header": [
- {
- "key": "Content-Type",
- "value": "application/json"
- },
- {
- "key": "Cookie",
- "value": "Cookie_1=value"
- }
- ],
- "body": {
- "mode": "raw",
- "raw": "{\"email\":\"{{user_email}}\",\"password\":\"{{wrong_password}}\"}"
- },
- "url": {
- "raw": "{{baseUrl}}/user/v2/signin?token_only=true",
- "host": [
- "{{baseUrl}}"
- ],
- "path": [
- "user",
- "v2",
- "signin"
- ],
- "query": [
- {
- "key": "token_only",
- "value": "true"
- }
- ]
- }
- },
- "response": []
- }
- ]
- }
- ]
- }
- ],
- "info": {
- "_postman_id": "b5b40c9a-7e58-42c7-8b89-0adb208c45c9",
- "name": "users",
- "description": "## Get started\n\nJuspay Router provides a collection of APIs that enable you to process and manage payments. Our APIs accept and return JSON in the HTTP body, and return standard HTTP response codes. \nYou can consume the APIs directly using your favorite HTTP/REST library. \nWe have a testing environment referred to \"sandbox\", which you can setup to test API calls without affecting production data.\n\n### Base URLs\n\nUse the following base URLs when making requests to the APIs:\n\n| Environment | Base URL |\n| --- | --- |\n| Sandbox | [https://sandbox.hyperswitch.io](https://sandbox.hyperswitch.io) |\n| Production | [https://router.juspay.io](https://router.juspay.io) |\n\n# Authentication\n\nWhen you sign up for an account, you are given a secret key (also referred as api-key). You may authenticate all API requests with Juspay server by providing the appropriate key in the request Authorization header. \nNever share your secret api keys. Keep them guarded and secure.\n\nContact Support: \nName: Juspay Support \nEmail: [support@juspay.in](mailto:support@juspay.in)",
- "schema": "https://schema.getpostman.com/json/collection/v2.1.0/collection.json",
- "_exporter_id": "26710321"
- },
- "variable": [
- {
- "key": "baseUrl",
- "value": "",
- "type": "string"
- },
- {
- "key": "admin_api_key",
- "value": "",
- "type": "string"
- },
- {
- "key": "api_key",
- "value": "",
- "type": "string"
- },
- {
- "key": "merchant_id",
- "value": ""
- },
- {
- "key": "payment_id",
- "value": ""
- },
- {
- "key": "customer_id",
- "value": ""
- },
- {
- "key": "mandate_id",
- "value": ""
- },
- {
- "key": "payment_method_id",
- "value": ""
- },
- {
- "key": "refund_id",
- "value": ""
- },
- {
- "key": "merchant_connector_id",
- "value": ""
- },
- {
- "key": "client_secret",
- "value": "",
- "type": "string"
- },
- {
- "key": "connector_api_key",
- "value": "",
- "type": "string"
- },
- {
- "key": "publishable_key",
- "value": "",
- "type": "string"
- },
- {
- "key": "api_key_id",
- "value": "",
- "type": "string"
- },
- {
- "key": "payment_token",
- "value": ""
- },
- {
- "key": "gateway_merchant_id",
- "value": "",
- "type": "string"
- },
- {
- "key": "certificate",
- "value": "",
- "type": "string"
- },
- {
- "key": "certificate_keys",
- "value": "",
- "type": "string"
- },
- {
- "key": "connector_api_secret",
- "value": "",
- "type": "string"
- },
- {
- "key": "connector_key1",
- "value": "",
- "type": "string"
- },
- {
- "key": "connector_key2",
- "value": "",
- "type": "string"
- },
- {
- "key": "user_email",
- "value": "",
- "type": "string"
- },
- {
- "key": "user_password",
- "value": "",
- "type": "string"
- },
- {
- "key": "wrong_password",
- "value": "",
- "type": "string"
- },
- {
- "key": "user_base_email_for_signup",
- "value": "",
- "type": "string"
- },
- {
- "key": "user_domain_for_signup",
- "value": "",
- "type": "string"
- }
- ]
-}
+ "info": {
+ "_postman_id": "b5b40c9a-7e58-42c7-8b89-0adb208c45c9",
+ "name": "users",
+ "description": "## Get started\n\nJuspay Router provides a collection of APIs that enable you to process and manage payments. Our APIs accept and return JSON in the HTTP body, and return standard HTTP response codes. \nYou can consume the APIs directly using your favorite HTTP/REST library. \nWe have a testing environment referred to \"sandbox\", which you can setup to test API calls without affecting production data.\n\n### Base URLs\n\nUse the following base URLs when making requests to the APIs:\n\n| Environment | Base URL |\n| --- | --- |\n| Sandbox | [https://sandbox.hyperswitch.io](https://sandbox.hyperswitch.io) |\n| Production | [https://router.juspay.io](https://router.juspay.io) |\n\n# Authentication\n\nWhen you sign up for an account, you are given a secret key (also referred as api-key). You may authenticate all API requests with Juspay server by providing the appropriate key in the request Authorization header. \nNever share your secret api keys. Keep them guarded and secure.\n\nContact Support: \nName: Juspay Support \nEmail: [support@juspay.in](mailto:support@juspay.in)",
+ "schema": "https://schema.getpostman.com/json/collection/v2.1.0/collection.json",
+ "_exporter_id": "26710321"
+ },
+ "item": [
+ {
+ "name": "Health check",
+ "item": [
+ {
+ "name": "New Request",
+ "event": [
+ {
+ "listen": "test",
+ "script": {
+ "exec": [
+ "// Validate status 2xx",
+ "pm.test(\"[POST]::/health - Status code is 2xx\", function () {",
+ " pm.response.to.be.success;",
+ "});",
+ ""
+ ],
+ "type": "text/javascript"
+ }
+ }
+ ],
+ "request": {
+ "method": "GET",
+ "header": [],
+ "url": {
+ "raw": "{{baseUrl}}/health",
+ "host": [
+ "{{baseUrl}}"
+ ],
+ "path": [
+ "health"
+ ]
+ }
+ },
+ "response": []
+ }
+ ]
+ },
+ {
+ "name": "Flow Testcases",
+ "item": [
+ {
+ "name": "Sign Up",
+ "item": [
+ {
+ "name": "Connect Account",
+ "event": [
+ {
+ "listen": "test",
+ "script": {
+ "exec": [
+ "console.log(\"[LOG]::x-request-id - \" + pm.response.headers.get(\"x-request-id\"));",
+ "",
+ "// Validate status 2xx",
+ "pm.test(\"[POST]::/user/connect_account - Status code is 2xx\", function () {",
+ " pm.response.to.be.success;",
+ "});",
+ "",
+ "// Validate if response header has matching content-type",
+ "pm.test(\"[POST]::/user/connect_account - Content-Type is application/json\", function () {",
+ " pm.expect(pm.response.headers.get(\"Content-Type\")).to.include(",
+ " \"application/json\",",
+ " );",
+ "});",
+ "",
+ "// Validate if response has JSON Body",
+ "pm.test(\"[POST]::/user/connect_account - Response has JSON Body\", function () {",
+ " pm.response.to.have.jsonBody();",
+ "});",
+ "",
+ "// Validate specific JSON response content",
+ "pm.test(\"[POST]::/user/connect_account - Response contains is_email_sent\", function () {",
+ " var jsonData = pm.response.json();",
+ " pm.expect(jsonData).to.have.property(\"is_email_sent\");",
+ " pm.expect(jsonData.is_email_sent).to.be.true;",
+ "});",
+ "",
+ ""
+ ],
+ "type": "text/javascript"
+ }
+ },
+ {
+ "listen": "prerequest",
+ "script": {
+ "exec": [
+ "",
+ "var baseEmail = pm.environment.get('user_base_email_for_signup');",
+ "var emailDomain = pm.environment.get(\"user_domain_for_signup\");",
+ "",
+ "// Generate a unique email address",
+ "var uniqueEmail = baseEmail + new Date().getTime() + emailDomain;",
+ "// Set the unique email address as an environment variable",
+ "pm.environment.set('unique_email', uniqueEmail);",
+ ""
+ ],
+ "type": "text/javascript"
+ }
+ }
+ ],
+ "request": {
+ "method": "POST",
+ "header": [
+ {
+ "key": "Content-Type",
+ "value": "application/json"
+ },
+ {
+ "key": "Cookie",
+ "value": "Cookie_1=value"
+ }
+ ],
+ "body": {
+ "mode": "raw",
+ "raw": "{\n \"email\": \"{{unique_email}}\"\n}"
+ },
+ "url": {
+ "raw": "{{baseUrl}}/user/connect_account",
+ "host": [
+ "{{baseUrl}}"
+ ],
+ "path": [
+ "user",
+ "connect_account"
+ ]
+ }
+ },
+ "response": []
+ }
+ ]
+ },
+ {
+ "name": "Sign In",
+ "item": [
+ {
+ "name": "Signin",
+ "event": [
+ {
+ "listen": "test",
+ "script": {
+ "exec": [
+ "console.log(\"[LOG]::x-request-id - \" + pm.response.headers.get(\"x-request-id\"));",
+ "",
+ "// Validate status 2xx",
+ "pm.test(\"[POST]::/user/signin - Status code is 2xx\", function () {",
+ " pm.response.to.be.success;",
+ "});",
+ "",
+ "// Validate if response header has matching content-type",
+ "pm.test(\"[POST]::/user/signin - Content-Type is application/json\", function () {",
+ " pm.expect(pm.response.headers.get(\"Content-Type\")).to.include(",
+ " \"application/json\",",
+ " );",
+ "});",
+ "",
+ "// Validate if response has JSON Body",
+ "pm.test(\"[POST]::/user/signin - Response has JSON Body\", function () {",
+ " pm.response.to.have.jsonBody();",
+ "});",
+ "",
+ "// Validate specific JSON response content",
+ "pm.test(\"[POST]::/user/signin - Response contains token\", function () {",
+ " var jsonData = pm.response.json();",
+ " pm.expect(jsonData).to.have.property(\"token\");",
+ " pm.expect(jsonData.token).to.be.a(\"string\").and.to.not.be.empty;",
+ "});"
+ ],
+ "type": "text/javascript"
+ }
+ },
+ {
+ "listen": "prerequest",
+ "script": {
+ "exec": [
+ ""
+ ],
+ "type": "text/javascript"
+ }
+ }
+ ],
+ "request": {
+ "method": "POST",
+ "header": [
+ {
+ "key": "Content-Type",
+ "value": "application/json"
+ },
+ {
+ "key": "Cookie",
+ "value": "Cookie_1=value"
+ }
+ ],
+ "body": {
+ "mode": "raw",
+ "raw": "{\n \"email\": \"{{user_email}}\",\n \"password\": \"{{user_password}}\"\n}"
+ },
+ "url": {
+ "raw": "{{baseUrl}}/user/signin",
+ "host": [
+ "{{baseUrl}}"
+ ],
+ "path": [
+ "user",
+ "signin"
+ ]
+ }
+ },
+ "response": []
+ },
+ {
+ "name": "Signin Wrong",
+ "event": [
+ {
+ "listen": "test",
+ "script": {
+ "exec": [
+ "console.log(\"[LOG]::x-request-id - \" + pm.response.headers.get(\"x-request-id\"));",
+ "",
+ "// Validate status code is 4xx Bad Request",
+ "pm.test(\"[POST]::/user/signin - Status code is 401\", function () {",
+ " pm.response.to.have.status(401);",
+ "});",
+ "",
+ "// Validate if response header has matching content-type",
+ "pm.test(\"[POST]::/user/signin - Content-Type is application/json\", function () {",
+ " pm.expect(pm.response.headers.get(\"Content-Type\")).to.include(",
+ " \"application/json\",",
+ " );",
+ "});",
+ "",
+ "// Validate if response has JSON Body",
+ "pm.test(\"[POST]::/user/signin - Response has JSON Body\", function () {",
+ " pm.response.to.have.jsonBody();",
+ "});"
+ ],
+ "type": "text/javascript"
+ }
+ }
+ ],
+ "request": {
+ "method": "POST",
+ "header": [
+ {
+ "key": "Content-Type",
+ "value": "application/json"
+ },
+ {
+ "key": "Cookie",
+ "value": "Cookie_1=value"
+ }
+ ],
+ "body": {
+ "mode": "raw",
+ "raw": "{\n \"email\": \"{{user_email}}\",\n \"password\": \"{{wrong_password}}\"\n}"
+ },
+ "url": {
+ "raw": "{{baseUrl}}/user/signin",
+ "host": [
+ "{{baseUrl}}"
+ ],
+ "path": [
+ "user",
+ "signin"
+ ]
+ }
+ },
+ "response": []
+ },
+ {
+ "name": "Signin V2 - To be deprecated",
+ "event": [
+ {
+ "listen": "test",
+ "script": {
+ "exec": [
+ "console.log(\"[LOG]::x-request-id - \" + pm.response.headers.get(\"x-request-id\"));",
+ "",
+ "// Validate status 2xx",
+ "pm.test(\"[POST]::user/v2/signin - Status code is 2xx\", function () {",
+ " pm.response.to.be.success;",
+ "});",
+ "",
+ "// Validate if response header has matching content-type",
+ "pm.test(\"[POST]::user/v2/signin - Content-Type is application/json\", function () {",
+ " pm.expect(pm.response.headers.get(\"Content-Type\")).to.include(",
+ " \"application/json\",",
+ " );",
+ "});",
+ "",
+ "// Validate if response has JSON Body",
+ "pm.test(\"[POST]::user/v2/signin - Response has JSON Body\", function () {",
+ " pm.response.to.have.jsonBody();",
+ "});",
+ "",
+ "// Validate specific JSON response content",
+ "pm.test(\"[POST]::user/v2/signin - Response contains token\", function () {",
+ " var jsonData = pm.response.json();",
+ " pm.expect(jsonData).to.have.property(\"token\");",
+ " pm.expect(jsonData.token).to.be.a(\"string\").and.to.not.be.empty;",
+ "});"
+ ],
+ "type": "text/javascript"
+ }
+ }
+ ],
+ "request": {
+ "method": "POST",
+ "header": [
+ {
+ "key": "Content-Type",
+ "value": "application/json"
+ },
+ {
+ "key": "Cookie",
+ "value": "Cookie_1=value"
+ }
+ ],
+ "body": {
+ "mode": "raw",
+ "raw": "{\n \"email\": \"{{user_email}}\",\n \"password\": \"{{user_password}}\" \n}"
+ },
+ "url": {
+ "raw": "{{baseUrl}}/user/v2/signin",
+ "host": [
+ "{{baseUrl}}"
+ ],
+ "path": [
+ "user",
+ "v2",
+ "signin"
+ ]
+ }
+ },
+ "response": []
+ },
+ {
+ "name": "Signin V2 Wrong",
+ "event": [
+ {
+ "listen": "test",
+ "script": {
+ "exec": [
+ "console.log(\"[LOG]::x-request-id - \" + pm.response.headers.get(\"x-request-id\"));",
+ "",
+ "// Validate status 4xx",
+ "pm.test(\"[POST]::/user/v2/signin - Status code is 401\", function () {",
+ " pm.response.to.have.status(401);",
+ "});",
+ "",
+ "// Validate if response header has matching content-type",
+ "pm.test(\"[POST]::user/v2/signin - Content-Type is application/json\", function () {",
+ " pm.expect(pm.response.headers.get(\"Content-Type\")).to.include(",
+ " \"application/json\",",
+ " );",
+ "});",
+ "",
+ "// Validate if response has JSON Body",
+ "pm.test(\"[POST]::user/v2/signin - Response has JSON Body\", function () {",
+ " pm.response.to.have.jsonBody();",
+ "});"
+ ],
+ "type": "text/javascript"
+ }
+ }
+ ],
+ "request": {
+ "method": "POST",
+ "header": [
+ {
+ "key": "Content-Type",
+ "value": "application/json"
+ },
+ {
+ "key": "Cookie",
+ "value": "Cookie_1=value"
+ }
+ ],
+ "body": {
+ "mode": "raw",
+ "raw": "{\n \"email\": \"{{user_email}}\",\n \"password\": \"{{wrong_password}}\" \n}"
+ },
+ "url": {
+ "raw": "{{baseUrl}}/user/v2/signin",
+ "host": [
+ "{{baseUrl}}"
+ ],
+ "path": [
+ "user",
+ "v2",
+ "signin"
+ ]
+ }
+ },
+ "response": []
+ }
+ ]
+ }
+ ]
+ }
+ ],
+ "event": [
+ {
+ "listen": "prerequest",
+ "script": {
+ "type": "text/javascript",
+ "exec": [
+ ""
+ ]
+ }
+ },
+ {
+ "listen": "test",
+ "script": {
+ "type": "text/javascript",
+ "exec": [
+ ""
+ ]
+ }
+ }
+ ],
+ "variable": [
+ {
+ "key": "baseUrl",
+ "value": "",
+ "type": "string"
+ },
+ {
+ "key": "admin_api_key",
+ "value": "",
+ "type": "string"
+ },
+ {
+ "key": "api_key",
+ "value": "",
+ "type": "string"
+ },
+ {
+ "key": "merchant_id",
+ "value": ""
+ },
+ {
+ "key": "payment_id",
+ "value": ""
+ },
+ {
+ "key": "customer_id",
+ "value": ""
+ },
+ {
+ "key": "mandate_id",
+ "value": ""
+ },
+ {
+ "key": "payment_method_id",
+ "value": ""
+ },
+ {
+ "key": "refund_id",
+ "value": ""
+ },
+ {
+ "key": "merchant_connector_id",
+ "value": ""
+ },
+ {
+ "key": "client_secret",
+ "value": "",
+ "type": "string"
+ },
+ {
+ "key": "connector_api_key",
+ "value": "",
+ "type": "string"
+ },
+ {
+ "key": "publishable_key",
+ "value": "",
+ "type": "string"
+ },
+ {
+ "key": "api_key_id",
+ "value": "",
+ "type": "string"
+ },
+ {
+ "key": "payment_token",
+ "value": ""
+ },
+ {
+ "key": "gateway_merchant_id",
+ "value": "",
+ "type": "string"
+ },
+ {
+ "key": "certificate",
+ "value": "",
+ "type": "string"
+ },
+ {
+ "key": "certificate_keys",
+ "value": "",
+ "type": "string"
+ },
+ {
+ "key": "connector_api_secret",
+ "value": "",
+ "type": "string"
+ },
+ {
+ "key": "connector_key1",
+ "value": "",
+ "type": "string"
+ },
+ {
+ "key": "connector_key2",
+ "value": "",
+ "type": "string"
+ },
+ {
+ "key": "user_email",
+ "value": "",
+ "type": "string"
+ },
+ {
+ "key": "user_password",
+ "value": "",
+ "type": "string"
+ },
+ {
+ "key": "wrong_password",
+ "value": "",
+ "type": "string"
+ },
+ {
+ "key": "user_base_email_for_signup",
+ "value": "",
+ "type": "string"
+ },
+ {
+ "key": "user_domain_for_signup",
+ "value": "",
+ "type": "string"
+ }
+ ]
+}
\ No newline at end of file
|
2024-08-31T09:14:39Z
|
## Type of Change
<!-- Put an `x` in the boxes that apply -->
- [ ] Bugfix
- [ ] New feature
- [ ] Enhancement
- [x] Refactoring
- [ ] Dependency updates
- [ ] Documentation
- [ ] CI/CD
## Description
<!-- Describe your changes in detail -->
- Deprecate all the APIs which are used when `is_token_only` and `groups` query params are false.
- Add logic to get merchant_id from the db if not found in user_role.
### Additional Changes
- [x] This PR modifies the API contract
- [ ] This PR modifies the database schema
- [ ] This PR modifies application configuration/environment variables
<!--
Provide links to the files with corresponding changes.
Following are the paths where you can find config files:
1. `config`
2. `crates/router/src/configs`
3. `loadtest/config`
-->
## Motivation and Context
<!--
Why is this change required? What problem does it solve?
If it fixes an open issue, please link to the issue here.
If you don't have an issue, we'd recommend starting with one first so the PR
can focus on the implementation (unless it is an obvious bug or documentation fix
that will have little conversation).
-->
Closes #5761.
Closes #5762.
## How did you test it?
<!--
Did you write an integration/unit/API test to verify the code changes?
Or did you test this change manually (provide relevant screenshots)?
-->
From the following endpoints, `token_only` query parameter is removed.
- `/v2/signin`
- `/reset_password`
- `/v2/verify_email`
- `/accept_invite_from_email`
- `/invite/accept` - Post only
All the above APIs will give the following response.
```
{
"token": "JWT",
"token_type": "type"
}
```
From the following endpoints, `groups` query parameter is removed.
- `/role` - Get only
- `/role/list`
- `/role/{role_id}` - Get only
They will always respond with groups from now on.
2 new APIs are added.
```
curl --location 'http://localhost:8080/user/signin' \
--header 'Content-Type: application/json' \
--data-raw '{
"email": "email",
"password": "password"
}
'
```
```
curl --location 'http://localhost:8080/user/verify_email' \
--header 'Content-Type: application/json' \
--header 'Authorization: ••••••' \
--data '{
"token": "email token"
}'
```
Both will give the following response if hit correctly.
```
{
"token": "JWT",
"token_type": "type"
}
```
## Checklist
<!-- Put an `x` in the boxes that apply -->
- [x] I formatted the code `cargo +nightly fmt --all`
- [x] I addressed lints thrown by `cargo clippy`
- [x] I reviewed the submitted code
- [ ] I added unit tests for my changes where possible
|
f7f5ba7c0bbf694dbeecec73f8383ac678dd4425
|
|
juspay/hyperswitch
|
juspay__hyperswitch-5761
|
Bug: refactor(users): Deprecate unused APIs
For backwards compatibility, BE will not remove old APIs when adding new APIs.
We have to deprecate the APIs which are kept for backwards compatibility. This will make BE changes easier for user management changes.
These APIs include:
- All the APIs which are having `is_token_only` and `groups` query param. The false version of these APIs are not in use.
|
diff --git a/crates/api_models/src/events/user.rs b/crates/api_models/src/events/user.rs
index 590179c052c..8d1ae60b325 100644
--- a/crates/api_models/src/events/user.rs
+++ b/crates/api_models/src/events/user.rs
@@ -16,11 +16,11 @@ use crate::user::{
GetSsoAuthUrlRequest, GetUserAuthenticationMethodsRequest, GetUserDetailsResponse,
GetUserRoleDetailsRequest, GetUserRoleDetailsResponse, InviteUserRequest, ListUsersResponse,
ReInviteUserRequest, RecoveryCodes, ResetPasswordRequest, RotatePasswordRequest,
- SendVerifyEmailRequest, SignInResponse, SignUpRequest, SignUpWithMerchantIdRequest,
- SsoSignInRequest, SwitchMerchantRequest, SwitchOrganizationRequest, SwitchProfileRequest,
- TokenOrPayloadResponse, TokenResponse, TwoFactorAuthStatusResponse,
- UpdateUserAccountDetailsRequest, UpdateUserAuthenticationMethodRequest, UserFromEmailRequest,
- UserMerchantCreate, VerifyEmailRequest, VerifyRecoveryCodeRequest, VerifyTotpRequest,
+ SendVerifyEmailRequest, SignUpRequest, SignUpWithMerchantIdRequest, SsoSignInRequest,
+ SwitchMerchantRequest, SwitchOrganizationRequest, SwitchProfileRequest, TokenResponse,
+ TwoFactorAuthStatusResponse, UpdateUserAccountDetailsRequest,
+ UpdateUserAuthenticationMethodRequest, UserFromEmailRequest, UserMerchantCreate,
+ VerifyEmailRequest, VerifyRecoveryCodeRequest, VerifyTotpRequest,
};
impl ApiEventMetric for DashboardEntryResponse {
@@ -40,12 +40,6 @@ impl ApiEventMetric for VerifyTokenResponse {
}
}
-impl<T> ApiEventMetric for TokenOrPayloadResponse<T> {
- fn get_api_event_type(&self) -> Option<ApiEventsType> {
- Some(ApiEventsType::Miscellaneous)
- }
-}
-
common_utils::impl_api_event_type!(
Miscellaneous,
(
@@ -72,7 +66,6 @@ common_utils::impl_api_event_type!(
VerifyEmailRequest,
SendVerifyEmailRequest,
AcceptInviteFromEmailRequest,
- SignInResponse,
UpdateUserAccountDetailsRequest,
GetUserDetailsResponse,
GetUserRoleDetailsRequest,
diff --git a/crates/api_models/src/events/user_role.rs b/crates/api_models/src/events/user_role.rs
index 5b5da0ec50a..f88c318477a 100644
--- a/crates/api_models/src/events/user_role.rs
+++ b/crates/api_models/src/events/user_role.rs
@@ -2,9 +2,8 @@ use common_utils::events::{ApiEventMetric, ApiEventsType};
use crate::user_role::{
role::{
- CreateRoleRequest, GetRoleFromTokenResponse, GetRoleRequest, ListRolesResponse,
- RoleInfoResponse, RoleInfoWithGroupsResponse, RoleInfoWithPermissionsResponse,
- UpdateRoleRequest,
+ CreateRoleRequest, GetRoleRequest, ListRolesResponse, RoleInfoWithGroupsResponse,
+ RoleInfoWithPermissionsResponse, UpdateRoleRequest,
},
AcceptInvitationRequest, AuthorizationInfoResponse, DeleteUserRoleRequest,
MerchantSelectRequest, UpdateUserRoleRequest,
@@ -23,8 +22,6 @@ common_utils::impl_api_event_type!(
CreateRoleRequest,
UpdateRoleRequest,
ListRolesResponse,
- RoleInfoResponse,
- GetRoleFromTokenResponse,
RoleInfoWithGroupsResponse
)
);
diff --git a/crates/api_models/src/user.rs b/crates/api_models/src/user.rs
index 97d0c63fdf1..abc09c8bbee 100644
--- a/crates/api_models/src/user.rs
+++ b/crates/api_models/src/user.rs
@@ -23,8 +23,6 @@ pub struct SignUpRequest {
pub password: Secret<String>,
}
-pub type SignUpResponse = DashboardEntryResponse;
-
#[derive(serde::Serialize, Debug, Clone)]
pub struct DashboardEntryResponse {
pub token: Secret<String>,
@@ -40,22 +38,6 @@ pub struct DashboardEntryResponse {
pub type SignInRequest = SignUpRequest;
-#[derive(Debug, serde::Serialize)]
-#[serde(tag = "flow_type", rename_all = "snake_case")]
-pub enum SignInResponse {
- MerchantSelect(MerchantSelectResponse),
- DashboardEntry(DashboardEntryResponse),
-}
-
-#[derive(Debug, serde::Serialize)]
-pub struct MerchantSelectResponse {
- pub token: Secret<String>,
- pub name: Secret<String>,
- pub email: pii::Email,
- pub verification_days_left: Option<i64>,
- pub merchants: Vec<UserMerchantAccount>,
-}
-
#[derive(serde::Deserialize, Debug, Clone, serde::Serialize)]
pub struct ConnectAccountRequest {
pub email: pii::Email,
@@ -202,8 +184,6 @@ pub struct VerifyEmailRequest {
pub token: Secret<String>,
}
-pub type VerifyEmailResponse = SignInResponse;
-
#[derive(serde::Deserialize, Debug, serde::Serialize)]
pub struct SendVerifyEmailRequest {
pub email: pii::Email,
@@ -232,11 +212,6 @@ pub struct UpdateUserAccountDetailsRequest {
pub preferred_merchant_id: Option<id_type::MerchantId>,
}
-#[derive(Debug, serde::Deserialize, serde::Serialize)]
-pub struct TokenOnlyQueryParam {
- pub token_only: Option<bool>,
-}
-
#[derive(Debug, serde::Deserialize, serde::Serialize)]
pub struct SkipTwoFactorAuthQueryParam {
pub skip_two_factor_auth: Option<bool>,
@@ -254,12 +229,6 @@ pub struct TwoFactorAuthStatusResponse {
pub recovery_code: bool,
}
-#[derive(Debug, serde::Serialize)]
-#[serde(untagged)]
-pub enum TokenOrPayloadResponse<T> {
- Token(TokenResponse),
- Payload(T),
-}
#[derive(Debug, serde::Deserialize, serde::Serialize)]
pub struct UserFromEmailRequest {
pub token: Secret<String>,
diff --git a/crates/api_models/src/user_role.rs b/crates/api_models/src/user_role.rs
index c9f222cb7be..ed6911016b1 100644
--- a/crates/api_models/src/user_role.rs
+++ b/crates/api_models/src/user_role.rs
@@ -121,9 +121,8 @@ pub enum UserStatus {
#[derive(Debug, serde::Deserialize, serde::Serialize)]
pub struct MerchantSelectRequest {
pub merchant_ids: Vec<common_utils::id_type::MerchantId>,
- // TODO: Remove this once the token only api is being used
- pub need_dashboard_entry_response: Option<bool>,
}
+
#[derive(Debug, serde::Deserialize, serde::Serialize)]
pub struct AcceptInvitationRequest {
pub merchant_ids: Vec<common_utils::id_type::MerchantId>,
diff --git a/crates/api_models/src/user_role/role.rs b/crates/api_models/src/user_role/role.rs
index 73b25c84af5..acbad9152ae 100644
--- a/crates/api_models/src/user_role/role.rs
+++ b/crates/api_models/src/user_role/role.rs
@@ -1,4 +1,5 @@
-use common_enums::{EntityType, PermissionGroup, RoleScope};
+pub use common_enums::PermissionGroup;
+use common_enums::{EntityType, RoleScope};
use super::Permission;
@@ -17,26 +18,7 @@ pub struct UpdateRoleRequest {
}
#[derive(Debug, serde::Serialize)]
-pub struct ListRolesResponse(pub Vec<RoleInfoResponse>);
-
-#[derive(Debug, serde::Deserialize)]
-pub struct GetGroupsQueryParam {
- pub groups: Option<bool>,
-}
-
-#[derive(Debug, serde::Serialize)]
-#[serde(untagged)]
-pub enum GetRoleFromTokenResponse {
- Permissions(Vec<Permission>),
- Groups(Vec<PermissionGroup>),
-}
-
-#[derive(Debug, serde::Serialize)]
-#[serde(untagged)]
-pub enum RoleInfoResponse {
- Permissions(RoleInfoWithPermissionsResponse),
- Groups(RoleInfoWithGroupsResponse),
-}
+pub struct ListRolesResponse(pub Vec<RoleInfoWithGroupsResponse>);
#[derive(Debug, serde::Serialize)]
pub struct RoleInfoWithPermissionsResponse {
diff --git a/crates/router/src/core/user.rs b/crates/router/src/core/user.rs
index ace8c3babc6..93a557d5688 100644
--- a/crates/router/src/core/user.rs
+++ b/crates/router/src/core/user.rs
@@ -121,42 +121,10 @@ pub async fn get_user_details(
))
}
-pub async fn signup(
- state: SessionState,
- request: user_api::SignUpRequest,
-) -> UserResponse<user_api::TokenOrPayloadResponse<user_api::SignUpResponse>> {
- let new_user = domain::NewUser::try_from(request)?;
- new_user
- .get_new_merchant()
- .get_new_organization()
- .insert_org_in_db(state.clone())
- .await?;
- let user_from_db = new_user
- .insert_user_and_merchant_in_db(state.clone())
- .await?;
- let user_role = new_user
- .insert_org_level_user_role_in_db(
- state.clone(),
- common_utils::consts::ROLE_ID_ORGANIZATION_ADMIN.to_string(),
- UserStatus::Active,
- None,
- )
- .await?;
- utils::user_role::set_role_permissions_in_cache_by_user_role(&state, &user_role).await;
-
- let token =
- utils::user::generate_jwt_auth_token_without_profile(&state, &user_from_db, &user_role)
- .await?;
- let response =
- utils::user::get_dashboard_entry_response(&state, user_from_db, user_role, token.clone())?;
-
- auth::cookies::set_cookie_response(user_api::TokenOrPayloadResponse::Payload(response), token)
-}
-
pub async fn signup_token_only_flow(
state: SessionState,
request: user_api::SignUpRequest,
-) -> UserResponse<user_api::TokenOrPayloadResponse<user_api::SignUpResponse>> {
+) -> UserResponse<user_api::TokenResponse> {
let new_user = domain::NewUser::try_from(request)?;
new_user
.get_new_merchant()
@@ -182,61 +150,17 @@ pub async fn signup_token_only_flow(
.get_token_with_user_role(&state, &user_role)
.await?;
- let response = user_api::TokenOrPayloadResponse::Token(user_api::TokenResponse {
+ let response = user_api::TokenResponse {
token: token.clone(),
token_type: next_flow.get_flow().into(),
- });
+ };
auth::cookies::set_cookie_response(response, token)
}
-pub async fn signin(
- state: SessionState,
- request: user_api::SignInRequest,
-) -> UserResponse<user_api::TokenOrPayloadResponse<user_api::SignInResponse>> {
- let user_from_db: domain::UserFromStorage = state
- .global_store
- .find_user_by_email(&request.email)
- .await
- .map_err(|e| {
- if e.current_context().is_db_not_found() {
- e.change_context(UserErrors::InvalidCredentials)
- } else {
- e.change_context(UserErrors::InternalServerError)
- }
- })?
- .into();
-
- user_from_db.compare_password(&request.password)?;
-
- let signin_strategy =
- if let Some(preferred_merchant_id) = user_from_db.get_preferred_merchant_id() {
- let preferred_role = user_from_db
- .get_role_from_db_by_merchant_id(&state, &preferred_merchant_id)
- .await
- .to_not_found_response(UserErrors::InternalServerError)
- .attach_printable("User role with preferred_merchant_id not found")?;
- domain::SignInWithRoleStrategyType::SingleRole(domain::SignInWithSingleRoleStrategy {
- user: user_from_db,
- user_role: Box::new(preferred_role),
- })
- } else {
- let user_roles = user_from_db.get_roles_from_db(&state).await?;
- domain::SignInWithRoleStrategyType::decide_signin_strategy_by_user_roles(
- user_from_db,
- user_roles,
- )
- .await?
- };
-
- let response = signin_strategy.get_signin_response(&state).await?;
- let token = utils::user::get_token_from_signin_response(&response);
- auth::cookies::set_cookie_response(user_api::TokenOrPayloadResponse::Payload(response), token)
-}
-
pub async fn signin_token_only_flow(
state: SessionState,
request: user_api::SignInRequest,
-) -> UserResponse<user_api::TokenOrPayloadResponse<user_api::SignInResponse>> {
+) -> UserResponse<user_api::TokenResponse> {
let user_from_db: domain::UserFromStorage = state
.global_store
.find_user_by_email(&request.email)
@@ -251,10 +175,10 @@ pub async fn signin_token_only_flow(
let token = next_flow.get_token(&state).await?;
- let response = user_api::TokenOrPayloadResponse::Token(user_api::TokenResponse {
+ let response = user_api::TokenResponse {
token: token.clone(),
token_type: next_flow.get_flow().into(),
- });
+ };
auth::cookies::set_cookie_response(response, token)
}
@@ -573,105 +497,11 @@ pub async fn reset_password_token_only_flow(
auth::cookies::remove_cookie_response()
}
-#[cfg(feature = "email")]
-pub async fn reset_password(
- state: SessionState,
- request: user_api::ResetPasswordRequest,
-) -> UserResponse<()> {
- let token = request.token.expose();
- let email_token = auth::decode_jwt::<email_types::EmailToken>(&token, &state)
- .await
- .change_context(UserErrors::LinkInvalid)?;
-
- auth::blacklist::check_email_token_in_blacklist(&state, &token).await?;
-
- let password = domain::UserPassword::new(request.password)?;
- let hash_password = utils::user::password::generate_password_hash(password.get_secret())?;
-
- let user = state
- .global_store
- .update_user_by_email(
- &email_token
- .get_email()
- .change_context(UserErrors::InternalServerError)?,
- storage_user::UserUpdate::PasswordUpdate {
- password: hash_password,
- },
- )
- .await
- .change_context(UserErrors::InternalServerError)?;
-
- if let Some(inviter_merchant_id) = email_token.get_merchant_id() {
- let key_manager_state = &(&state).into();
-
- let key_store = state
- .store
- .get_merchant_key_store_by_merchant_id(
- key_manager_state,
- inviter_merchant_id,
- &state.store.get_master_key().to_vec().into(),
- )
- .await
- .change_context(UserErrors::InternalServerError)
- .attach_printable("merchant_key_store not found")?;
-
- let merchant_account = state
- .store
- .find_merchant_account_by_merchant_id(
- key_manager_state,
- inviter_merchant_id,
- &key_store,
- )
- .await
- .change_context(UserErrors::InternalServerError)
- .attach_printable("merchant_account not found")?;
-
- let (update_v1_result, update_v2_result) =
- utils::user_role::update_v1_and_v2_user_roles_in_db(
- &state,
- user.user_id.clone().as_str(),
- &merchant_account.organization_id,
- inviter_merchant_id,
- None,
- UserRoleUpdate::UpdateStatus {
- status: UserStatus::Active,
- modified_by: user.user_id.clone(),
- },
- )
- .await;
-
- if update_v1_result
- .as_ref()
- .is_err_and(|err| !err.current_context().is_db_not_found())
- || update_v2_result
- .as_ref()
- .is_err_and(|err| !err.current_context().is_db_not_found())
- {
- return Err(report!(UserErrors::InternalServerError));
- }
-
- if update_v1_result.is_err() && update_v2_result.is_err() {
- return Err(report!(UserErrors::InvalidRoleOperation))
- .attach_printable("User not found in the organization")?;
- }
- }
-
- let _ = auth::blacklist::insert_email_token_in_blacklist(&state, &token)
- .await
- .map_err(|error| logger::error!(?error));
- let _ = auth::blacklist::insert_user_in_blacklist(&state, &user.user_id)
- .await
- .map_err(|error| logger::error!(?error));
-
- auth::cookies::remove_cookie_response()
-}
-
pub async fn invite_multiple_user(
state: SessionState,
user_from_token: auth::UserFromToken,
requests: Vec<user_api::InviteUserRequest>,
req_state: ReqState,
- is_token_only: Option<bool>,
auth_id: Option<String>,
) -> UserResponse<Vec<InviteMultipleUserResponse>> {
if requests.len() > 10 {
@@ -680,16 +510,7 @@ pub async fn invite_multiple_user(
}
let responses = futures::future::join_all(requests.iter().map(|request| async {
- match handle_invitation(
- &state,
- &user_from_token,
- request,
- &req_state,
- is_token_only,
- &auth_id,
- )
- .await
- {
+ match handle_invitation(&state, &user_from_token, request, &req_state, &auth_id).await {
Ok(response) => response,
Err(error) => InviteMultipleUserResponse {
email: request.email.clone(),
@@ -709,7 +530,6 @@ async fn handle_invitation(
user_from_token: &auth::UserFromToken,
request: &user_api::InviteUserRequest,
req_state: &ReqState,
- is_token_only: Option<bool>,
auth_id: &Option<String>,
) -> UserResult<InviteMultipleUserResponse> {
let inviter_user = user_from_token.get_user_from_db(state).await?;
@@ -756,15 +576,8 @@ async fn handle_invitation(
.err()
.unwrap_or(false)
{
- handle_new_user_invitation(
- state,
- user_from_token,
- request,
- req_state.clone(),
- is_token_only,
- auth_id,
- )
- .await
+ handle_new_user_invitation(state, user_from_token, request, req_state.clone(), auth_id)
+ .await
} else {
Err(UserErrors::InternalServerError.into())
}
@@ -877,7 +690,6 @@ async fn handle_new_user_invitation(
user_from_token: &auth::UserFromToken,
request: &user_api::InviteUserRequest,
req_state: ReqState,
- is_token_only: Option<bool>,
auth_id: &Option<String>,
) -> UserResult<InviteMultipleUserResponse> {
let new_user = domain::NewUser::try_from((request.clone(), user_from_token.clone()))?;
@@ -912,8 +724,6 @@ async fn handle_new_user_invitation(
.await?;
let is_email_sent;
- // TODO: Adding this to avoid clippy lints, remove this once the token only flow is being used
- let _ = is_token_only;
#[cfg(feature = "email")]
{
@@ -921,8 +731,7 @@ async fn handle_new_user_invitation(
// Will be adding actual usage for this variable later
let _ = req_state.clone();
let invitee_email = domain::UserEmail::from_pii_email(request.email.clone())?;
- let email_contents: Box<dyn EmailData + Send + 'static> = if let Some(true) = is_token_only
- {
+ let email_contents: Box<dyn EmailData + Send + 'static> =
Box::new(email_types::InviteRegisteredUser {
recipient_email: invitee_email,
user_name: domain::UserName::new(new_user.get_name())?,
@@ -930,17 +739,7 @@ async fn handle_new_user_invitation(
subject: "You have been invited to join Hyperswitch Community!",
merchant_id: user_from_token.merchant_id.clone(),
auth_id: auth_id.clone(),
- })
- } else {
- Box::new(email_types::InviteUser {
- recipient_email: invitee_email,
- user_name: domain::UserName::new(new_user.get_name())?,
- settings: state.conf.clone(),
- subject: "You have been invited to join Hyperswitch Community!",
- merchant_id: user_from_token.merchant_id.clone(),
- auth_id: auth_id.clone(),
- })
- };
+ });
let send_email_result = state
.email_client
.compose_and_send_email(email_contents, state.conf.proxy.https_url.as_ref())
@@ -1047,115 +846,12 @@ pub async fn resend_invite(
Ok(ApplicationResponse::StatusOk)
}
-#[cfg(feature = "email")]
-pub async fn accept_invite_from_email(
- state: SessionState,
- request: user_api::AcceptInviteFromEmailRequest,
-) -> UserResponse<user_api::DashboardEntryResponse> {
- let token = request.token.expose();
-
- let email_token = auth::decode_jwt::<email_types::EmailToken>(&token, &state)
- .await
- .change_context(UserErrors::LinkInvalid)?;
-
- auth::blacklist::check_email_token_in_blacklist(&state, &token).await?;
-
- let user: domain::UserFromStorage = state
- .global_store
- .find_user_by_email(
- &email_token
- .get_email()
- .change_context(UserErrors::InternalServerError)?,
- )
- .await
- .change_context(UserErrors::InternalServerError)?
- .into();
-
- let merchant_id = email_token
- .get_merchant_id()
- .ok_or(UserErrors::InternalServerError)?;
-
- let key_manager_state = &(&state).into();
-
- let key_store = state
- .store
- .get_merchant_key_store_by_merchant_id(
- key_manager_state,
- merchant_id,
- &state.store.get_master_key().to_vec().into(),
- )
- .await
- .change_context(UserErrors::InternalServerError)
- .attach_printable("merchant_key_store not found")?;
-
- let merchant_account = state
- .store
- .find_merchant_account_by_merchant_id(key_manager_state, merchant_id, &key_store)
- .await
- .change_context(UserErrors::InternalServerError)
- .attach_printable("merchant_account not found")?;
-
- let (update_v1_result, update_v2_result) = utils::user_role::update_v1_and_v2_user_roles_in_db(
- &state,
- user.get_user_id(),
- &merchant_account.organization_id,
- merchant_id,
- None,
- UserRoleUpdate::UpdateStatus {
- status: UserStatus::Active,
- modified_by: user.get_user_id().to_string(),
- },
- )
- .await;
-
- if update_v1_result
- .as_ref()
- .is_err_and(|err| !err.current_context().is_db_not_found())
- || update_v2_result
- .as_ref()
- .is_err_and(|err| !err.current_context().is_db_not_found())
- {
- return Err(report!(UserErrors::InternalServerError));
- }
-
- if update_v1_result.is_err() && update_v2_result.is_err() {
- return Err(report!(UserErrors::InvalidRoleOperation))
- .attach_printable("User not found in the organization")?;
- }
-
- let _ = auth::blacklist::insert_email_token_in_blacklist(&state, &token)
- .await
- .map_err(|error| logger::error!(?error));
-
- let user_from_db: domain::UserFromStorage = state
- .global_store
- .update_user_by_user_id(user.get_user_id(), storage_user::UserUpdate::VerifyUser)
- .await
- .change_context(UserErrors::InternalServerError)?
- .into();
-
- let user_role = user_from_db
- .get_preferred_or_active_user_role_from_db(&state)
- .await
- .change_context(UserErrors::InternalServerError)?;
-
- let token =
- utils::user::generate_jwt_auth_token_without_profile(&state, &user_from_db, &user_role)
- .await?;
- utils::user_role::set_role_permissions_in_cache_by_user_role(&state, &user_role).await;
-
- let response =
- utils::user::get_dashboard_entry_response(&state, user_from_db, user_role, token.clone())?;
-
- auth::cookies::set_cookie_response(response, token)
-}
-
#[cfg(feature = "email")]
pub async fn accept_invite_from_email_token_only_flow(
state: SessionState,
user_token: auth::UserFromSinglePurposeToken,
request: user_api::AcceptInviteFromEmailRequest,
-) -> UserResponse<user_api::TokenOrPayloadResponse<user_api::DashboardEntryResponse>> {
+) -> UserResponse<user_api::TokenResponse> {
let token = request.token.expose();
let email_token = auth::decode_jwt::<email_types::EmailToken>(&token, &state)
@@ -1261,10 +957,10 @@ pub async fn accept_invite_from_email_token_only_flow(
.get_token_with_user_role(&state, &user_role)
.await?;
- let response = user_api::TokenOrPayloadResponse::Token(user_api::TokenResponse {
+ let response = user_api::TokenResponse {
token: token.clone(),
token_type: next_flow.get_flow().into(),
- });
+ };
auth::cookies::set_cookie_response(response, token)
}
@@ -1503,7 +1199,7 @@ pub async fn list_merchants_for_user(
.await
.change_context(UserErrors::InternalServerError)?;
- let merchant_accounts = state
+ let merchant_accounts_map = state
.store
.list_multiple_merchant_accounts(
&(&state).into(),
@@ -1517,17 +1213,62 @@ pub async fn list_merchants_for_user(
.collect::<Result<Vec<_>, _>>()?,
)
.await
- .change_context(UserErrors::InternalServerError)?;
+ .change_context(UserErrors::InternalServerError)?
+ .into_iter()
+ .map(|merchant_account| (merchant_account.get_id().clone(), merchant_account))
+ .collect::<HashMap<_, _>>();
- let roles =
- utils::user_role::get_multiple_role_info_for_user_roles(&state, &user_roles).await?;
+ let roles_map = futures::future::try_join_all(user_roles.iter().map(|user_role| async {
+ let Some(merchant_id) = &user_role.merchant_id else {
+ return Err(report!(UserErrors::InternalServerError))
+ .attach_printable("merchant_id not found for user_role");
+ };
+ let Some(org_id) = &user_role.org_id else {
+ return Err(report!(UserErrors::InternalServerError)
+ .attach_printable("org_id not found in user_role"));
+ };
+ roles::RoleInfo::from_role_id(&state, &user_role.role_id, merchant_id, org_id)
+ .await
+ .change_context(UserErrors::InternalServerError)
+ .attach_printable("Unable to find role info for user role")
+ }))
+ .await?
+ .into_iter()
+ .map(|role_info| (role_info.get_role_id().to_owned(), role_info))
+ .collect::<HashMap<_, _>>();
Ok(ApplicationResponse::Json(
- utils::user::get_multiple_merchant_details_with_status(
- user_roles,
- merchant_accounts,
- roles,
- )?,
+ user_roles
+ .into_iter()
+ .map(|user_role| {
+ let Some(merchant_id) = &user_role.merchant_id else {
+ return Err(report!(UserErrors::InternalServerError))
+ .attach_printable("merchant_id not found for user_role");
+ };
+ let Some(org_id) = &user_role.org_id else {
+ return Err(report!(UserErrors::InternalServerError)
+ .attach_printable("org_id not found in user_role"));
+ };
+ let merchant_account = merchant_accounts_map
+ .get(merchant_id)
+ .ok_or(UserErrors::InternalServerError)
+ .attach_printable("Merchant account for user role doesn't exist")?;
+
+ let role_info = roles_map
+ .get(&user_role.role_id)
+ .ok_or(UserErrors::InternalServerError)
+ .attach_printable("Role info for user role doesn't exist")?;
+
+ Ok(user_api::UserMerchantAccount {
+ merchant_id: merchant_id.to_owned(),
+ merchant_name: merchant_account.merchant_name.clone(),
+ is_active: user_role.status == UserStatus::Active,
+ role_id: user_role.role_id,
+ role_name: role_info.get_role_name().to_string(),
+ org_id: org_id.to_owned(),
+ })
+ })
+ .collect::<Result<Vec<_>, _>>()?,
))
}
@@ -1650,71 +1391,12 @@ pub async fn list_users_for_merchant_account(
)))
}
-#[cfg(feature = "email")]
-pub async fn verify_email(
- state: SessionState,
- req: user_api::VerifyEmailRequest,
-) -> UserResponse<user_api::SignInResponse> {
- let token = req.token.clone().expose();
- let email_token = auth::decode_jwt::<email_types::EmailToken>(&token, &state)
- .await
- .change_context(UserErrors::LinkInvalid)?;
-
- auth::blacklist::check_email_token_in_blacklist(&state, &token).await?;
-
- let user = state
- .global_store
- .find_user_by_email(
- &email_token
- .get_email()
- .change_context(UserErrors::InternalServerError)?,
- )
- .await
- .change_context(UserErrors::InternalServerError)?;
-
- let user = state
- .global_store
- .update_user_by_user_id(user.user_id.as_str(), storage_user::UserUpdate::VerifyUser)
- .await
- .change_context(UserErrors::InternalServerError)?;
-
- let user_from_db: domain::UserFromStorage = user.into();
-
- let signin_strategy =
- if let Some(preferred_merchant_id) = user_from_db.get_preferred_merchant_id() {
- let preferred_role = user_from_db
- .get_role_from_db_by_merchant_id(&state, &preferred_merchant_id)
- .await
- .change_context(UserErrors::InternalServerError)
- .attach_printable("User role with preferred_merchant_id not found")?;
- domain::SignInWithRoleStrategyType::SingleRole(domain::SignInWithSingleRoleStrategy {
- user: user_from_db,
- user_role: Box::new(preferred_role),
- })
- } else {
- let user_roles = user_from_db.get_roles_from_db(&state).await?;
- domain::SignInWithRoleStrategyType::decide_signin_strategy_by_user_roles(
- user_from_db,
- user_roles,
- )
- .await?
- };
-
- let _ = auth::blacklist::insert_email_token_in_blacklist(&state, &token)
- .await
- .map_err(|error| logger::error!(?error));
-
- let response = signin_strategy.get_signin_response(&state).await?;
- let token = utils::user::get_token_from_signin_response(&response);
- auth::cookies::set_cookie_response(response, token)
-}
-
#[cfg(feature = "email")]
pub async fn verify_email_token_only_flow(
state: SessionState,
user_token: auth::UserFromSinglePurposeToken,
req: user_api::VerifyEmailRequest,
-) -> UserResponse<user_api::TokenOrPayloadResponse<user_api::SignInResponse>> {
+) -> UserResponse<user_api::TokenResponse> {
let token = req.token.clone().expose();
let email_token = auth::decode_jwt::<email_types::EmailToken>(&token, &state)
.await
@@ -1754,10 +1436,10 @@ pub async fn verify_email_token_only_flow(
let next_flow = current_flow.next(user_from_db, &state).await?;
let token = next_flow.get_token(&state).await?;
- let response = user_api::TokenOrPayloadResponse::Token(user_api::TokenResponse {
+ let response = user_api::TokenResponse {
token: token.clone(),
token_type: next_flow.get_flow().into(),
- });
+ };
auth::cookies::set_cookie_response(response, token)
}
@@ -2839,24 +2521,7 @@ pub async fn switch_org_for_user(
))?
.to_owned();
- let merchant_id = if let Some(merchant_id) = &user_role.merchant_id {
- merchant_id.clone()
- } else {
- state
- .store
- .list_merchant_accounts_by_organization_id(
- key_manager_state,
- request.org_id.get_string_repr(),
- )
- .await
- .change_context(UserErrors::InternalServerError)
- .attach_printable("Failed to list merchant accounts by organization_id")?
- .first()
- .ok_or(UserErrors::InternalServerError)
- .attach_printable("No merchant account found for the given organization_id")?
- .get_id()
- .clone()
- };
+ let merchant_id = utils::user_role::get_single_merchant_id(&state, &user_role).await?;
let profile_id = if let Some(profile_id) = &user_role.profile_id {
profile_id.clone()
diff --git a/crates/router/src/core/user_role.rs b/crates/router/src/core/user_role.rs
index 971b34b0667..4204e91678d 100644
--- a/crates/router/src/core/user_role.rs
+++ b/crates/router/src/core/user_role.rs
@@ -24,20 +24,6 @@ pub mod role;
use common_enums::{EntityType, PermissionGroup};
use strum::IntoEnumIterator;
-// TODO: To be deprecated once groups are stable
-pub async fn get_authorization_info_with_modules(
- _state: SessionState,
-) -> UserResponse<user_role_api::AuthorizationInfoResponse> {
- Ok(ApplicationResponse::Json(
- user_role_api::AuthorizationInfoResponse(
- info::get_module_authorization_info()
- .into_iter()
- .map(|module_info| user_role_api::AuthorizationInfo::Module(module_info.into()))
- .collect(),
- ),
- ))
-}
-
pub async fn get_authorization_info_with_groups(
_state: SessionState,
) -> UserResponse<user_role_api::AuthorizationInfoResponse> {
@@ -50,6 +36,7 @@ pub async fn get_authorization_info_with_groups(
),
))
}
+
pub async fn get_authorization_info_with_group_tag(
) -> UserResponse<user_role_api::AuthorizationInfoResponse> {
static GROUPS_WITH_PARENT_TAGS: Lazy<Vec<user_role_api::ParentInfo>> = Lazy::new(|| {
@@ -309,85 +296,11 @@ pub async fn accept_invitation(
Ok(ApplicationResponse::StatusOk)
}
-pub async fn merchant_select(
- state: SessionState,
- user_token: auth::UserFromSinglePurposeToken,
- req: user_role_api::MerchantSelectRequest,
-) -> UserResponse<user_api::TokenOrPayloadResponse<user_api::DashboardEntryResponse>> {
- let merchant_accounts = state
- .store
- .list_multiple_merchant_accounts(&(&state).into(), req.merchant_ids)
- .await
- .change_context(UserErrors::InternalServerError)?;
-
- let update_result =
- futures::future::join_all(merchant_accounts.iter().map(|merchant_account| async {
- let (update_v1_result, update_v2_result) =
- utils::user_role::update_v1_and_v2_user_roles_in_db(
- &state,
- user_token.user_id.as_str(),
- &merchant_account.organization_id,
- merchant_account.get_id(),
- None,
- UserRoleUpdate::UpdateStatus {
- status: UserStatus::Active,
- modified_by: user_token.user_id.clone(),
- },
- )
- .await;
-
- if update_v1_result.is_err_and(|err| !err.current_context().is_db_not_found())
- || update_v2_result.is_err_and(|err| !err.current_context().is_db_not_found())
- {
- Err(report!(UserErrors::InternalServerError))
- } else {
- Ok(())
- }
- }))
- .await;
-
- if update_result.iter().all(Result::is_err) {
- return Err(UserErrors::MerchantIdNotFound.into());
- }
-
- if let Some(true) = req.need_dashboard_entry_response {
- let user_from_db: domain::UserFromStorage = state
- .global_store
- .find_user_by_id(user_token.user_id.as_str())
- .await
- .change_context(UserErrors::InternalServerError)?
- .into();
-
- let user_role = user_from_db
- .get_preferred_or_active_user_role_from_db(&state)
- .await
- .change_context(UserErrors::InternalServerError)?;
-
- utils::user_role::set_role_permissions_in_cache_by_user_role(&state, &user_role).await;
-
- let token =
- utils::user::generate_jwt_auth_token_without_profile(&state, &user_from_db, &user_role)
- .await?;
- let response = utils::user::get_dashboard_entry_response(
- &state,
- user_from_db,
- user_role,
- token.clone(),
- )?;
- return auth::cookies::set_cookie_response(
- user_api::TokenOrPayloadResponse::Payload(response),
- token,
- );
- }
-
- Ok(ApplicationResponse::StatusOk)
-}
-
pub async fn merchant_select_token_only_flow(
state: SessionState,
user_token: auth::UserFromSinglePurposeToken,
req: user_role_api::MerchantSelectRequest,
-) -> UserResponse<user_api::TokenOrPayloadResponse<user_api::DashboardEntryResponse>> {
+) -> UserResponse<user_api::TokenResponse> {
let merchant_accounts = state
.store
.list_multiple_merchant_accounts(&(&state).into(), req.merchant_ids)
@@ -444,10 +357,10 @@ pub async fn merchant_select_token_only_flow(
.get_token_with_user_role(&state, &user_role)
.await?;
- let response = user_api::TokenOrPayloadResponse::Token(user_api::TokenResponse {
+ let response = user_api::TokenResponse {
token: token.clone(),
token_type: next_flow.get_flow().into(),
- });
+ };
auth::cookies::set_cookie_response(response, token)
}
diff --git a/crates/router/src/core/user_role/role.rs b/crates/router/src/core/user_role/role.rs
index d79b3136422..7a2c7020512 100644
--- a/crates/router/src/core/user_role/role.rs
+++ b/crates/router/src/core/user_role/role.rs
@@ -16,30 +16,10 @@ use crate::{
utils,
};
-pub async fn get_role_from_token_with_permissions(
- state: SessionState,
- user_from_token: UserFromToken,
-) -> UserResponse<role_api::GetRoleFromTokenResponse> {
- let role_info = user_from_token
- .get_role_info_from_db(&state)
- .await
- .attach_printable("Invalid role_id in JWT")?;
-
- let permissions = role_info
- .get_permissions_set()
- .into_iter()
- .map(Into::into)
- .collect();
-
- Ok(ApplicationResponse::Json(
- role_api::GetRoleFromTokenResponse::Permissions(permissions),
- ))
-}
-
pub async fn get_role_from_token_with_groups(
state: SessionState,
user_from_token: UserFromToken,
-) -> UserResponse<role_api::GetRoleFromTokenResponse> {
+) -> UserResponse<Vec<role_api::PermissionGroup>> {
let role_info = user_from_token
.get_role_info_from_db(&state)
.await
@@ -47,9 +27,7 @@ pub async fn get_role_from_token_with_groups(
let permissions = role_info.get_permission_groups().to_vec();
- Ok(ApplicationResponse::Json(
- role_api::GetRoleFromTokenResponse::Groups(permissions),
- ))
+ Ok(ApplicationResponse::Json(permissions))
}
pub async fn create_role(
@@ -105,56 +83,6 @@ pub async fn create_role(
))
}
-// TODO: To be deprecated once groups are stable
-pub async fn list_invitable_roles_with_permissions(
- state: SessionState,
- user_from_token: UserFromToken,
-) -> UserResponse<role_api::ListRolesResponse> {
- let predefined_roles_map = PREDEFINED_ROLES
- .iter()
- .filter(|(_, role_info)| role_info.is_invitable())
- .map(|(role_id, role_info)| {
- role_api::RoleInfoResponse::Permissions(role_api::RoleInfoWithPermissionsResponse {
- permissions: role_info
- .get_permissions_set()
- .into_iter()
- .map(Into::into)
- .collect(),
- role_id: role_id.to_string(),
- role_name: role_info.get_role_name().to_string(),
- role_scope: role_info.get_scope(),
- })
- });
-
- let custom_roles_map = state
- .store
- .list_all_roles(&user_from_token.merchant_id, &user_from_token.org_id)
- .await
- .change_context(UserErrors::InternalServerError)?
- .into_iter()
- .filter_map(|role| {
- let role_info = roles::RoleInfo::from(role);
- role_info
- .is_invitable()
- .then_some(role_api::RoleInfoResponse::Permissions(
- role_api::RoleInfoWithPermissionsResponse {
- permissions: role_info
- .get_permissions_set()
- .into_iter()
- .map(Into::into)
- .collect(),
- role_id: role_info.get_role_id().to_string(),
- role_name: role_info.get_role_name().to_string(),
- role_scope: role_info.get_scope(),
- },
- ))
- });
-
- Ok(ApplicationResponse::Json(role_api::ListRolesResponse(
- predefined_roles_map.chain(custom_roles_map).collect(),
- )))
-}
-
pub async fn list_invitable_roles_with_groups(
state: SessionState,
user_from_token: UserFromToken,
@@ -162,14 +90,14 @@ pub async fn list_invitable_roles_with_groups(
let predefined_roles_map = PREDEFINED_ROLES
.iter()
.filter(|(_, role_info)| role_info.is_invitable())
- .map(|(role_id, role_info)| {
- role_api::RoleInfoResponse::Groups(role_api::RoleInfoWithGroupsResponse {
+ .map(
+ |(role_id, role_info)| role_api::RoleInfoWithGroupsResponse {
groups: role_info.get_permission_groups().to_vec(),
role_id: role_id.to_string(),
role_name: role_info.get_role_name().to_string(),
role_scope: role_info.get_scope(),
- })
- });
+ },
+ );
let custom_roles_map = state
.store
@@ -181,14 +109,12 @@ pub async fn list_invitable_roles_with_groups(
let role_info = roles::RoleInfo::from(role);
role_info
.is_invitable()
- .then_some(role_api::RoleInfoResponse::Groups(
- role_api::RoleInfoWithGroupsResponse {
- groups: role_info.get_permission_groups().to_vec(),
- role_id: role_info.get_role_id().to_string(),
- role_name: role_info.get_role_name().to_string(),
- role_scope: role_info.get_scope(),
- },
- ))
+ .then_some(role_api::RoleInfoWithGroupsResponse {
+ groups: role_info.get_permission_groups().to_vec(),
+ role_id: role_info.get_role_id().to_string(),
+ role_name: role_info.get_role_name().to_string(),
+ role_scope: role_info.get_scope(),
+ })
});
Ok(ApplicationResponse::Json(role_api::ListRolesResponse(
@@ -196,46 +122,11 @@ pub async fn list_invitable_roles_with_groups(
)))
}
-// TODO: To be deprecated once groups are stable
-pub async fn get_role_with_permissions(
- state: SessionState,
- user_from_token: UserFromToken,
- role: role_api::GetRoleRequest,
-) -> UserResponse<role_api::RoleInfoResponse> {
- let role_info = roles::RoleInfo::from_role_id(
- &state,
- &role.role_id,
- &user_from_token.merchant_id,
- &user_from_token.org_id,
- )
- .await
- .to_not_found_response(UserErrors::InvalidRoleId)?;
-
- if role_info.is_internal() {
- return Err(UserErrors::InvalidRoleId.into());
- }
-
- let permissions = role_info
- .get_permissions_set()
- .into_iter()
- .map(Into::into)
- .collect();
-
- Ok(ApplicationResponse::Json(
- role_api::RoleInfoResponse::Permissions(role_api::RoleInfoWithPermissionsResponse {
- permissions,
- role_id: role.role_id,
- role_name: role_info.get_role_name().to_string(),
- role_scope: role_info.get_scope(),
- }),
- ))
-}
-
pub async fn get_role_with_groups(
state: SessionState,
user_from_token: UserFromToken,
role: role_api::GetRoleRequest,
-) -> UserResponse<role_api::RoleInfoResponse> {
+) -> UserResponse<role_api::RoleInfoWithGroupsResponse> {
let role_info = roles::RoleInfo::from_role_id(
&state,
&role.role_id,
@@ -250,12 +141,12 @@ pub async fn get_role_with_groups(
}
Ok(ApplicationResponse::Json(
- role_api::RoleInfoResponse::Groups(role_api::RoleInfoWithGroupsResponse {
+ role_api::RoleInfoWithGroupsResponse {
groups: role_info.get_permission_groups().to_vec(),
role_id: role.role_id,
role_name: role_info.get_role_name().to_string(),
role_scope: role_info.get_scope(),
- }),
+ },
))
}
diff --git a/crates/router/src/db/user_role.rs b/crates/router/src/db/user_role.rs
index 57090632725..eadd1ef4a5b 100644
--- a/crates/router/src/db/user_role.rs
+++ b/crates/router/src/db/user_role.rs
@@ -357,11 +357,7 @@ impl UserRoleInterface for MockDb {
for user_role in user_roles.iter() {
let Some(user_role_merchant_id) = &user_role.merchant_id else {
- return Err(errors::StorageError::DatabaseError(
- report!(errors::DatabaseError::Others)
- .attach_printable("merchant_id not found for user_role"),
- )
- .into());
+ continue;
};
if user_role.user_id == user_id
&& user_role_merchant_id == merchant_id
diff --git a/crates/router/src/routes/app.rs b/crates/router/src/routes/app.rs
index 8201380cc29..42f46e39d2e 100644
--- a/crates/router/src/routes/app.rs
+++ b/crates/router/src/routes/app.rs
@@ -1681,6 +1681,7 @@ impl User {
route = route
.service(web::resource("").route(web::get().to(get_user_details)))
+ .service(web::resource("/signin").route(web::post().to(user_signin)))
.service(web::resource("/v2/signin").route(web::post().to(user_signin)))
// signin/signup with sso using openidconnect
.service(web::resource("/oidc").route(web::post().to(sso_sign)))
@@ -1796,6 +1797,7 @@ impl User {
web::resource("/signup_with_merchant_id")
.route(web::post().to(user_signup_with_merchant_id)),
)
+ .service(web::resource("/verify_email").route(web::post().to(verify_email)))
.service(web::resource("/v2/verify_email").route(web::post().to(verify_email)))
.service(
web::resource("/verify_email_request")
diff --git a/crates/router/src/routes/user.rs b/crates/router/src/routes/user.rs
index c52c5d1321c..1d5e3d601b6 100644
--- a/crates/router/src/routes/user.rs
+++ b/crates/router/src/routes/user.rs
@@ -62,22 +62,16 @@ pub async fn user_signup(
state: web::Data<AppState>,
http_req: HttpRequest,
json_payload: web::Json<user_api::SignUpRequest>,
- query: web::Query<user_api::TokenOnlyQueryParam>,
) -> HttpResponse {
let flow = Flow::UserSignUp;
let req_payload = json_payload.into_inner();
- let is_token_only = query.into_inner().token_only;
Box::pin(api::server_wrap(
flow.clone(),
state,
&http_req,
req_payload.clone(),
|state, _: (), req_body, _| async move {
- if let Some(true) = is_token_only {
- user_core::signup_token_only_flow(state, req_body).await
- } else {
- user_core::signup(state, req_body).await
- }
+ user_core::signup_token_only_flow(state, req_body).await
},
&auth::NoAuth,
api_locking::LockAction::NotApplicable,
@@ -89,22 +83,16 @@ pub async fn user_signin(
state: web::Data<AppState>,
http_req: HttpRequest,
json_payload: web::Json<user_api::SignInRequest>,
- query: web::Query<user_api::TokenOnlyQueryParam>,
) -> HttpResponse {
let flow = Flow::UserSignIn;
let req_payload = json_payload.into_inner();
- let is_token_only = query.into_inner().token_only;
Box::pin(api::server_wrap(
flow.clone(),
state,
&http_req,
req_payload.clone(),
|state, _: (), req_body, _| async move {
- if let Some(true) = is_token_only {
- user_core::signin_token_only_flow(state, req_body).await
- } else {
- user_core::signin(state, req_body).await
- }
+ user_core::signin_token_only_flow(state, req_body).await
},
&auth::NoAuth,
api_locking::LockAction::NotApplicable,
@@ -409,46 +397,27 @@ pub async fn reset_password(
state: web::Data<AppState>,
req: HttpRequest,
payload: web::Json<user_api::ResetPasswordRequest>,
- query: web::Query<user_api::TokenOnlyQueryParam>,
) -> HttpResponse {
let flow = Flow::ResetPassword;
- let is_token_only = query.into_inner().token_only;
- if let Some(true) = is_token_only {
- 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
- } else {
- Box::pin(api::server_wrap(
- flow,
- state.clone(),
- &req,
- payload.into_inner(),
- |state, _: (), payload, _| user_core::reset_password(state, payload),
- &auth::NoAuth,
- api_locking::LockAction::NotApplicable,
- ))
- .await
- }
+ 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>>,
- token_only_query_param: web::Query<user_api::TokenOnlyQueryParam>,
auth_id_query_param: web::Query<user_api::AuthIdQueryParam>,
) -> HttpResponse {
let flow = Flow::InviteMultipleUser;
- let is_token_only = token_only_query_param.into_inner().token_only;
let auth_id = auth_id_query_param.into_inner().auth_id;
Box::pin(api::server_wrap(
flow,
@@ -456,14 +425,7 @@ pub async fn invite_multiple_user(
&req,
payload.into_inner(),
|state, user, payload, req_state| {
- user_core::invite_multiple_user(
- state,
- user,
- payload,
- req_state,
- is_token_only,
- auth_id.clone(),
- )
+ user_core::invite_multiple_user(state, user, payload, req_state, auth_id.clone())
},
&auth::JWTAuth(Permission::UsersWrite),
api_locking::LockAction::NotApplicable,
@@ -499,37 +461,20 @@ pub async fn accept_invite_from_email(
state: web::Data<AppState>,
req: HttpRequest,
payload: web::Json<user_api::AcceptInviteFromEmailRequest>,
- query: web::Query<user_api::TokenOnlyQueryParam>,
) -> HttpResponse {
let flow = Flow::AcceptInviteFromEmail;
- let is_token_only = query.into_inner().token_only;
- if let Some(true) = is_token_only {
- 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)
- },
- &auth::SinglePurposeJWTAuth(TokenPurpose::AcceptInvitationFromEmail),
- api_locking::LockAction::NotApplicable,
- ))
- .await
- } else {
- Box::pin(api::server_wrap(
- flow,
- state.clone(),
- &req,
- payload.into_inner(),
- |state, _: (), request_payload, _| {
- user_core::accept_invite_from_email(state, request_payload)
- },
- &auth::NoAuth,
- api_locking::LockAction::NotApplicable,
- ))
- .await
- }
+ 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)
+ },
+ &auth::SinglePurposeJWTAuth(TokenPurpose::AcceptInvitationFromEmail),
+ api_locking::LockAction::NotApplicable,
+ ))
+ .await
}
#[cfg(feature = "email")]
@@ -537,35 +482,20 @@ pub async fn verify_email(
state: web::Data<AppState>,
http_req: HttpRequest,
json_payload: web::Json<user_api::VerifyEmailRequest>,
- query: web::Query<user_api::TokenOnlyQueryParam>,
) -> HttpResponse {
let flow = Flow::VerifyEmail;
- let is_token_only = query.into_inner().token_only;
- if let Some(true) = is_token_only {
- 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
- } else {
- Box::pin(api::server_wrap(
- flow.clone(),
- state,
- &http_req,
- json_payload.into_inner(),
- |state, _: (), req_payload, _| user_core::verify_email(state, req_payload),
- &auth::NoAuth,
- api_locking::LockAction::NotApplicable,
- ))
- .await
- }
+ 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")]
diff --git a/crates/router/src/routes/user_role.rs b/crates/router/src/routes/user_role.rs
index a730321e190..5f1e4301d45 100644
--- a/crates/router/src/routes/user_role.rs
+++ b/crates/router/src/routes/user_role.rs
@@ -1,8 +1,5 @@
use actix_web::{web, HttpRequest, HttpResponse};
-use api_models::{
- user as user_api,
- user_role::{self as user_role_api, role as role_api},
-};
+use api_models::user_role::{self as user_role_api, role as role_api};
use common_enums::TokenPurpose;
use router_env::Flow;
@@ -22,22 +19,15 @@ use crate::{
pub async fn get_authorization_info(
state: web::Data<AppState>,
http_req: HttpRequest,
- query: web::Query<role_api::GetGroupsQueryParam>,
) -> HttpResponse {
let flow = Flow::GetAuthorizationInfo;
- let respond_with_groups = query.into_inner().groups.unwrap_or(false);
Box::pin(api::server_wrap(
flow,
state.clone(),
&http_req,
(),
|state, _: (), _, _| async move {
- // TODO: Permissions to be deprecated once groups are stable
- if respond_with_groups {
- user_role_core::get_authorization_info_with_groups(state).await
- } else {
- user_role_core::get_authorization_info_with_modules(state).await
- }
+ user_role_core::get_authorization_info_with_groups(state).await
},
&auth::JWTAuth(Permission::UsersRead),
api_locking::LockAction::NotApplicable,
@@ -45,13 +35,8 @@ pub async fn get_authorization_info(
.await
}
-pub async fn get_role_from_token(
- state: web::Data<AppState>,
- req: HttpRequest,
- query: web::Query<role_api::GetGroupsQueryParam>,
-) -> HttpResponse {
+pub async fn get_role_from_token(state: web::Data<AppState>, req: HttpRequest) -> HttpResponse {
let flow = Flow::GetRoleFromToken;
- let respond_with_groups = query.into_inner().groups.unwrap_or(false);
Box::pin(api::server_wrap(
flow,
@@ -59,12 +44,7 @@ pub async fn get_role_from_token(
&req,
(),
|state, user, _, _| async move {
- // TODO: Permissions to be deprecated once groups are stable
- if respond_with_groups {
- role_core::get_role_from_token_with_groups(state, user).await
- } else {
- role_core::get_role_from_token_with_permissions(state, user).await
- }
+ role_core::get_role_from_token_with_groups(state, user).await
},
&auth::DashboardNoPermissionAuth,
api_locking::LockAction::NotApplicable,
@@ -90,25 +70,15 @@ pub async fn create_role(
.await
}
-pub async fn list_all_roles(
- state: web::Data<AppState>,
- req: HttpRequest,
- query: web::Query<role_api::GetGroupsQueryParam>,
-) -> HttpResponse {
+pub async fn list_all_roles(state: web::Data<AppState>, req: HttpRequest) -> HttpResponse {
let flow = Flow::ListRoles;
- let respond_with_groups = query.into_inner().groups.unwrap_or(false);
Box::pin(api::server_wrap(
flow,
state.clone(),
&req,
(),
|state, user, _, _| async move {
- // TODO: Permissions to be deprecated once groups are stable
- if respond_with_groups {
- role_core::list_invitable_roles_with_groups(state, user).await
- } else {
- role_core::list_invitable_roles_with_permissions(state, user).await
- }
+ role_core::list_invitable_roles_with_groups(state, user).await
},
&auth::JWTAuth(Permission::UsersRead),
api_locking::LockAction::NotApplicable,
@@ -120,25 +90,18 @@ pub async fn get_role(
state: web::Data<AppState>,
req: HttpRequest,
path: web::Path<String>,
- query: web::Query<role_api::GetGroupsQueryParam>,
) -> HttpResponse {
let flow = Flow::GetRole;
let request_payload = user_role_api::role::GetRoleRequest {
role_id: path.into_inner(),
};
- let respond_with_groups = query.into_inner().groups.unwrap_or(false);
Box::pin(api::server_wrap(
flow,
state.clone(),
&req,
request_payload,
|state, user, payload, _| async move {
- // TODO: Permissions to be deprecated once groups are stable
- if respond_with_groups {
- role_core::get_role_with_groups(state, user, payload).await
- } else {
- role_core::get_role_with_permissions(state, user, payload).await
- }
+ role_core::get_role_with_groups(state, user, payload).await
},
&auth::JWTAuth(Permission::UsersRead),
api_locking::LockAction::NotApplicable,
@@ -209,22 +172,16 @@ pub async fn merchant_select(
state: web::Data<AppState>,
req: HttpRequest,
json_payload: web::Json<user_role_api::MerchantSelectRequest>,
- query: web::Query<user_api::TokenOnlyQueryParam>,
) -> HttpResponse {
let flow = Flow::MerchantSelect;
let payload = json_payload.into_inner();
- let is_token_only = query.into_inner().token_only;
Box::pin(api::server_wrap(
flow,
state.clone(),
&req,
payload,
|state, user, req_body, _| async move {
- if let Some(true) = is_token_only {
- user_role_core::merchant_select_token_only_flow(state, user, req_body).await
- } else {
- user_role_core::merchant_select(state, user, req_body).await
- }
+ user_role_core::merchant_select_token_only_flow(state, user, req_body).await
},
&auth::SinglePurposeJWTAuth(TokenPurpose::AcceptInvite),
api_locking::LockAction::NotApplicable,
diff --git a/crates/router/src/services/authorization/predefined_permissions.rs b/crates/router/src/services/authorization/predefined_permissions.rs
deleted file mode 100644
index 50f9a7196b8..00000000000
--- a/crates/router/src/services/authorization/predefined_permissions.rs
+++ /dev/null
@@ -1,346 +0,0 @@
-use std::collections::HashMap;
-
-#[cfg(feature = "olap")]
-use error_stack::ResultExt;
-use once_cell::sync::Lazy;
-
-use super::permissions::Permission;
-use crate::consts;
-#[cfg(feature = "olap")]
-use crate::core::errors::{UserErrors, UserResult};
-
-#[allow(dead_code)]
-pub struct RoleInfo {
- permissions: Vec<Permission>,
- name: Option<&'static str>,
- is_invitable: bool,
- is_deletable: bool,
- is_updatable: bool,
-}
-
-impl RoleInfo {
- pub fn get_permissions(&self) -> &Vec<Permission> {
- &self.permissions
- }
-
- pub fn get_name(&self) -> Option<&'static str> {
- self.name
- }
-
- pub fn is_invitable(&self) -> bool {
- self.is_invitable
- }
-}
-
-pub static PREDEFINED_PERMISSIONS: Lazy<HashMap<&'static str, RoleInfo>> = Lazy::new(|| {
- let mut roles = HashMap::new();
- roles.insert(
- consts::user_role::ROLE_ID_INTERNAL_ADMIN,
- RoleInfo {
- permissions: vec![
- Permission::PaymentRead,
- Permission::PaymentWrite,
- Permission::RefundRead,
- Permission::RefundWrite,
- Permission::ApiKeyRead,
- Permission::ApiKeyWrite,
- Permission::MerchantAccountRead,
- Permission::MerchantAccountWrite,
- Permission::MerchantConnectorAccountRead,
- Permission::MerchantConnectorAccountWrite,
- Permission::RoutingRead,
- Permission::RoutingWrite,
- Permission::ThreeDsDecisionManagerWrite,
- Permission::ThreeDsDecisionManagerRead,
- Permission::SurchargeDecisionManagerWrite,
- Permission::SurchargeDecisionManagerRead,
- Permission::DisputeRead,
- Permission::DisputeWrite,
- Permission::MandateRead,
- Permission::MandateWrite,
- Permission::CustomerRead,
- Permission::CustomerWrite,
- Permission::Analytics,
- Permission::UsersRead,
- Permission::UsersWrite,
- Permission::MerchantAccountCreate,
- Permission::PayoutRead,
- Permission::PayoutWrite,
- ],
- name: None,
- is_invitable: false,
- is_deletable: false,
- is_updatable: false,
- },
- );
- roles.insert(
- consts::user_role::ROLE_ID_INTERNAL_VIEW_ONLY_USER,
- RoleInfo {
- permissions: vec![
- Permission::PaymentRead,
- Permission::RefundRead,
- Permission::ApiKeyRead,
- Permission::MerchantAccountRead,
- Permission::MerchantConnectorAccountRead,
- Permission::RoutingRead,
- Permission::ThreeDsDecisionManagerRead,
- Permission::SurchargeDecisionManagerRead,
- Permission::Analytics,
- Permission::DisputeRead,
- Permission::MandateRead,
- Permission::CustomerRead,
- Permission::UsersRead,
- Permission::PayoutRead,
- ],
- name: None,
- is_invitable: false,
- is_deletable: false,
- is_updatable: false,
- },
- );
-
- roles.insert(
- consts::user_role::ROLE_ID_ORGANIZATION_ADMIN,
- RoleInfo {
- permissions: vec![
- Permission::PaymentRead,
- Permission::PaymentWrite,
- Permission::RefundRead,
- Permission::RefundWrite,
- Permission::ApiKeyRead,
- Permission::ApiKeyWrite,
- Permission::MerchantAccountRead,
- Permission::MerchantAccountWrite,
- Permission::MerchantConnectorAccountRead,
- Permission::MerchantConnectorAccountWrite,
- Permission::RoutingRead,
- Permission::RoutingWrite,
- Permission::ThreeDsDecisionManagerWrite,
- Permission::ThreeDsDecisionManagerRead,
- Permission::SurchargeDecisionManagerWrite,
- Permission::SurchargeDecisionManagerRead,
- Permission::DisputeRead,
- Permission::DisputeWrite,
- Permission::MandateRead,
- Permission::MandateWrite,
- Permission::CustomerRead,
- Permission::CustomerWrite,
- Permission::Analytics,
- Permission::UsersRead,
- Permission::UsersWrite,
- Permission::MerchantAccountCreate,
- Permission::PayoutRead,
- Permission::PayoutWrite,
- ],
- name: Some("Organization Admin"),
- is_invitable: false,
- is_deletable: false,
- is_updatable: false,
- },
- );
-
- // MERCHANT ROLES
- roles.insert(
- consts::user_role::ROLE_ID_MERCHANT_ADMIN,
- RoleInfo {
- permissions: vec![
- Permission::PaymentRead,
- Permission::PaymentWrite,
- Permission::RefundRead,
- Permission::RefundWrite,
- Permission::ApiKeyRead,
- Permission::ApiKeyWrite,
- Permission::MerchantAccountRead,
- Permission::MerchantAccountWrite,
- Permission::MerchantConnectorAccountRead,
- Permission::MerchantConnectorAccountWrite,
- Permission::RoutingRead,
- Permission::RoutingWrite,
- Permission::ThreeDsDecisionManagerWrite,
- Permission::ThreeDsDecisionManagerRead,
- Permission::SurchargeDecisionManagerWrite,
- Permission::SurchargeDecisionManagerRead,
- Permission::DisputeRead,
- Permission::DisputeWrite,
- Permission::MandateRead,
- Permission::MandateWrite,
- Permission::CustomerRead,
- Permission::CustomerWrite,
- Permission::Analytics,
- Permission::UsersRead,
- Permission::UsersWrite,
- Permission::PayoutRead,
- Permission::PayoutWrite,
- ],
- name: Some("Admin"),
- is_invitable: true,
- is_deletable: true,
- is_updatable: true,
- },
- );
- roles.insert(
- consts::user_role::ROLE_ID_MERCHANT_VIEW_ONLY,
- RoleInfo {
- permissions: vec![
- Permission::PaymentRead,
- Permission::RefundRead,
- Permission::ApiKeyRead,
- Permission::MerchantAccountRead,
- Permission::MerchantConnectorAccountRead,
- Permission::RoutingRead,
- Permission::ThreeDsDecisionManagerRead,
- Permission::SurchargeDecisionManagerRead,
- Permission::DisputeRead,
- Permission::MandateRead,
- Permission::CustomerRead,
- Permission::Analytics,
- Permission::UsersRead,
- Permission::PayoutRead,
- ],
- name: Some("View Only"),
- is_invitable: true,
- is_deletable: true,
- is_updatable: true,
- },
- );
- roles.insert(
- consts::user_role::ROLE_ID_MERCHANT_IAM_ADMIN,
- RoleInfo {
- permissions: vec![
- Permission::PaymentRead,
- Permission::RefundRead,
- Permission::ApiKeyRead,
- Permission::MerchantAccountRead,
- Permission::MerchantConnectorAccountRead,
- Permission::RoutingRead,
- Permission::ThreeDsDecisionManagerRead,
- Permission::SurchargeDecisionManagerRead,
- Permission::DisputeRead,
- Permission::MandateRead,
- Permission::CustomerRead,
- Permission::Analytics,
- Permission::UsersRead,
- Permission::UsersWrite,
- Permission::PayoutRead,
- ],
- name: Some("IAM"),
- is_invitable: true,
- is_deletable: true,
- is_updatable: true,
- },
- );
- roles.insert(
- consts::user_role::ROLE_ID_MERCHANT_DEVELOPER,
- RoleInfo {
- permissions: vec![
- Permission::PaymentRead,
- Permission::RefundRead,
- Permission::ApiKeyRead,
- Permission::ApiKeyWrite,
- Permission::MerchantAccountRead,
- Permission::MerchantConnectorAccountRead,
- Permission::RoutingRead,
- Permission::ThreeDsDecisionManagerRead,
- Permission::SurchargeDecisionManagerRead,
- Permission::DisputeRead,
- Permission::MandateRead,
- Permission::CustomerRead,
- Permission::Analytics,
- Permission::UsersRead,
- Permission::PayoutRead,
- ],
- name: Some("Developer"),
- is_invitable: true,
- is_deletable: true,
- is_updatable: true,
- },
- );
- roles.insert(
- consts::user_role::ROLE_ID_MERCHANT_OPERATOR,
- RoleInfo {
- permissions: vec![
- Permission::PaymentRead,
- Permission::PaymentWrite,
- Permission::RefundRead,
- Permission::RefundWrite,
- Permission::ApiKeyRead,
- Permission::MerchantAccountRead,
- Permission::MerchantConnectorAccountRead,
- Permission::MerchantConnectorAccountWrite,
- Permission::RoutingRead,
- Permission::RoutingWrite,
- Permission::ThreeDsDecisionManagerRead,
- Permission::ThreeDsDecisionManagerWrite,
- Permission::SurchargeDecisionManagerRead,
- Permission::SurchargeDecisionManagerWrite,
- Permission::DisputeRead,
- Permission::MandateRead,
- Permission::CustomerRead,
- Permission::Analytics,
- Permission::UsersRead,
- Permission::PayoutRead,
- Permission::PayoutWrite,
- ],
- name: Some("Operator"),
- is_invitable: true,
- is_deletable: true,
- is_updatable: true,
- },
- );
- roles.insert(
- consts::user_role::ROLE_ID_MERCHANT_CUSTOMER_SUPPORT,
- RoleInfo {
- permissions: vec![
- Permission::PaymentRead,
- Permission::RefundRead,
- Permission::RefundWrite,
- Permission::DisputeRead,
- Permission::DisputeWrite,
- Permission::MerchantAccountRead,
- Permission::MerchantConnectorAccountRead,
- Permission::MandateRead,
- Permission::CustomerRead,
- Permission::Analytics,
- Permission::PayoutRead,
- ],
- name: Some("Customer Support"),
- is_invitable: true,
- is_deletable: true,
- is_updatable: true,
- },
- );
- roles
-});
-
-pub fn get_role_name_from_id(role_id: &str) -> Option<&'static str> {
- PREDEFINED_PERMISSIONS
- .get(role_id)
- .and_then(|role_info| role_info.name)
-}
-
-#[cfg(feature = "olap")]
-pub fn is_role_invitable(role_id: &str) -> UserResult<bool> {
- PREDEFINED_PERMISSIONS
- .get(role_id)
- .map(|role_info| role_info.is_invitable)
- .ok_or(UserErrors::InvalidRoleId.into())
- .attach_printable(format!("role_id = {} doesn't exist", role_id))
-}
-
-#[cfg(feature = "olap")]
-pub fn is_role_deletable(role_id: &str) -> UserResult<bool> {
- PREDEFINED_PERMISSIONS
- .get(role_id)
- .map(|role_info| role_info.is_deletable)
- .ok_or(UserErrors::InvalidRoleId.into())
- .attach_printable(format!("role_id = {} doesn't exist", role_id))
-}
-
-#[cfg(feature = "olap")]
-pub fn is_role_updatable(role_id: &str) -> UserResult<bool> {
- PREDEFINED_PERMISSIONS
- .get(role_id)
- .map(|role_info| role_info.is_updatable)
- .ok_or(UserErrors::InvalidRoleId.into())
- .attach_printable(format!("role_id = {} doesn't exist", role_id))
-}
diff --git a/crates/router/src/types/domain/user.rs b/crates/router/src/types/domain/user.rs
index 42cb71458d5..58a0a68df51 100644
--- a/crates/router/src/types/domain/user.rs
+++ b/crates/router/src/types/domain/user.rs
@@ -3,7 +3,7 @@ use std::{collections::HashSet, ops, str::FromStr};
use api_models::{
admin as admin_api, organization as api_org, user as user_api, user_role as user_role_api,
};
-use common_enums::{EntityType, TokenPurpose};
+use common_enums::EntityType;
use common_utils::{
crypto::Encryptable, errors::CustomResult, id_type, new_type::MerchantName, pii, type_name,
types::keymanager::Identifier,
@@ -32,13 +32,9 @@ use crate::{
},
db::{user_role::InsertUserRolePayload, GlobalStorageInterface},
routes::SessionState,
- services::{
- self,
- authentication::{self as auth, UserFromToken},
- authorization::info,
- },
+ services::{self, authentication::UserFromToken, authorization::info},
types::transformers::ForeignFrom,
- utils::{self, user::password},
+ utils::user::password,
};
pub mod dashboard_metadata;
@@ -1115,130 +1111,6 @@ impl From<info::PermissionModule> for user_role_api::PermissionModule {
}
}
-pub enum SignInWithRoleStrategyType {
- SingleRole(SignInWithSingleRoleStrategy),
- MultipleRoles(SignInWithMultipleRolesStrategy),
-}
-
-impl SignInWithRoleStrategyType {
- pub async fn decide_signin_strategy_by_user_roles(
- user: UserFromStorage,
- user_roles: Vec<UserRole>,
- ) -> UserResult<Self> {
- if user_roles.is_empty() {
- return Err(UserErrors::InternalServerError.into());
- }
-
- if let Some(user_role) = user_roles
- .iter()
- .find(|role| role.status == UserStatus::Active)
- {
- Ok(Self::SingleRole(SignInWithSingleRoleStrategy {
- user,
- user_role: Box::new(user_role.clone()),
- }))
- } else {
- Ok(Self::MultipleRoles(SignInWithMultipleRolesStrategy {
- user,
- user_roles,
- }))
- }
- }
-
- pub async fn get_signin_response(
- self,
- state: &SessionState,
- ) -> UserResult<user_api::SignInResponse> {
- match self {
- Self::SingleRole(strategy) => strategy.get_signin_response(state).await,
- Self::MultipleRoles(strategy) => strategy.get_signin_response(state).await,
- }
- }
-}
-
-pub struct SignInWithSingleRoleStrategy {
- pub user: UserFromStorage,
- pub user_role: Box<UserRole>,
-}
-
-impl SignInWithSingleRoleStrategy {
- async fn get_signin_response(
- self,
- state: &SessionState,
- ) -> UserResult<user_api::SignInResponse> {
- let token = utils::user::generate_jwt_auth_token_without_profile(
- state,
- &self.user,
- &self.user_role,
- )
- .await?;
- utils::user_role::set_role_permissions_in_cache_by_user_role(state, &self.user_role).await;
-
- let dashboard_entry_response =
- utils::user::get_dashboard_entry_response(state, self.user, *self.user_role, token)?;
-
- Ok(user_api::SignInResponse::DashboardEntry(
- dashboard_entry_response,
- ))
- }
-}
-
-pub struct SignInWithMultipleRolesStrategy {
- pub user: UserFromStorage,
- pub user_roles: Vec<UserRole>,
-}
-
-impl SignInWithMultipleRolesStrategy {
- async fn get_signin_response(
- self,
- state: &SessionState,
- ) -> UserResult<user_api::SignInResponse> {
- let merchant_accounts = state
- .store
- .list_multiple_merchant_accounts(
- &state.into(),
- self.user_roles
- .iter()
- .map(|role| {
- role.merchant_id
- .clone()
- .ok_or(UserErrors::InternalServerError)
- })
- .collect::<Result<Vec<_>, _>>()?,
- )
- .await
- .change_context(UserErrors::InternalServerError)?;
-
- let roles =
- utils::user_role::get_multiple_role_info_for_user_roles(state, &self.user_roles)
- .await?;
-
- let merchant_details = utils::user::get_multiple_merchant_details_with_status(
- self.user_roles,
- merchant_accounts,
- roles,
- )?;
-
- Ok(user_api::SignInResponse::MerchantSelect(
- user_api::MerchantSelectResponse {
- name: self.user.get_name(),
- email: self.user.get_email(),
- token: auth::SinglePurposeToken::new_token(
- self.user.get_user_id().to_string(),
- TokenPurpose::AcceptInvite,
- Origin::SignIn,
- &state.conf,
- vec![],
- )
- .await?
- .into(),
- merchants: merchant_details,
- verification_days_left: utils::user::get_verification_days_left(state, &self.user)?,
- },
- ))
- }
-}
-
impl ForeignFrom<UserStatus> for user_role_api::UserStatus {
fn foreign_from(value: UserStatus) -> Self {
match value {
diff --git a/crates/router/src/types/domain/user/decision_manager.rs b/crates/router/src/types/domain/user/decision_manager.rs
index 92f1d4ba5ba..4206b16df6d 100644
--- a/crates/router/src/types/domain/user/decision_manager.rs
+++ b/crates/router/src/types/domain/user/decision_manager.rs
@@ -1,6 +1,6 @@
use common_enums::TokenPurpose;
use diesel_models::{enums::UserStatus, user_role::UserRole};
-use error_stack::report;
+use error_stack::{report, ResultExt};
use masking::Secret;
use super::UserFromStorage;
@@ -109,16 +109,14 @@ impl JWTFlow {
) -> UserResult<Secret<String>> {
auth::AuthToken::new_token(
next_flow.user.get_user_id().to_string(),
- user_role
- .merchant_id
- .clone()
- .ok_or(report!(UserErrors::InternalServerError))?,
+ utils::user_role::get_single_merchant_id(state, user_role).await?,
user_role.role_id.clone(),
&state.conf,
user_role
.org_id
.clone()
- .ok_or(report!(UserErrors::InternalServerError))?,
+ .ok_or(report!(UserErrors::InternalServerError))
+ .attach_printable("org_id not found")?,
None,
)
.await
diff --git a/crates/router/src/utils/user.rs b/crates/router/src/utils/user.rs
index b2170e7294a..a1bd6972dab 100644
--- a/crates/router/src/utils/user.rs
+++ b/crates/router/src/utils/user.rs
@@ -1,11 +1,11 @@
-use std::{collections::HashMap, sync::Arc};
+use std::sync::Arc;
use api_models::user as user_api;
use common_enums::UserAuthType;
use common_utils::{
encryption::Encryption, errors::CustomResult, id_type, type_name, types::keymanager::Identifier,
};
-use diesel_models::{enums::UserStatus, user_role::UserRole};
+use diesel_models::user_role::UserRole;
use error_stack::{report, ResultExt};
use masking::{ExposeInterface, Secret};
use redis_interface::RedisConnectionPool;
@@ -128,28 +128,6 @@ pub async fn generate_jwt_auth_token_with_attributes(
Ok(Secret::new(token))
}
-pub fn get_dashboard_entry_response(
- state: &SessionState,
- user: UserFromStorage,
- user_role: UserRole,
- token: Secret<String>,
-) -> UserResult<user_api::DashboardEntryResponse> {
- let verification_days_left = get_verification_days_left(state, &user)?;
-
- Ok(user_api::DashboardEntryResponse {
- merchant_id: user_role.merchant_id.ok_or(
- report!(UserErrors::InternalServerError)
- .attach_printable("merchant_id not found for user_role"),
- )?,
- token,
- name: user.get_name(),
- email: user.get_email(),
- user_id: user.get_user_id().to_string(),
- verification_days_left,
- user_role: user_role.role_id,
- })
-}
-
#[allow(unused_variables)]
pub fn get_verification_days_left(
state: &SessionState,
@@ -161,54 +139,6 @@ pub fn get_verification_days_left(
return Ok(None);
}
-pub fn get_multiple_merchant_details_with_status(
- user_roles: Vec<UserRole>,
- merchant_accounts: Vec<MerchantAccount>,
- roles: Vec<RoleInfo>,
-) -> UserResult<Vec<user_api::UserMerchantAccount>> {
- let merchant_account_map = merchant_accounts
- .into_iter()
- .map(|merchant_account| (merchant_account.get_id().clone(), merchant_account))
- .collect::<HashMap<_, _>>();
-
- let role_map = roles
- .into_iter()
- .map(|role_info| (role_info.get_role_id().to_string(), role_info))
- .collect::<HashMap<_, _>>();
-
- user_roles
- .into_iter()
- .map(|user_role| {
- let Some(merchant_id) = &user_role.merchant_id else {
- return Err(report!(UserErrors::InternalServerError))
- .attach_printable("merchant_id not found for user_role");
- };
- let Some(org_id) = &user_role.org_id else {
- return Err(report!(UserErrors::InternalServerError)
- .attach_printable("org_id not found in user_role"));
- };
- let merchant_account = merchant_account_map
- .get(merchant_id)
- .ok_or(UserErrors::InternalServerError)
- .attach_printable("Merchant account for user role doesn't exist")?;
-
- let role_info = role_map
- .get(&user_role.role_id)
- .ok_or(UserErrors::InternalServerError)
- .attach_printable("Role info for user role doesn't exist")?;
-
- Ok(user_api::UserMerchantAccount {
- merchant_id: merchant_id.to_owned(),
- merchant_name: merchant_account.merchant_name.clone(),
- is_active: user_role.status == UserStatus::Active,
- role_id: user_role.role_id,
- role_name: role_info.get_role_name().to_string(),
- org_id: org_id.to_owned(),
- })
- })
- .collect()
-}
-
pub async fn get_user_from_db_by_email(
state: &SessionState,
email: domain::UserEmail,
@@ -220,13 +150,6 @@ pub async fn get_user_from_db_by_email(
.map(UserFromStorage::from)
}
-pub fn get_token_from_signin_response(resp: &user_api::SignInResponse) -> Secret<String> {
- match resp {
- user_api::SignInResponse::DashboardEntry(data) => data.token.clone(),
- user_api::SignInResponse::MerchantSelect(data) => data.token.clone(),
- }
-}
-
pub fn get_redis_connection(state: &SessionState) -> UserResult<Arc<RedisConnectionPool>> {
state
.store
diff --git a/crates/router/src/utils/user_role.rs b/crates/router/src/utils/user_role.rs
index 1791b5308b4..dbe3ed6d585 100644
--- a/crates/router/src/utils/user_role.rs
+++ b/crates/router/src/utils/user_role.rs
@@ -1,7 +1,7 @@
use std::collections::HashSet;
use api_models::user_role as user_role_api;
-use common_enums::PermissionGroup;
+use common_enums::{EntityType, PermissionGroup};
use common_utils::id_type;
use diesel_models::{
enums::UserRoleVersion,
@@ -13,7 +13,7 @@ use storage_impl::errors::StorageError;
use crate::{
consts,
- core::errors::{StorageErrorExt, UserErrors, UserResult},
+ core::errors::{UserErrors, UserResult},
routes::SessionState,
services::authorization::{self as authz, permissions::Permission, roles},
types::domain,
@@ -167,28 +167,6 @@ pub async fn set_role_permissions_in_cache_if_required(
.attach_printable("Error setting permissions in redis")
}
-pub async fn get_multiple_role_info_for_user_roles(
- state: &SessionState,
- user_roles: &[UserRole],
-) -> UserResult<Vec<roles::RoleInfo>> {
- futures::future::try_join_all(user_roles.iter().map(|user_role| async {
- let Some(merchant_id) = &user_role.merchant_id else {
- return Err(report!(UserErrors::InternalServerError))
- .attach_printable("merchant_id not found for user_role");
- };
- let Some(org_id) = &user_role.org_id else {
- return Err(report!(UserErrors::InternalServerError)
- .attach_printable("org_id not found in user_role"));
- };
- let role = roles::RoleInfo::from_role_id(state, &user_role.role_id, merchant_id, org_id)
- .await
- .to_not_found_response(UserErrors::InternalServerError)
- .attach_printable("Role for user role doesn't exist")?;
- Ok::<_, Report<UserErrors>>(role)
- }))
- .await
-}
-
pub async fn update_v1_and_v2_user_roles_in_db(
state: &SessionState,
user_id: &str,
@@ -234,3 +212,38 @@ pub async fn update_v1_and_v2_user_roles_in_db(
(updated_v1_role, updated_v2_role)
}
+
+pub async fn get_single_merchant_id(
+ state: &SessionState,
+ user_role: &UserRole,
+) -> UserResult<id_type::MerchantId> {
+ match user_role.entity_type {
+ Some(EntityType::Organization) => Ok(state
+ .store
+ .list_merchant_accounts_by_organization_id(
+ &state.into(),
+ user_role
+ .org_id
+ .as_ref()
+ .ok_or(UserErrors::InternalServerError)
+ .attach_printable("org_id not found")?
+ .get_string_repr(),
+ )
+ .await
+ .change_context(UserErrors::InternalServerError)
+ .attach_printable("Failed to get merchant list for org")?
+ .first()
+ .ok_or(UserErrors::InternalServerError)
+ .attach_printable("No merchants found for org_id")?
+ .get_id()
+ .clone()),
+ Some(EntityType::Merchant)
+ | Some(EntityType::Internal)
+ | Some(EntityType::Profile)
+ | None => user_role
+ .merchant_id
+ .clone()
+ .ok_or(UserErrors::InternalServerError)
+ .attach_printable("merchant_id not found"),
+ }
+}
diff --git a/postman/collection-dir/users/Flow Testcases/Sign In/.meta.json b/postman/collection-dir/users/Flow Testcases/Sign In/.meta.json
index 84ed2cb9494..75badf2502c 100644
--- a/postman/collection-dir/users/Flow Testcases/Sign In/.meta.json
+++ b/postman/collection-dir/users/Flow Testcases/Sign In/.meta.json
@@ -2,7 +2,7 @@
"childrenOrder": [
"Signin",
"Signin Wrong",
- "Signin Token Only",
- "Signin Token Only Wrong"
+ "Signin V2 - To be deprecated",
+ "Signin V2 Wrong"
]
}
diff --git a/postman/collection-dir/users/Flow Testcases/Sign In/Signin Token Only Wrong/.event.meta.json b/postman/collection-dir/users/Flow Testcases/Sign In/Signin V2 - To be deprecated/.event.meta.json
similarity index 100%
rename from postman/collection-dir/users/Flow Testcases/Sign In/Signin Token Only Wrong/.event.meta.json
rename to postman/collection-dir/users/Flow Testcases/Sign In/Signin V2 - To be deprecated/.event.meta.json
diff --git a/postman/collection-dir/users/Flow Testcases/Sign In/Signin Token Only/event.test.js b/postman/collection-dir/users/Flow Testcases/Sign In/Signin V2 - To be deprecated/event.test.js
similarity index 61%
rename from postman/collection-dir/users/Flow Testcases/Sign In/Signin Token Only/event.test.js
rename to postman/collection-dir/users/Flow Testcases/Sign In/Signin V2 - To be deprecated/event.test.js
index 9105ce122cb..c8d654d21e9 100644
--- a/postman/collection-dir/users/Flow Testcases/Sign In/Signin Token Only/event.test.js
+++ b/postman/collection-dir/users/Flow Testcases/Sign In/Signin V2 - To be deprecated/event.test.js
@@ -1,24 +1,24 @@
console.log("[LOG]::x-request-id - " + pm.response.headers.get("x-request-id"));
// Validate status 2xx
-pm.test("[POST]::user/v2/signin?token_only=true - Status code is 2xx", function () {
+pm.test("[POST]::user/v2/signin - Status code is 2xx", function () {
pm.response.to.be.success;
});
// Validate if response header has matching content-type
-pm.test("[POST]::user/v2/signin?token_only=true - Content-Type is application/json", function () {
+pm.test("[POST]::user/v2/signin - Content-Type is application/json", function () {
pm.expect(pm.response.headers.get("Content-Type")).to.include(
"application/json",
);
});
// Validate if response has JSON Body
-pm.test("[POST]::user/v2/signin?token_only=true - Response has JSON Body", function () {
+pm.test("[POST]::user/v2/signin - Response has JSON Body", function () {
pm.response.to.have.jsonBody();
});
// Validate specific JSON response content
-pm.test("[POST]::user/v2/signin?token_only=true - Response contains token", function () {
+pm.test("[POST]::user/v2/signin - Response contains token", function () {
var jsonData = pm.response.json();
pm.expect(jsonData).to.have.property("token");
pm.expect(jsonData.token).to.be.a("string").and.to.not.be.empty;
diff --git a/postman/collection-dir/users/Flow Testcases/Sign In/Signin Token Only/request.json b/postman/collection-dir/users/Flow Testcases/Sign In/Signin V2 - To be deprecated/request.json
similarity index 75%
rename from postman/collection-dir/users/Flow Testcases/Sign In/Signin Token Only/request.json
rename to postman/collection-dir/users/Flow Testcases/Sign In/Signin V2 - To be deprecated/request.json
index 62028501a50..1d23f6e9652 100644
--- a/postman/collection-dir/users/Flow Testcases/Sign In/Signin Token Only/request.json
+++ b/postman/collection-dir/users/Flow Testcases/Sign In/Signin V2 - To be deprecated/request.json
@@ -18,7 +18,7 @@
}
},
"url": {
- "raw": "{{baseUrl}}/user/v2/signin?token_only=true",
+ "raw": "{{baseUrl}}/user/v2/signin",
"host": [
"{{baseUrl}}"
],
@@ -26,12 +26,6 @@
"user",
"v2",
"signin"
- ],
- "query": [
- {
- "key": "token_only",
- "value": "true"
- }
]
}
}
diff --git a/postman/collection-dir/users/Flow Testcases/Sign In/Signin Token Only Wrong/response.json b/postman/collection-dir/users/Flow Testcases/Sign In/Signin V2 - To be deprecated/response.json
similarity index 100%
rename from postman/collection-dir/users/Flow Testcases/Sign In/Signin Token Only Wrong/response.json
rename to postman/collection-dir/users/Flow Testcases/Sign In/Signin V2 - To be deprecated/response.json
diff --git a/postman/collection-dir/users/Flow Testcases/Sign In/Signin Token Only/.event.meta.json b/postman/collection-dir/users/Flow Testcases/Sign In/Signin V2 Wrong/.event.meta.json
similarity index 100%
rename from postman/collection-dir/users/Flow Testcases/Sign In/Signin Token Only/.event.meta.json
rename to postman/collection-dir/users/Flow Testcases/Sign In/Signin V2 Wrong/.event.meta.json
diff --git a/postman/collection-dir/users/Flow Testcases/Sign In/Signin Token Only Wrong/event.test.js b/postman/collection-dir/users/Flow Testcases/Sign In/Signin V2 Wrong/event.test.js
similarity index 57%
rename from postman/collection-dir/users/Flow Testcases/Sign In/Signin Token Only Wrong/event.test.js
rename to postman/collection-dir/users/Flow Testcases/Sign In/Signin V2 Wrong/event.test.js
index a9297538452..3cc82ebb013 100644
--- a/postman/collection-dir/users/Flow Testcases/Sign In/Signin Token Only Wrong/event.test.js
+++ b/postman/collection-dir/users/Flow Testcases/Sign In/Signin V2 Wrong/event.test.js
@@ -1,18 +1,18 @@
console.log("[LOG]::x-request-id - " + pm.response.headers.get("x-request-id"));
// Validate status 4xx
-pm.test("[POST]::/user/v2/signin?token_only=true - Status code is 401", function () {
+pm.test("[POST]::/user/v2/signin - Status code is 401", function () {
pm.response.to.have.status(401);
});
// Validate if response header has matching content-type
-pm.test("[POST]::user/v2/signin?token_only=true - Content-Type is application/json", function () {
+pm.test("[POST]::user/v2/signin - Content-Type is application/json", function () {
pm.expect(pm.response.headers.get("Content-Type")).to.include(
"application/json",
);
});
// Validate if response has JSON Body
-pm.test("[POST]::user/v2/signin?token_only=true - Response has JSON Body", function () {
+pm.test("[POST]::user/v2/signin - Response has JSON Body", function () {
pm.response.to.have.jsonBody();
});
\ No newline at end of file
diff --git a/postman/collection-dir/users/Flow Testcases/Sign In/Signin Token Only Wrong/request.json b/postman/collection-dir/users/Flow Testcases/Sign In/Signin V2 Wrong/request.json
similarity index 75%
rename from postman/collection-dir/users/Flow Testcases/Sign In/Signin Token Only Wrong/request.json
rename to postman/collection-dir/users/Flow Testcases/Sign In/Signin V2 Wrong/request.json
index 7fee4c465c8..775b0972d57 100644
--- a/postman/collection-dir/users/Flow Testcases/Sign In/Signin Token Only Wrong/request.json
+++ b/postman/collection-dir/users/Flow Testcases/Sign In/Signin V2 Wrong/request.json
@@ -18,7 +18,7 @@
}
},
"url": {
- "raw": "{{baseUrl}}/user/v2/signin?token_only=true",
+ "raw": "{{baseUrl}}/user/v2/signin",
"host": [
"{{baseUrl}}"
],
@@ -26,12 +26,6 @@
"user",
"v2",
"signin"
- ],
- "query": [
- {
- "key": "token_only",
- "value": "true"
- }
]
}
}
diff --git a/postman/collection-dir/users/Flow Testcases/Sign In/Signin Token Only/response.json b/postman/collection-dir/users/Flow Testcases/Sign In/Signin V2 Wrong/response.json
similarity index 100%
rename from postman/collection-dir/users/Flow Testcases/Sign In/Signin Token Only/response.json
rename to postman/collection-dir/users/Flow Testcases/Sign In/Signin V2 Wrong/response.json
diff --git a/postman/collection-dir/users/Flow Testcases/Sign In/Signin Wrong/event.test.js b/postman/collection-dir/users/Flow Testcases/Sign In/Signin Wrong/event.test.js
index 6cb6b69ba6c..bd346bc0cb3 100644
--- a/postman/collection-dir/users/Flow Testcases/Sign In/Signin Wrong/event.test.js
+++ b/postman/collection-dir/users/Flow Testcases/Sign In/Signin Wrong/event.test.js
@@ -1,18 +1,18 @@
console.log("[LOG]::x-request-id - " + pm.response.headers.get("x-request-id"));
// Validate status code is 4xx Bad Request
-pm.test("[POST]::/user/v2/signin - Status code is 401", function () {
+pm.test("[POST]::/user/signin - Status code is 401", function () {
pm.response.to.have.status(401);
});
// Validate if response header has matching content-type
-pm.test("[POST]::/user/v2/signin - Content-Type is application/json", function () {
+pm.test("[POST]::/user/signin - Content-Type is application/json", function () {
pm.expect(pm.response.headers.get("Content-Type")).to.include(
"application/json",
);
});
// Validate if response has JSON Body
-pm.test("[POST]::/user/v2/signin - Response has JSON Body", function () {
+pm.test("[POST]::/user/signin - Response has JSON Body", function () {
pm.response.to.have.jsonBody();
});
\ No newline at end of file
diff --git a/postman/collection-dir/users/Flow Testcases/Sign In/Signin Wrong/request.json b/postman/collection-dir/users/Flow Testcases/Sign In/Signin Wrong/request.json
index 775b0972d57..0cd97ee6de1 100644
--- a/postman/collection-dir/users/Flow Testcases/Sign In/Signin Wrong/request.json
+++ b/postman/collection-dir/users/Flow Testcases/Sign In/Signin Wrong/request.json
@@ -18,13 +18,12 @@
}
},
"url": {
- "raw": "{{baseUrl}}/user/v2/signin",
+ "raw": "{{baseUrl}}/user/signin",
"host": [
"{{baseUrl}}"
],
"path": [
"user",
- "v2",
"signin"
]
}
diff --git a/postman/collection-dir/users/Flow Testcases/Sign In/Signin/event.test.js b/postman/collection-dir/users/Flow Testcases/Sign In/Signin/event.test.js
index 4724ff5981f..23dc84eb8a9 100644
--- a/postman/collection-dir/users/Flow Testcases/Sign In/Signin/event.test.js
+++ b/postman/collection-dir/users/Flow Testcases/Sign In/Signin/event.test.js
@@ -1,24 +1,24 @@
console.log("[LOG]::x-request-id - " + pm.response.headers.get("x-request-id"));
// Validate status 2xx
-pm.test("[POST]::/user/v2/signin - Status code is 2xx", function () {
+pm.test("[POST]::/user/signin - Status code is 2xx", function () {
pm.response.to.be.success;
});
// Validate if response header has matching content-type
-pm.test("[POST]::/user/v2/signin - Content-Type is application/json", function () {
+pm.test("[POST]::/user/signin - Content-Type is application/json", function () {
pm.expect(pm.response.headers.get("Content-Type")).to.include(
"application/json",
);
});
// Validate if response has JSON Body
-pm.test("[POST]::/user/v2/signin - Response has JSON Body", function () {
+pm.test("[POST]::/user/signin - Response has JSON Body", function () {
pm.response.to.have.jsonBody();
});
// Validate specific JSON response content
-pm.test("[POST]::/user/v2/signin - Response contains token", function () {
+pm.test("[POST]::/user/signin - Response contains token", function () {
var jsonData = pm.response.json();
pm.expect(jsonData).to.have.property("token");
pm.expect(jsonData.token).to.be.a("string").and.to.not.be.empty;
diff --git a/postman/collection-dir/users/Flow Testcases/Sign In/Signin/request.json b/postman/collection-dir/users/Flow Testcases/Sign In/Signin/request.json
index 1d23f6e9652..17f0eccff36 100644
--- a/postman/collection-dir/users/Flow Testcases/Sign In/Signin/request.json
+++ b/postman/collection-dir/users/Flow Testcases/Sign In/Signin/request.json
@@ -18,13 +18,12 @@
}
},
"url": {
- "raw": "{{baseUrl}}/user/v2/signin",
+ "raw": "{{baseUrl}}/user/signin",
"host": [
"{{baseUrl}}"
],
"path": [
"user",
- "v2",
"signin"
]
}
diff --git a/postman/collection-json/users.postman_collection.json b/postman/collection-json/users.postman_collection.json
index 142eaf3b232..ac6ee2f8cb0 100644
--- a/postman/collection-json/users.postman_collection.json
+++ b/postman/collection-json/users.postman_collection.json
@@ -1,567 +1,553 @@
{
- "event": [
- {
- "listen": "prerequest",
- "script": {
- "exec": [
- ""
- ],
- "type": "text/javascript"
- }
- },
- {
- "listen": "test",
- "script": {
- "exec": [
- ""
- ],
- "type": "text/javascript"
- }
- }
- ],
- "item": [
- {
- "name": "Health check",
- "item": [
- {
- "name": "New Request",
- "event": [
- {
- "listen": "test",
- "script": {
- "exec": [
- "// Validate status 2xx",
- "pm.test(\"[POST]::/health - Status code is 2xx\", function () {",
- " pm.response.to.be.success;",
- "});",
- ""
- ],
- "type": "text/javascript"
- }
- }
- ],
- "request": {
- "method": "GET",
- "header": [],
- "url": {
- "raw": "{{baseUrl}}/health",
- "host": [
- "{{baseUrl}}"
- ],
- "path": [
- "health"
- ]
- }
- },
- "response": []
- }
- ]
- },
- {
- "name": "Flow Testcases",
- "item": [
- {
- "name": "Sign Up",
- "item": [
- {
- "name": "Connect Account",
- "event": [
- {
- "listen": "test",
- "script": {
- "exec": [
- "console.log(\"[LOG]::x-request-id - \" + pm.response.headers.get(\"x-request-id\"));",
- "",
- "// Validate status 2xx",
- "pm.test(\"[POST]::/user/connect_account - Status code is 2xx\", function () {",
- " pm.response.to.be.success;",
- "});",
- "",
- "// Validate if response header has matching content-type",
- "pm.test(\"[POST]::/user/connect_account - Content-Type is application/json\", function () {",
- " pm.expect(pm.response.headers.get(\"Content-Type\")).to.include(",
- " \"application/json\",",
- " );",
- "});",
- "",
- "// Validate if response has JSON Body",
- "pm.test(\"[POST]::/user/connect_account - Response has JSON Body\", function () {",
- " pm.response.to.have.jsonBody();",
- "});",
- "",
- "// Validate specific JSON response content",
- "pm.test(\"[POST]::/user/connect_account - Response contains is_email_sent\", function () {",
- " var jsonData = pm.response.json();",
- " pm.expect(jsonData).to.have.property(\"is_email_sent\");",
- " pm.expect(jsonData.is_email_sent).to.be.true;",
- "});",
- "",
- ""
- ],
- "type": "text/javascript"
- }
- },
- {
- "listen": "prerequest",
- "script": {
- "exec": [
- "",
- "var baseEmail = pm.environment.get('user_base_email_for_signup');",
- "var emailDomain = pm.environment.get(\"user_domain_for_signup\");",
- "",
- "// Generate a unique email address",
- "var uniqueEmail = baseEmail + new Date().getTime() + emailDomain;",
- "// Set the unique email address as an environment variable",
- "pm.environment.set('unique_email', uniqueEmail);",
- ""
- ],
- "type": "text/javascript"
- }
- }
- ],
- "request": {
- "method": "POST",
- "header": [
- {
- "key": "Content-Type",
- "value": "application/json"
- },
- {
- "key": "Cookie",
- "value": "Cookie_1=value"
- }
- ],
- "body": {
- "mode": "raw",
- "raw": "{\"email\":\"{{unique_email}}\"}"
- },
- "url": {
- "raw": "{{baseUrl}}/user/connect_account",
- "host": [
- "{{baseUrl}}"
- ],
- "path": [
- "user",
- "connect_account"
- ]
- }
- },
- "response": []
- }
- ]
- },
- {
- "name": "Sign In",
- "item": [
- {
- "name": "Signin",
- "event": [
- {
- "listen": "test",
- "script": {
- "exec": [
- "console.log(\"[LOG]::x-request-id - \" + pm.response.headers.get(\"x-request-id\"));",
- "",
- "// Validate status 2xx",
- "pm.test(\"[POST]::/user/v2/signin - Status code is 2xx\", function () {",
- " pm.response.to.be.success;",
- "});",
- "",
- "// Validate if response header has matching content-type",
- "pm.test(\"[POST]::/user/v2/signin - Content-Type is application/json\", function () {",
- " pm.expect(pm.response.headers.get(\"Content-Type\")).to.include(",
- " \"application/json\",",
- " );",
- "});",
- "",
- "// Validate if response has JSON Body",
- "pm.test(\"[POST]::/user/v2/signin - Response has JSON Body\", function () {",
- " pm.response.to.have.jsonBody();",
- "});",
- "",
- "// Validate specific JSON response content",
- "pm.test(\"[POST]::/user/v2/signin - Response contains token\", function () {",
- " var jsonData = pm.response.json();",
- " pm.expect(jsonData).to.have.property(\"token\");",
- " pm.expect(jsonData.token).to.be.a(\"string\").and.to.not.be.empty;",
- "});"
- ],
- "type": "text/javascript"
- }
- },
- {
- "listen": "prerequest",
- "script": {
- "exec": [
- ""
- ],
- "type": "text/javascript"
- }
- }
- ],
- "request": {
- "method": "POST",
- "header": [
- {
- "key": "Content-Type",
- "value": "application/json"
- },
- {
- "key": "Cookie",
- "value": "Cookie_1=value"
- }
- ],
- "body": {
- "mode": "raw",
- "raw": "{\"email\":\"{{user_email}}\",\"password\":\"{{user_password}}\"}"
- },
- "url": {
- "raw": "{{baseUrl}}/user/v2/signin",
- "host": [
- "{{baseUrl}}"
- ],
- "path": [
- "user",
- "v2",
- "signin"
- ]
- }
- },
- "response": []
- },
- {
- "name": "Signin Wrong",
- "event": [
- {
- "listen": "test",
- "script": {
- "exec": [
- "console.log(\"[LOG]::x-request-id - \" + pm.response.headers.get(\"x-request-id\"));",
- "",
- "// Validate status code is 4xx Bad Request",
- "pm.test(\"[POST]::/user/v2/signin - Status code is 401\", function () {",
- " pm.response.to.have.status(401);",
- "});",
- "",
- "// Validate if response header has matching content-type",
- "pm.test(\"[POST]::/user/v2/signin - Content-Type is application/json\", function () {",
- " pm.expect(pm.response.headers.get(\"Content-Type\")).to.include(",
- " \"application/json\",",
- " );",
- "});",
- "",
- "// Validate if response has JSON Body",
- "pm.test(\"[POST]::/user/v2/signin - Response has JSON Body\", function () {",
- " pm.response.to.have.jsonBody();",
- "});"
- ],
- "type": "text/javascript"
- }
- }
- ],
- "request": {
- "method": "POST",
- "header": [
- {
- "key": "Content-Type",
- "value": "application/json"
- },
- {
- "key": "Cookie",
- "value": "Cookie_1=value"
- }
- ],
- "body": {
- "mode": "raw",
- "raw": "{\"email\":\"{{user_email}}\",\"password\":\"{{wrong_password}}\"}"
- },
- "url": {
- "raw": "{{baseUrl}}/user/v2/signin",
- "host": [
- "{{baseUrl}}"
- ],
- "path": [
- "user",
- "v2",
- "signin"
- ]
- }
- },
- "response": []
- },
- {
- "name": "Signin Token Only",
- "event": [
- {
- "listen": "test",
- "script": {
- "exec": [
- "console.log(\"[LOG]::x-request-id - \" + pm.response.headers.get(\"x-request-id\"));",
- "",
- "// Validate status 2xx",
- "pm.test(\"[POST]::user/v2/signin?token_only=true - Status code is 2xx\", function () {",
- " pm.response.to.be.success;",
- "});",
- "",
- "// Validate if response header has matching content-type",
- "pm.test(\"[POST]::user/v2/signin?token_only=true - Content-Type is application/json\", function () {",
- " pm.expect(pm.response.headers.get(\"Content-Type\")).to.include(",
- " \"application/json\",",
- " );",
- "});",
- "",
- "// Validate if response has JSON Body",
- "pm.test(\"[POST]::user/v2/signin?token_only=true - Response has JSON Body\", function () {",
- " pm.response.to.have.jsonBody();",
- "});",
- "",
- "// Validate specific JSON response content",
- "pm.test(\"[POST]::user/v2/signin?token_only=true - Response contains token\", function () {",
- " var jsonData = pm.response.json();",
- " pm.expect(jsonData).to.have.property(\"token\");",
- " pm.expect(jsonData.token).to.be.a(\"string\").and.to.not.be.empty;",
- "});"
- ],
- "type": "text/javascript"
- }
- }
- ],
- "request": {
- "method": "POST",
- "header": [
- {
- "key": "Content-Type",
- "value": "application/json"
- },
- {
- "key": "Cookie",
- "value": "Cookie_1=value"
- }
- ],
- "body": {
- "mode": "raw",
- "raw": "{\"email\":\"{{user_email}}\",\"password\":\"{{user_password}}\"}"
- },
- "url": {
- "raw": "{{baseUrl}}/user/v2/signin?token_only=true",
- "host": [
- "{{baseUrl}}"
- ],
- "path": [
- "user",
- "v2",
- "signin"
- ],
- "query": [
- {
- "key": "token_only",
- "value": "true"
- }
- ]
- }
- },
- "response": []
- },
- {
- "name": "Signin Token Only Wrong",
- "event": [
- {
- "listen": "test",
- "script": {
- "exec": [
- "console.log(\"[LOG]::x-request-id - \" + pm.response.headers.get(\"x-request-id\"));",
- "",
- "// Validate status 4xx",
- "pm.test(\"[POST]::/user/v2/signin?token_only=true - Status code is 401\", function () {",
- " pm.response.to.have.status(401);",
- "});",
- "",
- "// Validate if response header has matching content-type",
- "pm.test(\"[POST]::user/v2/signin?token_only=true - Content-Type is application/json\", function () {",
- " pm.expect(pm.response.headers.get(\"Content-Type\")).to.include(",
- " \"application/json\",",
- " );",
- "});",
- "",
- "// Validate if response has JSON Body",
- "pm.test(\"[POST]::user/v2/signin?token_only=true - Response has JSON Body\", function () {",
- " pm.response.to.have.jsonBody();",
- "});"
- ],
- "type": "text/javascript"
- }
- }
- ],
- "request": {
- "method": "POST",
- "header": [
- {
- "key": "Content-Type",
- "value": "application/json"
- },
- {
- "key": "Cookie",
- "value": "Cookie_1=value"
- }
- ],
- "body": {
- "mode": "raw",
- "raw": "{\"email\":\"{{user_email}}\",\"password\":\"{{wrong_password}}\"}"
- },
- "url": {
- "raw": "{{baseUrl}}/user/v2/signin?token_only=true",
- "host": [
- "{{baseUrl}}"
- ],
- "path": [
- "user",
- "v2",
- "signin"
- ],
- "query": [
- {
- "key": "token_only",
- "value": "true"
- }
- ]
- }
- },
- "response": []
- }
- ]
- }
- ]
- }
- ],
- "info": {
- "_postman_id": "b5b40c9a-7e58-42c7-8b89-0adb208c45c9",
- "name": "users",
- "description": "## Get started\n\nJuspay Router provides a collection of APIs that enable you to process and manage payments. Our APIs accept and return JSON in the HTTP body, and return standard HTTP response codes. \nYou can consume the APIs directly using your favorite HTTP/REST library. \nWe have a testing environment referred to \"sandbox\", which you can setup to test API calls without affecting production data.\n\n### Base URLs\n\nUse the following base URLs when making requests to the APIs:\n\n| Environment | Base URL |\n| --- | --- |\n| Sandbox | [https://sandbox.hyperswitch.io](https://sandbox.hyperswitch.io) |\n| Production | [https://router.juspay.io](https://router.juspay.io) |\n\n# Authentication\n\nWhen you sign up for an account, you are given a secret key (also referred as api-key). You may authenticate all API requests with Juspay server by providing the appropriate key in the request Authorization header. \nNever share your secret api keys. Keep them guarded and secure.\n\nContact Support: \nName: Juspay Support \nEmail: [support@juspay.in](mailto:support@juspay.in)",
- "schema": "https://schema.getpostman.com/json/collection/v2.1.0/collection.json",
- "_exporter_id": "26710321"
- },
- "variable": [
- {
- "key": "baseUrl",
- "value": "",
- "type": "string"
- },
- {
- "key": "admin_api_key",
- "value": "",
- "type": "string"
- },
- {
- "key": "api_key",
- "value": "",
- "type": "string"
- },
- {
- "key": "merchant_id",
- "value": ""
- },
- {
- "key": "payment_id",
- "value": ""
- },
- {
- "key": "customer_id",
- "value": ""
- },
- {
- "key": "mandate_id",
- "value": ""
- },
- {
- "key": "payment_method_id",
- "value": ""
- },
- {
- "key": "refund_id",
- "value": ""
- },
- {
- "key": "merchant_connector_id",
- "value": ""
- },
- {
- "key": "client_secret",
- "value": "",
- "type": "string"
- },
- {
- "key": "connector_api_key",
- "value": "",
- "type": "string"
- },
- {
- "key": "publishable_key",
- "value": "",
- "type": "string"
- },
- {
- "key": "api_key_id",
- "value": "",
- "type": "string"
- },
- {
- "key": "payment_token",
- "value": ""
- },
- {
- "key": "gateway_merchant_id",
- "value": "",
- "type": "string"
- },
- {
- "key": "certificate",
- "value": "",
- "type": "string"
- },
- {
- "key": "certificate_keys",
- "value": "",
- "type": "string"
- },
- {
- "key": "connector_api_secret",
- "value": "",
- "type": "string"
- },
- {
- "key": "connector_key1",
- "value": "",
- "type": "string"
- },
- {
- "key": "connector_key2",
- "value": "",
- "type": "string"
- },
- {
- "key": "user_email",
- "value": "",
- "type": "string"
- },
- {
- "key": "user_password",
- "value": "",
- "type": "string"
- },
- {
- "key": "wrong_password",
- "value": "",
- "type": "string"
- },
- {
- "key": "user_base_email_for_signup",
- "value": "",
- "type": "string"
- },
- {
- "key": "user_domain_for_signup",
- "value": "",
- "type": "string"
- }
- ]
-}
+ "info": {
+ "_postman_id": "b5b40c9a-7e58-42c7-8b89-0adb208c45c9",
+ "name": "users",
+ "description": "## Get started\n\nJuspay Router provides a collection of APIs that enable you to process and manage payments. Our APIs accept and return JSON in the HTTP body, and return standard HTTP response codes. \nYou can consume the APIs directly using your favorite HTTP/REST library. \nWe have a testing environment referred to \"sandbox\", which you can setup to test API calls without affecting production data.\n\n### Base URLs\n\nUse the following base URLs when making requests to the APIs:\n\n| Environment | Base URL |\n| --- | --- |\n| Sandbox | [https://sandbox.hyperswitch.io](https://sandbox.hyperswitch.io) |\n| Production | [https://router.juspay.io](https://router.juspay.io) |\n\n# Authentication\n\nWhen you sign up for an account, you are given a secret key (also referred as api-key). You may authenticate all API requests with Juspay server by providing the appropriate key in the request Authorization header. \nNever share your secret api keys. Keep them guarded and secure.\n\nContact Support: \nName: Juspay Support \nEmail: [support@juspay.in](mailto:support@juspay.in)",
+ "schema": "https://schema.getpostman.com/json/collection/v2.1.0/collection.json",
+ "_exporter_id": "26710321"
+ },
+ "item": [
+ {
+ "name": "Health check",
+ "item": [
+ {
+ "name": "New Request",
+ "event": [
+ {
+ "listen": "test",
+ "script": {
+ "exec": [
+ "// Validate status 2xx",
+ "pm.test(\"[POST]::/health - Status code is 2xx\", function () {",
+ " pm.response.to.be.success;",
+ "});",
+ ""
+ ],
+ "type": "text/javascript"
+ }
+ }
+ ],
+ "request": {
+ "method": "GET",
+ "header": [],
+ "url": {
+ "raw": "{{baseUrl}}/health",
+ "host": [
+ "{{baseUrl}}"
+ ],
+ "path": [
+ "health"
+ ]
+ }
+ },
+ "response": []
+ }
+ ]
+ },
+ {
+ "name": "Flow Testcases",
+ "item": [
+ {
+ "name": "Sign Up",
+ "item": [
+ {
+ "name": "Connect Account",
+ "event": [
+ {
+ "listen": "test",
+ "script": {
+ "exec": [
+ "console.log(\"[LOG]::x-request-id - \" + pm.response.headers.get(\"x-request-id\"));",
+ "",
+ "// Validate status 2xx",
+ "pm.test(\"[POST]::/user/connect_account - Status code is 2xx\", function () {",
+ " pm.response.to.be.success;",
+ "});",
+ "",
+ "// Validate if response header has matching content-type",
+ "pm.test(\"[POST]::/user/connect_account - Content-Type is application/json\", function () {",
+ " pm.expect(pm.response.headers.get(\"Content-Type\")).to.include(",
+ " \"application/json\",",
+ " );",
+ "});",
+ "",
+ "// Validate if response has JSON Body",
+ "pm.test(\"[POST]::/user/connect_account - Response has JSON Body\", function () {",
+ " pm.response.to.have.jsonBody();",
+ "});",
+ "",
+ "// Validate specific JSON response content",
+ "pm.test(\"[POST]::/user/connect_account - Response contains is_email_sent\", function () {",
+ " var jsonData = pm.response.json();",
+ " pm.expect(jsonData).to.have.property(\"is_email_sent\");",
+ " pm.expect(jsonData.is_email_sent).to.be.true;",
+ "});",
+ "",
+ ""
+ ],
+ "type": "text/javascript"
+ }
+ },
+ {
+ "listen": "prerequest",
+ "script": {
+ "exec": [
+ "",
+ "var baseEmail = pm.environment.get('user_base_email_for_signup');",
+ "var emailDomain = pm.environment.get(\"user_domain_for_signup\");",
+ "",
+ "// Generate a unique email address",
+ "var uniqueEmail = baseEmail + new Date().getTime() + emailDomain;",
+ "// Set the unique email address as an environment variable",
+ "pm.environment.set('unique_email', uniqueEmail);",
+ ""
+ ],
+ "type": "text/javascript"
+ }
+ }
+ ],
+ "request": {
+ "method": "POST",
+ "header": [
+ {
+ "key": "Content-Type",
+ "value": "application/json"
+ },
+ {
+ "key": "Cookie",
+ "value": "Cookie_1=value"
+ }
+ ],
+ "body": {
+ "mode": "raw",
+ "raw": "{\n \"email\": \"{{unique_email}}\"\n}"
+ },
+ "url": {
+ "raw": "{{baseUrl}}/user/connect_account",
+ "host": [
+ "{{baseUrl}}"
+ ],
+ "path": [
+ "user",
+ "connect_account"
+ ]
+ }
+ },
+ "response": []
+ }
+ ]
+ },
+ {
+ "name": "Sign In",
+ "item": [
+ {
+ "name": "Signin",
+ "event": [
+ {
+ "listen": "test",
+ "script": {
+ "exec": [
+ "console.log(\"[LOG]::x-request-id - \" + pm.response.headers.get(\"x-request-id\"));",
+ "",
+ "// Validate status 2xx",
+ "pm.test(\"[POST]::/user/signin - Status code is 2xx\", function () {",
+ " pm.response.to.be.success;",
+ "});",
+ "",
+ "// Validate if response header has matching content-type",
+ "pm.test(\"[POST]::/user/signin - Content-Type is application/json\", function () {",
+ " pm.expect(pm.response.headers.get(\"Content-Type\")).to.include(",
+ " \"application/json\",",
+ " );",
+ "});",
+ "",
+ "// Validate if response has JSON Body",
+ "pm.test(\"[POST]::/user/signin - Response has JSON Body\", function () {",
+ " pm.response.to.have.jsonBody();",
+ "});",
+ "",
+ "// Validate specific JSON response content",
+ "pm.test(\"[POST]::/user/signin - Response contains token\", function () {",
+ " var jsonData = pm.response.json();",
+ " pm.expect(jsonData).to.have.property(\"token\");",
+ " pm.expect(jsonData.token).to.be.a(\"string\").and.to.not.be.empty;",
+ "});"
+ ],
+ "type": "text/javascript"
+ }
+ },
+ {
+ "listen": "prerequest",
+ "script": {
+ "exec": [
+ ""
+ ],
+ "type": "text/javascript"
+ }
+ }
+ ],
+ "request": {
+ "method": "POST",
+ "header": [
+ {
+ "key": "Content-Type",
+ "value": "application/json"
+ },
+ {
+ "key": "Cookie",
+ "value": "Cookie_1=value"
+ }
+ ],
+ "body": {
+ "mode": "raw",
+ "raw": "{\n \"email\": \"{{user_email}}\",\n \"password\": \"{{user_password}}\"\n}"
+ },
+ "url": {
+ "raw": "{{baseUrl}}/user/signin",
+ "host": [
+ "{{baseUrl}}"
+ ],
+ "path": [
+ "user",
+ "signin"
+ ]
+ }
+ },
+ "response": []
+ },
+ {
+ "name": "Signin Wrong",
+ "event": [
+ {
+ "listen": "test",
+ "script": {
+ "exec": [
+ "console.log(\"[LOG]::x-request-id - \" + pm.response.headers.get(\"x-request-id\"));",
+ "",
+ "// Validate status code is 4xx Bad Request",
+ "pm.test(\"[POST]::/user/signin - Status code is 401\", function () {",
+ " pm.response.to.have.status(401);",
+ "});",
+ "",
+ "// Validate if response header has matching content-type",
+ "pm.test(\"[POST]::/user/signin - Content-Type is application/json\", function () {",
+ " pm.expect(pm.response.headers.get(\"Content-Type\")).to.include(",
+ " \"application/json\",",
+ " );",
+ "});",
+ "",
+ "// Validate if response has JSON Body",
+ "pm.test(\"[POST]::/user/signin - Response has JSON Body\", function () {",
+ " pm.response.to.have.jsonBody();",
+ "});"
+ ],
+ "type": "text/javascript"
+ }
+ }
+ ],
+ "request": {
+ "method": "POST",
+ "header": [
+ {
+ "key": "Content-Type",
+ "value": "application/json"
+ },
+ {
+ "key": "Cookie",
+ "value": "Cookie_1=value"
+ }
+ ],
+ "body": {
+ "mode": "raw",
+ "raw": "{\n \"email\": \"{{user_email}}\",\n \"password\": \"{{wrong_password}}\"\n}"
+ },
+ "url": {
+ "raw": "{{baseUrl}}/user/signin",
+ "host": [
+ "{{baseUrl}}"
+ ],
+ "path": [
+ "user",
+ "signin"
+ ]
+ }
+ },
+ "response": []
+ },
+ {
+ "name": "Signin V2 - To be deprecated",
+ "event": [
+ {
+ "listen": "test",
+ "script": {
+ "exec": [
+ "console.log(\"[LOG]::x-request-id - \" + pm.response.headers.get(\"x-request-id\"));",
+ "",
+ "// Validate status 2xx",
+ "pm.test(\"[POST]::user/v2/signin - Status code is 2xx\", function () {",
+ " pm.response.to.be.success;",
+ "});",
+ "",
+ "// Validate if response header has matching content-type",
+ "pm.test(\"[POST]::user/v2/signin - Content-Type is application/json\", function () {",
+ " pm.expect(pm.response.headers.get(\"Content-Type\")).to.include(",
+ " \"application/json\",",
+ " );",
+ "});",
+ "",
+ "// Validate if response has JSON Body",
+ "pm.test(\"[POST]::user/v2/signin - Response has JSON Body\", function () {",
+ " pm.response.to.have.jsonBody();",
+ "});",
+ "",
+ "// Validate specific JSON response content",
+ "pm.test(\"[POST]::user/v2/signin - Response contains token\", function () {",
+ " var jsonData = pm.response.json();",
+ " pm.expect(jsonData).to.have.property(\"token\");",
+ " pm.expect(jsonData.token).to.be.a(\"string\").and.to.not.be.empty;",
+ "});"
+ ],
+ "type": "text/javascript"
+ }
+ }
+ ],
+ "request": {
+ "method": "POST",
+ "header": [
+ {
+ "key": "Content-Type",
+ "value": "application/json"
+ },
+ {
+ "key": "Cookie",
+ "value": "Cookie_1=value"
+ }
+ ],
+ "body": {
+ "mode": "raw",
+ "raw": "{\n \"email\": \"{{user_email}}\",\n \"password\": \"{{user_password}}\" \n}"
+ },
+ "url": {
+ "raw": "{{baseUrl}}/user/v2/signin",
+ "host": [
+ "{{baseUrl}}"
+ ],
+ "path": [
+ "user",
+ "v2",
+ "signin"
+ ]
+ }
+ },
+ "response": []
+ },
+ {
+ "name": "Signin V2 Wrong",
+ "event": [
+ {
+ "listen": "test",
+ "script": {
+ "exec": [
+ "console.log(\"[LOG]::x-request-id - \" + pm.response.headers.get(\"x-request-id\"));",
+ "",
+ "// Validate status 4xx",
+ "pm.test(\"[POST]::/user/v2/signin - Status code is 401\", function () {",
+ " pm.response.to.have.status(401);",
+ "});",
+ "",
+ "// Validate if response header has matching content-type",
+ "pm.test(\"[POST]::user/v2/signin - Content-Type is application/json\", function () {",
+ " pm.expect(pm.response.headers.get(\"Content-Type\")).to.include(",
+ " \"application/json\",",
+ " );",
+ "});",
+ "",
+ "// Validate if response has JSON Body",
+ "pm.test(\"[POST]::user/v2/signin - Response has JSON Body\", function () {",
+ " pm.response.to.have.jsonBody();",
+ "});"
+ ],
+ "type": "text/javascript"
+ }
+ }
+ ],
+ "request": {
+ "method": "POST",
+ "header": [
+ {
+ "key": "Content-Type",
+ "value": "application/json"
+ },
+ {
+ "key": "Cookie",
+ "value": "Cookie_1=value"
+ }
+ ],
+ "body": {
+ "mode": "raw",
+ "raw": "{\n \"email\": \"{{user_email}}\",\n \"password\": \"{{wrong_password}}\" \n}"
+ },
+ "url": {
+ "raw": "{{baseUrl}}/user/v2/signin",
+ "host": [
+ "{{baseUrl}}"
+ ],
+ "path": [
+ "user",
+ "v2",
+ "signin"
+ ]
+ }
+ },
+ "response": []
+ }
+ ]
+ }
+ ]
+ }
+ ],
+ "event": [
+ {
+ "listen": "prerequest",
+ "script": {
+ "type": "text/javascript",
+ "exec": [
+ ""
+ ]
+ }
+ },
+ {
+ "listen": "test",
+ "script": {
+ "type": "text/javascript",
+ "exec": [
+ ""
+ ]
+ }
+ }
+ ],
+ "variable": [
+ {
+ "key": "baseUrl",
+ "value": "",
+ "type": "string"
+ },
+ {
+ "key": "admin_api_key",
+ "value": "",
+ "type": "string"
+ },
+ {
+ "key": "api_key",
+ "value": "",
+ "type": "string"
+ },
+ {
+ "key": "merchant_id",
+ "value": ""
+ },
+ {
+ "key": "payment_id",
+ "value": ""
+ },
+ {
+ "key": "customer_id",
+ "value": ""
+ },
+ {
+ "key": "mandate_id",
+ "value": ""
+ },
+ {
+ "key": "payment_method_id",
+ "value": ""
+ },
+ {
+ "key": "refund_id",
+ "value": ""
+ },
+ {
+ "key": "merchant_connector_id",
+ "value": ""
+ },
+ {
+ "key": "client_secret",
+ "value": "",
+ "type": "string"
+ },
+ {
+ "key": "connector_api_key",
+ "value": "",
+ "type": "string"
+ },
+ {
+ "key": "publishable_key",
+ "value": "",
+ "type": "string"
+ },
+ {
+ "key": "api_key_id",
+ "value": "",
+ "type": "string"
+ },
+ {
+ "key": "payment_token",
+ "value": ""
+ },
+ {
+ "key": "gateway_merchant_id",
+ "value": "",
+ "type": "string"
+ },
+ {
+ "key": "certificate",
+ "value": "",
+ "type": "string"
+ },
+ {
+ "key": "certificate_keys",
+ "value": "",
+ "type": "string"
+ },
+ {
+ "key": "connector_api_secret",
+ "value": "",
+ "type": "string"
+ },
+ {
+ "key": "connector_key1",
+ "value": "",
+ "type": "string"
+ },
+ {
+ "key": "connector_key2",
+ "value": "",
+ "type": "string"
+ },
+ {
+ "key": "user_email",
+ "value": "",
+ "type": "string"
+ },
+ {
+ "key": "user_password",
+ "value": "",
+ "type": "string"
+ },
+ {
+ "key": "wrong_password",
+ "value": "",
+ "type": "string"
+ },
+ {
+ "key": "user_base_email_for_signup",
+ "value": "",
+ "type": "string"
+ },
+ {
+ "key": "user_domain_for_signup",
+ "value": "",
+ "type": "string"
+ }
+ ]
+}
\ No newline at end of file
|
2024-08-31T09:14:39Z
|
## Type of Change
<!-- Put an `x` in the boxes that apply -->
- [ ] Bugfix
- [ ] New feature
- [ ] Enhancement
- [x] Refactoring
- [ ] Dependency updates
- [ ] Documentation
- [ ] CI/CD
## Description
<!-- Describe your changes in detail -->
- Deprecate all the APIs which are used when `is_token_only` and `groups` query params are false.
- Add logic to get merchant_id from the db if not found in user_role.
### Additional Changes
- [x] This PR modifies the API contract
- [ ] This PR modifies the database schema
- [ ] This PR modifies application configuration/environment variables
<!--
Provide links to the files with corresponding changes.
Following are the paths where you can find config files:
1. `config`
2. `crates/router/src/configs`
3. `loadtest/config`
-->
## Motivation and Context
<!--
Why is this change required? What problem does it solve?
If it fixes an open issue, please link to the issue here.
If you don't have an issue, we'd recommend starting with one first so the PR
can focus on the implementation (unless it is an obvious bug or documentation fix
that will have little conversation).
-->
Closes #5761.
Closes #5762.
## How did you test it?
<!--
Did you write an integration/unit/API test to verify the code changes?
Or did you test this change manually (provide relevant screenshots)?
-->
From the following endpoints, `token_only` query parameter is removed.
- `/v2/signin`
- `/reset_password`
- `/v2/verify_email`
- `/accept_invite_from_email`
- `/invite/accept` - Post only
All the above APIs will give the following response.
```
{
"token": "JWT",
"token_type": "type"
}
```
From the following endpoints, `groups` query parameter is removed.
- `/role` - Get only
- `/role/list`
- `/role/{role_id}` - Get only
They will always respond with groups from now on.
2 new APIs are added.
```
curl --location 'http://localhost:8080/user/signin' \
--header 'Content-Type: application/json' \
--data-raw '{
"email": "email",
"password": "password"
}
'
```
```
curl --location 'http://localhost:8080/user/verify_email' \
--header 'Content-Type: application/json' \
--header 'Authorization: ••••••' \
--data '{
"token": "email token"
}'
```
Both will give the following response if hit correctly.
```
{
"token": "JWT",
"token_type": "type"
}
```
## Checklist
<!-- Put an `x` in the boxes that apply -->
- [x] I formatted the code `cargo +nightly fmt --all`
- [x] I addressed lints thrown by `cargo clippy`
- [x] I reviewed the submitted code
- [ ] I added unit tests for my changes where possible
|
f7f5ba7c0bbf694dbeecec73f8383ac678dd4425
|
|
juspay/hyperswitch
|
juspay__hyperswitch-5747
|
Bug: Refactor: make the mca_id optional for PPT mandate flow
## Description
<!-- Describe your changes in detail -->
This refactor will make `mca_id` as optional in request and will completely remove the connector_name field, So the updation will make this request :
```
"recurring_details": {
"type": "processor_payment_token",
"data": {
"processor_payment_token": "pm_1Psh0bD5R7gDAGffspOhjKxn",
"connector": "adyen",
"merchant_connector_id": "mca_KcjKmhxEzSacoksdT5rN"
}
},
```
into:
```
"recurring_details": {
"type": "processor_payment_token",
"data": {
"processor_payment_token": "pm_1Psh0bD5R7gDAGffspOhjKxn"
}
},
```
Now listing the flows on how it will work:
First of all it is to be worked out after a routing rule is configured regarding ppt payments,
> So if proxy is to be used (considering maximum simultaneous connector as 1) then a specific routing rule needs to be created.
> Which will be something like
```
If `payment_type `----> `ppt_mandate`
then
`Connnector` ----> `Bambora`
```
> This will insure ppt payments will be routed through Bambora connector.
> Once all payments of Bambora is transactioned. The rule can be modified for another connector use-case.
> Now for the cases where simultaneously more than one connector is needed to make payment, the optional `mca_id` can be used. Which will automatically fetch the connector details and route the payment.
How the flow works:
1. First it will check for the mca_id
> If there it will go through the mca_id's connector
2. If not it will go accordingly to the routing configured:
> if ppt_routing is configured then the payment will go with the appropriate connector and succeed.
> else the payment will go to the default fallback connector and fail.
## Test
1. create a merchant account.
2. create api_key.
3. create mca (stripe).
4. create a routing rule:
```
curl --location 'http://127.0.0.1:8080/routing' \
--header 'Content-Type: application/json' \
--header 'api-key: xxxxxxxxx' \
--data '{
"name": "advanced config",
"description": "It is my ADVANCED config",
"profile_id": "pro_6WR6UUG3NEdZ19EHCOU7",
"algorithm": {
"type": "advanced",
"data": {
"defaultSelection": {
"type": "priority",
"data": [
]
},
"rules": [
{
"name": "stripe first",
"connectorSelection": {
"type": "priority",
"data": [
{
"connector": "stripe",
"merchant_connector_id": "mca_KcjKmhxEzSacoksdT5rN"
}
]
},
"statements": [
{
"condition": [
{
"lhs": "payment_type",
"comparison": "equal",
"value": {
"type": "enum_variant",
"value": "ppt_mandate"
},
"metadata": {}
}
],
"nested": null
}
]
}
],
"metadata": {}
}
}
}'
```
5.(optional only for testing / only for generating the ppt token): Create a setup mandate payment
```
curl --location 'http://localhost:8080/payments' \
--header 'Content-Type: application/json' \
--header 'Accept: application/json' \
--header 'api-key: xxxxxx' \
--data-raw '{
"amount": 0,
"currency": "USD",
"confirm": true,
"capture_method": "automatic",
"capture_on": "2022-09-10T10:11:12Z",
"customer_id": "cus_fvkFoCfd9bgmvFhGVoyz",
"description": "Its my first payment request",
"authentication_type": "no_three_ds",
"return_url": "https://google.com",
"setup_future_usage": "off_session",
"off_session": true,
"shipping": {
"address": {
"line1": "1467",
"line2": "Harrison Street",
"line3": "Harrison Street",
"city": "San Fransico",
"state": "California",
"zip": "94122",
"country": "US",
"first_name": "John",
"last_name": "Doe"
}
},
"statement_descriptor_name": "joseph",
"statement_descriptor_suffix": "JS",
"metadata": {
"udf1": "value1",
"new_customer": "true",
"login_date": "2019-09-10T10:11:12Z"
},
"payment_type": "setup_mandate",
"payment_method": "card",
"payment_method_type": "credit",
"payment_method_data": {
"card": {
"card_number": "4242424242424242",
"card_exp_month": "02",
"card_exp_year": "26",
"card_holder_name": "Joseph Doe",
"card_cvc": "999"
}
},
"billing": {
"address": {
"line1": "8th block",
"line2": "8th block",
"line3": "8th block",
"city": "Bengaluru",
"state": "Karnataka",
"zip": "560095",
"country": "IN",
"first_name": "Sakil",
"last_name": "Mostak"
}
},
"customer_acceptance": {
"acceptance_type": "online"
}
}'
```
6.(optional only for testing / only for generating the ppt token): query the `payment_method's` table with the `pm_id` and not the `connector_mandate_id`, as this is our ppt token.
7. Create a ppt payment :
```
curl --location 'http://localhost:8080/payments' \
--header 'Content-Type: application/json' \
--header 'Accept: application/json' \
--header 'api-key: xxxxx' \
--data '{
"amount": 499,
"currency": "USD",
"capture_method": "automatic",
"profile_id": "pro_6WR6UUG3NEdZ19EHCOU7",
"customer_id": "cus_fvkFoCfd9bgmvFhGVoyz",
"off_session": true,
"confirm": true,
"recurring_details": {
"type": "processor_payment_token",
"data": {
"processor_payment_token": "pm_1Psh0bD5R7gDAGffspOhjKxn"
}
},
"payment_method": "card",
"authentication_type": "no_three_ds"
}'
```
8.(optional flow) Create a ppt payment with mca_id:
```
curl --location 'http://localhost:8080/payments' \
--header 'Content-Type: application/json' \
--header 'Accept: application/json' \
--header 'api-key: xxxxx' \
--data '{
"amount": 499,
"currency": "USD",
"capture_method": "automatic",
"profile_id": "pro_6WR6UUG3NEdZ19EHCOU7",
"customer_id": "cus_fvkFoCfd9bgmvFhGVoyz",
"off_session": true,
"confirm": true,
"recurring_details": {
"type": "processor_payment_token",
"data": {
"processor_payment_token": "pm_1Psh0bD5R7gDAGffspOhjKxn",
"merchant_connector_id": "mca_KcjKmhxEzSacoksdT5rN"
}
},
"payment_method": "card",
"authentication_type": "no_three_ds"
}'
```
Things to note:
1. The payment should go throught the connector configured in the rule based routing.
2. The payment should succeed.
|
diff --git a/api-reference-v2/openapi_spec.json b/api-reference-v2/openapi_spec.json
index 6882e823905..ed591af7a6c 100644
--- a/api-reference-v2/openapi_spec.json
+++ b/api-reference-v2/openapi_spec.json
@@ -16052,19 +16052,15 @@
"type": "object",
"description": "Processor payment token for MIT payments where payment_method_data is not available",
"required": [
- "processor_payment_token",
- "connector",
- "merchant_connector_id"
+ "processor_payment_token"
],
"properties": {
"processor_payment_token": {
"type": "string"
},
- "connector": {
- "$ref": "#/components/schemas/Connector"
- },
"merchant_connector_id": {
- "type": "string"
+ "type": "string",
+ "nullable": true
}
}
},
diff --git a/crates/api_models/src/mandates.rs b/crates/api_models/src/mandates.rs
index 44a83319424..fe5b053b180 100644
--- a/crates/api_models/src/mandates.rs
+++ b/crates/api_models/src/mandates.rs
@@ -127,8 +127,6 @@ pub enum RecurringDetails {
#[derive(Debug, Clone, serde::Serialize, serde::Deserialize, ToSchema, PartialEq, Eq)]
pub struct ProcessorPaymentToken {
pub processor_payment_token: String,
- #[schema(value_type = Connector, example = "stripe")]
- pub connector: api_enums::Connector,
- #[schema(value_type = String)]
- pub merchant_connector_id: common_utils::id_type::MerchantConnectorAccountId,
+ #[schema(value_type = Option<String>)]
+ pub merchant_connector_id: Option<common_utils::id_type::MerchantConnectorAccountId>,
}
diff --git a/crates/router/src/core/payments.rs b/crates/router/src/core/payments.rs
index 1af097114fb..75fe544ae5e 100644
--- a/crates/router/src/core/payments.rs
+++ b/crates/router/src/core/payments.rs
@@ -3809,6 +3809,30 @@ pub async fn decide_multiplex_connector_for_normal_or_recurring_payment<F: Clone
Ok(ConnectorCallType::PreDetermined(chosen_connector_data))
}
+ (
+ None,
+ None,
+ Some(RecurringDetails::ProcessorPaymentToken(_token)),
+ Some(true),
+ Some(api::MandateTransactionType::RecurringMandateTransaction),
+ ) => {
+ if let Some(connector) = connectors.first() {
+ routing_data.routed_through = Some(connector.connector_name.clone().to_string());
+ routing_data
+ .merchant_connector_id
+ .clone_from(&connector.merchant_connector_id);
+ Ok(ConnectorCallType::PreDetermined(api::ConnectorData {
+ connector: connector.connector.clone(),
+ connector_name: connector.connector_name,
+ get_token: connector.get_token.clone(),
+ merchant_connector_id: connector.merchant_connector_id.clone(),
+ }))
+ } else {
+ logger::error!("no eligible connector found for the ppt_mandate payment");
+ Err(errors::ApiErrorResponse::IncorrectPaymentMethodConfiguration.into())
+ }
+ }
+
_ => {
helpers::override_setup_future_usage_to_on_session(&*state.store, payment_data).await?;
diff --git a/crates/router/src/core/payments/helpers.rs b/crates/router/src/core/payments/helpers.rs
index 52e439a2e47..34fb2e954ba 100644
--- a/crates/router/src/core/payments/helpers.rs
+++ b/crates/router/src/core/payments/helpers.rs
@@ -420,73 +420,108 @@ pub async fn get_token_pm_type_mandate_details(
),
Some(api::MandateTransactionType::RecurringMandateTransaction) => {
match &request.recurring_details {
- Some(recurring_details) => match recurring_details {
- RecurringDetails::ProcessorPaymentToken(processor_payment_token) => (
- None,
- request.payment_method,
- None,
- None,
- None,
- Some(payments::MandateConnectorDetails {
- connector: processor_payment_token.connector.to_string(),
- merchant_connector_id: Some(
- processor_payment_token.merchant_connector_id.clone(),
- ),
- }),
- None,
- ),
- RecurringDetails::MandateId(mandate_id) => {
- let mandate_generic_data = get_token_for_recurring_mandate(
- state,
- request,
- merchant_account,
- merchant_key_store,
- mandate_id.to_owned(),
- )
- .await?;
+ Some(recurring_details) => {
+ match recurring_details {
+ RecurringDetails::ProcessorPaymentToken(processor_payment_token) => {
+ if let Some(mca_id) = &processor_payment_token.merchant_connector_id {
+ let db = &*state.store;
+ let key_manager_state = &state.into();
+
+ #[cfg(all(
+ any(feature = "v1", feature = "v2"),
+ not(feature = "merchant_connector_account_v2")
+ ))]
+ let connector_name = db
+ .find_by_merchant_connector_account_merchant_id_merchant_connector_id(
+ key_manager_state,
+ merchant_account.get_id(),
+ mca_id,
+ merchant_key_store,
+ )
+ .await
+ .to_not_found_response(errors::ApiErrorResponse::MerchantConnectorAccountNotFound {
+ id: mca_id.clone().get_string_repr().to_string(),
+ })?.connector_name;
- (
- mandate_generic_data.token,
- mandate_generic_data.payment_method,
- mandate_generic_data
- .payment_method_type
- .or(request.payment_method_type),
- None,
- mandate_generic_data.recurring_mandate_payment_data,
- mandate_generic_data.mandate_connector,
- mandate_generic_data.payment_method_info,
- )
- }
- RecurringDetails::PaymentMethodId(payment_method_id) => {
- let payment_method_info = state
- .store
- .find_payment_method(payment_method_id, merchant_account.storage_scheme)
- .await
- .to_not_found_response(
- errors::ApiErrorResponse::PaymentMethodNotFound,
+ #[cfg(all(feature = "v2", feature = "merchant_connector_account_v2"))]
+ let connector_name = db
+ .find_merchant_connector_account_by_id(key_manager_state, &mca_id, &merchant_key_store)
+ .await
+ .to_not_found_response(errors::ApiErrorResponse::MerchantConnectorAccountNotFound {
+ id: mca_id.clone().get_string_repr().to_string(),
+ })?.connector_name;
+ (
+ None,
+ request.payment_method,
+ None,
+ None,
+ None,
+ Some(payments::MandateConnectorDetails {
+ connector: connector_name,
+ merchant_connector_id: Some(mca_id.clone()),
+ }),
+ None,
+ )
+ } else {
+ (None, request.payment_method, None, None, None, None, None)
+ }
+ }
+ RecurringDetails::MandateId(mandate_id) => {
+ let mandate_generic_data = get_token_for_recurring_mandate(
+ state,
+ request,
+ merchant_account,
+ merchant_key_store,
+ mandate_id.to_owned(),
+ )
+ .await?;
+
+ (
+ mandate_generic_data.token,
+ mandate_generic_data.payment_method,
+ mandate_generic_data
+ .payment_method_type
+ .or(request.payment_method_type),
+ None,
+ mandate_generic_data.recurring_mandate_payment_data,
+ mandate_generic_data.mandate_connector,
+ mandate_generic_data.payment_method_info,
+ )
+ }
+ RecurringDetails::PaymentMethodId(payment_method_id) => {
+ let payment_method_info = state
+ .store
+ .find_payment_method(
+ payment_method_id,
+ merchant_account.storage_scheme,
+ )
+ .await
+ .to_not_found_response(
+ errors::ApiErrorResponse::PaymentMethodNotFound,
+ )?;
+ let customer_id = request
+ .get_customer_id()
+ .get_required_value("customer_id")?;
+
+ verify_mandate_details_for_recurring_payments(
+ &payment_method_info.merchant_id,
+ merchant_account.get_id(),
+ &payment_method_info.customer_id,
+ customer_id,
)?;
- let customer_id = request
- .get_customer_id()
- .get_required_value("customer_id")?;
-
- verify_mandate_details_for_recurring_payments(
- &payment_method_info.merchant_id,
- merchant_account.get_id(),
- &payment_method_info.customer_id,
- customer_id,
- )?;
- (
- None,
- payment_method_info.payment_method,
- payment_method_info.payment_method_type,
- None,
- None,
- None,
- Some(payment_method_info),
- )
+ (
+ None,
+ payment_method_info.payment_method,
+ payment_method_info.payment_method_type,
+ None,
+ None,
+ None,
+ Some(payment_method_info),
+ )
+ }
}
- },
+ }
None => {
if let Some(mandate_id) = request.mandate_id.clone() {
let mandate_generic_data = get_token_for_recurring_mandate(
|
2024-08-29T10:59:00Z
|
## Type of Change
<!-- Put an `x` in the boxes that apply -->
- [ ] Bugfix
- [ ] New feature
- [x] Enhancement
- [ ] Refactoring
- [ ] Dependency updates
- [ ] Documentation
- [ ] CI/CD
## Description
<!-- Describe your changes in detail -->
This refactor will make `mca_id` as optional in request and will completely remove the connector_name field, So the updation will make this request :
```
"recurring_details": {
"type": "processor_payment_token",
"data": {
"processor_payment_token": "pm_1Psh0bD5R7gDAGffspOhjKxn",
"connector": "adyen",
"merchant_connector_id": "mca_KcjKmhxEzSacoksdT5rN"
}
},
```
into:
```
"recurring_details": {
"type": "processor_payment_token",
"data": {
"processor_payment_token": "pm_1Psh0bD5R7gDAGffspOhjKxn"
}
},
```
Now listing the flows on how it will work:
First of all it is to be worked out after a routing rule is configured regarding ppt payments,
> So if proxy is to be used (considering maximum simultaneous connector as 1) then a specific routing rule needs to be created.
> Which will be something like
```
If `payment_type `----> `ppt_mandate`
then
`Connnector` ----> `Bambora`
```
> This will insure ppt payments will be routed through Bambora connector.
> Once all payments of Bambora is transactioned. The rule can be modified for another connector use-case.
> Now for the cases where simultaneously more than one connector is needed to make payment, the optional `mca_id` can be used. Which will automatically fetch the connector details and route the payment.
How the flow works:
1. First it will check for the mca_id
> If there it will go through the mca_id's connector
2. If not it will go accordingly to the routing configured:
> if ppt_routing is configured then the payment will go with the appropriate connector and succeed.
> else the payment will go to the default fallback connector and fail.
### Additional Changes
- [x] This PR modifies the API contract
- [ ] This PR modifies the database schema
- [ ] This PR modifies application configuration/environment variables
<!--
Provide links to the files with corresponding changes.
Following are the paths where you can find config files:
1. `config`
4. `crates/router/src/configs`
5. `loadtest/config`
-->
## Motivation and Context
<!--
Why is this change required? What problem does it solve?
If it fixes an open issue, please link to the issue here.
If you don't have an issue, we'd recommend starting with one first so the PR
can focus on the implementation (unless it is an obvious bug or documentation fix
that will have little conversation).
-->
For better user experience.
## How did you test it?
<!--
Did you write an integration/unit/API test to verify the code changes?
Or did you test this change manually (provide relevant screenshots)?
-->
1. create a merchant account.
2. create api_key.
3. create mca (stripe).
4. create a routing rule:
```
curl --location 'http://127.0.0.1:8080/routing' \
--header 'Content-Type: application/json' \
--header 'api-key: xxxxxxxxx' \
--data '{
"name": "advanced config",
"description": "It is my ADVANCED config",
"profile_id": "pro_6WR6UUG3NEdZ19EHCOU7",
"algorithm": {
"type": "advanced",
"data": {
"defaultSelection": {
"type": "priority",
"data": [
]
},
"rules": [
{
"name": "stripe first",
"connectorSelection": {
"type": "priority",
"data": [
{
"connector": "stripe",
"merchant_connector_id": "mca_KcjKmhxEzSacoksdT5rN"
}
]
},
"statements": [
{
"condition": [
{
"lhs": "payment_type",
"comparison": "equal",
"value": {
"type": "enum_variant",
"value": "ppt_mandate"
},
"metadata": {}
}
],
"nested": null
}
]
}
],
"metadata": {}
}
}
}'
```
5.(optional only for testing / only for generating the ppt token): Create a setup mandate payment
```
curl --location 'http://localhost:8080/payments' \
--header 'Content-Type: application/json' \
--header 'Accept: application/json' \
--header 'api-key: xxxxxx' \
--data-raw '{
"amount": 0,
"currency": "USD",
"confirm": true,
"capture_method": "automatic",
"capture_on": "2022-09-10T10:11:12Z",
"customer_id": "cus_fvkFoCfd9bgmvFhGVoyz",
"description": "Its my first payment request",
"authentication_type": "no_three_ds",
"return_url": "https://google.com",
"setup_future_usage": "off_session",
"off_session": true,
"shipping": {
"address": {
"line1": "1467",
"line2": "Harrison Street",
"line3": "Harrison Street",
"city": "San Fransico",
"state": "California",
"zip": "94122",
"country": "US",
"first_name": "John",
"last_name": "Doe"
}
},
"statement_descriptor_name": "joseph",
"statement_descriptor_suffix": "JS",
"metadata": {
"udf1": "value1",
"new_customer": "true",
"login_date": "2019-09-10T10:11:12Z"
},
"payment_type": "setup_mandate",
"payment_method": "card",
"payment_method_type": "credit",
"payment_method_data": {
"card": {
"card_number": "4242424242424242",
"card_exp_month": "02",
"card_exp_year": "26",
"card_holder_name": "Joseph Doe",
"card_cvc": "999"
}
},
"billing": {
"address": {
"line1": "8th block",
"line2": "8th block",
"line3": "8th block",
"city": "Bengaluru",
"state": "Karnataka",
"zip": "560095",
"country": "IN",
"first_name": "Sakil",
"last_name": "Mostak"
}
},
"customer_acceptance": {
"acceptance_type": "online"
}
}'
```
6.(optional only for testing / only for generating the ppt token): query the `payment_method's` table with the `pm_id` and get the `connector_mandate_id`, as this is our ppt token.
7. Create a ppt payment :
```
curl --location 'http://localhost:8080/payments' \
--header 'Content-Type: application/json' \
--header 'Accept: application/json' \
--header 'api-key: xxxxx' \
--data '{
"amount": 499,
"currency": "USD",
"capture_method": "automatic",
"profile_id": "pro_6WR6UUG3NEdZ19EHCOU7",
"customer_id": "cus_fvkFoCfd9bgmvFhGVoyz",
"off_session": true,
"confirm": true,
"recurring_details": {
"type": "processor_payment_token",
"data": {
"processor_payment_token": "pm_1Psh0bD5R7gDAGffspOhjKxn"
}
},
"payment_method": "card",
"authentication_type": "no_three_ds"
}'
```
8.(optional flow) Create a ppt payment with mca_id:
```
curl --location 'http://localhost:8080/payments' \
--header 'Content-Type: application/json' \
--header 'Accept: application/json' \
--header 'api-key: xxxxx' \
--data '{
"amount": 499,
"currency": "USD",
"capture_method": "automatic",
"profile_id": "pro_6WR6UUG3NEdZ19EHCOU7",
"customer_id": "cus_fvkFoCfd9bgmvFhGVoyz",
"off_session": true,
"confirm": true,
"recurring_details": {
"type": "processor_payment_token",
"data": {
"processor_payment_token": "pm_1Psh0bD5R7gDAGffspOhjKxn",
"merchant_connector_id": "mca_KcjKmhxEzSacoksdT5rN"
}
},
"payment_method": "card",
"authentication_type": "no_three_ds"
}'
```
Things to note:
1. The payment should go throught the connector configured in the rule based routing.
2. The payment should succeed.
## Checklist
<!-- Put an `x` in the boxes that apply -->
- [x] I formatted the code `cargo +nightly fmt --all`
- [x] I addressed lints thrown by `cargo clippy`
- [x] I reviewed the submitted code
- [ ] I added unit tests for my changes where possible
|
2049ab055469a43c0cb2e543740571913a027eab
|
|
juspay/hyperswitch
|
juspay__hyperswitch-5725
|
Bug: [BUG] Fix Routing activate Route
### Bug Description
When trying to hit the routing activate route , it was throwing a deserialisation error due to the passing a struct instead of a tuple struct
### Expected Behavior
When trying to hit the routing activate route ,it should not throw a error
### Actual Behavior
Should pass the String in the path param
### Steps To Reproduce
Provide an unambiguous set of steps to reproduce this bug. Include code or configuration to reproduce, if relevant.
1. Go to '...'
2. Click on '....'
3. Scroll down to '....'
### Context For The Bug
_No response_
### Environment
Are you using hyperswitch hosted version? Yes/No
If yes, please provide the value of the `x-request-id` response header to help us debug your issue.
If not (or if building/running locally), please provide the following details:
1. Operating System or Linux distribution:
2. Rust version (output of `rustc --version`): ``
3. App version (output of `cargo r --features vergen -- --version`): ``
### Have you spent some time checking if this bug has been raised before?
- [X] I checked and didn't find a similar issue
### Have you read the Contributing Guidelines?
- [X] I have read the [Contributing Guidelines](https://github.com/juspay/hyperswitch/blob/main/docs/CONTRIBUTING.md)
### Are you willing to submit a PR?
Yes, I am willing to submit a PR!
|
diff --git a/crates/router/src/core/routing.rs b/crates/router/src/core/routing.rs
index 267a3d55ce4..d5a3a96d155 100644
--- a/crates/router/src/core/routing.rs
+++ b/crates/router/src/core/routing.rs
@@ -428,18 +428,15 @@ pub async fn retrieve_routing_algorithm_from_algorithm_id(
state: SessionState,
merchant_account: domain::MerchantAccount,
key_store: domain::MerchantKeyStore,
- algorithm_id: routing_types::RoutingAlgorithmId,
+ algorithm_id: String,
) -> RouterResponse<routing_types::MerchantRoutingAlgorithm> {
metrics::ROUTING_RETRIEVE_CONFIG.add(&metrics::CONTEXT, 1, &[]);
let db = state.store.as_ref();
let key_manager_state = &(&state).into();
- let routing_algorithm = RoutingAlgorithmUpdate::fetch_routing_algo(
- merchant_account.get_id(),
- &algorithm_id.routing_algorithm_id,
- db,
- )
- .await?;
+ let routing_algorithm =
+ RoutingAlgorithmUpdate::fetch_routing_algo(merchant_account.get_id(), &algorithm_id, db)
+ .await?;
core_utils::validate_and_get_business_profile(
db,
key_manager_state,
@@ -464,7 +461,7 @@ pub async fn retrieve_routing_algorithm_from_algorithm_id(
state: SessionState,
merchant_account: domain::MerchantAccount,
key_store: domain::MerchantKeyStore,
- algorithm_id: routing_types::RoutingAlgorithmId,
+ algorithm_id: String,
) -> RouterResponse<routing_types::MerchantRoutingAlgorithm> {
metrics::ROUTING_RETRIEVE_CONFIG.add(&metrics::CONTEXT, 1, &[]);
let db = state.store.as_ref();
@@ -472,7 +469,7 @@ pub async fn retrieve_routing_algorithm_from_algorithm_id(
let routing_algorithm = db
.find_routing_algorithm_by_algorithm_id_merchant_id(
- &algorithm_id.routing_algorithm_id,
+ &algorithm_id,
merchant_account.get_id(),
)
.await
diff --git a/crates/router/src/routes/routing.rs b/crates/router/src/routes/routing.rs
index 61d89e5e773..ecce0f96198 100644
--- a/crates/router/src/routes/routing.rs
+++ b/crates/router/src/routes/routing.rs
@@ -60,7 +60,7 @@ pub async fn routing_create_config(
pub async fn routing_link_config(
state: web::Data<AppState>,
req: HttpRequest,
- path: web::Path<routing_types::RoutingAlgorithmId>,
+ path: web::Path<String>,
transaction_type: &enums::TransactionType,
) -> impl Responder {
let flow = Flow::RoutingLinkConfig;
@@ -74,7 +74,7 @@ pub async fn routing_link_config(
state,
auth.merchant_account,
auth.key_store,
- algorithm.routing_algorithm_id,
+ algorithm,
transaction_type,
)
},
@@ -139,7 +139,7 @@ pub async fn routing_link_config(
pub async fn routing_retrieve_config(
state: web::Data<AppState>,
req: HttpRequest,
- path: web::Path<routing_types::RoutingAlgorithmId>,
+ path: web::Path<String>,
) -> impl Responder {
let algorithm_id = path.into_inner();
let flow = Flow::RoutingRetrieveConfig;
|
2024-08-27T14:10:28Z
|
## Type of Change
<!-- Put an `x` in the boxes that apply -->
- [x] Bugfix
- [ ] New feature
- [ ] Enhancement
- [ ] Refactoring
- [ ] Dependency updates
- [ ] Documentation
- [ ] CI/CD
## Description
fix routing routes for activating and retrieving the routing algorithms where not able to deserialise correctly due to the following [PR](https://github.com/juspay/hyperswitch/pull/5686)
### Additional Changes
- [ ] This PR modifies the API contract
- [ ] This PR modifies the database schema
- [ ] This PR modifies application configuration/environment variables
<!--
Provide links to the files with corresponding changes.
Following are the paths where you can find config files:
1. `config`
2. `crates/router/src/configs`
3. `loadtest/config`
-->
## Motivation and Context
<!--
Why is this change required? What problem does it solve?
If it fixes an open issue, please link to the issue here.
If you don't have an issue, we'd recommend starting with one first so the PR
can focus on the implementation (unless it is an obvious bug or documentation fix
that will have little conversation).
-->
## How did you test it?
- Create a MA and a MCa
- Create a Routing Rule
```
curl --location 'http://localhost:8080/routing' \
--header 'Content-Type: application/json' \
--header 'api-key: dev_HIL1XwQlvsJtPbfaOoWrYPznXmFoKE2F0Sg2Kq58Rjnj8PsV5k51g33I6a8chvLN' \
--data '{
"profile_id": "pro_2ScZ3GfSL10mn5BMMuFH",
"name": "Brand based",
"description": "This is a rule based routing created at Wed, 21 Aug 2024 08:28:31 GMT",
"algorithm": {
"type": "advanced",
"data": {
"defaultSelection": {
"type": "priority",
"data": []
},
"rules": [
{
"name": "rule_1",
"connectorSelection": {
"type": "priority",
"data": [
{
"connector": "adyen",
"merchant_connector_id": "mca_TAhGgaYPtdIYiPfQ2684"
}
]
},
"statements": [
{
"condition": [
{
"lhs": "metadata",
"comparison": "equal",
"value": {
"type": "metadata_variant",
"value": {
"key": "brand",
"value": "waytopark"
}
},
"metadata": {}
}
],
"nested": null
}
]
},
{
"name": "rule_2",
"connectorSelection": {
"type": "priority",
"data": [
{
"connector": "adyen",
"merchant_connector_id": "mca_TAhGgaYPtdIYiPfQ2684"
}
]
},
"statements": [
{
"condition": [
{
"lhs": "metadata",
"comparison": "equal",
"value": {
"type": "metadata_variant",
"value": {
"key": "brand",
"value": "flowbird"
}
},
"metadata": {}
}
],
"nested": null
}
]
}
],
"metadata": {}
}
}
}'
```
- Activate the routing rule, should be activated correctly
```
Response
curl --location --request POST 'http://localhost:8080/routing/routing_merchant_1724767283_pDOPqSye0G/activate' \
--header 'api-key: dev_HIL1XwQlvsJtPbfaOoWrYPznXmFoKE2F0Sg2Kq58Rjnj8PsV5k51g33I6a8chvLN'
```
- Retrieve the routing rule, should be retrieved successfully
```
curl --location 'http://localhost:8080/routing/routing_merchant_1724767283_pDOPqSye0G' \
--header 'api-key: dev_HIL1XwQlvsJtPbfaOoWrYPznXmFoKE2F0Sg2Kq58Rjnj8PsV5k51g33I6a8chvLN'
```
```
Response
{
"id": "routing_merchant_1724767283_pDOPqSye0G",
"profile_id": "pro_2ScZ3GfSL10mn5BMMuFH",
"name": "Brand based",
"description": "This is a rule based routing created at Wed, 21 Aug 2024 08:28:31 GMT",
"algorithm": {
"type": "advanced",
"data": {
"defaultSelection": {
"type": "priority",
"data": []
},
"rules": [
{
"name": "rule_1",
"connectorSelection": {
"type": "priority",
"data": [
{
"connector": "adyen",
"merchant_connector_id": "mca_TAhGgaYPtdIYiPfQ2684"
}
]
},
"statements": [
{
"condition": [
{
"lhs": "metadata",
"comparison": "equal",
"value": {
"type": "metadata_variant",
"value": {
"key": "brand",
"value": "waytopark"
}
},
"metadata": {}
}
],
"nested": null
}
]
},
{
"name": "rule_2",
"connectorSelection": {
"type": "priority",
"data": [
{
"connector": "adyen",
"merchant_connector_id": "mca_TAhGgaYPtdIYiPfQ2684"
}
]
},
"statements": [
{
"condition": [
{
"lhs": "metadata",
"comparison": "equal",
"value": {
"type": "metadata_variant",
"value": {
"key": "brand",
"value": "flowbird"
}
},
"metadata": {}
}
],
"nested": null
}
]
}
],
"metadata": {}
}
},
"created_at": 1724767426,
"modified_at": 1724767426,
"algorithm_for": "payment"
}
```
## Checklist
<!-- Put an `x` in the boxes that apply -->
- [ ] I formatted the code `cargo +nightly fmt --all`
- [ ] I addressed lints thrown by `cargo clippy`
- [ ] I reviewed the submitted code
- [ ] I added unit tests for my changes where possible
|
716d76c53e07327cd07844dd8b40f5be18c0df4b
|
|
juspay/hyperswitch
|
juspay__hyperswitch-5731
|
Bug: make customer details None in the `Psync` flow if the customer is deleted
If the customer is deleted after the payment is done the payments retrieve will fail as the customer details are redacted. But we should be able to retrieve a payment even is the customer details are redacted.
|
diff --git a/crates/router/src/core/payments/helpers.rs b/crates/router/src/core/payments/helpers.rs
index c2a14871a47..b9c89cd4387 100644
--- a/crates/router/src/core/payments/helpers.rs
+++ b/crates/router/src/core/payments/helpers.rs
@@ -1372,6 +1372,18 @@ pub async fn get_customer_from_details<F: Clone>(
todo!()
}
+#[cfg(all(feature = "v2", feature = "customer_v2"))]
+pub async fn get_customer_details_even_for_redacted_customer<F: Clone>(
+ _state: &SessionState,
+ _customer_id: Option<id_type::CustomerId>,
+ _merchant_id: &id_type::MerchantId,
+ _payment_data: &mut PaymentData<F>,
+ _merchant_key_store: &domain::MerchantKeyStore,
+ _storage_scheme: enums::MerchantStorageScheme,
+) -> CustomResult<Option<domain::Customer>, errors::StorageError> {
+ todo!()
+}
+
#[cfg(all(any(feature = "v1", feature = "v2"), not(feature = "customer_v2")))]
pub async fn get_customer_from_details<F: Clone>(
state: &SessionState,
@@ -1712,6 +1724,44 @@ pub async fn create_customer_if_not_exist<'a, F: Clone, R>(
))
}
+// This function is to retrieve customer details. If the customer is deleted, it returns
+// customer details that contains the fields as Redacted
+#[cfg(all(any(feature = "v1", feature = "v2"), not(feature = "customer_v2")))]
+pub async fn get_customer_details_even_for_redacted_customer<F: Clone>(
+ state: &SessionState,
+ customer_id: Option<id_type::CustomerId>,
+ merchant_id: &id_type::MerchantId,
+ payment_data: &mut PaymentData<F>,
+ merchant_key_store: &domain::MerchantKeyStore,
+ storage_scheme: enums::MerchantStorageScheme,
+) -> CustomResult<Option<domain::Customer>, errors::StorageError> {
+ match customer_id {
+ None => Ok(None),
+ Some(customer_id) => {
+ let db = &*state.store;
+ let customer_details = db
+ .find_customer_optional_with_redacted_customer_details_by_customer_id_merchant_id(
+ &state.into(),
+ &customer_id,
+ merchant_id,
+ merchant_key_store,
+ storage_scheme,
+ )
+ .await?;
+
+ payment_data.email = payment_data.email.clone().or_else(|| {
+ customer_details.as_ref().and_then(|inner| {
+ inner
+ .email
+ .clone()
+ .map(|encrypted_value| encrypted_value.into())
+ })
+ });
+ Ok(customer_details)
+ }
+ }
+}
+
pub async fn retrieve_payment_method_with_temporary_token(
state: &SessionState,
token: &str,
diff --git a/crates/router/src/core/payments/operations.rs b/crates/router/src/core/payments/operations.rs
index ebc00e42e5a..0eef08c104c 100644
--- a/crates/router/src/core/payments/operations.rs
+++ b/crates/router/src/core/payments/operations.rs
@@ -276,7 +276,7 @@ where
> {
Ok((
Box::new(self),
- helpers::get_customer_from_details(
+ helpers::get_customer_details_even_for_redacted_customer(
state,
payment_data.payment_intent.customer_id.clone(),
&merchant_key_store.merchant_id,
diff --git a/crates/router/src/core/payments/transformers.rs b/crates/router/src/core/payments/transformers.rs
index cb4c0ce2898..b2070718892 100644
--- a/crates/router/src/core/payments/transformers.rs
+++ b/crates/router/src/core/payments/transformers.rs
@@ -601,36 +601,50 @@ where
let customer_table_response: Option<CustomerDetailsResponse> =
customer.as_ref().map(ForeignInto::foreign_into);
- // If we have customer data in Payment Intent, We are populating the Retrieve response from the
- // same
+ // If we have customer data in Payment Intent and if the customer is not deleted, We are populating the Retrieve response from the
+ // same. If the customer is deleted then we use the customer table to populate customer details
let customer_details_response =
if let Some(customer_details_raw) = payment_intent.customer_details.clone() {
let customer_details_encrypted =
serde_json::from_value::<CustomerData>(customer_details_raw.into_inner().expose());
if let Ok(customer_details_encrypted_data) = customer_details_encrypted {
Some(CustomerDetailsResponse {
- id: customer_table_response.and_then(|customer_data| customer_data.id),
- name: customer_details_encrypted_data
- .name
- .or(customer.as_ref().and_then(|customer| {
- customer.name.as_ref().map(|name| name.clone().into_inner())
- })),
- email: customer_details_encrypted_data.email.or(customer
+ id: customer_table_response
.as_ref()
- .and_then(|customer| customer.email.clone().map(Email::from))),
- phone: customer_details_encrypted_data
- .phone
- .or(customer.as_ref().and_then(|customer| {
- customer
- .phone
- .as_ref()
- .map(|phone| phone.clone().into_inner())
- })),
- phone_country_code: customer_details_encrypted_data.phone_country_code.or(
- customer
+ .and_then(|customer_data| customer_data.id.clone()),
+ name: customer_table_response
+ .as_ref()
+ .and_then(|customer_data| customer_data.name.clone())
+ .or(customer_details_encrypted_data
+ .name
+ .or(customer.as_ref().and_then(|customer| {
+ customer.name.as_ref().map(|name| name.clone().into_inner())
+ }))),
+ email: customer_table_response
+ .as_ref()
+ .and_then(|customer_data| customer_data.email.clone())
+ .or(customer_details_encrypted_data.email.or(customer
.as_ref()
- .and_then(|customer| customer.phone_country_code.clone()),
- ),
+ .and_then(|customer| customer.email.clone().map(Email::from)))),
+ phone: customer_table_response
+ .as_ref()
+ .and_then(|customer_data| customer_data.phone.clone())
+ .or(customer_details_encrypted_data
+ .phone
+ .or(customer.as_ref().and_then(|customer| {
+ customer
+ .phone
+ .as_ref()
+ .map(|phone| phone.clone().into_inner())
+ }))),
+ phone_country_code: customer_table_response
+ .as_ref()
+ .and_then(|customer_data| customer_data.phone_country_code.clone())
+ .or(customer_details_encrypted_data
+ .phone_country_code
+ .or(customer
+ .as_ref()
+ .and_then(|customer| customer.phone_country_code.clone()))),
})
} else {
customer_table_response
diff --git a/crates/router/src/db/customers.rs b/crates/router/src/db/customers.rs
index b271a16d9d9..24402c343fa 100644
--- a/crates/router/src/db/customers.rs
+++ b/crates/router/src/db/customers.rs
@@ -55,6 +55,16 @@ where
storage_scheme: MerchantStorageScheme,
) -> CustomResult<Option<customer::Customer>, errors::StorageError>;
+ #[cfg(all(any(feature = "v1", feature = "v2"), not(feature = "customer_v2")))]
+ async fn find_customer_optional_with_redacted_customer_details_by_customer_id_merchant_id(
+ &self,
+ state: &KeyManagerState,
+ customer_id: &id_type::CustomerId,
+ merchant_id: &id_type::MerchantId,
+ key_store: &domain::MerchantKeyStore,
+ storage_scheme: MerchantStorageScheme,
+ ) -> CustomResult<Option<customer::Customer>, errors::StorageError>;
+
#[cfg(all(feature = "v2", feature = "customer_v2"))]
async fn find_optional_by_merchant_id_merchant_reference_id(
&self,
@@ -242,6 +252,73 @@ mod storage {
})
}
+ #[instrument(skip_all)]
+ // check customer not found in kv and fallback to db
+ #[cfg(all(any(feature = "v1", feature = "v2"), not(feature = "customer_v2")))]
+ async fn find_customer_optional_with_redacted_customer_details_by_customer_id_merchant_id(
+ &self,
+ state: &KeyManagerState,
+ customer_id: &id_type::CustomerId,
+ merchant_id: &id_type::MerchantId,
+ key_store: &domain::MerchantKeyStore,
+ storage_scheme: MerchantStorageScheme,
+ ) -> CustomResult<Option<customer::Customer>, errors::StorageError> {
+ let conn = connection::pg_connection_read(self).await?;
+ let database_call = || async {
+ storage_types::Customer::find_optional_by_customer_id_merchant_id(
+ &conn,
+ customer_id,
+ merchant_id,
+ )
+ .await
+ .map_err(|err| report!(errors::StorageError::from(err)))
+ };
+ let storage_scheme =
+ decide_storage_scheme::<_, diesel_models::Customer>(self, storage_scheme, Op::Find)
+ .await;
+ let maybe_customer = match storage_scheme {
+ MerchantStorageScheme::PostgresOnly => database_call().await,
+ MerchantStorageScheme::RedisKv => {
+ let key = PartitionKey::MerchantIdCustomerId {
+ merchant_id,
+ customer_id: customer_id.get_string_repr(),
+ };
+ let field = format!("cust_{}", customer_id.get_string_repr());
+ Box::pin(db_utils::try_redis_get_else_try_database_get(
+ // check for ValueNotFound
+ async {
+ kv_wrapper(
+ self,
+ KvOperation::<diesel_models::Customer>::HGet(&field),
+ key,
+ )
+ .await?
+ .try_into_hget()
+ .map(Some)
+ },
+ database_call,
+ ))
+ .await
+ }
+ }?;
+
+ let maybe_result = maybe_customer
+ .async_map(|customer| async {
+ customer
+ .convert(
+ state,
+ key_store.key.get_inner(),
+ key_store.merchant_id.clone().into(),
+ )
+ .await
+ .change_context(errors::StorageError::DecryptionError)
+ })
+ .await
+ .transpose()?;
+
+ Ok(maybe_result)
+ }
+
#[cfg(all(feature = "v2", feature = "customer_v2"))]
async fn find_optional_by_merchant_id_merchant_reference_id(
&self,
@@ -938,6 +1015,35 @@ mod storage {
})
}
+ #[instrument(skip_all)]
+ #[cfg(all(any(feature = "v1", feature = "v2"), not(feature = "customer_v2")))]
+ async fn find_customer_optional_with_redacted_customer_details_by_customer_id_merchant_id(
+ &self,
+ state: &KeyManagerState,
+ customer_id: &id_type::CustomerId,
+ merchant_id: &id_type::MerchantId,
+ key_store: &domain::MerchantKeyStore,
+ _storage_scheme: MerchantStorageScheme,
+ ) -> CustomResult<Option<customer::Customer>, errors::StorageError> {
+ let conn = connection::pg_connection_read(self).await?;
+ let maybe_customer: Option<customer::Customer> =
+ storage_types::Customer::find_optional_by_customer_id_merchant_id(
+ &conn,
+ customer_id,
+ merchant_id,
+ )
+ .await
+ .map_err(|error| report!(errors::StorageError::from(error)))?
+ .async_map(|c| async {
+ c.convert(state, key_store.key.get_inner(), merchant_id.clone().into())
+ .await
+ .change_context(errors::StorageError::DecryptionError)
+ })
+ .await
+ .transpose()?;
+ Ok(maybe_customer)
+ }
+
#[cfg(all(any(feature = "v1", feature = "v2"), not(feature = "customer_v2")))]
#[instrument(skip_all)]
#[cfg(all(feature = "v2", feature = "customer_v2"))]
@@ -1239,6 +1345,37 @@ impl CustomerInterface for MockDb {
.transpose()
}
+ #[allow(clippy::panic)]
+ #[cfg(all(any(feature = "v1", feature = "v2"), not(feature = "customer_v2")))]
+ async fn find_customer_optional_with_redacted_customer_details_by_customer_id_merchant_id(
+ &self,
+ state: &KeyManagerState,
+ customer_id: &id_type::CustomerId,
+ merchant_id: &id_type::MerchantId,
+ key_store: &domain::MerchantKeyStore,
+ _storage_scheme: MerchantStorageScheme,
+ ) -> CustomResult<Option<customer::Customer>, errors::StorageError> {
+ let customers = self.customers.lock().await;
+ let customer = customers
+ .iter()
+ .find(|customer| {
+ customer.get_customer_id() == *customer_id && &customer.merchant_id == merchant_id
+ })
+ .cloned();
+ customer
+ .async_map(|c| async {
+ c.convert(
+ state,
+ key_store.key.get_inner(),
+ key_store.merchant_id.clone().into(),
+ )
+ .await
+ .change_context(errors::StorageError::DecryptionError)
+ })
+ .await
+ .transpose()
+ }
+
#[allow(clippy::panic)]
#[cfg(all(feature = "v2", feature = "customer_v2"))]
async fn find_optional_by_merchant_id_merchant_reference_id(
diff --git a/crates/router/src/db/kafka_store.rs b/crates/router/src/db/kafka_store.rs
index f7b15cdb3a3..d4e261792f7 100644
--- a/crates/router/src/db/kafka_store.rs
+++ b/crates/router/src/db/kafka_store.rs
@@ -375,6 +375,26 @@ impl CustomerInterface for KafkaStore {
.await
}
+ #[cfg(all(any(feature = "v1", feature = "v2"), not(feature = "customer_v2")))]
+ async fn find_customer_optional_with_redacted_customer_details_by_customer_id_merchant_id(
+ &self,
+ state: &KeyManagerState,
+ customer_id: &id_type::CustomerId,
+ merchant_id: &id_type::MerchantId,
+ key_store: &domain::MerchantKeyStore,
+ storage_scheme: MerchantStorageScheme,
+ ) -> CustomResult<Option<domain::Customer>, errors::StorageError> {
+ self.diesel_store
+ .find_customer_optional_with_redacted_customer_details_by_customer_id_merchant_id(
+ state,
+ customer_id,
+ merchant_id,
+ key_store,
+ storage_scheme,
+ )
+ .await
+ }
+
#[cfg(all(feature = "v2", feature = "customer_v2"))]
async fn find_optional_by_merchant_id_merchant_reference_id(
&self,
|
2024-08-28T10:40:26Z
|
## Type of Change
<!-- Put an `x` in the boxes that apply -->
- [x] Bugfix
- [ ] New feature
- [ ] Enhancement
- [ ] Refactoring
- [ ] Dependency updates
- [ ] Documentation
- [ ] CI/CD
## Description
<!-- Describe your changes in detail -->
If the customer is deleted after the payment is done the payments retrieve will fail as the customer details are redacted. But we should be able to retrieve a payment even is the customer details are redacted.
This pr contains the changes that will set the customer details to `None` if the customer details are redacted during the `Psync`.
### Additional Changes
- [ ] This PR modifies the API contract
- [ ] This PR modifies the database schema
- [ ] This PR modifies application configuration/environment variables
<!--
Provide links to the files with corresponding changes.
Following are the paths where you can find config files:
1. `config`
2. `crates/router/src/configs`
3. `loadtest/config`
-->
## Motivation and Context
<!--
Why is this change required? What problem does it solve?
If it fixes an open issue, please link to the issue here.
If you don't have an issue, we'd recommend starting with one first so the PR
can focus on the implementation (unless it is an obvious bug or documentation fix
that will have little conversation).
-->
## How did you test it?
<!--
Did you write an integration/unit/API test to verify the code changes?
Or did you test this change manually (provide relevant screenshots)?
-->
-> Make a card payment
```
curl --location 'http://localhost:8080/payments' \
--header 'Content-Type: application/json' \
--header 'Accept: application/json' \
--header 'api-key: dev_RPC8caLJDX8s4AFPVxr0KCy6UOTSJNs7IjbfK9WmkDddIBTfibFPBuQxM4A1nKu0' \
--data-raw '{
"amount": 100,
"amount_to_capture": 100,
"currency": "USD",
"confirm": true,
"capture_method": "automatic",
"capture_on": "2022-09-10T10:11:12Z",
"email": "guest@example.com",
"name": "John Doe",
"phone": "999999999",
"customer_id": "cu_1725352557",
"phone_country_code": "+1",
"description": "Its my first payment request",
"authentication_type": "no_three_ds",
"return_url": "http://127.0.0.1:4040",
"customer_acceptance": {
"acceptance_type": "offline",
"accepted_at": "1963-05-03T04:07:52.723Z",
"online": {
"ip_address": "in sit",
"user_agent": "amet irure esse"
}
},
"payment_method": "card",
"payment_method_data": {
"card": {
"card_number": "4000000000000119",
"card_exp_month": "03",
"card_exp_year": "2030",
"card_holder_name": "joseph Doe",
"card_cvc": "838"
}
},
"billing": {
"address": {
"line1": "1467",
"line2": "Harrison Street",
"line3": "Harrison Street",
"city": "San",
"state": "California",
"zip": "94122",
"country": "US",
"first_name": "PiX",
"last_name": "ss"
}
},
"shipping": {
"address": {
"line1": "1467",
"line2": "Harrison Street",
"line3": "Harrison Street",
"city": "San Fransico",
"state": "California",
"zip": "94122",
"country": "US",
"first_name": "PiX"
}
},
"browser_info": {
"user_agent": "Mozilla\/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit\/537.36 (KHTML, like Gecko) Chrome\/70.0.3538.110 Safari\/537.36",
"accept_header": "text\/html,application\/xhtml+xml,application\/xml;q=0.9,image\/webp,image\/apng,*\/*;q=0.8",
"language": "nl-NL",
"color_depth": 24,
"screen_height": 723,
"screen_width": 1536,
"time_zone": 0,
"java_enabled": true,
"java_script_enabled": true,
"ip_address": "125.0.0.1"
},
"statement_descriptor_name": "joseph",
"statement_descriptor_suffix": "JS",
"metadata": {
"udf1": "value1",
"new_customer": "true",
"login_date": "2019-09-10T10:11:12Z"
}
}'
```
```
{
"payment_id": "pay_5zhIYYmNTX8Tt5aBhh9L",
"merchant_id": "merchant_1725352456",
"status": "succeeded",
"amount": 100,
"net_amount": 100,
"amount_capturable": 0,
"amount_received": 100,
"connector": "cybersource",
"client_secret": "pay_5zhIYYmNTX8Tt5aBhh9L_secret_7ZVEnylnSEZT4hzpqmWS",
"created": "2024-09-03T08:37:35.629Z",
"currency": "USD",
"customer_id": "cu_1725352656",
"customer": {
"id": "cu_1725352656",
"name": "John Doe",
"email": "guest@example.com",
"phone": "999999999",
"phone_country_code": "+1"
},
"description": "Its my first payment request",
"refunds": null,
"disputes": null,
"mandate_id": null,
"mandate_data": null,
"setup_future_usage": null,
"off_session": null,
"capture_on": null,
"capture_method": "automatic",
"payment_method": "card",
"payment_method_data": {
"card": {
"last4": "0119",
"card_type": null,
"card_network": null,
"card_issuer": null,
"card_issuing_country": null,
"card_isin": "400000",
"card_extended_bin": null,
"card_exp_month": "03",
"card_exp_year": "2030",
"card_holder_name": null,
"payment_checks": {
"avs_response": {
"code": "Y",
"codeRaw": "Y"
},
"card_verification": null
},
"authentication_data": null
},
"billing": null
},
"payment_token": "token_XPgomv4iZkbxp4PX9Jrt",
"shipping": {
"address": {
"city": "San Fransico",
"country": "US",
"line1": "1467",
"line2": "Harrison Street",
"line3": "Harrison Street",
"zip": "94122",
"state": "California",
"first_name": "PiX",
"last_name": null
},
"phone": null,
"email": null
},
"billing": {
"address": {
"city": "San",
"country": "US",
"line1": "1467",
"line2": "Harrison Street",
"line3": "Harrison Street",
"zip": "94122",
"state": "California",
"first_name": "PiX",
"last_name": "ss"
},
"phone": null,
"email": null
},
"order_details": null,
"email": "guest@example.com",
"name": "John Doe",
"phone": "999999999",
"return_url": "http://127.0.0.1:4040/",
"authentication_type": "no_three_ds",
"statement_descriptor_name": "joseph",
"statement_descriptor_suffix": "JS",
"next_action": null,
"cancellation_reason": null,
"error_code": null,
"error_message": null,
"unified_code": null,
"unified_message": null,
"payment_experience": null,
"payment_method_type": null,
"connector_label": null,
"business_country": null,
"business_label": "default",
"business_sub_label": null,
"allowed_payment_method_types": null,
"ephemeral_key": {
"customer_id": "cu_1725352656",
"created_at": 1725352655,
"expires": 1725356255,
"secret": "epk_11de191943614d18b24ffda26474d9eb"
},
"manual_retry_allowed": false,
"connector_transaction_id": "7253526568986196003955",
"frm_message": null,
"metadata": {
"udf1": "value1",
"login_date": "2019-09-10T10:11:12Z",
"new_customer": "true"
},
"connector_metadata": null,
"feature_metadata": null,
"reference_id": "pay_5zhIYYmNTX8Tt5aBhh9L_1",
"payment_link": null,
"profile_id": "pro_pCmVCFH8Jh9CRAOq71tG",
"surcharge_details": null,
"attempt_count": 1,
"merchant_decision": null,
"merchant_connector_id": "mca_HLz5UXL0F35JM3QsRh6f",
"incremental_authorization_allowed": false,
"authorization_count": null,
"incremental_authorizations": null,
"external_authentication_details": null,
"external_3ds_authentication_attempted": false,
"expires_on": "2024-09-03T08:52:35.629Z",
"fingerprint": null,
"browser_info": {
"language": "nl-NL",
"time_zone": 0,
"ip_address": "125.0.0.1",
"user_agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/70.0.3538.110 Safari/537.36",
"color_depth": 24,
"java_enabled": true,
"screen_width": 1536,
"accept_header": "text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,image/apng,*/*;q=0.8",
"screen_height": 723,
"java_script_enabled": true
},
"payment_method_id": null,
"payment_method_status": null,
"updated": "2024-09-03T08:37:38.445Z",
"charges": null,
"frm_metadata": null,
"merchant_order_reference_id": null
}
```
-> Delete the customer
```
curl --location --request DELETE 'http://localhost:8080/customers/cu_1725352656' \
--header 'Accept: application/json' \
--header 'api-key: dev_RPC8caLJDX8s4AFPVxr0KCy6UOTSJNs7IjbfK9WmkDddIBTfibFPBuQxM4A1nKu0'
```
```
{
"customer_id": "cu_1725352656",
"customer_deleted": true,
"address_deleted": true,
"payment_methods_deleted": true
}
```
-> force sync
```
curl --location 'http://localhost:8080/payments/pay_5zhIYYmNTX8Tt5aBhh9L?force_sync=true' \
--header 'Accept: application/json' \
--header 'api-key: dev_RPC8caLJDX8s4AFPVxr0KCy6UOTSJNs7IjbfK9WmkDddIBTfibFPBuQxM4A1nKu0'
```
```
{
"payment_id": "pay_5zhIYYmNTX8Tt5aBhh9L",
"merchant_id": "merchant_1725352456",
"status": "succeeded",
"amount": 100,
"net_amount": 100,
"amount_capturable": 0,
"amount_received": 100,
"connector": "cybersource",
"client_secret": "pay_5zhIYYmNTX8Tt5aBhh9L_secret_7ZVEnylnSEZT4hzpqmWS",
"created": "2024-09-03T08:37:35.629Z",
"currency": "USD",
"customer_id": "cu_1725352656",
"customer": {
"id": "cu_1725352656",
"name": "Redacted",
"email": "Redacted",
"phone": "Redacted",
"phone_country_code": "Redacted"
},
"description": "Its my first payment request",
"refunds": null,
"disputes": null,
"mandate_id": null,
"mandate_data": null,
"setup_future_usage": null,
"off_session": null,
"capture_on": null,
"capture_method": "automatic",
"payment_method": "card",
"payment_method_data": {
"card": {
"last4": "0119",
"card_type": null,
"card_network": null,
"card_issuer": null,
"card_issuing_country": null,
"card_isin": "400000",
"card_extended_bin": null,
"card_exp_month": "03",
"card_exp_year": "2030",
"card_holder_name": null,
"payment_checks": {
"avs_response": {
"code": "Y",
"codeRaw": "Y"
},
"card_verification": null
},
"authentication_data": null
},
"billing": null
},
"payment_token": "token_XPgomv4iZkbxp4PX9Jrt",
"shipping": {
"address": {
"city": "Redacted",
"country": "US",
"line1": "Redacted",
"line2": "Redacted",
"line3": "Redacted",
"zip": "Redacted",
"state": "Redacted",
"first_name": "Redacted",
"last_name": "Redacted"
},
"phone": {
"number": "Redacted",
"country_code": "Redacted"
},
"email": "Redacted"
},
"billing": {
"address": {
"city": "Redacted",
"country": "US",
"line1": "Redacted",
"line2": "Redacted",
"line3": "Redacted",
"zip": "Redacted",
"state": "Redacted",
"first_name": "Redacted",
"last_name": "Redacted"
},
"phone": {
"number": "Redacted",
"country_code": "Redacted"
},
"email": "Redacted"
},
"order_details": null,
"email": "Redacted",
"name": "Redacted",
"phone": "Redacted",
"return_url": "http://127.0.0.1:4040/",
"authentication_type": "no_three_ds",
"statement_descriptor_name": "joseph",
"statement_descriptor_suffix": "JS",
"next_action": null,
"cancellation_reason": null,
"error_code": null,
"error_message": null,
"unified_code": null,
"unified_message": null,
"payment_experience": null,
"payment_method_type": null,
"connector_label": null,
"business_country": null,
"business_label": "default",
"business_sub_label": null,
"allowed_payment_method_types": null,
"ephemeral_key": null,
"manual_retry_allowed": false,
"connector_transaction_id": "7253526568986196003955",
"frm_message": null,
"metadata": {
"udf1": "value1",
"login_date": "2019-09-10T10:11:12Z",
"new_customer": "true"
},
"connector_metadata": null,
"feature_metadata": null,
"reference_id": "pay_5zhIYYmNTX8Tt5aBhh9L_1",
"payment_link": null,
"profile_id": "pro_pCmVCFH8Jh9CRAOq71tG",
"surcharge_details": null,
"attempt_count": 1,
"merchant_decision": null,
"merchant_connector_id": "mca_HLz5UXL0F35JM3QsRh6f",
"incremental_authorization_allowed": false,
"authorization_count": null,
"incremental_authorizations": null,
"external_authentication_details": null,
"external_3ds_authentication_attempted": false,
"expires_on": "2024-09-03T08:52:35.629Z",
"fingerprint": null,
"browser_info": {
"language": "nl-NL",
"time_zone": 0,
"ip_address": "125.0.0.1",
"user_agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/70.0.3538.110 Safari/537.36",
"color_depth": 24,
"java_enabled": true,
"screen_width": 1536,
"accept_header": "text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,image/apng,*/*;q=0.8",
"screen_height": 723,
"java_script_enabled": true
},
"payment_method_id": "pm_2HS0C3hN1bhCisZRiHRB",
"payment_method_status": null,
"updated": "2024-09-03T08:37:38.445Z",
"charges": null,
"frm_metadata": null,
"merchant_order_reference_id": null
}
```
-> sync
```
curl --location 'http://localhost:8080/payments/pay_5zhIYYmNTX8Tt5aBhh9L' \
--header 'Accept: application/json' \
--header 'api-key: dev_RPC8caLJDX8s4AFPVxr0KCy6UOTSJNs7IjbfK9WmkDddIBTfibFPBuQxM4A1nKu0'
```
```
{
"payment_id": "pay_5zhIYYmNTX8Tt5aBhh9L",
"merchant_id": "merchant_1725352456",
"status": "succeeded",
"amount": 100,
"net_amount": 100,
"amount_capturable": 0,
"amount_received": 100,
"connector": "cybersource",
"client_secret": "pay_5zhIYYmNTX8Tt5aBhh9L_secret_7ZVEnylnSEZT4hzpqmWS",
"created": "2024-09-03T08:37:35.629Z",
"currency": "USD",
"customer_id": "cu_1725352656",
"customer": {
"id": "cu_1725352656",
"name": "Redacted",
"email": "Redacted",
"phone": "Redacted",
"phone_country_code": "Redacted"
},
"description": "Its my first payment request",
"refunds": null,
"disputes": null,
"mandate_id": null,
"mandate_data": null,
"setup_future_usage": null,
"off_session": null,
"capture_on": null,
"capture_method": "automatic",
"payment_method": "card",
"payment_method_data": {
"card": {
"last4": "0119",
"card_type": null,
"card_network": null,
"card_issuer": null,
"card_issuing_country": null,
"card_isin": "400000",
"card_extended_bin": null,
"card_exp_month": "03",
"card_exp_year": "2030",
"card_holder_name": null,
"payment_checks": {
"avs_response": {
"code": "Y",
"codeRaw": "Y"
},
"card_verification": null
},
"authentication_data": null
},
"billing": null
},
"payment_token": "token_XPgomv4iZkbxp4PX9Jrt",
"shipping": {
"address": {
"city": "Redacted",
"country": "US",
"line1": "Redacted",
"line2": "Redacted",
"line3": "Redacted",
"zip": "Redacted",
"state": "Redacted",
"first_name": "Redacted",
"last_name": "Redacted"
},
"phone": {
"number": "Redacted",
"country_code": "Redacted"
},
"email": "Redacted"
},
"billing": {
"address": {
"city": "Redacted",
"country": "US",
"line1": "Redacted",
"line2": "Redacted",
"line3": "Redacted",
"zip": "Redacted",
"state": "Redacted",
"first_name": "Redacted",
"last_name": "Redacted"
},
"phone": {
"number": "Redacted",
"country_code": "Redacted"
},
"email": "Redacted"
},
"order_details": null,
"email": "Redacted",
"name": "Redacted",
"phone": "Redacted",
"return_url": "http://127.0.0.1:4040/",
"authentication_type": "no_three_ds",
"statement_descriptor_name": "joseph",
"statement_descriptor_suffix": "JS",
"next_action": null,
"cancellation_reason": null,
"error_code": null,
"error_message": null,
"unified_code": null,
"unified_message": null,
"payment_experience": null,
"payment_method_type": null,
"connector_label": null,
"business_country": null,
"business_label": "default",
"business_sub_label": null,
"allowed_payment_method_types": null,
"ephemeral_key": null,
"manual_retry_allowed": false,
"connector_transaction_id": "7253526568986196003955",
"frm_message": null,
"metadata": {
"udf1": "value1",
"login_date": "2019-09-10T10:11:12Z",
"new_customer": "true"
},
"connector_metadata": null,
"feature_metadata": null,
"reference_id": "pay_5zhIYYmNTX8Tt5aBhh9L_1",
"payment_link": null,
"profile_id": "pro_pCmVCFH8Jh9CRAOq71tG",
"surcharge_details": null,
"attempt_count": 1,
"merchant_decision": null,
"merchant_connector_id": "mca_HLz5UXL0F35JM3QsRh6f",
"incremental_authorization_allowed": false,
"authorization_count": null,
"incremental_authorizations": null,
"external_authentication_details": null,
"external_3ds_authentication_attempted": false,
"expires_on": "2024-09-03T08:52:35.629Z",
"fingerprint": null,
"browser_info": {
"language": "nl-NL",
"time_zone": 0,
"ip_address": "125.0.0.1",
"user_agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/70.0.3538.110 Safari/537.36",
"color_depth": 24,
"java_enabled": true,
"screen_width": 1536,
"accept_header": "text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,image/apng,*/*;q=0.8",
"screen_height": 723,
"java_script_enabled": true
},
"payment_method_id": "pm_2HS0C3hN1bhCisZRiHRB",
"payment_method_status": null,
"updated": "2024-09-03T08:37:38.445Z",
"charges": null,
"frm_metadata": null,
"merchant_order_reference_id": null
}
```
-> Create a 3DS payment
```
{
"amount": 100,
"amount_to_capture": 100,
"currency": "USD",
"confirm": true,
"capture_method": "automatic",
"capture_on": "2022-09-10T10:11:12Z",
"customer_id": "cu_{{$timestamp}}",
"email": "guest@example.com",
"name": "John Doe",
"phone": "999999999",
"phone_country_code": "+1",
"description": "Its my first payment request",
"authentication_type": "three_ds",
"setup_future_usage": "on_session",
"return_url": "http://127.0.0.1:4040",
"customer_acceptance": {
"acceptance_type": "offline",
"accepted_at": "1963-05-03T04:07:52.723Z",
"online": {
"ip_address": "in sit",
"user_agent": "amet irure esse"
}
},
"payment_method": "card",
"payment_method_data": {
"card": {
"card_number": "4000000000000119",
"card_exp_month": "03",
"card_exp_year": "2030",
"card_holder_name": "joseph Doe",
"card_cvc": "838"
}
},
"billing": {
"address": {
"line1": "1467",
"line2": "Harrison Street",
"line3": "Harrison Street",
"city": "San",
"state": "California",
"zip": "94122",
"country": "US",
"first_name": "PiX",
"last_name": "ss"
}
},
"shipping": {
"address": {
"line1": "1467",
"line2": "Harrison Street",
"line3": "Harrison Street",
"city": "San Fransico",
"state": "California",
"zip": "94122",
"country": "US",
"first_name": "PiX"
}
},
"browser_info": {
"user_agent": "Mozilla\/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit\/537.36 (KHTML, like Gecko) Chrome\/70.0.3538.110 Safari\/537.36",
"accept_header": "text\/html,application\/xhtml+xml,application\/xml;q=0.9,image\/webp,image\/apng,*\/*;q=0.8",
"language": "nl-NL",
"color_depth": 24,
"screen_height": 723,
"screen_width": 1536,
"time_zone": 0,
"java_enabled": true,
"java_script_enabled": true,
"ip_address": "125.0.0.1"
},
"statement_descriptor_name": "joseph",
"statement_descriptor_suffix": "JS",
"metadata": {
"udf1": "value1",
"new_customer": "true",
"login_date": "2019-09-10T10:11:12Z"
}
}
```
```
{
"payment_id": "pay_41DjpxBAJQivxfQeKPv8",
"merchant_id": "merchant_1725352456",
"status": "requires_customer_action",
"amount": 100,
"net_amount": 100,
"amount_capturable": 100,
"amount_received": null,
"connector": "cybersource",
"client_secret": "pay_41DjpxBAJQivxfQeKPv8_secret_3smf34QBXKWJtCauS4jm",
"created": "2024-09-03T08:40:44.643Z",
"currency": "USD",
"customer_id": "cu_1725352845",
"customer": {
"id": "cu_1725352845",
"name": "John Doe",
"email": "guest@example.com",
"phone": "999999999",
"phone_country_code": "+1"
},
"description": "Its my first payment request",
"refunds": null,
"disputes": null,
"mandate_id": null,
"mandate_data": null,
"setup_future_usage": "on_session",
"off_session": null,
"capture_on": null,
"capture_method": "automatic",
"payment_method": "card",
"payment_method_data": {
"card": {
"last4": "0119",
"card_type": null,
"card_network": null,
"card_issuer": null,
"card_issuing_country": null,
"card_isin": "400000",
"card_extended_bin": null,
"card_exp_month": "03",
"card_exp_year": "2030",
"card_holder_name": null,
"payment_checks": null,
"authentication_data": null
},
"billing": null
},
"payment_token": "token_QQOmOKb72IHX9oc0V6pi",
"shipping": {
"address": {
"city": "San Fransico",
"country": "US",
"line1": "1467",
"line2": "Harrison Street",
"line3": "Harrison Street",
"zip": "94122",
"state": "California",
"first_name": "PiX",
"last_name": null
},
"phone": null,
"email": null
},
"billing": {
"address": {
"city": "San",
"country": "US",
"line1": "1467",
"line2": "Harrison Street",
"line3": "Harrison Street",
"zip": "94122",
"state": "California",
"first_name": "PiX",
"last_name": "ss"
},
"phone": null,
"email": null
},
"order_details": null,
"email": "guest@example.com",
"name": "John Doe",
"phone": "999999999",
"return_url": "http://127.0.0.1:4040/",
"authentication_type": "three_ds",
"statement_descriptor_name": "joseph",
"statement_descriptor_suffix": "JS",
"next_action": {
"type": "redirect_to_url",
"redirect_to_url": "http://localhost:8080/payments/redirect/pay_41DjpxBAJQivxfQeKPv8/merchant_1725352456/pay_41DjpxBAJQivxfQeKPv8_1"
},
"cancellation_reason": null,
"error_code": null,
"error_message": null,
"unified_code": null,
"unified_message": null,
"payment_experience": null,
"payment_method_type": null,
"connector_label": null,
"business_country": null,
"business_label": "default",
"business_sub_label": null,
"allowed_payment_method_types": null,
"ephemeral_key": {
"customer_id": "cu_1725352845",
"created_at": 1725352844,
"expires": 1725356444,
"secret": "epk_1a74a81a985a417fbcea5ec3740c3945"
},
"manual_retry_allowed": null,
"connector_transaction_id": null,
"frm_message": null,
"metadata": {
"udf1": "value1",
"login_date": "2019-09-10T10:11:12Z",
"new_customer": "true"
},
"connector_metadata": null,
"feature_metadata": null,
"reference_id": "pay_41DjpxBAJQivxfQeKPv8_1",
"payment_link": null,
"profile_id": "pro_pCmVCFH8Jh9CRAOq71tG",
"surcharge_details": null,
"attempt_count": 1,
"merchant_decision": null,
"merchant_connector_id": "mca_HLz5UXL0F35JM3QsRh6f",
"incremental_authorization_allowed": null,
"authorization_count": null,
"incremental_authorizations": null,
"external_authentication_details": null,
"external_3ds_authentication_attempted": false,
"expires_on": "2024-09-03T08:55:44.643Z",
"fingerprint": null,
"browser_info": {
"language": "nl-NL",
"time_zone": 0,
"ip_address": "125.0.0.1",
"user_agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/70.0.3538.110 Safari/537.36",
"color_depth": 24,
"java_enabled": true,
"screen_width": 1536,
"accept_header": "text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,image/apng,*/*;q=0.8",
"screen_height": 723,
"java_script_enabled": true
},
"payment_method_id": null,
"payment_method_status": null,
"updated": "2024-09-03T08:40:46.043Z",
"charges": null,
"frm_metadata": null,
"merchant_order_reference_id": null
}
```
-> Perform the 3DS action
-> Delete the customer
-> Retrieve the payment
```
curl --location 'http://localhost:8080/payments/pay_41DjpxBAJQivxfQeKPv8' \
--header 'Accept: application/json' \
--header 'api-key: dev_RPC8caLJDX8s4AFPVxr0KCy6UOTSJNs7IjbfK9WmkDddIBTfibFPBuQxM4A1nKu0'
```
```
{
"payment_id": "pay_41DjpxBAJQivxfQeKPv8",
"merchant_id": "merchant_1725352456",
"status": "succeeded",
"amount": 100,
"net_amount": 100,
"amount_capturable": 0,
"amount_received": 100,
"connector": "cybersource",
"client_secret": "pay_41DjpxBAJQivxfQeKPv8_secret_3smf34QBXKWJtCauS4jm",
"created": "2024-09-03T08:40:44.643Z",
"currency": "USD",
"customer_id": "cu_1725352845",
"customer": {
"id": "cu_1725352845",
"name": "Redacted",
"email": "Redacted",
"phone": "Redacted",
"phone_country_code": "Redacted"
},
"description": "Its my first payment request",
"refunds": null,
"disputes": null,
"mandate_id": null,
"mandate_data": null,
"setup_future_usage": "on_session",
"off_session": null,
"capture_on": null,
"capture_method": "automatic",
"payment_method": "card",
"payment_method_data": {
"card": {
"last4": "0119",
"card_type": null,
"card_network": null,
"card_issuer": null,
"card_issuing_country": null,
"card_isin": "400000",
"card_extended_bin": null,
"card_exp_month": "03",
"card_exp_year": "2030",
"card_holder_name": null,
"payment_checks": {
"avs_response": {
"code": "Y",
"codeRaw": "Y"
},
"card_verification": null
},
"authentication_data": null
},
"billing": null
},
"payment_token": "token_QQOmOKb72IHX9oc0V6pi",
"shipping": {
"address": {
"city": "Redacted",
"country": "US",
"line1": "Redacted",
"line2": "Redacted",
"line3": "Redacted",
"zip": "Redacted",
"state": "Redacted",
"first_name": "Redacted",
"last_name": "Redacted"
},
"phone": {
"number": "Redacted",
"country_code": "Redacted"
},
"email": "Redacted"
},
"billing": {
"address": {
"city": "Redacted",
"country": "US",
"line1": "Redacted",
"line2": "Redacted",
"line3": "Redacted",
"zip": "Redacted",
"state": "Redacted",
"first_name": "Redacted",
"last_name": "Redacted"
},
"phone": {
"number": "Redacted",
"country_code": "Redacted"
},
"email": "Redacted"
},
"order_details": null,
"email": "Redacted",
"name": "Redacted",
"phone": "Redacted",
"return_url": "http://127.0.0.1:4040/",
"authentication_type": "three_ds",
"statement_descriptor_name": "joseph",
"statement_descriptor_suffix": "JS",
"next_action": null,
"cancellation_reason": null,
"error_code": null,
"error_message": null,
"unified_code": null,
"unified_message": null,
"payment_experience": null,
"payment_method_type": null,
"connector_label": null,
"business_country": null,
"business_label": "default",
"business_sub_label": null,
"allowed_payment_method_types": null,
"ephemeral_key": null,
"manual_retry_allowed": false,
"connector_transaction_id": "7253528712066298603955",
"frm_message": null,
"metadata": {
"udf1": "value1",
"login_date": "2019-09-10T10:11:12Z",
"new_customer": "true"
},
"connector_metadata": null,
"feature_metadata": null,
"reference_id": "pay_41DjpxBAJQivxfQeKPv8_1",
"payment_link": null,
"profile_id": "pro_pCmVCFH8Jh9CRAOq71tG",
"surcharge_details": null,
"attempt_count": 1,
"merchant_decision": null,
"merchant_connector_id": "mca_HLz5UXL0F35JM3QsRh6f",
"incremental_authorization_allowed": false,
"authorization_count": null,
"incremental_authorizations": null,
"external_authentication_details": null,
"external_3ds_authentication_attempted": false,
"expires_on": "2024-09-03T08:55:44.643Z",
"fingerprint": null,
"browser_info": {
"language": "nl-NL",
"time_zone": 0,
"ip_address": "125.0.0.1",
"user_agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/70.0.3538.110 Safari/537.36",
"color_depth": 24,
"java_enabled": true,
"screen_width": 1536,
"accept_header": "text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,image/apng,*/*;q=0.8",
"screen_height": 723,
"java_script_enabled": true
},
"payment_method_id": "pm_wxeK1LrwVZaeHOYeMqYu",
"payment_method_status": null,
"updated": "2024-09-03T08:41:12.583Z",
"charges": null,
"frm_metadata": null,
"merchant_order_reference_id": null
}
```
```
curl --location 'http://localhost:8080/payments/pay_41DjpxBAJQivxfQeKPv8?force_sync=true' \
--header 'Accept: application/json' \
--header 'api-key: dev_RPC8caLJDX8s4AFPVxr0KCy6UOTSJNs7IjbfK9WmkDddIBTfibFPBuQxM4A1nKu0'
```
```
{
"payment_id": "pay_41DjpxBAJQivxfQeKPv8",
"merchant_id": "merchant_1725352456",
"status": "succeeded",
"amount": 100,
"net_amount": 100,
"amount_capturable": 0,
"amount_received": 100,
"connector": "cybersource",
"client_secret": "pay_41DjpxBAJQivxfQeKPv8_secret_3smf34QBXKWJtCauS4jm",
"created": "2024-09-03T08:40:44.643Z",
"currency": "USD",
"customer_id": "cu_1725352845",
"customer": {
"id": "cu_1725352845",
"name": "Redacted",
"email": "Redacted",
"phone": "Redacted",
"phone_country_code": "Redacted"
},
"description": "Its my first payment request",
"refunds": null,
"disputes": null,
"mandate_id": null,
"mandate_data": null,
"setup_future_usage": "on_session",
"off_session": null,
"capture_on": null,
"capture_method": "automatic",
"payment_method": "card",
"payment_method_data": {
"card": {
"last4": "0119",
"card_type": null,
"card_network": null,
"card_issuer": null,
"card_issuing_country": null,
"card_isin": "400000",
"card_extended_bin": null,
"card_exp_month": "03",
"card_exp_year": "2030",
"card_holder_name": null,
"payment_checks": {
"avs_response": {
"code": "Y",
"codeRaw": "Y"
},
"card_verification": null
},
"authentication_data": null
},
"billing": null
},
"payment_token": "token_QQOmOKb72IHX9oc0V6pi",
"shipping": {
"address": {
"city": "Redacted",
"country": "US",
"line1": "Redacted",
"line2": "Redacted",
"line3": "Redacted",
"zip": "Redacted",
"state": "Redacted",
"first_name": "Redacted",
"last_name": "Redacted"
},
"phone": {
"number": "Redacted",
"country_code": "Redacted"
},
"email": "Redacted"
},
"billing": {
"address": {
"city": "Redacted",
"country": "US",
"line1": "Redacted",
"line2": "Redacted",
"line3": "Redacted",
"zip": "Redacted",
"state": "Redacted",
"first_name": "Redacted",
"last_name": "Redacted"
},
"phone": {
"number": "Redacted",
"country_code": "Redacted"
},
"email": "Redacted"
},
"order_details": null,
"email": "Redacted",
"name": "Redacted",
"phone": "Redacted",
"return_url": "http://127.0.0.1:4040/",
"authentication_type": "three_ds",
"statement_descriptor_name": "joseph",
"statement_descriptor_suffix": "JS",
"next_action": null,
"cancellation_reason": null,
"error_code": null,
"error_message": null,
"unified_code": null,
"unified_message": null,
"payment_experience": null,
"payment_method_type": null,
"connector_label": null,
"business_country": null,
"business_label": "default",
"business_sub_label": null,
"allowed_payment_method_types": null,
"ephemeral_key": null,
"manual_retry_allowed": false,
"connector_transaction_id": "7253528712066298603955",
"frm_message": null,
"metadata": {
"udf1": "value1",
"login_date": "2019-09-10T10:11:12Z",
"new_customer": "true"
},
"connector_metadata": null,
"feature_metadata": null,
"reference_id": "pay_41DjpxBAJQivxfQeKPv8_1",
"payment_link": null,
"profile_id": "pro_pCmVCFH8Jh9CRAOq71tG",
"surcharge_details": null,
"attempt_count": 1,
"merchant_decision": null,
"merchant_connector_id": "mca_HLz5UXL0F35JM3QsRh6f",
"incremental_authorization_allowed": false,
"authorization_count": null,
"incremental_authorizations": null,
"external_authentication_details": null,
"external_3ds_authentication_attempted": false,
"expires_on": "2024-09-03T08:55:44.643Z",
"fingerprint": null,
"browser_info": {
"language": "nl-NL",
"time_zone": 0,
"ip_address": "125.0.0.1",
"user_agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/70.0.3538.110 Safari/537.36",
"color_depth": 24,
"java_enabled": true,
"screen_width": 1536,
"accept_header": "text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,image/apng,*/*;q=0.8",
"screen_height": 723,
"java_script_enabled": true
},
"payment_method_id": "pm_wxeK1LrwVZaeHOYeMqYu",
"payment_method_status": null,
"updated": "2024-09-03T08:41:12.583Z",
"charges": null,
"frm_metadata": null,
"merchant_order_reference_id": null
}
```
-> Create a payment with manual capture
```
curl --location 'http://localhost:8080/payments' \
--header 'Content-Type: application/json' \
--header 'Accept: application/json' \
--header 'api-key: dev_0GFABoDSJOBz6xazfsPttF4srDNXV6bFjsg9u5Uyt0z2hNGnyluDlVHf0GjU7qUm' \
--data-raw '{
"amount": 100,
"amount_to_capture": 100,
"currency": "USD",
"confirm": true,
"capture_method": "manual",
"capture_on": "2022-09-10T10:11:12Z",
"customer_id": "cu_1724853507",
"email": "guest@example.com",
"name": "John Doe",
"phone": "999999999",
"phone_country_code": "+1",
"description": "Its my first payment request",
"authentication_type": "no_three_ds",
"setup_future_usage": "on_session",
"return_url": "http://127.0.0.1:4040",
"customer_acceptance": {
"acceptance_type": "offline",
"accepted_at": "1963-05-03T04:07:52.723Z",
"online": {
"ip_address": "in sit",
"user_agent": "amet irure esse"
}
},
"payment_method": "card",
"payment_method_data": {
"card": {
"card_number": "4000000000000119",
"card_exp_month": "03",
"card_exp_year": "2030",
"card_holder_name": "joseph Doe",
"card_cvc": "838"
}
},
"billing": {
"address": {
"line1": "1467",
"line2": "Harrison Street",
"line3": "Harrison Street",
"city": "San",
"state": "California",
"zip": "94122",
"country": "US",
"first_name": "PiX",
"last_name": "ss"
}
},
"shipping": {
"address": {
"line1": "1467",
"line2": "Harrison Street",
"line3": "Harrison Street",
"city": "San Fransico",
"state": "California",
"zip": "94122",
"country": "US",
"first_name": "PiX"
}
},
"browser_info": {
"user_agent": "Mozilla\/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit\/537.36 (KHTML, like Gecko) Chrome\/70.0.3538.110 Safari\/537.36",
"accept_header": "text\/html,application\/xhtml+xml,application\/xml;q=0.9,image\/webp,image\/apng,*\/*;q=0.8",
"language": "nl-NL",
"color_depth": 24,
"screen_height": 723,
"screen_width": 1536,
"time_zone": 0,
"java_enabled": true,
"java_script_enabled": true,
"ip_address": "125.0.0.1"
},
"statement_descriptor_name": "joseph",
"statement_descriptor_suffix": "JS",
"metadata": {
"udf1": "value1",
"new_customer": "true",
"login_date": "2019-09-10T10:11:12Z"
}
}'
```
```
{
"payment_id": "pay_AwRQSrjv0N7tQEYzZnQ1",
"merchant_id": "merchant_1725352456",
"status": "requires_capture",
"amount": 100,
"net_amount": 100,
"amount_capturable": 100,
"amount_received": null,
"connector": "cybersource",
"client_secret": "pay_AwRQSrjv0N7tQEYzZnQ1_secret_VGJkIXf0NncMLVeXfMcX",
"created": "2024-09-03T08:45:14.448Z",
"currency": "USD",
"customer_id": "cu_1724853507",
"customer": {
"id": "cu_1724853507",
"name": "John Doe",
"email": "guest@example.com",
"phone": "999999999",
"phone_country_code": "+1"
},
"description": "Its my first payment request",
"refunds": null,
"disputes": null,
"mandate_id": null,
"mandate_data": null,
"setup_future_usage": "on_session",
"off_session": null,
"capture_on": null,
"capture_method": "manual",
"payment_method": "card",
"payment_method_data": {
"card": {
"last4": "0119",
"card_type": null,
"card_network": null,
"card_issuer": null,
"card_issuing_country": null,
"card_isin": "400000",
"card_extended_bin": null,
"card_exp_month": "03",
"card_exp_year": "2030",
"card_holder_name": null,
"payment_checks": {
"avs_response": {
"code": "Y",
"codeRaw": "Y"
},
"card_verification": null
},
"authentication_data": null
},
"billing": null
},
"payment_token": "token_rs2SpEaYBN0nGtwNEyGa",
"shipping": {
"address": {
"city": "San Fransico",
"country": "US",
"line1": "1467",
"line2": "Harrison Street",
"line3": "Harrison Street",
"zip": "94122",
"state": "California",
"first_name": "PiX",
"last_name": null
},
"phone": null,
"email": null
},
"billing": {
"address": {
"city": "San",
"country": "US",
"line1": "1467",
"line2": "Harrison Street",
"line3": "Harrison Street",
"zip": "94122",
"state": "California",
"first_name": "PiX",
"last_name": "ss"
},
"phone": null,
"email": null
},
"order_details": null,
"email": "guest@example.com",
"name": "John Doe",
"phone": "999999999",
"return_url": "http://127.0.0.1:4040/",
"authentication_type": "no_three_ds",
"statement_descriptor_name": "joseph",
"statement_descriptor_suffix": "JS",
"next_action": null,
"cancellation_reason": null,
"error_code": null,
"error_message": null,
"unified_code": null,
"unified_message": null,
"payment_experience": null,
"payment_method_type": null,
"connector_label": null,
"business_country": null,
"business_label": "default",
"business_sub_label": null,
"allowed_payment_method_types": null,
"ephemeral_key": {
"customer_id": "cu_1724853507",
"created_at": 1725353114,
"expires": 1725356714,
"secret": "epk_a1e4edaf5d4d4db986de6299d40e2c1d"
},
"manual_retry_allowed": false,
"connector_transaction_id": "7253531155796565703954",
"frm_message": null,
"metadata": {
"udf1": "value1",
"login_date": "2019-09-10T10:11:12Z",
"new_customer": "true"
},
"connector_metadata": null,
"feature_metadata": null,
"reference_id": "pay_AwRQSrjv0N7tQEYzZnQ1_1",
"payment_link": null,
"profile_id": "pro_pCmVCFH8Jh9CRAOq71tG",
"surcharge_details": null,
"attempt_count": 1,
"merchant_decision": null,
"merchant_connector_id": "mca_HLz5UXL0F35JM3QsRh6f",
"incremental_authorization_allowed": true,
"authorization_count": null,
"incremental_authorizations": null,
"external_authentication_details": null,
"external_3ds_authentication_attempted": false,
"expires_on": "2024-09-03T09:00:14.448Z",
"fingerprint": null,
"browser_info": {
"language": "nl-NL",
"time_zone": 0,
"ip_address": "125.0.0.1",
"user_agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/70.0.3538.110 Safari/537.36",
"color_depth": 24,
"java_enabled": true,
"screen_width": 1536,
"accept_header": "text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,image/apng,*/*;q=0.8",
"screen_height": 723,
"java_script_enabled": true
},
"payment_method_id": null,
"payment_method_status": null,
"updated": "2024-09-03T08:45:16.897Z",
"charges": null,
"frm_metadata": null,
"merchant_order_reference_id": null
}
```
-> Delete the customer
```
curl --location --request DELETE 'http://localhost:8080/customers/cu_1724853507' \
--header 'Accept: application/json' \
--header 'api-key: dev_RPC8caLJDX8s4AFPVxr0KCy6UOTSJNs7IjbfK9WmkDddIBTfibFPBuQxM4A1nKu0'
```
```
{
"customer_id": "cu_1724853507",
"customer_deleted": true,
"address_deleted": true,
"payment_methods_deleted": true
}
```
-> Retrieve payment
```
curl --location 'http://localhost:8080/payments/pay_AwRQSrjv0N7tQEYzZnQ1' \
--header 'Accept: application/json' \
--header 'api-key: dev_RPC8caLJDX8s4AFPVxr0KCy6UOTSJNs7IjbfK9WmkDddIBTfibFPBuQxM4A1nKu0'
```
```
{
"payment_id": "pay_AwRQSrjv0N7tQEYzZnQ1",
"merchant_id": "merchant_1725352456",
"status": "requires_capture",
"amount": 100,
"net_amount": 100,
"amount_capturable": 100,
"amount_received": null,
"connector": "cybersource",
"client_secret": "pay_AwRQSrjv0N7tQEYzZnQ1_secret_VGJkIXf0NncMLVeXfMcX",
"created": "2024-09-03T08:45:14.448Z",
"currency": "USD",
"customer_id": "cu_1724853507",
"customer": {
"id": "cu_1724853507",
"name": "Redacted",
"email": "Redacted",
"phone": "Redacted",
"phone_country_code": "Redacted"
},
"description": "Its my first payment request",
"refunds": null,
"disputes": null,
"mandate_id": null,
"mandate_data": null,
"setup_future_usage": "on_session",
"off_session": null,
"capture_on": null,
"capture_method": "manual",
"payment_method": "card",
"payment_method_data": {
"card": {
"last4": "0119",
"card_type": null,
"card_network": null,
"card_issuer": null,
"card_issuing_country": null,
"card_isin": "400000",
"card_extended_bin": null,
"card_exp_month": "03",
"card_exp_year": "2030",
"card_holder_name": null,
"payment_checks": {
"avs_response": {
"code": "Y",
"codeRaw": "Y"
},
"card_verification": null
},
"authentication_data": null
},
"billing": null
},
"payment_token": "token_rs2SpEaYBN0nGtwNEyGa",
"shipping": {
"address": {
"city": "Redacted",
"country": "US",
"line1": "Redacted",
"line2": "Redacted",
"line3": "Redacted",
"zip": "Redacted",
"state": "Redacted",
"first_name": "Redacted",
"last_name": "Redacted"
},
"phone": {
"number": "Redacted",
"country_code": "Redacted"
},
"email": "Redacted"
},
"billing": {
"address": {
"city": "Redacted",
"country": "US",
"line1": "Redacted",
"line2": "Redacted",
"line3": "Redacted",
"zip": "Redacted",
"state": "Redacted",
"first_name": "Redacted",
"last_name": "Redacted"
},
"phone": {
"number": "Redacted",
"country_code": "Redacted"
},
"email": "Redacted"
},
"order_details": null,
"email": "Redacted",
"name": "Redacted",
"phone": "Redacted",
"return_url": "http://127.0.0.1:4040/",
"authentication_type": "no_three_ds",
"statement_descriptor_name": "joseph",
"statement_descriptor_suffix": "JS",
"next_action": null,
"cancellation_reason": null,
"error_code": null,
"error_message": null,
"unified_code": null,
"unified_message": null,
"payment_experience": null,
"payment_method_type": null,
"connector_label": null,
"business_country": null,
"business_label": "default",
"business_sub_label": null,
"allowed_payment_method_types": null,
"ephemeral_key": null,
"manual_retry_allowed": false,
"connector_transaction_id": "7253531155796565703954",
"frm_message": null,
"metadata": {
"udf1": "value1",
"login_date": "2019-09-10T10:11:12Z",
"new_customer": "true"
},
"connector_metadata": null,
"feature_metadata": null,
"reference_id": "pay_AwRQSrjv0N7tQEYzZnQ1_1",
"payment_link": null,
"profile_id": "pro_pCmVCFH8Jh9CRAOq71tG",
"surcharge_details": null,
"attempt_count": 1,
"merchant_decision": null,
"merchant_connector_id": "mca_HLz5UXL0F35JM3QsRh6f",
"incremental_authorization_allowed": true,
"authorization_count": null,
"incremental_authorizations": null,
"external_authentication_details": null,
"external_3ds_authentication_attempted": false,
"expires_on": "2024-09-03T09:00:14.448Z",
"fingerprint": null,
"browser_info": {
"language": "nl-NL",
"time_zone": 0,
"ip_address": "125.0.0.1",
"user_agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/70.0.3538.110 Safari/537.36",
"color_depth": 24,
"java_enabled": true,
"screen_width": 1536,
"accept_header": "text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,image/apng,*/*;q=0.8",
"screen_height": 723,
"java_script_enabled": true
},
"payment_method_id": "pm_ZLuJJO15IFfb9jvoHjIb",
"payment_method_status": null,
"updated": "2024-09-03T08:45:16.897Z",
"charges": null,
"frm_metadata": null,
"merchant_order_reference_id": null
}
```
```
curl --location 'http://localhost:8080/payments/pay_AwRQSrjv0N7tQEYzZnQ1?force_sync=true' \
--header 'Accept: application/json' \
--header 'api-key: dev_RPC8caLJDX8s4AFPVxr0KCy6UOTSJNs7IjbfK9WmkDddIBTfibFPBuQxM4A1nKu0'
```
```
{
"payment_id": "pay_AwRQSrjv0N7tQEYzZnQ1",
"merchant_id": "merchant_1725352456",
"status": "requires_capture",
"amount": 100,
"net_amount": 100,
"amount_capturable": 100,
"amount_received": null,
"connector": "cybersource",
"client_secret": "pay_AwRQSrjv0N7tQEYzZnQ1_secret_VGJkIXf0NncMLVeXfMcX",
"created": "2024-09-03T08:45:14.448Z",
"currency": "USD",
"customer_id": "cu_1724853507",
"customer": {
"id": "cu_1724853507",
"name": "Redacted",
"email": "Redacted",
"phone": "Redacted",
"phone_country_code": "Redacted"
},
"description": "Its my first payment request",
"refunds": null,
"disputes": null,
"mandate_id": null,
"mandate_data": null,
"setup_future_usage": "on_session",
"off_session": null,
"capture_on": null,
"capture_method": "manual",
"payment_method": "card",
"payment_method_data": {
"card": {
"last4": "0119",
"card_type": null,
"card_network": null,
"card_issuer": null,
"card_issuing_country": null,
"card_isin": "400000",
"card_extended_bin": null,
"card_exp_month": "03",
"card_exp_year": "2030",
"card_holder_name": null,
"payment_checks": {
"avs_response": {
"code": "Y",
"codeRaw": "Y"
},
"card_verification": null
},
"authentication_data": null
},
"billing": null
},
"payment_token": "token_rs2SpEaYBN0nGtwNEyGa",
"shipping": {
"address": {
"city": "Redacted",
"country": "US",
"line1": "Redacted",
"line2": "Redacted",
"line3": "Redacted",
"zip": "Redacted",
"state": "Redacted",
"first_name": "Redacted",
"last_name": "Redacted"
},
"phone": {
"number": "Redacted",
"country_code": "Redacted"
},
"email": "Redacted"
},
"billing": {
"address": {
"city": "Redacted",
"country": "US",
"line1": "Redacted",
"line2": "Redacted",
"line3": "Redacted",
"zip": "Redacted",
"state": "Redacted",
"first_name": "Redacted",
"last_name": "Redacted"
},
"phone": {
"number": "Redacted",
"country_code": "Redacted"
},
"email": "Redacted"
},
"order_details": null,
"email": "Redacted",
"name": "Redacted",
"phone": "Redacted",
"return_url": "http://127.0.0.1:4040/",
"authentication_type": "no_three_ds",
"statement_descriptor_name": "joseph",
"statement_descriptor_suffix": "JS",
"next_action": null,
"cancellation_reason": null,
"error_code": null,
"error_message": null,
"unified_code": null,
"unified_message": null,
"payment_experience": null,
"payment_method_type": null,
"connector_label": null,
"business_country": null,
"business_label": "default",
"business_sub_label": null,
"allowed_payment_method_types": null,
"ephemeral_key": null,
"manual_retry_allowed": false,
"connector_transaction_id": "7253531155796565703954",
"frm_message": null,
"metadata": {
"udf1": "value1",
"login_date": "2019-09-10T10:11:12Z",
"new_customer": "true"
},
"connector_metadata": null,
"feature_metadata": null,
"reference_id": "7253531155796565703954",
"payment_link": null,
"profile_id": "pro_pCmVCFH8Jh9CRAOq71tG",
"surcharge_details": null,
"attempt_count": 1,
"merchant_decision": null,
"merchant_connector_id": "mca_HLz5UXL0F35JM3QsRh6f",
"incremental_authorization_allowed": true,
"authorization_count": null,
"incremental_authorizations": null,
"external_authentication_details": null,
"external_3ds_authentication_attempted": false,
"expires_on": "2024-09-03T09:00:14.448Z",
"fingerprint": null,
"browser_info": {
"language": "nl-NL",
"time_zone": 0,
"ip_address": "125.0.0.1",
"user_agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/70.0.3538.110 Safari/537.36",
"color_depth": 24,
"java_enabled": true,
"screen_width": 1536,
"accept_header": "text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,image/apng,*/*;q=0.8",
"screen_height": 723,
"java_script_enabled": true
},
"payment_method_id": "pm_ZLuJJO15IFfb9jvoHjIb",
"payment_method_status": null,
"updated": "2024-09-03T08:47:14.334Z",
"charges": null,
"frm_metadata": null,
"merchant_order_reference_id": null
}
```
-> Guest customer
Create a payment
```
curl --location 'http://localhost:8080/payments' \
--header 'Content-Type: application/json' \
--header 'Accept: application/json' \
--header 'api-key: dev_RPC8caLJDX8s4AFPVxr0KCy6UOTSJNs7IjbfK9WmkDddIBTfibFPBuQxM4A1nKu0' \
--data-raw '{
"amount": 100,
"amount_to_capture": 100,
"currency": "USD",
"confirm": true,
"capture_method": "automatic",
"capture_on": "2022-09-10T10:11:12Z",
"email": "guest@example.com",
"name": "John Doe",
"phone": "999999999",
"phone_country_code": "+1",
"description": "Its my first payment request",
"authentication_type": "no_three_ds",
"return_url": "http://127.0.0.1:4040",
"customer_acceptance": {
"acceptance_type": "offline",
"accepted_at": "1963-05-03T04:07:52.723Z",
"online": {
"ip_address": "in sit",
"user_agent": "amet irure esse"
}
},
"payment_method": "card",
"payment_method_data": {
"card": {
"card_number": "4000000000000119",
"card_exp_month": "03",
"card_exp_year": "2030",
"card_holder_name": "joseph Doe",
"card_cvc": "838"
}
},
"billing": {
"address": {
"line1": "1467",
"line2": "Harrison Street",
"line3": "Harrison Street",
"city": "San",
"state": "California",
"zip": "94122",
"country": "US",
"first_name": "PiX",
"last_name": "ss"
}
},
"shipping": {
"address": {
"line1": "1467",
"line2": "Harrison Street",
"line3": "Harrison Street",
"city": "San Fransico",
"state": "California",
"zip": "94122",
"country": "US",
"first_name": "PiX"
}
},
"browser_info": {
"user_agent": "Mozilla\/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit\/537.36 (KHTML, like Gecko) Chrome\/70.0.3538.110 Safari\/537.36",
"accept_header": "text\/html,application\/xhtml+xml,application\/xml;q=0.9,image\/webp,image\/apng,*\/*;q=0.8",
"language": "nl-NL",
"color_depth": 24,
"screen_height": 723,
"screen_width": 1536,
"time_zone": 0,
"java_enabled": true,
"java_script_enabled": true,
"ip_address": "125.0.0.1"
},
"statement_descriptor_name": "joseph",
"statement_descriptor_suffix": "JS",
"metadata": {
"udf1": "value1",
"new_customer": "true",
"login_date": "2019-09-10T10:11:12Z"
}
}'
```
```
{
"payment_id": "pay_v5429vfsJdjtaQqhhNMB",
"merchant_id": "merchant_1725352456",
"status": "succeeded",
"amount": 100,
"net_amount": 100,
"amount_capturable": 0,
"amount_received": 100,
"connector": "cybersource",
"client_secret": "pay_v5429vfsJdjtaQqhhNMB_secret_G7epyOKsACfNDr0Sgivo",
"created": "2024-09-03T08:48:12.266Z",
"currency": "USD",
"customer_id": null,
"customer": {
"id": null,
"name": "John Doe",
"email": "guest@example.com",
"phone": "999999999",
"phone_country_code": "+1"
},
"description": "Its my first payment request",
"refunds": null,
"disputes": null,
"mandate_id": null,
"mandate_data": null,
"setup_future_usage": null,
"off_session": null,
"capture_on": null,
"capture_method": "automatic",
"payment_method": "card",
"payment_method_data": {
"card": {
"last4": "0119",
"card_type": null,
"card_network": null,
"card_issuer": null,
"card_issuing_country": null,
"card_isin": "400000",
"card_extended_bin": null,
"card_exp_month": "03",
"card_exp_year": "2030",
"card_holder_name": null,
"payment_checks": {
"avs_response": {
"code": "Y",
"codeRaw": "Y"
},
"card_verification": null
},
"authentication_data": null
},
"billing": null
},
"payment_token": "token_2LY32nDUPNvVLcg6hDiu",
"shipping": {
"address": {
"city": "San Fransico",
"country": "US",
"line1": "1467",
"line2": "Harrison Street",
"line3": "Harrison Street",
"zip": "94122",
"state": "California",
"first_name": "PiX",
"last_name": null
},
"phone": null,
"email": null
},
"billing": {
"address": {
"city": "San",
"country": "US",
"line1": "1467",
"line2": "Harrison Street",
"line3": "Harrison Street",
"zip": "94122",
"state": "California",
"first_name": "PiX",
"last_name": "ss"
},
"phone": null,
"email": null
},
"order_details": null,
"email": null,
"name": null,
"phone": null,
"return_url": "http://127.0.0.1:4040/",
"authentication_type": "no_three_ds",
"statement_descriptor_name": "joseph",
"statement_descriptor_suffix": "JS",
"next_action": null,
"cancellation_reason": null,
"error_code": null,
"error_message": null,
"unified_code": null,
"unified_message": null,
"payment_experience": null,
"payment_method_type": null,
"connector_label": null,
"business_country": null,
"business_label": "default",
"business_sub_label": null,
"allowed_payment_method_types": null,
"ephemeral_key": null,
"manual_retry_allowed": false,
"connector_transaction_id": "7253532925156616403954",
"frm_message": null,
"metadata": {
"udf1": "value1",
"login_date": "2019-09-10T10:11:12Z",
"new_customer": "true"
},
"connector_metadata": null,
"feature_metadata": null,
"reference_id": "pay_v5429vfsJdjtaQqhhNMB_1",
"payment_link": null,
"profile_id": "pro_pCmVCFH8Jh9CRAOq71tG",
"surcharge_details": null,
"attempt_count": 1,
"merchant_decision": null,
"merchant_connector_id": "mca_HLz5UXL0F35JM3QsRh6f",
"incremental_authorization_allowed": false,
"authorization_count": null,
"incremental_authorizations": null,
"external_authentication_details": null,
"external_3ds_authentication_attempted": false,
"expires_on": "2024-09-03T09:03:12.266Z",
"fingerprint": null,
"browser_info": {
"language": "nl-NL",
"time_zone": 0,
"ip_address": "125.0.0.1",
"user_agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/70.0.3538.110 Safari/537.36",
"color_depth": 24,
"java_enabled": true,
"screen_width": 1536,
"accept_header": "text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,image/apng,*/*;q=0.8",
"screen_height": 723,
"java_script_enabled": true
},
"payment_method_id": null,
"payment_method_status": null,
"updated": "2024-09-03T08:48:13.596Z",
"charges": null,
"frm_metadata": null,
"merchant_order_reference_id": null
}
```
Payments retrieve
```
curl --location 'http://localhost:8080/payments/pay_v5429vfsJdjtaQqhhNMB?force_sync=true' \
--header 'Accept: application/json' \
--header 'api-key: dev_RPC8caLJDX8s4AFPVxr0KCy6UOTSJNs7IjbfK9WmkDddIBTfibFPBuQxM4A1nKu0'
```
```
{
"payment_id": "pay_v5429vfsJdjtaQqhhNMB",
"merchant_id": "merchant_1725352456",
"status": "succeeded",
"amount": 100,
"net_amount": 100,
"amount_capturable": 0,
"amount_received": 100,
"connector": "cybersource",
"client_secret": "pay_v5429vfsJdjtaQqhhNMB_secret_G7epyOKsACfNDr0Sgivo",
"created": "2024-09-03T08:48:12.266Z",
"currency": "USD",
"customer_id": null,
"customer": {
"id": null,
"name": "John Doe",
"email": "guest@example.com",
"phone": "999999999",
"phone_country_code": "+1"
},
"description": "Its my first payment request",
"refunds": null,
"disputes": null,
"mandate_id": null,
"mandate_data": null,
"setup_future_usage": null,
"off_session": null,
"capture_on": null,
"capture_method": "automatic",
"payment_method": "card",
"payment_method_data": {
"card": {
"last4": "0119",
"card_type": null,
"card_network": null,
"card_issuer": null,
"card_issuing_country": null,
"card_isin": "400000",
"card_extended_bin": null,
"card_exp_month": "03",
"card_exp_year": "2030",
"card_holder_name": null,
"payment_checks": {
"avs_response": {
"code": "Y",
"codeRaw": "Y"
},
"card_verification": null
},
"authentication_data": null
},
"billing": null
},
"payment_token": "token_2LY32nDUPNvVLcg6hDiu",
"shipping": {
"address": {
"city": "San Fransico",
"country": "US",
"line1": "1467",
"line2": "Harrison Street",
"line3": "Harrison Street",
"zip": "94122",
"state": "California",
"first_name": "PiX",
"last_name": null
},
"phone": null,
"email": null
},
"billing": {
"address": {
"city": "San",
"country": "US",
"line1": "1467",
"line2": "Harrison Street",
"line3": "Harrison Street",
"zip": "94122",
"state": "California",
"first_name": "PiX",
"last_name": "ss"
},
"phone": null,
"email": null
},
"order_details": null,
"email": null,
"name": null,
"phone": null,
"return_url": "http://127.0.0.1:4040/",
"authentication_type": "no_three_ds",
"statement_descriptor_name": "joseph",
"statement_descriptor_suffix": "JS",
"next_action": null,
"cancellation_reason": null,
"error_code": null,
"error_message": null,
"unified_code": null,
"unified_message": null,
"payment_experience": null,
"payment_method_type": null,
"connector_label": null,
"business_country": null,
"business_label": "default",
"business_sub_label": null,
"allowed_payment_method_types": null,
"ephemeral_key": null,
"manual_retry_allowed": false,
"connector_transaction_id": "7253532925156616403954",
"frm_message": null,
"metadata": {
"udf1": "value1",
"login_date": "2019-09-10T10:11:12Z",
"new_customer": "true"
},
"connector_metadata": null,
"feature_metadata": null,
"reference_id": "pay_v5429vfsJdjtaQqhhNMB_1",
"payment_link": null,
"profile_id": "pro_pCmVCFH8Jh9CRAOq71tG",
"surcharge_details": null,
"attempt_count": 1,
"merchant_decision": null,
"merchant_connector_id": "mca_HLz5UXL0F35JM3QsRh6f",
"incremental_authorization_allowed": false,
"authorization_count": null,
"incremental_authorizations": null,
"external_authentication_details": null,
"external_3ds_authentication_attempted": false,
"expires_on": "2024-09-03T09:03:12.266Z",
"fingerprint": null,
"browser_info": {
"language": "nl-NL",
"time_zone": 0,
"ip_address": "125.0.0.1",
"user_agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/70.0.3538.110 Safari/537.36",
"color_depth": 24,
"java_enabled": true,
"screen_width": 1536,
"accept_header": "text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,image/apng,*/*;q=0.8",
"screen_height": 723,
"java_script_enabled": true
},
"payment_method_id": null,
"payment_method_status": null,
"updated": "2024-09-03T08:48:13.596Z",
"charges": null,
"frm_metadata": null,
"merchant_order_reference_id": null
}
```
-> Customer details are sent in the customer object
```
curl --location 'http://localhost:8080/payments' \
--header 'Content-Type: application/json' \
--header 'Accept: application/json' \
--header 'api-key: dev_RPC8caLJDX8s4AFPVxr0KCy6UOTSJNs7IjbfK9WmkDddIBTfibFPBuQxM4A1nKu0' \
--data-raw '{
"amount": 100,
"amount_to_capture": 100,
"currency": "USD",
"confirm": true,
"capture_method": "automatic",
"capture_on": "2022-09-10T10:11:12Z",
"email": "guest@example.com",
"name": "John Doe",
"phone": "999999999",
"customer": {
"id": "cu_1725353517",
"name": "John Doe",
"email": "guest@example.com",
"phone": "999999999",
"phone_country_code": "+1"
},
"phone_country_code": "+1",
"description": "Its my first payment request",
"authentication_type": "no_three_ds",
"return_url": "http://127.0.0.1:4040",
"customer_acceptance": {
"acceptance_type": "offline",
"accepted_at": "1963-05-03T04:07:52.723Z",
"online": {
"ip_address": "in sit",
"user_agent": "amet irure esse"
}
},
"payment_method": "card",
"payment_method_data": {
"card": {
"card_number": "4000000000000119",
"card_exp_month": "03",
"card_exp_year": "2030",
"card_holder_name": "joseph Doe",
"card_cvc": "838"
}
},
"billing": {
"address": {
"line1": "1467",
"line2": "Harrison Street",
"line3": "Harrison Street",
"city": "San",
"state": "California",
"zip": "94122",
"country": "US",
"first_name": "PiX",
"last_name": "ss"
}
},
"shipping": {
"address": {
"line1": "1467",
"line2": "Harrison Street",
"line3": "Harrison Street",
"city": "San Fransico",
"state": "California",
"zip": "94122",
"country": "US",
"first_name": "PiX"
}
},
"browser_info": {
"user_agent": "Mozilla\/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit\/537.36 (KHTML, like Gecko) Chrome\/70.0.3538.110 Safari\/537.36",
"accept_header": "text\/html,application\/xhtml+xml,application\/xml;q=0.9,image\/webp,image\/apng,*\/*;q=0.8",
"language": "nl-NL",
"color_depth": 24,
"screen_height": 723,
"screen_width": 1536,
"time_zone": 0,
"java_enabled": true,
"java_script_enabled": true,
"ip_address": "125.0.0.1"
},
"statement_descriptor_name": "joseph",
"statement_descriptor_suffix": "JS",
"metadata": {
"udf1": "value1",
"new_customer": "true",
"login_date": "2019-09-10T10:11:12Z"
}
}'
```
```
{
"payment_id": "pay_RJBqVC4xSMkv9YqojScT",
"merchant_id": "merchant_1725352456",
"status": "succeeded",
"amount": 100,
"net_amount": 100,
"amount_capturable": 0,
"amount_received": 100,
"connector": "cybersource",
"client_secret": "pay_RJBqVC4xSMkv9YqojScT_secret_OpoEIrC5SEX8D1lejuya",
"created": "2024-09-03T08:51:51.753Z",
"currency": "USD",
"customer_id": "cu_1725353512",
"customer": {
"id": "cu_1725353512",
"name": "John Doe",
"email": "guest@example.com",
"phone": "999999999",
"phone_country_code": "+1"
},
"description": "Its my first payment request",
"refunds": null,
"disputes": null,
"mandate_id": null,
"mandate_data": null,
"setup_future_usage": null,
"off_session": null,
"capture_on": null,
"capture_method": "automatic",
"payment_method": "card",
"payment_method_data": {
"card": {
"last4": "0119",
"card_type": null,
"card_network": null,
"card_issuer": null,
"card_issuing_country": null,
"card_isin": "400000",
"card_extended_bin": null,
"card_exp_month": "03",
"card_exp_year": "2030",
"card_holder_name": null,
"payment_checks": {
"avs_response": {
"code": "Y",
"codeRaw": "Y"
},
"card_verification": null
},
"authentication_data": null
},
"billing": null
},
"payment_token": "token_UNh5IWViTJSnR6DmWnMi",
"shipping": {
"address": {
"city": "San Fransico",
"country": "US",
"line1": "1467",
"line2": "Harrison Street",
"line3": "Harrison Street",
"zip": "94122",
"state": "California",
"first_name": "PiX",
"last_name": null
},
"phone": null,
"email": null
},
"billing": {
"address": {
"city": "San",
"country": "US",
"line1": "1467",
"line2": "Harrison Street",
"line3": "Harrison Street",
"zip": "94122",
"state": "California",
"first_name": "PiX",
"last_name": "ss"
},
"phone": null,
"email": null
},
"order_details": null,
"email": "guest@example.com",
"name": "John Doe",
"phone": "999999999",
"return_url": "http://127.0.0.1:4040/",
"authentication_type": "no_three_ds",
"statement_descriptor_name": "joseph",
"statement_descriptor_suffix": "JS",
"next_action": null,
"cancellation_reason": null,
"error_code": null,
"error_message": null,
"unified_code": null,
"unified_message": null,
"payment_experience": null,
"payment_method_type": null,
"connector_label": null,
"business_country": null,
"business_label": "default",
"business_sub_label": null,
"allowed_payment_method_types": null,
"ephemeral_key": {
"customer_id": "cu_1725353512",
"created_at": 1725353511,
"expires": 1725357111,
"secret": "epk_c5c3bbc2a43b4effb8b7af30f23c8119"
},
"manual_retry_allowed": false,
"connector_transaction_id": "7253535128366701403954",
"frm_message": null,
"metadata": {
"udf1": "value1",
"login_date": "2019-09-10T10:11:12Z",
"new_customer": "true"
},
"connector_metadata": null,
"feature_metadata": null,
"reference_id": "pay_RJBqVC4xSMkv9YqojScT_1",
"payment_link": null,
"profile_id": "pro_pCmVCFH8Jh9CRAOq71tG",
"surcharge_details": null,
"attempt_count": 1,
"merchant_decision": null,
"merchant_connector_id": "mca_HLz5UXL0F35JM3QsRh6f",
"incremental_authorization_allowed": false,
"authorization_count": null,
"incremental_authorizations": null,
"external_authentication_details": null,
"external_3ds_authentication_attempted": false,
"expires_on": "2024-09-03T09:06:51.753Z",
"fingerprint": null,
"browser_info": {
"language": "nl-NL",
"time_zone": 0,
"ip_address": "125.0.0.1",
"user_agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/70.0.3538.110 Safari/537.36",
"color_depth": 24,
"java_enabled": true,
"screen_width": 1536,
"accept_header": "text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,image/apng,*/*;q=0.8",
"screen_height": 723,
"java_script_enabled": true
},
"payment_method_id": null,
"payment_method_status": null,
"updated": "2024-09-03T08:51:53.907Z",
"charges": null,
"frm_metadata": null,
"merchant_order_reference_id": null
}
```
-> Delete a customer and retrieve a payment
```
{
"payment_id": "pay_RJBqVC4xSMkv9YqojScT",
"merchant_id": "merchant_1725352456",
"status": "succeeded",
"amount": 100,
"net_amount": 100,
"amount_capturable": 0,
"amount_received": 100,
"connector": "cybersource",
"client_secret": "pay_RJBqVC4xSMkv9YqojScT_secret_OpoEIrC5SEX8D1lejuya",
"created": "2024-09-03T08:51:51.753Z",
"currency": "USD",
"customer_id": "cu_1725353512",
"customer": {
"id": "cu_1725353512",
"name": "Redacted",
"email": "Redacted",
"phone": "Redacted",
"phone_country_code": "Redacted"
},
"description": "Its my first payment request",
"refunds": null,
"disputes": null,
"mandate_id": null,
"mandate_data": null,
"setup_future_usage": null,
"off_session": null,
"capture_on": null,
"capture_method": "automatic",
"payment_method": "card",
"payment_method_data": {
"card": {
"last4": "0119",
"card_type": null,
"card_network": null,
"card_issuer": null,
"card_issuing_country": null,
"card_isin": "400000",
"card_extended_bin": null,
"card_exp_month": "03",
"card_exp_year": "2030",
"card_holder_name": null,
"payment_checks": {
"avs_response": {
"code": "Y",
"codeRaw": "Y"
},
"card_verification": null
},
"authentication_data": null
},
"billing": null
},
"payment_token": "token_UNh5IWViTJSnR6DmWnMi",
"shipping": {
"address": {
"city": "Redacted",
"country": "US",
"line1": "Redacted",
"line2": "Redacted",
"line3": "Redacted",
"zip": "Redacted",
"state": "Redacted",
"first_name": "Redacted",
"last_name": "Redacted"
},
"phone": {
"number": "Redacted",
"country_code": "Redacted"
},
"email": "Redacted"
},
"billing": {
"address": {
"city": "Redacted",
"country": "US",
"line1": "Redacted",
"line2": "Redacted",
"line3": "Redacted",
"zip": "Redacted",
"state": "Redacted",
"first_name": "Redacted",
"last_name": "Redacted"
},
"phone": {
"number": "Redacted",
"country_code": "Redacted"
},
"email": "Redacted"
},
"order_details": null,
"email": "Redacted",
"name": "Redacted",
"phone": "Redacted",
"return_url": "http://127.0.0.1:4040/",
"authentication_type": "no_three_ds",
"statement_descriptor_name": "joseph",
"statement_descriptor_suffix": "JS",
"next_action": null,
"cancellation_reason": null,
"error_code": null,
"error_message": null,
"unified_code": null,
"unified_message": null,
"payment_experience": null,
"payment_method_type": null,
"connector_label": null,
"business_country": null,
"business_label": "default",
"business_sub_label": null,
"allowed_payment_method_types": null,
"ephemeral_key": null,
"manual_retry_allowed": false,
"connector_transaction_id": "7253535128366701403954",
"frm_message": null,
"metadata": {
"udf1": "value1",
"login_date": "2019-09-10T10:11:12Z",
"new_customer": "true"
},
"connector_metadata": null,
"feature_metadata": null,
"reference_id": "pay_RJBqVC4xSMkv9YqojScT_1",
"payment_link": null,
"profile_id": "pro_pCmVCFH8Jh9CRAOq71tG",
"surcharge_details": null,
"attempt_count": 1,
"merchant_decision": null,
"merchant_connector_id": "mca_HLz5UXL0F35JM3QsRh6f",
"incremental_authorization_allowed": false,
"authorization_count": null,
"incremental_authorizations": null,
"external_authentication_details": null,
"external_3ds_authentication_attempted": false,
"expires_on": "2024-09-03T09:06:51.753Z",
"fingerprint": null,
"browser_info": {
"language": "nl-NL",
"time_zone": 0,
"ip_address": "125.0.0.1",
"user_agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/70.0.3538.110 Safari/537.36",
"color_depth": 24,
"java_enabled": true,
"screen_width": 1536,
"accept_header": "text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,image/apng,*/*;q=0.8",
"screen_height": 723,
"java_script_enabled": true
},
"payment_method_id": "pm_jzj3gJnY1vfjSBWttyeg",
"payment_method_status": null,
"updated": "2024-09-03T08:51:53.907Z",
"charges": null,
"frm_metadata": null,
"merchant_order_reference_id": null
}
```
## Checklist
<!-- Put an `x` in the boxes that apply -->
- [x] I formatted the code `cargo +nightly fmt --all`
- [x] I addressed lints thrown by `cargo clippy`
- [x] I reviewed the submitted code
- [ ] I added unit tests for my changes where possible
|
7296cceba351dccf13a71ef2479dba3f24e3c31f
|
|
juspay/hyperswitch
|
juspay__hyperswitch-5720
|
Bug: [FIX] Fix Mca create for v2
### Feature Description
fix merchant connector account create for v2 , by handling the case where defaull fallback is null ,while updating the it
### Possible Implementation
fix merchant connector account create for v2 , by handling the case where defaull fallback is null ,while updating the it
### Have you spent some time checking if this feature request has been raised before?
- [X] I checked and didn't find a similar issue
### Have you read the Contributing Guidelines?
- [X] I have read the [Contributing Guidelines](https://github.com/juspay/hyperswitch/blob/main/docs/CONTRIBUTING.md)
### Are you willing to submit a PR?
Yes, I am willing to submit a PR!
|
diff --git a/crates/router/src/core/admin.rs b/crates/router/src/core/admin.rs
index 553de8c5608..ab20c1c68bf 100644
--- a/crates/router/src/core/admin.rs
+++ b/crates/router/src/core/admin.rs
@@ -4204,16 +4204,19 @@ impl BusinessProfileWrapper {
pub fn get_default_fallback_list_of_connector_under_profile(
&self,
) -> RouterResult<Vec<routing_types::RoutableConnectorChoice>> {
- use masking::ExposeOptionInterface;
- self.profile
- .default_fallback_routing
- .clone()
- .expose_option()
- .parse_value::<Vec<routing_types::RoutableConnectorChoice>>(
- "Vec<RoutableConnectorChoice>",
- )
- .change_context(errors::ApiErrorResponse::InternalServerError)
- .attach_printable("Merchant default config has invalid structure")
+ let fallback_connectors =
+ if let Some(default_fallback_routing) = self.profile.default_fallback_routing.clone() {
+ default_fallback_routing
+ .expose()
+ .parse_value::<Vec<routing_types::RoutableConnectorChoice>>(
+ "Vec<RoutableConnectorChoice>",
+ )
+ .change_context(errors::ApiErrorResponse::InternalServerError)
+ .attach_printable("Business Profile default config has invalid structure")?
+ } else {
+ Vec::new()
+ };
+ Ok(fallback_connectors)
}
pub fn get_default_routing_configs_from_profile(
&self,
|
2024-08-27T10:30:40Z
|
## Type of Change
<!-- Put an `x` in the boxes that apply -->
- [ ] Bugfix
- [ ] New feature
- [ ] Enhancement
- [ ] Refactoring
- [ ] Dependency updates
- [ ] Documentation
- [ ] CI/CD
## Description
fix merchant connector account create for v2 , by handling the case where defaull fallback is null ,while updating the it
### Additional Changes
- [ ] This PR modifies the API contract
- [ ] This PR modifies the database schema
- [ ] This PR modifies application configuration/environment variables
<!--
Provide links to the files with corresponding changes.
Following are the paths where you can find config files:
1. `config`
2. `crates/router/src/configs`
3. `loadtest/config`
-->
## Motivation and Context
<!--
Why is this change required? What problem does it solve?
If it fixes an open issue, please link to the issue here.
If you don't have an issue, we'd recommend starting with one first so the PR
can focus on the implementation (unless it is an obvious bug or documentation fix
that will have little conversation).
-->
## How did you test it?
- Create a Organization
```
curl --location 'http://localhost:8080/v2/organization' \
--header 'Content-Type: application/json' \
--header 'api-key: test_admin' \
--data '{
"organization_name": "my_org"
}'
```
- Create a MA and then a profile
```
curl --location 'http://localhost:8080/v2/accounts' \
--header 'Content-Type: application/json' \
--header 'api-key: test_admin' \
--data '{
"merchant_name": "cloth_seller",
"organization_id": "org_HzxLj0Nf9v9H0iKQDCFZ"
}'
```
```
curl --location 'http://localhost:8080/v2/profiles' \
--header 'x-merchant-id: cloth_seller_ea0VXdPfRBFXr2hd2vHL' \
--header 'Content-Type: application/json' \
--header 'api-key: test_admin' \
--data-raw '{
"profile_name": "business",
"return_url": "https://google.com/success",
"enable_payment_response_hash": true,
"redirect_to_merchant_with_http_post": false,
"webhook_details": {
"webhook_version": "1.0.1",
"webhook_username": "ekart_retail",
"webhook_password": "password_ekart@123",
"webhook_url": "https://webhook.site",
"payment_created_enabled": true,
"payment_succeeded_enabled": true,
"payment_failed_enabled": true
},
"metadata": null,
"order_fulfillment_time": 900
}'
```
- Create a MCA, it should be successfully created
```
Response
{
"connector_type": "payment_processor",
"connector_name": "adyen",
"connector_label": "adyen_business",
"id": "mca_019193515e77726687170b4d4dac2887",
"profile_id": "pro_YtPK4bYZ86jideG8KEBn",
"connector_account_details": {
"auth_type": "BodyKey",
"api_key": "AQEqhmfxK43MaR1Hw0m/n3Q5qf3VYp5eHZJTfEA0SnT87rrwTHXDVGtJ+kfCEMFdWw2+5HzctViMSCJMYAc=-3z4LNx7vk7s3KOZ6PMgPPx2HKrP9XfzQWMxU0OtdxTc=-suZ%I8NM9qv+?up}",
"key1": "JuspayDEECOM",
"api_secret": "AQEzgmDBbd+uOlwd9n6PxDJo8rXOaKhCAINLVnwY7G24jmdSuuL0Salp1G0BJE6opzqZqP6rEMFdWw2+5HzctViMSCJMYAc=-bn/JeFXqIxxfhhy67PE2sTZctbqzqe+fU0JprcbCEmE=-:M><zzc+t9Ne#2eb"
},
"payment_methods_enabled": [
{
"payment_method": "card_redirect",
"payment_method_types": [
{
"payment_method_type": "card_redirect",
"payment_experience": "redirect_to_url",
"card_networks": null,
"accepted_currencies": null,
"accepted_countries": null,
"minimum_amount": 1,
"maximum_amount": 68607706,
"recurring_enabled": true,
"installment_payment_enabled": true
}
]
},
{
"payment_method": "card",
"payment_method_types": [
{
"payment_method_type": "credit",
"payment_experience": null,
"card_networks": [
"Visa",
"Mastercard"
],
"accepted_currencies": null,
"accepted_countries": null,
"minimum_amount": -1,
"maximum_amount": 68607706,
"recurring_enabled": true,
"installment_payment_enabled": true
},
{
"payment_method_type": "debit",
"payment_experience": null,
"card_networks": [
"Visa",
"Mastercard"
],
"accepted_currencies": null,
"accepted_countries": null,
"minimum_amount": -1,
"maximum_amount": 68607706,
"recurring_enabled": true,
"installment_payment_enabled": true
}
]
},
{
"payment_method": "wallet",
"payment_method_types": [
{
"payment_method_type": "google_pay",
"payment_experience": null,
"card_networks": null,
"accepted_currencies": null,
"accepted_countries": null,
"minimum_amount": -1,
"maximum_amount": 68607706,
"recurring_enabled": true,
"installment_payment_enabled": true
},
{
"payment_method_type": "apple_pay",
"payment_experience": null,
"card_networks": null,
"accepted_currencies": null,
"accepted_countries": null,
"minimum_amount": -1,
"maximum_amount": 68607706,
"recurring_enabled": true,
"installment_payment_enabled": true
},
{
"payment_method_type": "we_chat_pay",
"payment_experience": null,
"card_networks": null,
"accepted_currencies": null,
"accepted_countries": null,
"minimum_amount": -1,
"maximum_amount": 68607706,
"recurring_enabled": true,
"installment_payment_enabled": true
},
{
"payment_method_type": "ali_pay",
"payment_experience": null,
"card_networks": null,
"accepted_currencies": null,
"accepted_countries": null,
"minimum_amount": -1,
"maximum_amount": 68607706,
"recurring_enabled": true,
"installment_payment_enabled": true
},
{
"payment_method_type": "paypal",
"payment_experience": null,
"card_networks": null,
"accepted_currencies": null,
"accepted_countries": null,
"minimum_amount": -1,
"maximum_amount": 68607706,
"recurring_enabled": true,
"installment_payment_enabled": true
},
{
"payment_method_type": "mb_way",
"payment_experience": null,
"card_networks": null,
"accepted_currencies": null,
"accepted_countries": null,
"minimum_amount": -1,
"maximum_amount": 68607706,
"recurring_enabled": true,
"installment_payment_enabled": true
}
]
},
{
"payment_method": "pay_later",
"payment_method_types": [
{
"payment_method_type": "klarna",
"payment_experience": "redirect_to_url",
"card_networks": null,
"accepted_currencies": null,
"accepted_countries": null,
"minimum_amount": -1,
"maximum_amount": 68607706,
"recurring_enabled": true,
"installment_payment_enabled": true
},
{
"payment_method_type": "affirm",
"payment_experience": "redirect_to_url",
"card_networks": null,
"accepted_currencies": null,
"accepted_countries": null,
"minimum_amount": -1,
"maximum_amount": 68607706,
"recurring_enabled": true,
"installment_payment_enabled": true
},
{
"payment_method_type": "afterpay_clearpay",
"payment_experience": "redirect_to_url",
"card_networks": null,
"accepted_currencies": null,
"accepted_countries": null,
"minimum_amount": -1,
"maximum_amount": 68607706,
"recurring_enabled": true,
"installment_payment_enabled": true
},
{
"payment_method_type": "walley",
"payment_experience": "redirect_to_url",
"card_networks": null,
"accepted_currencies": null,
"accepted_countries": null,
"minimum_amount": -1,
"maximum_amount": 68607706,
"recurring_enabled": true,
"installment_payment_enabled": true
}
]
},
{
"payment_method": "bank_redirect",
"payment_method_types": [
{
"payment_method_type": "giropay",
"payment_experience": "redirect_to_url",
"card_networks": null,
"accepted_currencies": null,
"accepted_countries": null,
"minimum_amount": -1,
"maximum_amount": 68607706,
"recurring_enabled": true,
"installment_payment_enabled": true
},
{
"payment_method_type": "ideal",
"payment_experience": "redirect_to_url",
"card_networks": null,
"accepted_currencies": null,
"accepted_countries": null,
"minimum_amount": -1,
"maximum_amount": 68607706,
"recurring_enabled": true,
"installment_payment_enabled": true
},
{
"payment_method_type": "eps",
"payment_experience": "redirect_to_url",
"card_networks": null,
"accepted_currencies": null,
"accepted_countries": null,
"minimum_amount": -1,
"maximum_amount": 68607706,
"recurring_enabled": true,
"installment_payment_enabled": true
},
{
"payment_method_type": "bancontact_card",
"payment_experience": "redirect_to_url",
"card_networks": null,
"accepted_currencies": null,
"accepted_countries": null,
"minimum_amount": -1,
"maximum_amount": 68607706,
"recurring_enabled": true,
"installment_payment_enabled": true
},
{
"payment_method_type": "przelewy24",
"payment_experience": "redirect_to_url",
"card_networks": null,
"accepted_currencies": null,
"accepted_countries": null,
"minimum_amount": -1,
"maximum_amount": 68607706,
"recurring_enabled": true,
"installment_payment_enabled": true
},
{
"payment_method_type": "sofort",
"payment_experience": "redirect_to_url",
"card_networks": null,
"accepted_currencies": null,
"accepted_countries": null,
"minimum_amount": -1,
"maximum_amount": 68607706,
"recurring_enabled": true,
"installment_payment_enabled": true
},
{
"payment_method_type": "blik",
"payment_experience": "redirect_to_url",
"card_networks": null,
"accepted_currencies": null,
"accepted_countries": null,
"minimum_amount": -1,
"maximum_amount": 68607706,
"recurring_enabled": true,
"installment_payment_enabled": true
},
{
"payment_method_type": "trustly",
"payment_experience": "redirect_to_url",
"card_networks": null,
"accepted_currencies": null,
"accepted_countries": null,
"minimum_amount": -1,
"maximum_amount": 68607706,
"recurring_enabled": true,
"installment_payment_enabled": true
},
{
"payment_method_type": "online_banking_finland",
"payment_experience": "redirect_to_url",
"card_networks": null,
"accepted_currencies": null,
"accepted_countries": null,
"minimum_amount": -1,
"maximum_amount": 68607706,
"recurring_enabled": true,
"installment_payment_enabled": true
},
{
"payment_method_type": "online_banking_poland",
"payment_experience": "redirect_to_url",
"card_networks": null,
"accepted_currencies": null,
"accepted_countries": null,
"minimum_amount": -1,
"maximum_amount": 68607706,
"recurring_enabled": true,
"installment_payment_enabled": true
}
]
},
{
"payment_method": "bank_transfer",
"payment_method_types": [
{
"payment_method_type": "ach",
"payment_experience": "redirect_to_url",
"card_networks": null,
"accepted_currencies": null,
"accepted_countries": null,
"minimum_amount": -1,
"maximum_amount": 68607706,
"recurring_enabled": true,
"installment_payment_enabled": true
},
{
"payment_method_type": "sepa",
"payment_experience": "redirect_to_url",
"card_networks": null,
"accepted_currencies": null,
"accepted_countries": null,
"minimum_amount": -1,
"maximum_amount": 68607706,
"recurring_enabled": true,
"installment_payment_enabled": true
},
{
"payment_method_type": "bacs",
"payment_experience": "redirect_to_url",
"card_networks": null,
"accepted_currencies": null,
"accepted_countries": null,
"minimum_amount": -1,
"maximum_amount": 68607706,
"recurring_enabled": true,
"installment_payment_enabled": true
}
]
},
{
"payment_method": "bank_debit",
"payment_method_types": [
{
"payment_method_type": "ach",
"payment_experience": null,
"card_networks": null,
"accepted_currencies": null,
"accepted_countries": null,
"minimum_amount": -1,
"maximum_amount": 68607706,
"recurring_enabled": true,
"installment_payment_enabled": true
},
{
"payment_method_type": "sepa",
"payment_experience": null,
"card_networks": null,
"accepted_currencies": null,
"accepted_countries": null,
"minimum_amount": -1,
"maximum_amount": 68607706,
"recurring_enabled": true,
"installment_payment_enabled": true
},
{
"payment_method_type": "bacs",
"payment_experience": null,
"card_networks": null,
"accepted_currencies": null,
"accepted_countries": null,
"minimum_amount": -1,
"maximum_amount": 68607706,
"recurring_enabled": true,
"installment_payment_enabled": true
},
{
"payment_method_type": "becs",
"payment_experience": null,
"card_networks": null,
"accepted_currencies": null,
"accepted_countries": null,
"minimum_amount": -1,
"maximum_amount": 68607706,
"recurring_enabled": true,
"installment_payment_enabled": true
}
]
}
],
"connector_webhook_details": {
"merchant_secret": "",
"additional_secret": null
},
"metadata": {
"status_url": "https://2753-2401-4900-1cb8-2ff9-24dd-1ccf-ed12-b464.in.ngrok.io/webhooks/merchant_1678699058/globalpay",
"account_name": "transaction_processing",
"acquirer_bin": "438309",
"pricing_type": "fixed_price",
"acquirer_merchant_id": "00002000000"
},
"disabled": null,
"frm_configs": null,
"applepay_verified_domains": null,
"pm_auth_config": null,
"status": "active",
"additional_merchant_data": null
}
```
## Checklist
<!-- Put an `x` in the boxes that apply -->
- [ ] I formatted the code `cargo +nightly fmt --all`
- [ ] I addressed lints thrown by `cargo clippy`
- [ ] I reviewed the submitted code
- [ ] I added unit tests for my changes where possible
|
4585e16245dd49d8c0b877cda148524afe395009
|
|
juspay/hyperswitch
|
juspay__hyperswitch-5714
|
Bug: feat(euclid): create a new variant under payment_type for ppt token flow
## Description
This change will add a new variant in payment_type which will be `ppt_token_flow` using which we will be able to make rule on basis of the ppt flow.
The new variant will be visible here:
<img width="1201" alt="Screenshot 2024-08-27 at 3 04 33 PM" src="https://github.com/user-attachments/assets/f8cf3954-ee5e-4504-a12d-40fece34adf5">
|
diff --git a/crates/api_models/src/mandates.rs b/crates/api_models/src/mandates.rs
index dc61aa08b0c..b62a2c38b9c 100644
--- a/crates/api_models/src/mandates.rs
+++ b/crates/api_models/src/mandates.rs
@@ -115,7 +115,7 @@ pub struct MandateListConstraints {
}
/// Details required for recurring payment
-#[derive(Debug, Clone, serde::Serialize, serde::Deserialize, ToSchema)]
+#[derive(Debug, Clone, serde::Serialize, serde::Deserialize, ToSchema, PartialEq, Eq)]
#[serde(tag = "type", content = "data", rename_all = "snake_case")]
pub enum RecurringDetails {
MandateId(String),
@@ -124,7 +124,7 @@ pub enum RecurringDetails {
}
/// Processor payment token for MIT payments where payment_method_data is not available
-#[derive(Debug, Clone, serde::Serialize, serde::Deserialize, ToSchema)]
+#[derive(Debug, Clone, serde::Serialize, serde::Deserialize, ToSchema, PartialEq, Eq)]
pub struct ProcessorPaymentToken {
pub processor_payment_token: String,
#[schema(value_type = Connector, example = "stripe")]
diff --git a/crates/euclid/src/backend/vir_interpreter.rs b/crates/euclid/src/backend/vir_interpreter.rs
index 0e7988bb3be..7fde8721be0 100644
--- a/crates/euclid/src/backend/vir_interpreter.rs
+++ b/crates/euclid/src/backend/vir_interpreter.rs
@@ -198,6 +198,47 @@ mod test {
assert_eq!(result.rule_name.expect("Rule Name").as_str(), "rule_1");
}
+ #[test]
+ fn test_ppt_flow() {
+ let program_str = r#"
+ default: ["stripe", "adyen"]
+ rule_1: ["stripe"]
+ {
+ payment_type = ppt_mandate
+ }
+ "#;
+
+ let (_, program) = ast::parser::program::<DummyOutput>(program_str).expect("Program");
+ let inp = inputs::BackendInput {
+ metadata: None,
+ payment: inputs::PaymentInput {
+ amount: MinorUnit::new(32),
+ currency: enums::Currency::USD,
+ card_bin: Some("123456".to_string()),
+ authentication_type: Some(enums::AuthenticationType::NoThreeDs),
+ capture_method: Some(enums::CaptureMethod::Automatic),
+ business_country: Some(enums::Country::UnitedStatesOfAmerica),
+ billing_country: Some(enums::Country::France),
+ business_label: None,
+ setup_future_usage: None,
+ },
+ payment_method: inputs::PaymentMethodInput {
+ payment_method: Some(enums::PaymentMethod::PayLater),
+ payment_method_type: Some(enums::PaymentMethodType::Affirm),
+ card_network: None,
+ },
+ mandate: inputs::MandateData {
+ mandate_acceptance_type: None,
+ mandate_type: None,
+ payment_type: Some(enums::PaymentType::PptMandate),
+ },
+ };
+
+ let backend = VirInterpreterBackend::<DummyOutput>::with_program(program).expect("Program");
+ let result = backend.execute(inp).expect("Execution");
+ assert_eq!(result.rule_name.expect("Rule Name").as_str(), "rule_1");
+ }
+
#[test]
fn test_mandate_type() {
let program_str = r#"
diff --git a/crates/euclid/src/enums.rs b/crates/euclid/src/enums.rs
index 8e65d23d5ea..cfd410f0d3b 100644
--- a/crates/euclid/src/enums.rs
+++ b/crates/euclid/src/enums.rs
@@ -81,6 +81,7 @@ pub enum PaymentType {
NonMandate,
NewMandate,
UpdateMandate,
+ PptMandate,
}
#[derive(
diff --git a/crates/router/src/core/payments/routing.rs b/crates/router/src/core/payments/routing.rs
index 692a5924a06..6f1912d7c65 100644
--- a/crates/router/src/core/payments/routing.rs
+++ b/crates/router/src/core/payments/routing.rs
@@ -208,10 +208,21 @@ where
}
})
}),
- payment_type: Some(payment_data.setup_mandate.clone().map_or_else(
- || euclid_enums::PaymentType::NonMandate,
- |_| euclid_enums::PaymentType::SetupMandate,
- )),
+ payment_type: Some(
+ if payment_data.recurring_details.as_ref().is_some_and(|data| {
+ matches!(
+ data,
+ api_models::mandates::RecurringDetails::ProcessorPaymentToken(_)
+ )
+ }) {
+ euclid_enums::PaymentType::PptMandate
+ } else {
+ payment_data.setup_mandate.clone().map_or_else(
+ || euclid_enums::PaymentType::NonMandate,
+ |_| euclid_enums::PaymentType::SetupMandate,
+ )
+ },
+ ),
};
let payment_method_input = dsl_inputs::PaymentMethodInput {
payment_method: payment_data.payment_attempt.payment_method,
|
2024-08-23T08:00:31Z
|
## Type of Change
<!-- Put an `x` in the boxes that apply -->
- [ ] Bugfix
- [x] New feature
- [ ] Enhancement
- [ ] Refactoring
- [ ] Dependency updates
- [ ] Documentation
- [ ] CI/CD
## Description
<!-- Describe your changes in detail -->
This change will add a new variant in payment_type which will be `ppt_token_flow` using which we will be able to make rule on basis of the ppt flow.
The new variant will be visible here:
<img width="1201" alt="Screenshot 2024-08-27 at 3 04 33 PM" src="https://github.com/user-attachments/assets/98d7ca6a-0a22-479b-a9ec-2867da20fd2f">
### Additional Changes
- [ ] This PR modifies the API contract
- [ ] This PR modifies the database schema
- [ ] This PR modifies application configuration/environment variables
<!--
Provide links to the files with corresponding changes.
Following are the paths where you can find config files:
1. `config`
2. `crates/router/src/configs`
3. `loadtest/config`
-->
## Motivation and Context
<!--
Why is this change required? What problem does it solve?
If it fixes an open issue, please link to the issue here.
If you don't have an issue, we'd recommend starting with one first so the PR
can focus on the implementation (unless it is an obvious bug or documentation fix
that will have little conversation).
-->
Required for PPT token flow
## How did you test it?
<!--
Did you write an integration/unit/API test to verify the code changes?
Or did you test this change manually (provide relevant screenshots)?
-->
Unit test cases are written for the same in PR (`vir_interpreter.rs` file).
## Checklist
<!-- Put an `x` in the boxes that apply -->
- [x] I formatted the code `cargo +nightly fmt --all`
- [x] I addressed lints thrown by `cargo clippy`
- [x] I reviewed the submitted code
- [ ] I added unit tests for my changes where possible
|
4585e16245dd49d8c0b877cda148524afe395009
|
|
juspay/hyperswitch
|
juspay__hyperswitch-5706
|
Bug: feat(opensearch): add profile_id and organization_id to /search APIs
Global Search is currently being done through the merchant_id authentication.
We have to enhance the global search to search through new hierarchical structure of OrgLevel, MerchantLevel and ProfileLevel.
Queries will now be of the following form:
```
OrgLevel {
org_id: id_type::OrganizationId,
},
MerchantLevel {
org_id: id_type::OrganizationId,
merchant_ids: Vec<id_type::MerchantId>,
},
ProfileLevel {
org_id: id_type::OrganizationId,
merchant_id: id_type::MerchantId,
profile_ids: Vec<id_type::ProfileId>,
}
```
|
diff --git a/crates/analytics/src/opensearch.rs b/crates/analytics/src/opensearch.rs
index f3dd5eea441..7486ab50a51 100644
--- a/crates/analytics/src/opensearch.rs
+++ b/crates/analytics/src/opensearch.rs
@@ -24,7 +24,7 @@ use storage_impl::errors::ApplicationError;
use time::PrimitiveDateTime;
use super::{health_check::HealthCheck, query::QueryResult, types::QueryExecutionError};
-use crate::query::QueryBuildingError;
+use crate::{enums::AuthInfo, query::QueryBuildingError};
#[derive(Clone, Debug, serde::Deserialize)]
#[serde(tag = "auth")]
@@ -397,13 +397,15 @@ pub struct OpenSearchQueryBuilder {
pub count: Option<i64>,
pub filters: Vec<(String, Vec<String>)>,
pub time_range: Option<OpensearchTimeRange>,
+ pub search_params: Vec<AuthInfo>,
}
impl OpenSearchQueryBuilder {
- pub fn new(query_type: OpenSearchQuery, query: String) -> Self {
+ pub fn new(query_type: OpenSearchQuery, query: String, search_params: Vec<AuthInfo>) -> Self {
Self {
query_type,
query,
+ search_params,
offset: Default::default(),
count: Default::default(),
filters: Default::default(),
@@ -498,8 +500,80 @@ impl OpenSearchQueryBuilder {
}));
}
- bool_obj.insert("filter".to_string(), Value::Array(filter_array));
- query_obj.insert("bool".to_string(), Value::Object(bool_obj));
+ let should_array = self
+ .search_params
+ .iter()
+ .map(|user_level| match user_level {
+ AuthInfo::OrgLevel { org_id } => {
+ let must_clauses = vec![json!({
+ "term": {
+ "organization_id.keyword": {
+ "value": org_id
+ }
+ }
+ })];
+
+ json!({
+ "bool": {
+ "must": must_clauses
+ }
+ })
+ }
+ AuthInfo::MerchantLevel {
+ org_id: _,
+ merchant_ids,
+ } => {
+ let must_clauses = vec![
+ // TODO: Add org_id field to the filters
+ json!({
+ "terms": {
+ "merchant_id.keyword": merchant_ids
+ }
+ }),
+ ];
+
+ json!({
+ "bool": {
+ "must": must_clauses
+ }
+ })
+ }
+ AuthInfo::ProfileLevel {
+ org_id: _,
+ merchant_id,
+ profile_ids,
+ } => {
+ let must_clauses = vec![
+ // TODO: Add org_id field to the filters
+ json!({
+ "term": {
+ "merchant_id.keyword": {
+ "value": merchant_id
+ }
+ }
+ }),
+ json!({
+ "terms": {
+ "profile_id.keyword": profile_ids
+ }
+ }),
+ ];
+
+ json!({
+ "bool": {
+ "must": must_clauses
+ }
+ })
+ }
+ })
+ .collect::<Vec<Value>>();
+
+ if !filter_array.is_empty() {
+ bool_obj.insert("filter".to_string(), Value::Array(filter_array));
+ }
+ if !bool_obj.is_empty() {
+ query_obj.insert("bool".to_string(), Value::Object(bool_obj));
+ }
let mut query = Map::new();
query.insert("query".to_string(), Value::Object(query_obj));
@@ -514,9 +588,19 @@ impl OpenSearchQueryBuilder {
.and_then(|f| f.as_array())
.map(|filters| self.replace_status_field(filters, index))
.unwrap_or_default();
-
+ let mut final_bool_obj = Map::new();
+ if !updated_query.is_empty() {
+ final_bool_obj.insert("filter".to_string(), Value::Array(updated_query));
+ }
+ if !should_array.is_empty() {
+ final_bool_obj.insert("should".to_string(), Value::Array(should_array.clone()));
+ final_bool_obj
+ .insert("minimum_should_match".to_string(), Value::Number(1.into()));
+ }
let mut final_query = Map::new();
- final_query.insert("bool".to_string(), json!({ "filter": updated_query }));
+ if !final_bool_obj.is_empty() {
+ final_query.insert("bool".to_string(), Value::Object(final_bool_obj));
+ }
let mut sort_obj = Map::new();
sort_obj.insert(
diff --git a/crates/analytics/src/search.rs b/crates/analytics/src/search.rs
index 95b7f204b97..c81ff2f416b 100644
--- a/crates/analytics/src/search.rs
+++ b/crates/analytics/src/search.rs
@@ -6,14 +6,15 @@ use common_utils::errors::{CustomResult, ReportSwitchExt};
use error_stack::ResultExt;
use router_env::tracing;
-use crate::opensearch::{
- OpenSearchClient, OpenSearchError, OpenSearchQuery, OpenSearchQueryBuilder,
+use crate::{
+ enums::AuthInfo,
+ opensearch::{OpenSearchClient, OpenSearchError, OpenSearchQuery, OpenSearchQueryBuilder},
};
pub async fn msearch_results(
client: &OpenSearchClient,
req: GetGlobalSearchRequest,
- merchant_id: &common_utils::id_type::MerchantId,
+ search_params: Vec<AuthInfo>,
indexes: Vec<SearchIndex>,
) -> CustomResult<Vec<GetSearchResponse>, OpenSearchError> {
if req.query.trim().is_empty()
@@ -27,15 +28,11 @@ pub async fn msearch_results(
)
.into());
}
- let mut query_builder =
- OpenSearchQueryBuilder::new(OpenSearchQuery::Msearch(indexes.clone()), req.query);
-
- query_builder
- .add_filter_clause(
- "merchant_id.keyword".to_string(),
- vec![merchant_id.get_string_repr().to_owned()],
- )
- .switch()?;
+ let mut query_builder = OpenSearchQueryBuilder::new(
+ OpenSearchQuery::Msearch(indexes.clone()),
+ req.query,
+ search_params,
+ );
if let Some(filters) = req.filters {
if let Some(currency) = filters.currency {
@@ -152,19 +149,15 @@ pub async fn msearch_results(
pub async fn search_results(
client: &OpenSearchClient,
req: GetSearchRequestWithIndex,
- merchant_id: &common_utils::id_type::MerchantId,
+ search_params: Vec<AuthInfo>,
) -> CustomResult<GetSearchResponse, OpenSearchError> {
let search_req = req.search_req;
- let mut query_builder =
- OpenSearchQueryBuilder::new(OpenSearchQuery::Search(req.index), search_req.query);
-
- query_builder
- .add_filter_clause(
- "merchant_id.keyword".to_string(),
- vec![merchant_id.get_string_repr().to_owned()],
- )
- .switch()?;
+ let mut query_builder = OpenSearchQueryBuilder::new(
+ OpenSearchQuery::Search(req.index),
+ search_req.query,
+ search_params,
+ );
if let Some(filters) = search_req.filters {
if let Some(currency) = filters.currency {
diff --git a/crates/router/src/analytics.rs b/crates/router/src/analytics.rs
index 1fcfbdb5df9..c9b0a956dbc 100644
--- a/crates/router/src/analytics.rs
+++ b/crates/router/src/analytics.rs
@@ -21,6 +21,7 @@ pub mod routes {
GetSdkEventMetricRequest, ReportRequest,
};
use common_enums::EntityType;
+ use common_utils::id_type::{MerchantId, OrganizationId};
use error_stack::{report, ResultExt};
use crate::{
@@ -1840,10 +1841,17 @@ pub mod routes {
.map(|(i, _)| *i)
.collect();
+ let merchant_id: MerchantId = auth.merchant_id;
+ let org_id: OrganizationId = auth.org_id;
+ let search_params: Vec<AuthInfo> = vec![AuthInfo::MerchantLevel {
+ org_id: org_id.clone(),
+ merchant_ids: vec![merchant_id.clone()],
+ }];
+
analytics::search::msearch_results(
&state.opensearch_client,
req,
- &auth.merchant_id,
+ search_params,
accessible_indexes,
)
.await
@@ -1888,7 +1896,15 @@ pub mod routes {
.filter(|(ind, _)| *ind == index)
.find(|i| i.1.iter().any(|p| permissions.contains(p)))
.ok_or(OpenSearchError::IndexAccessNotPermittedError(index))?;
- analytics::search::search_results(&state.opensearch_client, req, &auth.merchant_id)
+
+ let merchant_id: MerchantId = auth.merchant_id;
+ let org_id: OrganizationId = auth.org_id;
+ let search_params: Vec<AuthInfo> = vec![AuthInfo::MerchantLevel {
+ org_id: org_id.clone(),
+ merchant_ids: vec![merchant_id.clone()],
+ }];
+
+ analytics::search::search_results(&state.opensearch_client, req, search_params)
.await
.map(ApplicationResponse::Json)
},
|
2024-08-27T05:25:37Z
|
## Type of Change
<!-- Put an `x` in the boxes that apply -->
- [ ] Bugfix
- [x] New feature
- [ ] Enhancement
- [ ] Refactoring
- [ ] Dependency updates
- [ ] Documentation
- [ ] CI/CD
## Description
<!-- Describe your changes in detail -->
Global Search is currently being done through the `merchant_id` authentication.
Enhancing the global search to search through new hierarchical structure of OrgLevel, MerchantLevel and ProfileLevel.
Structure of the enum used:
```bash
pub enum AuthInfo {
OrgLevel {
org_id: id_type::OrganizationId,
},
MerchantLevel {
org_id: id_type::OrganizationId,
merchant_ids: Vec<id_type::MerchantId>,
},
ProfileLevel {
org_id: id_type::OrganizationId,
merchant_id: id_type::MerchantId,
profile_ids: Vec<id_type::ProfileId>,
},
}
```
- Modified the query-building for opensearch/elasticsearch by adding the orgLevel and ProfileLevel queries.
- Results will now be returned if any search query is matched, and for all matched queries
### Additional Changes
- [ ] This PR modifies the API contract
- [ ] This PR modifies the database schema
- [ ] This PR modifies application configuration/environment variables
<!--
Provide links to the files with corresponding changes.
Following are the paths where you can find config files:
1. `config`
2. `crates/router/src/configs`
3. `loadtest/config`
-->
## Motivation and Context
<!--
Why is this change required? What problem does it solve?
If it fixes an open issue, please link to the issue here.
If you don't have an issue, we'd recommend starting with one first so the PR
can focus on the implementation (unless it is an obvious bug or documentation fix
that will have little conversation).
-->
OrgLevel, MerchantLevel and ProfileLevel provide for enhanced analytics insights while using global search to the users
## How did you test it?
<!--
Did you write an integration/unit/API test to verify the code changes?
Or did you test this change manually (provide relevant screenshots)?
-->
- Sample Query Structure

- Hit the `/search` API (using query, filters and timeRange).
```bash
curl --location 'http://localhost:8080/analytics/v1/search' \
--header 'Accept: */*' \
--header 'Accept-Language: en-US,en;q=0.9' \
--header 'Connection: keep-alive' \
--header 'Content-Type: application/json' \
--header 'Origin: http://localhost:9000' \
--header 'Referer: http://localhost:9000/' \
--header 'Sec-Fetch-Dest: empty' \
--header 'Sec-Fetch-Mode: cors' \
--header 'Sec-Fetch-Site: same-site' \
--header 'User-Agent: Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/126.0.0.0 Safari/537.36' \
--header 'api-key: hyperswitch' \
--header 'authorization: Bearer eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJ1c2VyX2lkIjoiY2M3M2ZiY2EtYTExMS00Nzk5LWI3MDEtN2E4NmU0OWIxMzY1IiwibWVyY2hhbnRfaWQiOiJtZXJjaGFudF8xNzI1MjY3Mzk3Iiwicm9sZV9pZCI6Im9yZ19hZG1pbiIsImV4cCI6MTcyNTUxNzc2Nywib3JnX2lkIjoib3JnX0lpbTRxOHpPdlA3aGp3QTRxTkpoIiwicHJvZmlsZV9pZCI6bnVsbH0.7vZllJaSLEw1EsU4tgXkEcpAjRmjlukk6swzZfa6uU0' \
--header 'sec-ch-ua: "Not/A)Brand";v="8", "Chromium";v="126", "Google Chrome";v="126"' \
--header 'sec-ch-ua-mobile: ?0' \
--header 'sec-ch-ua-platform: "macOS"' \
--data '{
"query": "usd",
"filters": {
"status": [
"succeeded", "charged", "success"
]
},
"timeRange": {
"startTime": "2024-09-02T00:30:00Z",
"endTime": "2024-09-04T21:45:00Z"
}
}'
```
- Sample Response:
```bash
[
{
"count": 2,
"index": "payment_attempts",
"hits": [
{
"payment_id": "pay_mUtaBhUnlC2b7kTtxTJ0",
"merchant_id": "merchant_1725267397",
"attempt_id": "pay_mUtaBhUnlC2b7kTtxTJ0_1",
"status": "charged",
"amount": 6540,
"currency": "USD",
"save_to_locker": null,
"connector": "stripe_test",
"error_message": null,
"offer_amount": null,
"surcharge_amount": null,
"tax_amount": null,
"payment_method_id": null,
"payment_method": "card",
"connector_transaction_id": "pay_XO5KGoaMl5y7R8fM3Xya",
"capture_method": "automatic",
"capture_on": 1662804672,
"confirm": true,
"authentication_type": "no_three_ds",
"created_at": 1725339016,
"modified_at": 1725339017,
"last_synced": 1725339016,
"cancellation_reason": null,
"amount_to_capture": 6540,
"mandate_id": null,
"browser_info": null,
"error_code": null,
"connector_metadata": null,
"payment_experience": null,
"payment_method_type": "credit",
"payment_method_data": "{\"card\":{\"last4\":\"4242\",\"bank_code\":null,\"card_isin\":\"424242\",\"card_type\":null,\"card_issuer\":null,\"card_network\":null,\"card_exp_year\":\"25\",\"card_exp_month\":\"10\",\"payment_checks\":null,\"card_holder_name\":null,\"card_extended_bin\":null,\"authentication_data\":null,\"card_issuing_country\":null}}",
"error_reason": null,
"multiple_capture_count": null,
"amount_capturable": 0,
"merchant_connector_id": "mca_zPBTVwk8mQPMvW9rrW8n",
"net_amount": 6540,
"unified_code": null,
"unified_message": null,
"mandate_data": null,
"client_source": null,
"client_version": null,
"profile_id": "pro_GOyb8ecA2QA4pXnJTvAL",
"organization_id": "org_Iim4q8zOvP7hjwA4qNJh",
"card_network": null,
"sign_flag": 1,
"tenant_id": "public",
"clickhouse_database": "default",
"@timestamp": "2024-09-03T04:50:16.000000000+00:00"
},
{
"payment_id": "pay_CW0tpqeKk7F6q2TVKffH",
"merchant_id": "merchant_1725267397",
"attempt_id": "pay_CW0tpqeKk7F6q2TVKffH_1",
"status": "charged",
"amount": 6540,
"currency": "USD",
"save_to_locker": null,
"connector": "stripe_test",
"error_message": null,
"offer_amount": null,
"surcharge_amount": null,
"tax_amount": null,
"payment_method_id": null,
"payment_method": "card",
"connector_transaction_id": "pay_w5UHXOqOiLqRieOUQL63",
"capture_method": "automatic",
"capture_on": 1662804672,
"confirm": true,
"authentication_type": "no_three_ds",
"created_at": 1725283209,
"modified_at": 1725283210,
"last_synced": 1725283209,
"cancellation_reason": null,
"amount_to_capture": 6540,
"mandate_id": null,
"browser_info": null,
"error_code": null,
"connector_metadata": null,
"payment_experience": null,
"payment_method_type": "credit",
"payment_method_data": "{\"card\":{\"last4\":\"4242\",\"bank_code\":null,\"card_isin\":\"424242\",\"card_type\":null,\"card_issuer\":null,\"card_network\":null,\"card_exp_year\":\"25\",\"card_exp_month\":\"10\",\"payment_checks\":null,\"card_holder_name\":null,\"card_extended_bin\":null,\"authentication_data\":null,\"card_issuing_country\":null}}",
"error_reason": null,
"multiple_capture_count": null,
"amount_capturable": 0,
"merchant_connector_id": "mca_zPBTVwk8mQPMvW9rrW8n",
"net_amount": 6540,
"unified_code": null,
"unified_message": null,
"mandate_data": null,
"client_source": null,
"client_version": null,
"profile_id": "pro_GOyb8ecA2QA4pXnJTvAL",
"organization_id": "org_Iim4q8zOvP7hjwA4qNJh",
"card_network": null,
"sign_flag": 1,
"tenant_id": "public",
"clickhouse_database": "default",
"@timestamp": "2024-09-02T13:20:09.000000000+00:00"
}
],
"status": "Success"
},
{
"count": 2,
"index": "payment_intents",
"hits": [
{
"payment_id": "pay_mUtaBhUnlC2b7kTtxTJ0",
"merchant_id": "merchant_1725267397",
"status": "succeeded",
"amount": 6540,
"currency": "USD",
"amount_captured": 6540,
"customer_id": "StripeCustomer",
"description": "Its my first payment request",
"return_url": "https://google.com/",
"metadata": "{\"data2\":\"camel\",\"login_date\":\"2019-09-10T10:11:12Z\",\"new_customer\":\"true\"}",
"connector_id": null,
"statement_descriptor_name": "joseph",
"statement_descriptor_suffix": "JS",
"created_at": 1725339016,
"modified_at": 1725339017,
"last_synced": 1725339016,
"setup_future_usage": null,
"off_session": null,
"client_secret": "pay_mUtaBhUnlC2b7kTtxTJ0_secret_wiZ5NQnCZ2i9ajdAYyAJ",
"active_attempt_id": "pay_mUtaBhUnlC2b7kTtxTJ0_1",
"business_country": null,
"business_label": "default",
"attempt_count": 1,
"profile_id": "pro_GOyb8ecA2QA4pXnJTvAL",
"payment_confirm_source": null,
"billing_details": null,
"shipping_details": null,
"customer_email": "f6cd0753a831880835a0e0d23136ef66318d8303605bd37fa80b4ecf248bd303",
"feature_metadata": {
"redirect_response": null,
"search_tags": [
"9c202f2fabd12f758a12b449944f5cdaeadf39132680667543033158023bc805",
"ffd1c37eb18f3459e3da6f21f739866bce89a334061c248656cb71d83d2375f4"
]
},
"merchant_order_reference_id": null,
"organization_id": "org_Iim4q8zOvP7hjwA4qNJh",
"sign_flag": 1,
"tenant_id": "public",
"clickhouse_database": "default",
"@timestamp": "2024-09-03T04:50:16.000000000+00:00"
},
{
"payment_id": "pay_CW0tpqeKk7F6q2TVKffH",
"merchant_id": "merchant_1725267397",
"status": "succeeded",
"amount": 6540,
"currency": "USD",
"amount_captured": 6540,
"customer_id": "StripeCustomer",
"description": "Its my first payment request",
"return_url": "https://google.com/",
"metadata": "{\"data2\":\"camel\",\"login_date\":\"2019-09-10T10:11:12Z\",\"new_customer\":\"true\"}",
"connector_id": null,
"statement_descriptor_name": "joseph",
"statement_descriptor_suffix": "JS",
"created_at": 1725283209,
"modified_at": 1725283210,
"last_synced": 1725283209,
"setup_future_usage": null,
"off_session": null,
"client_secret": "pay_CW0tpqeKk7F6q2TVKffH_secret_rZIT5OsQzbhkE7rhsUrq",
"active_attempt_id": "pay_CW0tpqeKk7F6q2TVKffH_1",
"business_country": null,
"business_label": "default",
"attempt_count": 1,
"profile_id": "pro_GOyb8ecA2QA4pXnJTvAL",
"payment_confirm_source": null,
"billing_details": null,
"shipping_details": null,
"customer_email": "f6cd0753a831880835a0e0d23136ef66318d8303605bd37fa80b4ecf248bd303",
"feature_metadata": {
"redirect_response": null,
"search_tags": [
"9c202f2fabd12f758a12b449944f5cdaeadf39132680667543033158023bc805",
"ffd1c37eb18f3459e3da6f21f739866bce89a334061c248656cb71d83d2375f4"
]
},
"merchant_order_reference_id": null,
"organization_id": "org_Iim4q8zOvP7hjwA4qNJh",
"sign_flag": 1,
"tenant_id": "public",
"clickhouse_database": "default",
"@timestamp": "2024-09-02T13:20:09.000000000+00:00"
}
],
"status": "Success"
},
{
"count": 1,
"index": "refunds",
"hits": [
{
"internal_reference_id": "refid_yWIsLDexIn3LvMoEvXds",
"refund_id": "ref_WBSqj48rx3gaOuz1kUJv",
"payment_id": "pay_mUtaBhUnlC2b7kTtxTJ0",
"merchant_id": "merchant_1725267397",
"connector_transaction_id": "pay_XO5KGoaMl5y7R8fM3Xya",
"connector": "stripe_test",
"connector_refund_id": "dummy_ref_DA5VW0KwaiCvnTaeBtcA",
"external_reference_id": "ref_WBSqj48rx3gaOuz1kUJv",
"refund_type": "instant_refund",
"total_amount": 6540,
"currency": "USD",
"refund_amount": 600,
"refund_status": "success",
"sent_to_gateway": true,
"refund_error_message": null,
"refund_arn": "",
"created_at": 1725339184,
"modified_at": 1725339185,
"description": "Customer returned product",
"attempt_id": "pay_mUtaBhUnlC2b7kTtxTJ0_1",
"refund_reason": "Customer returned product",
"refund_error_code": null,
"profile_id": "pro_GOyb8ecA2QA4pXnJTvAL",
"organization_id": "org_Iim4q8zOvP7hjwA4qNJh",
"sign_flag": 1,
"tenant_id": "public",
"clickhouse_database": "default",
"@timestamp": "2024-09-03T04:53:04.000000000+00:00"
}
],
"status": "Success"
},
{
"count": 0,
"index": "disputes",
"hits": [],
"status": "Failure"
}
]
```
## Checklist
<!-- Put an `x` in the boxes that apply -->
- [x] I formatted the code `cargo +nightly fmt --all`
- [x] I addressed lints thrown by `cargo clippy`
- [x] I reviewed the submitted code
- [ ] I added unit tests for my changes where possible
|
296ca311c96cc032aaa9ad846299db24bacaeb56
|
|
juspay/hyperswitch
|
juspay__hyperswitch-5721
|
Bug: feat(users): List users in lineage API
- Currently user roles are grouped by user email in dashboard.
- Payload might look something like this
```json
[
{
"email": "e1",
"roles": [
{
"role_id": "r1",
"role_name": "name"
}
]
}
]
```
|
diff --git a/crates/api_models/src/user.rs b/crates/api_models/src/user.rs
index 2547f082039..97d0c63fdf1 100644
--- a/crates/api_models/src/user.rs
+++ b/crates/api_models/src/user.rs
@@ -418,3 +418,15 @@ pub struct ListProfilesForUserInOrgAndMerchantAccountResponse {
pub profile_id: id_type::ProfileId,
pub profile_name: String,
}
+
+#[derive(Debug, serde::Serialize)]
+pub struct ListUsersInEntityResponse {
+ pub email: pii::Email,
+ pub roles: Vec<MinimalRoleInfo>,
+}
+
+#[derive(Debug, serde::Serialize, Clone)]
+pub struct MinimalRoleInfo {
+ pub role_id: String,
+ pub role_name: String,
+}
diff --git a/crates/common_enums/src/enums.rs b/crates/common_enums/src/enums.rs
index dd935b9a50e..d221a95c255 100644
--- a/crates/common_enums/src/enums.rs
+++ b/crates/common_enums/src/enums.rs
@@ -3094,6 +3094,7 @@ pub enum ApiVersion {
strum::Display,
strum::EnumString,
ToSchema,
+ Hash,
)]
#[router_derive::diesel_enum(storage_type = "text")]
#[strum(serialize_all = "snake_case")]
diff --git a/crates/common_utils/src/consts.rs b/crates/common_utils/src/consts.rs
index 1f4353f25d7..f59fedf5c4e 100644
--- a/crates/common_utils/src/consts.rs
+++ b/crates/common_utils/src/consts.rs
@@ -142,3 +142,10 @@ pub const MAX_ALLOWED_MERCHANT_NAME_LENGTH: usize = 64;
/// Default locale
pub const DEFAULT_LOCALE: &str = "en";
+
+/// Role ID for Org Admin
+pub const ROLE_ID_ORGANIZATION_ADMIN: &str = "org_admin";
+/// Role ID for Internal View Only
+pub const ROLE_ID_INTERNAL_VIEW_ONLY_USER: &str = "internal_view_only";
+/// Role ID for Internal Admin
+pub const ROLE_ID_INTERNAL_ADMIN: &str = "internal_admin";
diff --git a/crates/diesel_models/src/query/user_role.rs b/crates/diesel_models/src/query/user_role.rs
index 7904d3c2645..85f866f2fc2 100644
--- a/crates/diesel_models/src/query/user_role.rs
+++ b/crates/diesel_models/src/query/user_role.rs
@@ -185,7 +185,7 @@ impl UserRole {
.await
}
- pub async fn generic_user_roles_list(
+ pub async fn generic_user_roles_list_for_user(
conn: &PgPooledConn,
user_id: String,
org_id: Option<id_type::OrganizationId>,
@@ -235,4 +235,50 @@ impl UserRole {
},
}
}
+
+ pub async fn generic_user_roles_list_for_org_and_extra(
+ conn: &PgPooledConn,
+ user_id: Option<String>,
+ org_id: id_type::OrganizationId,
+ merchant_id: Option<id_type::MerchantId>,
+ profile_id: Option<id_type::ProfileId>,
+ version: Option<UserRoleVersion>,
+ ) -> StorageResult<Vec<Self>> {
+ let mut query = <Self as HasTable>::table()
+ .filter(dsl::org_id.eq(org_id))
+ .into_boxed();
+
+ if let Some(user_id) = user_id {
+ query = query.filter(dsl::user_id.eq(user_id));
+ }
+
+ if let Some(merchant_id) = merchant_id {
+ query = query.filter(dsl::merchant_id.eq(merchant_id));
+ }
+
+ if let Some(profile_id) = profile_id {
+ query = query.filter(dsl::profile_id.eq(profile_id));
+ }
+
+ if let Some(version) = version {
+ query = query.filter(dsl::version.eq(version));
+ }
+
+ router_env::logger::debug!(query = %debug_query::<Pg,_>(&query).to_string());
+
+ match generics::db_metrics::track_database_call::<Self, _, _>(
+ query.get_results_async(conn),
+ generics::db_metrics::DatabaseOperation::Filter,
+ )
+ .await
+ {
+ Ok(value) => Ok(value),
+ Err(err) => match err {
+ DieselError::NotFound => {
+ Err(report!(err)).change_context(errors::DatabaseError::NotFound)
+ }
+ _ => Err(report!(err)).change_context(errors::DatabaseError::Others),
+ },
+ }
+ }
}
diff --git a/crates/diesel_models/src/user_role.rs b/crates/diesel_models/src/user_role.rs
index b508c86211b..ac7def5ec2a 100644
--- a/crates/diesel_models/src/user_role.rs
+++ b/crates/diesel_models/src/user_role.rs
@@ -1,11 +1,13 @@
+use std::hash::Hash;
+
use common_enums::EntityType;
-use common_utils::id_type;
+use common_utils::{consts, id_type};
use diesel::{AsChangeset, Identifiable, Insertable, Queryable, Selectable};
use time::PrimitiveDateTime;
use crate::{enums, schema::user_roles};
-#[derive(Clone, Debug, Identifiable, Queryable, Selectable)]
+#[derive(Clone, Debug, Identifiable, Queryable, Selectable, Eq)]
#[diesel(table_name = user_roles, check_for_backend(diesel::pg::Pg))]
pub struct UserRole {
pub id: i32,
@@ -24,6 +26,55 @@ pub struct UserRole {
pub version: enums::UserRoleVersion,
}
+fn get_entity_id_and_type(user_role: &UserRole) -> (Option<String>, Option<EntityType>) {
+ match (user_role.version, user_role.role_id.as_str()) {
+ (enums::UserRoleVersion::V1, consts::ROLE_ID_ORGANIZATION_ADMIN) => (
+ user_role
+ .org_id
+ .clone()
+ .map(|org_id| org_id.get_string_repr().to_string()),
+ Some(EntityType::Organization),
+ ),
+ (enums::UserRoleVersion::V1, consts::ROLE_ID_INTERNAL_VIEW_ONLY_USER)
+ | (enums::UserRoleVersion::V1, consts::ROLE_ID_INTERNAL_ADMIN) => (
+ user_role
+ .merchant_id
+ .clone()
+ .map(|merchant_id| merchant_id.get_string_repr().to_string()),
+ Some(EntityType::Internal),
+ ),
+ (enums::UserRoleVersion::V1, _) => (
+ user_role
+ .merchant_id
+ .clone()
+ .map(|merchant_id| merchant_id.get_string_repr().to_string()),
+ Some(EntityType::Merchant),
+ ),
+ (enums::UserRoleVersion::V2, _) => (user_role.entity_id.clone(), user_role.entity_type),
+ }
+}
+
+impl Hash for UserRole {
+ fn hash<H: std::hash::Hasher>(&self, state: &mut H) {
+ let (entity_id, entity_type) = get_entity_id_and_type(self);
+
+ self.user_id.hash(state);
+ entity_id.hash(state);
+ entity_type.hash(state);
+ }
+}
+
+impl PartialEq for UserRole {
+ fn eq(&self, other: &Self) -> bool {
+ let (self_entity_id, self_entity_type) = get_entity_id_and_type(self);
+ let (other_entity_id, other_entity_type) = get_entity_id_and_type(other);
+
+ self.user_id == other.user_id
+ && self_entity_id == other_entity_id
+ && self_entity_type == other_entity_type
+ }
+}
+
#[derive(router_derive::Setter, Clone, Debug, Insertable, router_derive::DebugAsDisplay)]
#[diesel(table_name = user_roles)]
pub struct UserRoleNew {
diff --git a/crates/router/src/consts/user_role.rs b/crates/router/src/consts/user_role.rs
index 0a5d6556a11..672e5830013 100644
--- a/crates/router/src/consts/user_role.rs
+++ b/crates/router/src/consts/user_role.rs
@@ -1,8 +1,5 @@
// User Roles
-pub const ROLE_ID_INTERNAL_VIEW_ONLY_USER: &str = "internal_view_only";
-pub const ROLE_ID_INTERNAL_ADMIN: &str = "internal_admin";
pub const ROLE_ID_MERCHANT_ADMIN: &str = "merchant_admin";
-pub const ROLE_ID_ORGANIZATION_ADMIN: &str = "org_admin";
pub const ROLE_ID_MERCHANT_VIEW_ONLY: &str = "merchant_view_only";
pub const ROLE_ID_MERCHANT_IAM_ADMIN: &str = "merchant_iam_admin";
pub const ROLE_ID_MERCHANT_DEVELOPER: &str = "merchant_developer";
diff --git a/crates/router/src/core/errors/user.rs b/crates/router/src/core/errors/user.rs
index 1cd37679ad4..e3c4bedab72 100644
--- a/crates/router/src/core/errors/user.rs
+++ b/crates/router/src/core/errors/user.rs
@@ -88,6 +88,8 @@ pub enum UserErrors {
AuthConfigParsingError,
#[error("Invalid SSO request")]
SSOFailed,
+ #[error("profile_id missing in JWT")]
+ JwtProfileIdMissing,
}
impl common_utils::errors::ErrorSwitch<api_models::errors::types::ApiErrorResponse> for UserErrors {
@@ -224,6 +226,9 @@ impl common_utils::errors::ErrorSwitch<api_models::errors::types::ApiErrorRespon
Self::SSOFailed => {
AER::BadRequest(ApiError::new(sub_code, 46, self.get_error_message(), None))
}
+ Self::JwtProfileIdMissing => {
+ AER::Unauthorized(ApiError::new(sub_code, 47, self.get_error_message(), None))
+ }
}
}
}
@@ -271,6 +276,7 @@ impl UserErrors {
Self::InvalidUserAuthMethodOperation => "Invalid user auth method operation",
Self::AuthConfigParsingError => "Auth config parsing error",
Self::SSOFailed => "Invalid SSO request",
+ Self::JwtProfileIdMissing => "profile_id missing in JWT",
}
}
}
diff --git a/crates/router/src/core/user.rs b/crates/router/src/core/user.rs
index 9510ddd632d..17ebd00a994 100644
--- a/crates/router/src/core/user.rs
+++ b/crates/router/src/core/user.rs
@@ -62,7 +62,7 @@ pub async fn signup_with_merchant_id(
let user_role = new_user
.insert_user_role_in_db(
state.clone(),
- consts::user_role::ROLE_ID_ORGANIZATION_ADMIN.to_string(),
+ common_utils::consts::ROLE_ID_ORGANIZATION_ADMIN.to_string(),
UserStatus::Active,
)
.await?;
@@ -134,7 +134,7 @@ pub async fn signup(
let user_role = new_user
.insert_user_role_in_db(
state.clone(),
- consts::user_role::ROLE_ID_ORGANIZATION_ADMIN.to_string(),
+ common_utils::consts::ROLE_ID_ORGANIZATION_ADMIN.to_string(),
UserStatus::Active,
)
.await?;
@@ -165,7 +165,7 @@ pub async fn signup_token_only_flow(
let user_role = new_user
.insert_user_role_in_db(
state.clone(),
- consts::user_role::ROLE_ID_ORGANIZATION_ADMIN.to_string(),
+ common_utils::consts::ROLE_ID_ORGANIZATION_ADMIN.to_string(),
UserStatus::Active,
)
.await?;
@@ -316,7 +316,7 @@ pub async fn connect_account(
let user_role = new_user
.insert_user_role_in_db(
state.clone(),
- consts::user_role::ROLE_ID_ORGANIZATION_ADMIN.to_string(),
+ common_utils::consts::ROLE_ID_ORGANIZATION_ADMIN.to_string(),
UserStatus::Active,
)
.await?;
@@ -1310,7 +1310,7 @@ pub async fn create_internal_user(
new_user
.insert_user_role_in_db(
state,
- consts::user_role::ROLE_ID_INTERNAL_VIEW_ONLY_USER.to_string(),
+ common_utils::consts::ROLE_ID_INTERNAL_VIEW_ONLY_USER.to_string(),
UserStatus::Active,
)
.await?;
@@ -1389,7 +1389,7 @@ pub async fn switch_merchant_id(
} else {
let user_roles = state
.store
- .list_user_roles_by_user_id(&user_from_token.user_id, UserRoleVersion::V1)
+ .list_user_roles_by_user_id_and_version(&user_from_token.user_id, UserRoleVersion::V1)
.await
.change_context(UserErrors::InternalServerError)?;
@@ -1450,7 +1450,7 @@ pub async fn create_merchant_account(
let role_insertion_res = new_user
.insert_user_role_in_db(
state.clone(),
- consts::user_role::ROLE_ID_ORGANIZATION_ADMIN.to_string(),
+ common_utils::consts::ROLE_ID_ORGANIZATION_ADMIN.to_string(),
UserStatus::Active,
)
.await;
@@ -1471,7 +1471,10 @@ pub async fn list_merchants_for_user(
) -> UserResponse<Vec<user_api::UserMerchantAccount>> {
let user_roles = state
.store
- .list_user_roles_by_user_id(user_from_token.user_id.as_str(), UserRoleVersion::V1)
+ .list_user_roles_by_user_id_and_version(
+ user_from_token.user_id.as_str(),
+ UserRoleVersion::V1,
+ )
.await
.change_context(UserErrors::InternalServerError)?;
@@ -2572,7 +2575,7 @@ pub async fn list_orgs_for_user(
) -> UserResponse<Vec<user_api::ListOrgsForUserResponse>> {
let orgs = state
.store
- .list_user_roles(
+ .list_user_roles_by_user_id(
user_from_token.user_id.as_str(),
None,
None,
@@ -2638,7 +2641,7 @@ pub async fn list_merchants_for_user_in_org(
} else {
let merchant_ids = state
.store
- .list_user_roles(
+ .list_user_roles_by_user_id(
user_from_token.user_id.as_str(),
Some(&user_from_token.org_id),
None,
@@ -2721,7 +2724,7 @@ pub async fn list_profiles_for_user_in_org_and_merchant_account(
} else {
let profile_ids = state
.store
- .list_user_roles(
+ .list_user_roles_by_user_id(
user_from_token.user_id.as_str(),
Some(&user_from_token.org_id),
Some(&user_from_token.merchant_id),
@@ -2793,7 +2796,7 @@ pub async fn switch_org_for_user(
let user_role = state
.store
- .list_user_roles(
+ .list_user_roles_by_user_id(
&user_from_token.user_id,
Some(&request.org_id),
None,
@@ -3012,7 +3015,7 @@ pub async fn switch_merchant_for_user_in_org(
EntityType::Merchant | EntityType::Profile => {
let user_role = state
.store
- .list_user_roles(
+ .list_user_roles_by_user_id(
&user_from_token.user_id,
Some(&user_from_token.org_id),
Some(&request.merchant_id),
@@ -3152,7 +3155,7 @@ pub async fn switch_profile_for_user_in_org_and_merchant(
EntityType::Profile => {
let user_role = state
.store
- .list_user_roles(
+ .list_user_roles_by_user_id(
&user_from_token.user_id,
Some(&user_from_token.org_id),
Some(&user_from_token.merchant_id),
diff --git a/crates/router/src/core/user_role.rs b/crates/router/src/core/user_role.rs
index b599a26fdfc..971b34b0667 100644
--- a/crates/router/src/core/user_role.rs
+++ b/crates/router/src/core/user_role.rs
@@ -1,4 +1,4 @@
-use std::collections::HashMap;
+use std::collections::{HashMap, HashSet};
use api_models::{user as user_api, user_role as user_role_api};
use diesel_models::{
@@ -10,6 +10,7 @@ use once_cell::sync::Lazy;
use crate::{
core::errors::{StorageErrorExt, UserErrors, UserResponse},
+ db::user_role::ListUserRolesByOrgIdPayload,
routes::{app::ReqState, SessionState},
services::{
authentication as auth,
@@ -20,7 +21,7 @@ use crate::{
utils,
};
pub mod role;
-use common_enums::PermissionGroup;
+use common_enums::{EntityType, PermissionGroup};
use strum::IntoEnumIterator;
// TODO: To be deprecated once groups are stable
@@ -618,13 +619,13 @@ pub async fn delete_user_role(
// Check if user has any more role associations
let user_roles_v2 = state
.store
- .list_user_roles_by_user_id(user_from_db.get_user_id(), UserRoleVersion::V2)
+ .list_user_roles_by_user_id_and_version(user_from_db.get_user_id(), UserRoleVersion::V2)
.await
.change_context(UserErrors::InternalServerError)?;
let user_roles_v1 = state
.store
- .list_user_roles_by_user_id(user_from_db.get_user_id(), UserRoleVersion::V1)
+ .list_user_roles_by_user_id_and_version(user_from_db.get_user_id(), UserRoleVersion::V1)
.await
.change_context(UserErrors::InternalServerError)?;
@@ -641,3 +642,135 @@ pub async fn delete_user_role(
auth::blacklist::insert_user_in_blacklist(&state, user_from_db.get_user_id()).await?;
Ok(ApplicationResponse::StatusOk)
}
+
+pub async fn list_users_in_lineage(
+ state: SessionState,
+ user_from_token: auth::UserFromToken,
+) -> UserResponse<Vec<user_api::ListUsersInEntityResponse>> {
+ let requestor_role_info = roles::RoleInfo::from_role_id(
+ &state,
+ &user_from_token.role_id,
+ &user_from_token.merchant_id,
+ &user_from_token.org_id,
+ )
+ .await
+ .change_context(UserErrors::InternalServerError)?;
+
+ let user_roles_set: HashSet<_> = match requestor_role_info.get_entity_type() {
+ EntityType::Organization => state
+ .store
+ .list_user_roles_by_org_id(ListUserRolesByOrgIdPayload {
+ user_id: None,
+ org_id: &user_from_token.org_id,
+ merchant_id: None,
+ profile_id: None,
+ version: None,
+ })
+ .await
+ .change_context(UserErrors::InternalServerError)?
+ .into_iter()
+ .collect(),
+ EntityType::Merchant => state
+ .store
+ .list_user_roles_by_org_id(ListUserRolesByOrgIdPayload {
+ user_id: None,
+ org_id: &user_from_token.org_id,
+ merchant_id: Some(&user_from_token.merchant_id),
+ profile_id: None,
+ version: None,
+ })
+ .await
+ .change_context(UserErrors::InternalServerError)?
+ .into_iter()
+ .collect(),
+ EntityType::Profile => {
+ let Some(profile_id) = user_from_token.profile_id.as_ref() else {
+ return Err(UserErrors::JwtProfileIdMissing.into());
+ };
+
+ state
+ .store
+ .list_user_roles_by_org_id(ListUserRolesByOrgIdPayload {
+ user_id: None,
+ org_id: &user_from_token.org_id,
+ merchant_id: Some(&user_from_token.merchant_id),
+ profile_id: Some(profile_id),
+ version: None,
+ })
+ .await
+ .change_context(UserErrors::InternalServerError)?
+ .into_iter()
+ .collect()
+ }
+ EntityType::Internal => HashSet::new(),
+ };
+
+ let mut email_map = state
+ .global_store
+ .find_users_by_user_ids(
+ user_roles_set
+ .iter()
+ .map(|user_role| user_role.user_id.clone())
+ .collect(),
+ )
+ .await
+ .change_context(UserErrors::InternalServerError)?
+ .into_iter()
+ .map(|user| (user.user_id.clone(), user.email))
+ .collect::<HashMap<_, _>>();
+
+ let role_info_map =
+ futures::future::try_join_all(user_roles_set.iter().map(|user_role| async {
+ roles::RoleInfo::from_role_id(
+ &state,
+ &user_role.role_id,
+ &user_from_token.merchant_id,
+ &user_from_token.org_id,
+ )
+ .await
+ .map(|role_info| {
+ (
+ user_role.role_id.clone(),
+ user_api::MinimalRoleInfo {
+ role_id: user_role.role_id.clone(),
+ role_name: role_info.get_role_name().to_string(),
+ },
+ )
+ })
+ }))
+ .await
+ .change_context(UserErrors::InternalServerError)?
+ .into_iter()
+ .collect::<HashMap<_, _>>();
+
+ let user_role_map = user_roles_set
+ .into_iter()
+ .fold(HashMap::new(), |mut map, user_role| {
+ map.entry(user_role.user_id)
+ .or_insert(Vec::with_capacity(1))
+ .push(user_role.role_id);
+ map
+ });
+
+ Ok(ApplicationResponse::Json(
+ user_role_map
+ .into_iter()
+ .map(|(user_id, role_id_vec)| {
+ Ok::<_, error_stack::Report<UserErrors>>(user_api::ListUsersInEntityResponse {
+ email: email_map
+ .remove(&user_id)
+ .ok_or(UserErrors::InternalServerError)?,
+ roles: role_id_vec
+ .into_iter()
+ .map(|role_id| {
+ role_info_map
+ .get(&role_id)
+ .cloned()
+ .ok_or(UserErrors::InternalServerError)
+ })
+ .collect::<Result<Vec<_>, _>>()?,
+ })
+ })
+ .collect::<Result<Vec<_>, _>>()?,
+ ))
+}
diff --git a/crates/router/src/core/user_role/role.rs b/crates/router/src/core/user_role/role.rs
index a286180e202..d79b3136422 100644
--- a/crates/router/src/core/user_role/role.rs
+++ b/crates/router/src/core/user_role/role.rs
@@ -5,7 +5,6 @@ use diesel_models::role::{RoleNew, RoleUpdate};
use error_stack::{report, ResultExt};
use crate::{
- consts,
core::errors::{StorageErrorExt, UserErrors, UserResponse},
routes::{app::ReqState, SessionState},
services::{
@@ -72,7 +71,7 @@ pub async fn create_role(
.await?;
if matches!(req.role_scope, RoleScope::Organization)
- && user_from_token.role_id != consts::user_role::ROLE_ID_ORGANIZATION_ADMIN
+ && user_from_token.role_id != common_utils::consts::ROLE_ID_ORGANIZATION_ADMIN
{
return Err(report!(UserErrors::InvalidRoleOperation))
.attach_printable("Non org admin user creating org level role");
@@ -292,7 +291,7 @@ pub async fn update_role(
.to_not_found_response(UserErrors::InvalidRoleOperation)?;
if matches!(role_info.get_scope(), RoleScope::Organization)
- && user_from_token.role_id != consts::user_role::ROLE_ID_ORGANIZATION_ADMIN
+ && user_from_token.role_id != common_utils::consts::ROLE_ID_ORGANIZATION_ADMIN
{
return Err(report!(UserErrors::InvalidRoleOperation))
.attach_printable("Non org admin user changing org level role");
diff --git a/crates/router/src/db/kafka_store.rs b/crates/router/src/db/kafka_store.rs
index 403b79a0377..0d8b753463b 100644
--- a/crates/router/src/db/kafka_store.rs
+++ b/crates/router/src/db/kafka_store.rs
@@ -35,7 +35,7 @@ use super::{
user::{sample_data::BatchSampleDataInterface, UserInterface},
user_authentication_method::UserAuthenticationMethodInterface,
user_key_store::UserKeyStoreInterface,
- user_role::UserRoleInterface,
+ user_role::{ListUserRolesByOrgIdPayload, UserRoleInterface},
};
#[cfg(feature = "payouts")]
use crate::services::kafka::payout::KafkaPayout;
@@ -2792,13 +2792,13 @@ impl UserRoleInterface for KafkaStore {
.await
}
- async fn list_user_roles_by_user_id(
+ async fn list_user_roles_by_user_id_and_version(
&self,
user_id: &str,
version: enums::UserRoleVersion,
) -> CustomResult<Vec<user_storage::UserRole>, errors::StorageError> {
self.diesel_store
- .list_user_roles_by_user_id(user_id, version)
+ .list_user_roles_by_user_id_and_version(user_id, version)
.await
}
@@ -2871,7 +2871,7 @@ impl UserRoleInterface for KafkaStore {
.await
}
- async fn list_user_roles(
+ async fn list_user_roles_by_user_id(
&self,
user_id: &str,
org_id: Option<&id_type::OrganizationId>,
@@ -2881,9 +2881,23 @@ impl UserRoleInterface for KafkaStore {
version: Option<enums::UserRoleVersion>,
) -> CustomResult<Vec<storage::UserRole>, errors::StorageError> {
self.diesel_store
- .list_user_roles(user_id, org_id, merchant_id, profile_id, entity_id, version)
+ .list_user_roles_by_user_id(
+ user_id,
+ org_id,
+ merchant_id,
+ profile_id,
+ entity_id,
+ version,
+ )
.await
}
+
+ async fn list_user_roles_by_org_id<'a>(
+ &self,
+ payload: ListUserRolesByOrgIdPayload<'a>,
+ ) -> CustomResult<Vec<user_storage::UserRole>, errors::StorageError> {
+ self.diesel_store.list_user_roles_by_org_id(payload).await
+ }
}
#[async_trait::async_trait]
diff --git a/crates/router/src/db/user_role.rs b/crates/router/src/db/user_role.rs
index 524eaaaab79..8d07f53e12d 100644
--- a/crates/router/src/db/user_role.rs
+++ b/crates/router/src/db/user_role.rs
@@ -30,7 +30,7 @@ pub trait UserRoleInterface {
version: enums::UserRoleVersion,
) -> CustomResult<storage::UserRole, errors::StorageError>;
- async fn list_user_roles_by_user_id(
+ async fn list_user_roles_by_user_id_and_version(
&self,
user_id: &str,
version: enums::UserRoleVersion,
@@ -70,7 +70,7 @@ pub trait UserRoleInterface {
version: enums::UserRoleVersion,
) -> CustomResult<storage::UserRole, errors::StorageError>;
- async fn list_user_roles(
+ async fn list_user_roles_by_user_id(
&self,
user_id: &str,
org_id: Option<&id_type::OrganizationId>,
@@ -79,6 +79,19 @@ pub trait UserRoleInterface {
entity_id: Option<&String>,
version: Option<enums::UserRoleVersion>,
) -> CustomResult<Vec<storage::UserRole>, errors::StorageError>;
+
+ async fn list_user_roles_by_org_id<'a>(
+ &self,
+ payload: ListUserRolesByOrgIdPayload<'a>,
+ ) -> CustomResult<Vec<storage::UserRole>, errors::StorageError>;
+}
+
+pub struct ListUserRolesByOrgIdPayload<'a> {
+ pub user_id: Option<&'a String>,
+ pub org_id: &'a id_type::OrganizationId,
+ pub merchant_id: Option<&'a id_type::MerchantId>,
+ pub profile_id: Option<&'a id_type::ProfileId>,
+ pub version: Option<enums::UserRoleVersion>,
}
#[async_trait::async_trait]
@@ -126,7 +139,7 @@ impl UserRoleInterface for Store {
}
#[instrument(skip_all)]
- async fn list_user_roles_by_user_id(
+ async fn list_user_roles_by_user_id_and_version(
&self,
user_id: &str,
version: enums::UserRoleVersion,
@@ -217,7 +230,7 @@ impl UserRoleInterface for Store {
.map_err(|error| report!(errors::StorageError::from(error)))
}
- async fn list_user_roles(
+ async fn list_user_roles_by_user_id(
&self,
user_id: &str,
org_id: Option<&id_type::OrganizationId>,
@@ -227,7 +240,7 @@ impl UserRoleInterface for Store {
version: Option<enums::UserRoleVersion>,
) -> CustomResult<Vec<storage::UserRole>, errors::StorageError> {
let conn = connection::pg_connection_read(self).await?;
- storage::UserRole::generic_user_roles_list(
+ storage::UserRole::generic_user_roles_list_for_user(
&conn,
user_id.to_owned(),
org_id.cloned(),
@@ -239,6 +252,23 @@ impl UserRoleInterface for Store {
.await
.map_err(|error| report!(errors::StorageError::from(error)))
}
+
+ async fn list_user_roles_by_org_id<'a>(
+ &self,
+ payload: ListUserRolesByOrgIdPayload<'a>,
+ ) -> CustomResult<Vec<storage::UserRole>, errors::StorageError> {
+ let conn = connection::pg_connection_read(self).await?;
+ storage::UserRole::generic_user_roles_list_for_org_and_extra(
+ &conn,
+ payload.user_id.cloned(),
+ payload.org_id.to_owned(),
+ payload.merchant_id.cloned(),
+ payload.profile_id.cloned(),
+ payload.version,
+ )
+ .await
+ .map_err(|error| report!(errors::StorageError::from(error)))
+ }
}
#[async_trait::async_trait]
@@ -328,7 +358,7 @@ impl UserRoleInterface for MockDb {
.into())
}
- async fn list_user_roles_by_user_id(
+ async fn list_user_roles_by_user_id_and_version(
&self,
user_id: &str,
version: enums::UserRoleVersion,
@@ -505,7 +535,7 @@ impl UserRoleInterface for MockDb {
}
}
- async fn list_user_roles(
+ async fn list_user_roles_by_user_id(
&self,
user_id: &str,
org_id: Option<&id_type::OrganizationId>,
@@ -551,4 +581,48 @@ impl UserRoleInterface for MockDb {
Ok(filtered_roles)
}
+
+ async fn list_user_roles_by_org_id<'a>(
+ &self,
+ payload: ListUserRolesByOrgIdPayload<'a>,
+ ) -> CustomResult<Vec<storage::UserRole>, errors::StorageError> {
+ let user_roles = self.user_roles.lock().await;
+
+ let mut filtered_roles = Vec::new();
+
+ for role in user_roles.iter() {
+ let role_org_id = role
+ .org_id
+ .as_ref()
+ .ok_or(report!(errors::StorageError::MockDbError))?;
+
+ let mut filter_condition = role_org_id == payload.org_id;
+
+ if let Some(user_id) = payload.user_id {
+ filter_condition = filter_condition && user_id == &role.user_id
+ }
+
+ role.merchant_id.as_ref().zip(payload.merchant_id).inspect(
+ |(role_merchant_id, merchant_id)| {
+ filter_condition = filter_condition && role_merchant_id == merchant_id
+ },
+ );
+
+ role.profile_id.as_ref().zip(payload.profile_id).inspect(
+ |(role_profile_id, profile_id)| {
+ filter_condition = filter_condition && role_profile_id == profile_id
+ },
+ );
+
+ payload
+ .version
+ .inspect(|ver| filter_condition = filter_condition && ver == &role.version);
+
+ if filter_condition {
+ filtered_roles.push(role.clone())
+ }
+ }
+
+ Ok(filtered_roles)
+ }
}
diff --git a/crates/router/src/routes/app.rs b/crates/router/src/routes/app.rs
index 97042485d6b..32bcc34d6bb 100644
--- a/crates/router/src/routes/app.rs
+++ b/crates/router/src/routes/app.rs
@@ -1799,6 +1799,7 @@ impl User {
.service(
web::resource("/list").route(web::get().to(list_users_for_merchant_account)),
)
+ .service(web::resource("/v2/list").route(web::get().to(list_users_in_lineage)))
.service(
web::resource("/invite_multiple").route(web::post().to(invite_multiple_user)),
)
diff --git a/crates/router/src/routes/lock_utils.rs b/crates/router/src/routes/lock_utils.rs
index f64fab1f408..f2a1d7e3458 100644
--- a/crates/router/src/routes/lock_utils.rs
+++ b/crates/router/src/routes/lock_utils.rs
@@ -263,7 +263,8 @@ impl From<Flow> for ApiIdentifier {
| Flow::DeleteUserRole
| Flow::CreateRole
| Flow::UpdateRole
- | Flow::UserFromEmail => Self::UserRole,
+ | Flow::UserFromEmail
+ | Flow::ListUsersInLineage => Self::UserRole,
Flow::GetActionUrl | Flow::SyncOnboardingStatus | Flow::ResetTrackingId => {
Self::ConnectorOnboarding
diff --git a/crates/router/src/routes/user_role.rs b/crates/router/src/routes/user_role.rs
index 526722af98c..a730321e190 100644
--- a/crates/router/src/routes/user_role.rs
+++ b/crates/router/src/routes/user_role.rs
@@ -269,3 +269,20 @@ pub async fn get_role_information(
))
.await
}
+
+pub async fn list_users_in_lineage(state: web::Data<AppState>, req: HttpRequest) -> HttpResponse {
+ let flow = Flow::ListUsersInLineage;
+
+ Box::pin(api::server_wrap(
+ flow,
+ state.clone(),
+ &req,
+ (),
+ |state, user_from_token, _, _| {
+ user_role_core::list_users_in_lineage(state, user_from_token)
+ },
+ &auth::DashboardNoPermissionAuth,
+ api_locking::LockAction::NotApplicable,
+ ))
+ .await
+}
diff --git a/crates/router/src/services/authorization/roles/predefined_roles.rs b/crates/router/src/services/authorization/roles/predefined_roles.rs
index 2f67af9f23a..f5320c41335 100644
--- a/crates/router/src/services/authorization/roles/predefined_roles.rs
+++ b/crates/router/src/services/authorization/roles/predefined_roles.rs
@@ -9,7 +9,7 @@ use crate::consts;
pub static PREDEFINED_ROLES: Lazy<HashMap<&'static str, RoleInfo>> = Lazy::new(|| {
let mut roles = HashMap::new();
roles.insert(
- consts::user_role::ROLE_ID_INTERNAL_ADMIN,
+ common_utils::consts::ROLE_ID_INTERNAL_ADMIN,
RoleInfo {
groups: vec![
PermissionGroup::OperationsView,
@@ -25,7 +25,7 @@ pub static PREDEFINED_ROLES: Lazy<HashMap<&'static str, RoleInfo>> = Lazy::new(|
PermissionGroup::MerchantDetailsManage,
PermissionGroup::OrganizationManage,
],
- role_id: consts::user_role::ROLE_ID_INTERNAL_ADMIN.to_string(),
+ role_id: common_utils::consts::ROLE_ID_INTERNAL_ADMIN.to_string(),
role_name: "internal_admin".to_string(),
scope: RoleScope::Organization,
entity_type: EntityType::Internal,
@@ -36,7 +36,7 @@ pub static PREDEFINED_ROLES: Lazy<HashMap<&'static str, RoleInfo>> = Lazy::new(|
},
);
roles.insert(
- consts::user_role::ROLE_ID_INTERNAL_VIEW_ONLY_USER,
+ common_utils::consts::ROLE_ID_INTERNAL_VIEW_ONLY_USER,
RoleInfo {
groups: vec![
PermissionGroup::OperationsView,
@@ -46,7 +46,7 @@ pub static PREDEFINED_ROLES: Lazy<HashMap<&'static str, RoleInfo>> = Lazy::new(|
PermissionGroup::UsersView,
PermissionGroup::MerchantDetailsView,
],
- role_id: consts::user_role::ROLE_ID_INTERNAL_VIEW_ONLY_USER.to_string(),
+ role_id: common_utils::consts::ROLE_ID_INTERNAL_VIEW_ONLY_USER.to_string(),
role_name: "internal_view_only".to_string(),
scope: RoleScope::Organization,
entity_type: EntityType::Internal,
@@ -58,7 +58,7 @@ pub static PREDEFINED_ROLES: Lazy<HashMap<&'static str, RoleInfo>> = Lazy::new(|
);
roles.insert(
- consts::user_role::ROLE_ID_ORGANIZATION_ADMIN,
+ common_utils::consts::ROLE_ID_ORGANIZATION_ADMIN,
RoleInfo {
groups: vec![
PermissionGroup::OperationsView,
@@ -74,7 +74,7 @@ pub static PREDEFINED_ROLES: Lazy<HashMap<&'static str, RoleInfo>> = Lazy::new(|
PermissionGroup::MerchantDetailsManage,
PermissionGroup::OrganizationManage,
],
- role_id: consts::user_role::ROLE_ID_ORGANIZATION_ADMIN.to_string(),
+ role_id: common_utils::consts::ROLE_ID_ORGANIZATION_ADMIN.to_string(),
role_name: "organization_admin".to_string(),
scope: RoleScope::Organization,
entity_type: EntityType::Organization,
diff --git a/crates/router/src/types/domain/user.rs b/crates/router/src/types/domain/user.rs
index 3df0a11af0e..b252e618536 100644
--- a/crates/router/src/types/domain/user.rs
+++ b/crates/router/src/types/domain/user.rs
@@ -868,7 +868,7 @@ impl UserFromStorage {
pub async fn get_roles_from_db(&self, state: &SessionState) -> UserResult<Vec<UserRole>> {
state
.store
- .list_user_roles_by_user_id(&self.0.user_id, UserRoleVersion::V1)
+ .list_user_roles_by_user_id_and_version(&self.0.user_id, UserRoleVersion::V1)
.await
.change_context(UserErrors::InternalServerError)
}
@@ -949,7 +949,7 @@ impl UserFromStorage {
} else {
state
.store
- .list_user_roles_by_user_id(&self.0.user_id, UserRoleVersion::V1)
+ .list_user_roles_by_user_id_and_version(&self.0.user_id, UserRoleVersion::V1)
.await?
.into_iter()
.find(|role| role.status == UserStatus::Active)
diff --git a/crates/router_env/src/logger/types.rs b/crates/router_env/src/logger/types.rs
index 88eec0f791a..538ae888cd5 100644
--- a/crates/router_env/src/logger/types.rs
+++ b/crates/router_env/src/logger/types.rs
@@ -466,6 +466,8 @@ pub enum Flow {
ListMerchantsForUserInOrg,
/// List Profile for user in org and merchant
ListProfileForUserInOrgAndMerchant,
+ /// List Users in Org
+ ListUsersInLineage,
/// List initial webhook delivery attempts
WebhookEventInitialDeliveryAttemptList,
/// List delivery attempts for a webhook event
|
2024-08-27T12:46:32Z
|
## Type of Change
<!-- Put an `x` in the boxes that apply -->
- [ ] Bugfix
- [x] New feature
- [ ] Enhancement
- [ ] Refactoring
- [ ] Dependency updates
- [ ] Documentation
- [ ] CI/CD
## Description
<!-- Describe your changes in detail -->
- This PR adds a new API which will be used to list the users in the lineage.
- This PR also adds a db function for listing users in a particular org.
### Additional Changes
- [x] This PR modifies the API contract
- [ ] This PR modifies the database schema
- [ ] This PR modifies application configuration/environment variables
<!--
Provide links to the files with corresponding changes.
Following are the paths where you can find config files:
1. `config`
2. `crates/router/src/configs`
3. `loadtest/config`
-->
## Motivation and Context
<!--
Why is this change required? What problem does it solve?
If it fixes an open issue, please link to the issue here.
If you don't have an issue, we'd recommend starting with one first so the PR
can focus on the implementation (unless it is an obvious bug or documentation fix
that will have little conversation).
-->
Closes #5721.
## How did you test it?
<!--
Did you write an integration/unit/API test to verify the code changes?
Or did you test this change manually (provide relevant screenshots)?
-->
```
curl --location 'http://localhost:8080/user/user/v2/list' \
--header 'Authorization: ••••••' \
```
If the JWT is of `org_admin`, it will list all the users in the org, else it will list all the users in merchant.
## Checklist
<!-- Put an `x` in the boxes that apply -->
- [x] I formatted the code `cargo +nightly fmt --all`
- [x] I addressed lints thrown by `cargo clippy`
- [x] I reviewed the submitted code
- [ ] I added unit tests for my changes where possible
|
32dd3f97ad094344d8bfe95f7cdcb5cff891990f
|
|
juspay/hyperswitch
|
juspay__hyperswitch-5697
|
Bug: [FEATURE] Open api for routing v2
### Feature Description
Open api for routing v2
### Possible Implementation
Open api for routing v2
### Have you spent some time checking if this feature request has been raised before?
- [X] I checked and didn't find a similar issue
### Have you read the Contributing Guidelines?
- [X] I have read the [Contributing Guidelines](https://github.com/juspay/hyperswitch/blob/main/docs/CONTRIBUTING.md)
### Are you willing to submit a PR?
Yes, I am willing to submit a PR!
|
diff --git a/api-reference-v2/api-reference/business-profile/business-profile--activate-routing-algorithm.mdx b/api-reference-v2/api-reference/business-profile/business-profile--activate-routing-algorithm.mdx
new file mode 100644
index 00000000000..9ff6f4fdd57
--- /dev/null
+++ b/api-reference-v2/api-reference/business-profile/business-profile--activate-routing-algorithm.mdx
@@ -0,0 +1,3 @@
+---
+openapi: patch /v2/profiles/{profile_id}/activate_routing_algorithm
+---
\ No newline at end of file
diff --git a/api-reference-v2/api-reference/business-profile/business-profile--deactivate-routing-algorithm.mdx b/api-reference-v2/api-reference/business-profile/business-profile--deactivate-routing-algorithm.mdx
new file mode 100644
index 00000000000..5cc815612e0
--- /dev/null
+++ b/api-reference-v2/api-reference/business-profile/business-profile--deactivate-routing-algorithm.mdx
@@ -0,0 +1,3 @@
+---
+openapi: patch /v2/profiles/{profile_id}/deactivate_routing_algorithm
+---
\ No newline at end of file
diff --git a/api-reference-v2/api-reference/business-profile/business-profile--retrieve-active-routing-algorithm.mdx b/api-reference-v2/api-reference/business-profile/business-profile--retrieve-active-routing-algorithm.mdx
new file mode 100644
index 00000000000..7aba27485ed
--- /dev/null
+++ b/api-reference-v2/api-reference/business-profile/business-profile--retrieve-active-routing-algorithm.mdx
@@ -0,0 +1,3 @@
+---
+openapi: get /v2/profiles/{profile_id}/routing_algorithm
+---
\ No newline at end of file
diff --git a/api-reference-v2/api-reference/business-profile/business-profile--retrieve-default-fallback-routing-algorithm.mdx b/api-reference-v2/api-reference/business-profile/business-profile--retrieve-default-fallback-routing-algorithm.mdx
new file mode 100644
index 00000000000..9b1b9429077
--- /dev/null
+++ b/api-reference-v2/api-reference/business-profile/business-profile--retrieve-default-fallback-routing-algorithm.mdx
@@ -0,0 +1,3 @@
+---
+openapi: get /v2/profiles/{profile_id}/fallback_routing
+---
\ No newline at end of file
diff --git a/api-reference-v2/api-reference/business-profile/business-profile--update-default-fallback-routing-algorithm.mdx b/api-reference-v2/api-reference/business-profile/business-profile--update-default-fallback-routing-algorithm.mdx
new file mode 100644
index 00000000000..ca4cb5f8fe2
--- /dev/null
+++ b/api-reference-v2/api-reference/business-profile/business-profile--update-default-fallback-routing-algorithm.mdx
@@ -0,0 +1,3 @@
+---
+openapi: post /v2/profiles/{profile_id}/fallback_routing
+---
\ No newline at end of file
diff --git a/api-reference-v2/api-reference/routing/routing--create.mdx b/api-reference-v2/api-reference/routing/routing--create.mdx
new file mode 100644
index 00000000000..65ef15008f2
--- /dev/null
+++ b/api-reference-v2/api-reference/routing/routing--create.mdx
@@ -0,0 +1,3 @@
+---
+openapi: post /v2/routing_algorithm
+---
\ No newline at end of file
diff --git a/api-reference-v2/api-reference/routing/routing--retrieve.mdx b/api-reference-v2/api-reference/routing/routing--retrieve.mdx
new file mode 100644
index 00000000000..03f209951c0
--- /dev/null
+++ b/api-reference-v2/api-reference/routing/routing--retrieve.mdx
@@ -0,0 +1,3 @@
+---
+openapi: get /v2/routing_algorithm/{routing_algorithm_id}
+---
\ No newline at end of file
diff --git a/api-reference-v2/mint.json b/api-reference-v2/mint.json
index b93e4e60006..27bc39d0762 100644
--- a/api-reference-v2/mint.json
+++ b/api-reference-v2/mint.json
@@ -63,7 +63,19 @@
"pages": [
"api-reference/business-profile/business-profile--create",
"api-reference/business-profile/business-profile--update",
- "api-reference/business-profile/business-profile--retrieve"
+ "api-reference/business-profile/business-profile--retrieve",
+ "api-reference/business-profile/business-profile--activate-routing-algorithm",
+ "api-reference/business-profile/business-profile--retrieve-active-routing-algorithm",
+ "api-reference/business-profile/business-profile--deactivate-routing-algorithm",
+ "api-reference/business-profile/business-profile--update-default-fallback-routing-algorithm",
+ "api-reference/business-profile/business-profile--retrieve-default-fallback-routing-algorithm"
+ ]
+ },
+ {
+ "group": "Routing",
+ "pages": [
+ "api-reference/routing/routing--create",
+ "api-reference/routing/routing--retrieve"
]
}
],
diff --git a/api-reference-v2/openapi_spec.json b/api-reference-v2/openapi_spec.json
index f0be48afecd..bdbdd9aec77 100644
--- a/api-reference-v2/openapi_spec.json
+++ b/api-reference-v2/openapi_spec.json
@@ -718,6 +718,416 @@
}
]
}
+ },
+ "/v2/profiles/{profile_id}/activate_routing_algorithm": {
+ "patch": {
+ "tags": [
+ "Business Profile"
+ ],
+ "summary": "Business Profile - Activate routing algorithm",
+ "description": "Business Profile - Activate routing algorithm\n\nActivates a routing algorithm under a business profile",
+ "operationId": "Activates a routing algorithm under a business profile",
+ "parameters": [
+ {
+ "name": "profile_id",
+ "in": "path",
+ "description": "The unique identifier for the business profile",
+ "required": true,
+ "schema": {
+ "type": "string"
+ }
+ }
+ ],
+ "requestBody": {
+ "content": {
+ "application/json": {
+ "schema": {
+ "$ref": "#/components/schemas/RoutingAlgorithmId"
+ },
+ "examples": {
+ "Activate a routing algorithm": {
+ "value": {
+ "routing_algorithm_id": "routing_algorithm_123"
+ }
+ }
+ }
+ }
+ },
+ "required": true
+ },
+ "responses": {
+ "200": {
+ "description": "Routing Algorithm is activated",
+ "content": {
+ "application/json": {
+ "schema": {
+ "$ref": "#/components/schemas/RoutingDictionaryRecord"
+ }
+ }
+ }
+ },
+ "400": {
+ "description": "Bad request"
+ },
+ "404": {
+ "description": "Resource missing"
+ },
+ "500": {
+ "description": "Internal server error"
+ }
+ },
+ "security": [
+ {
+ "api_key": []
+ },
+ {
+ "jwt_key": []
+ }
+ ]
+ }
+ },
+ "/v2/profiles/{profile_id}/deactivate_routing_algorithm": {
+ "patch": {
+ "tags": [
+ "Business Profile"
+ ],
+ "summary": "Business Profile - Deactivate routing algorithm",
+ "description": "Business Profile - Deactivate routing algorithm\n\nDeactivates a routing algorithm under a business profile",
+ "operationId": " Deactivates a routing algorithm under a business profile",
+ "parameters": [
+ {
+ "name": "profile_id",
+ "in": "path",
+ "description": "The unique identifier for the business profile",
+ "required": true,
+ "schema": {
+ "type": "string"
+ }
+ }
+ ],
+ "responses": {
+ "200": {
+ "description": "Successfully deactivated routing config",
+ "content": {
+ "application/json": {
+ "schema": {
+ "$ref": "#/components/schemas/RoutingDictionaryRecord"
+ }
+ }
+ }
+ },
+ "400": {
+ "description": "Malformed request"
+ },
+ "403": {
+ "description": "Malformed request"
+ },
+ "422": {
+ "description": "Unprocessable request"
+ },
+ "500": {
+ "description": "Internal server error"
+ }
+ },
+ "security": [
+ {
+ "api_key": []
+ },
+ {
+ "jwt_key": []
+ }
+ ]
+ }
+ },
+ "/v2/profiles/{profile_id}/fallback_routing": {
+ "post": {
+ "tags": [
+ "Business Profile"
+ ],
+ "summary": "Business Profile - Update Default Fallback Routing Algorithm",
+ "description": "Business Profile - Update Default Fallback Routing Algorithm\n\nUpdate the default fallback routing algorithm for the business profile",
+ "operationId": "Update the default fallback routing algorithm for the business profile",
+ "parameters": [
+ {
+ "name": "profile_id",
+ "in": "path",
+ "description": "The unique identifier for the business profile",
+ "required": true,
+ "schema": {
+ "type": "string"
+ }
+ }
+ ],
+ "requestBody": {
+ "content": {
+ "application/json": {
+ "schema": {
+ "type": "array",
+ "items": {
+ "$ref": "#/components/schemas/RoutableConnectorChoice"
+ }
+ }
+ }
+ },
+ "required": true
+ },
+ "responses": {
+ "200": {
+ "description": "Successfully updated the default fallback routing algorithm",
+ "content": {
+ "application/json": {
+ "schema": {
+ "type": "array",
+ "items": {
+ "$ref": "#/components/schemas/RoutableConnectorChoice"
+ }
+ }
+ }
+ }
+ },
+ "400": {
+ "description": "Malformed request"
+ },
+ "422": {
+ "description": "Unprocessable request"
+ },
+ "500": {
+ "description": "Internal server error"
+ }
+ },
+ "security": [
+ {
+ "api_key": []
+ },
+ {
+ "jwt_key": []
+ }
+ ]
+ },
+ "get": {
+ "tags": [
+ "Business Profile"
+ ],
+ "summary": "Business Profile - Retrieve Default Fallback Routing Algorithm",
+ "description": "Business Profile - Retrieve Default Fallback Routing Algorithm\n\nRetrieve the default fallback routing algorithm for the business profile",
+ "operationId": "Retrieve the default fallback routing algorithm for the business profile",
+ "parameters": [
+ {
+ "name": "profile_id",
+ "in": "path",
+ "description": "The unique identifier for the business profile",
+ "required": true,
+ "schema": {
+ "type": "string"
+ }
+ }
+ ],
+ "responses": {
+ "200": {
+ "description": "Successfully retrieved default fallback routing algorithm",
+ "content": {
+ "application/json": {
+ "schema": {
+ "type": "array",
+ "items": {
+ "$ref": "#/components/schemas/RoutableConnectorChoice"
+ }
+ }
+ }
+ }
+ },
+ "500": {
+ "description": "Internal server error"
+ }
+ },
+ "security": [
+ {
+ "api_key": []
+ },
+ {
+ "jwt_key": []
+ }
+ ]
+ }
+ },
+ "/v2/profiles/{profile_id}/routing_algorithm": {
+ "get": {
+ "tags": [
+ "Business Profile"
+ ],
+ "summary": "Business Profile - Retrieve Active Routing Algorithm",
+ "description": "Business Profile - Retrieve Active Routing Algorithm\n\nRetrieve active routing algorithm under the business profile",
+ "operationId": "Retrieve the active routing algorithm under the business profile",
+ "parameters": [
+ {
+ "name": "profile_id",
+ "in": "path",
+ "description": "The unique identifier for the business profile",
+ "required": true,
+ "schema": {
+ "type": "string"
+ }
+ },
+ {
+ "name": "limit",
+ "in": "query",
+ "description": "The number of records of the algorithms to be returned",
+ "required": false,
+ "schema": {
+ "type": "integer",
+ "format": "int32",
+ "nullable": true,
+ "minimum": 0
+ }
+ },
+ {
+ "name": "offset",
+ "in": "query",
+ "description": "The record offset of the algorithm from which to start gathering the results",
+ "required": false,
+ "schema": {
+ "type": "integer",
+ "format": "int32",
+ "nullable": true,
+ "minimum": 0
+ }
+ }
+ ],
+ "responses": {
+ "200": {
+ "description": "Successfully retrieved active config",
+ "content": {
+ "application/json": {
+ "schema": {
+ "$ref": "#/components/schemas/LinkedRoutingConfigRetrieveResponse"
+ }
+ }
+ }
+ },
+ "403": {
+ "description": "Forbidden"
+ },
+ "404": {
+ "description": "Resource missing"
+ },
+ "500": {
+ "description": "Internal server error"
+ }
+ },
+ "security": [
+ {
+ "api_key": []
+ },
+ {
+ "jwt_key": []
+ }
+ ]
+ }
+ },
+ "/v2/routing_algorithm": {
+ "post": {
+ "tags": [
+ "Routing"
+ ],
+ "summary": "Routing - Create",
+ "description": "Routing - Create\n\nCreate a routing algorithm",
+ "operationId": "Create a routing algprithm",
+ "requestBody": {
+ "content": {
+ "application/json": {
+ "schema": {
+ "$ref": "#/components/schemas/RoutingConfigRequest"
+ }
+ }
+ },
+ "required": true
+ },
+ "responses": {
+ "200": {
+ "description": "Routing Algorithm created",
+ "content": {
+ "application/json": {
+ "schema": {
+ "$ref": "#/components/schemas/RoutingDictionaryRecord"
+ }
+ }
+ }
+ },
+ "400": {
+ "description": "Request body is malformed"
+ },
+ "403": {
+ "description": "Forbidden"
+ },
+ "404": {
+ "description": "Resource missing"
+ },
+ "422": {
+ "description": "Unprocessable request"
+ },
+ "500": {
+ "description": "Internal server error"
+ }
+ },
+ "security": [
+ {
+ "api_key": []
+ },
+ {
+ "jwt_key": []
+ }
+ ]
+ }
+ },
+ "/v2/routing_algorithm/{routing_algorithm_id}": {
+ "get": {
+ "tags": [
+ "Routing"
+ ],
+ "summary": "Routing - Retrieve",
+ "description": "Routing - Retrieve\n\nRetrieve a routing algorithm with its algorithm id",
+ "operationId": "Retrieve a routing algorithm with its algorithm id",
+ "parameters": [
+ {
+ "name": "routing_algorithm_id",
+ "in": "path",
+ "description": "The unique identifier for a routing algorithm",
+ "required": true,
+ "schema": {
+ "type": "string"
+ }
+ }
+ ],
+ "responses": {
+ "200": {
+ "description": "Successfully fetched routing algorithm",
+ "content": {
+ "application/json": {
+ "schema": {
+ "$ref": "#/components/schemas/MerchantRoutingAlgorithm"
+ }
+ }
+ }
+ },
+ "403": {
+ "description": "Forbidden"
+ },
+ "404": {
+ "description": "Resource missing"
+ },
+ "500": {
+ "description": "Internal server error"
+ }
+ },
+ "security": [
+ {
+ "api_key": []
+ },
+ {
+ "jwt_key": []
+ }
+ ]
+ }
}
},
"components": {
@@ -16479,6 +16889,17 @@
"propertyName": "type"
}
},
+ "RoutingAlgorithmId": {
+ "type": "object",
+ "required": [
+ "routing_algorithm_id"
+ ],
+ "properties": {
+ "routing_algorithm_id": {
+ "type": "string"
+ }
+ }
+ },
"RoutingAlgorithmKind": {
"type": "string",
"enum": [
diff --git a/crates/api_models/src/routing.rs b/crates/api_models/src/routing.rs
index 04ca1fd4429..2c52f726c86 100644
--- a/crates/api_models/src/routing.rs
+++ b/crates/api_models/src/routing.rs
@@ -478,10 +478,10 @@ pub enum RoutingKind {
RoutingAlgorithm(Vec<RoutingDictionaryRecord>),
}
-#[repr(transparent)]
-#[derive(serde::Serialize, serde::Deserialize, Debug, Clone)]
-#[serde(transparent)]
-pub struct RoutingAlgorithmId(pub String);
+#[derive(serde::Serialize, serde::Deserialize, Debug, Clone, ToSchema)]
+pub struct RoutingAlgorithmId {
+ pub routing_algorithm_id: String,
+}
#[derive(Debug, Clone, serde::Serialize, serde::Deserialize)]
pub struct RoutingLinkWrapper {
diff --git a/crates/openapi/src/openapi_v2.rs b/crates/openapi/src/openapi_v2.rs
index f516839950c..2b02ec7f715 100644
--- a/crates/openapi/src/openapi_v2.rs
+++ b/crates/openapi/src/openapi_v2.rs
@@ -89,6 +89,17 @@ Never share your secret api keys. Keep them guarded and secure.
routes::business_profile::business_profile_create,
routes::business_profile::business_profile_retrieve,
routes::business_profile::business_profile_update,
+
+ // Routes for routing under business profile
+ routes::business_profile::routing_link_config,
+ routes::business_profile::routing_unlink_config,
+ routes::business_profile::routing_update_default_config,
+ routes::business_profile::routing_retrieve_default_config,
+ routes::business_profile::routing_retrieve_linked_config,
+
+ // Routes for routing
+ routes::routing::routing_create_config,
+ routes::routing::routing_retrieve_config,
),
components(schemas(
common_utils::types::MinorUnit,
@@ -452,6 +463,7 @@ Never share your secret api keys. Keep them guarded and secure.
api_models::routing::ast::ValueType,
api_models::routing::ast::MetadataValue,
api_models::routing::ast::NumberComparison,
+ api_models::routing::RoutingAlgorithmId,
api_models::payment_methods::RequestPaymentMethodTypes,
api_models::payments::PaymentLinkStatus,
api_models::blocklist::BlocklistRequest,
diff --git a/crates/openapi/src/routes/business_profile.rs b/crates/openapi/src/routes/business_profile.rs
index ac0a4c67768..07442f9757a 100644
--- a/crates/openapi/src/routes/business_profile.rs
+++ b/crates/openapi/src/routes/business_profile.rs
@@ -205,3 +205,121 @@ pub async fn business_profile_retrieve() {}
security(("admin_api_key" = []))
)]
pub async fn business_profile_retrieve() {}
+
+#[cfg(feature = "v2")]
+/// Business Profile - Retrieve Active Routing Algorithm
+///
+/// Retrieve active routing algorithm under the business profile
+#[utoipa::path(
+ get,
+ path = "/v2/profiles/{profile_id}/routing_algorithm",
+ params(
+ ("profile_id" = String, Path, description = "The unique identifier for the business profile"),
+ ("limit" = Option<u16>, Query, description = "The number of records of the algorithms to be returned"),
+ ("offset" = Option<u8>, Query, description = "The record offset of the algorithm from which to start gathering the results")),
+ responses(
+ (status = 200, description = "Successfully retrieved active config", body = LinkedRoutingConfigRetrieveResponse),
+ (status = 500, description = "Internal server error"),
+ (status = 404, description = "Resource missing"),
+ (status = 403, description = "Forbidden")
+ ),
+ tag = "Business Profile",
+ operation_id = "Retrieve the active routing algorithm under the business profile",
+ security(("api_key" = []), ("jwt_key" = []))
+)]
+pub async fn routing_retrieve_linked_config() {}
+#[cfg(feature = "v2")]
+/// Business Profile - Activate routing algorithm
+///
+/// Activates a routing algorithm under a business profile
+#[utoipa::path(
+ patch,
+ path = "/v2/profiles/{profile_id}/activate_routing_algorithm",
+ request_body ( content = RoutingAlgorithmId,
+ examples( (
+ "Activate a routing algorithm" = (
+ value = json!({
+ "routing_algorithm_id": "routing_algorithm_123"
+ })
+ )
+ ))),
+ params(
+ ("profile_id" = String, Path, description = "The unique identifier for the business profile"),
+ ),
+ responses(
+ (status = 200, description = "Routing Algorithm is activated", body = RoutingDictionaryRecord),
+ (status = 500, description = "Internal server error"),
+ (status = 404, description = "Resource missing"),
+ (status = 400, description = "Bad request")
+ ),
+ tag = "Business Profile",
+ operation_id = "Activates a routing algorithm under a business profile",
+ security(("api_key" = []), ("jwt_key" = []))
+)]
+pub async fn routing_link_config() {}
+
+#[cfg(feature = "v2")]
+/// Business Profile - Deactivate routing algorithm
+///
+/// Deactivates a routing algorithm under a business profile
+#[utoipa::path(
+ patch,
+ path = "/v2/profiles/{profile_id}/deactivate_routing_algorithm",
+ params(
+ ("profile_id" = String, Path, description = "The unique identifier for the business profile"),
+ ),
+ responses(
+ (status = 200, description = "Successfully deactivated routing config", body = RoutingDictionaryRecord),
+ (status = 500, description = "Internal server error"),
+ (status = 400, description = "Malformed request"),
+ (status = 403, description = "Malformed request"),
+ (status = 422, description = "Unprocessable request")
+ ),
+ tag = "Business Profile",
+ operation_id = " Deactivates a routing algorithm under a business profile",
+ security(("api_key" = []), ("jwt_key" = []))
+)]
+pub async fn routing_unlink_config() {}
+
+#[cfg(feature = "v2")]
+/// Business Profile - Update Default Fallback Routing Algorithm
+///
+/// Update the default fallback routing algorithm for the business profile
+#[utoipa::path(
+ post,
+ path = "/v2/profiles/{profile_id}/fallback_routing",
+ request_body = Vec<RoutableConnectorChoice>,
+ params(
+ ("profile_id" = String, Path, description = "The unique identifier for the business profile"),
+ ),
+ responses(
+ (status = 200, description = "Successfully updated the default fallback routing algorithm", body = Vec<RoutableConnectorChoice>),
+ (status = 500, description = "Internal server error"),
+ (status = 400, description = "Malformed request"),
+ (status = 422, description = "Unprocessable request")
+ ),
+ tag = "Business Profile",
+ operation_id = "Update the default fallback routing algorithm for the business profile",
+ security(("api_key" = []), ("jwt_key" = []))
+)]
+pub async fn routing_update_default_config() {}
+
+#[cfg(feature = "v2")]
+/// Business Profile - Retrieve Default Fallback Routing Algorithm
+///
+/// Retrieve the default fallback routing algorithm for the business profile
+#[utoipa::path(
+ get,
+ path = "/v2/profiles/{profile_id}/fallback_routing",
+ params(
+ ("profile_id" = String, Path, description = "The unique identifier for the business profile"),
+ ),
+ responses(
+ (status = 200, description = "Successfully retrieved default fallback routing algorithm", body = Vec<RoutableConnectorChoice>),
+ (status = 500, description = "Internal server error")
+ ),
+ tag = "Business Profile",
+ operation_id = "Retrieve the default fallback routing algorithm for the business profile",
+ security(("api_key" = []), ("jwt_key" = []))
+)]
+pub async fn routing_retrieve_default_config() {}
diff --git a/crates/openapi/src/routes/routing.rs b/crates/openapi/src/routes/routing.rs
index ecfac39f9e9..5e1e3f60c62 100644
--- a/crates/openapi/src/routes/routing.rs
+++ b/crates/openapi/src/routes/routing.rs
@@ -1,3 +1,4 @@
+#[cfg(feature = "v1")]
/// Routing - Create
///
/// Create a routing config
@@ -19,14 +20,37 @@
)]
pub async fn routing_create_config() {}
+#[cfg(feature = "v2")]
+/// Routing - Create
+///
+/// Create a routing algorithm
+#[utoipa::path(
+ post,
+ path = "/v2/routing_algorithm",
+ request_body = RoutingConfigRequest,
+ responses(
+ (status = 200, description = "Routing Algorithm created", body = RoutingDictionaryRecord),
+ (status = 400, description = "Request body is malformed"),
+ (status = 500, description = "Internal server error"),
+ (status = 404, description = "Resource missing"),
+ (status = 422, description = "Unprocessable request"),
+ (status = 403, description = "Forbidden"),
+ ),
+ tag = "Routing",
+ operation_id = "Create a routing algprithm",
+ security(("api_key" = []), ("jwt_key" = []))
+)]
+pub async fn routing_create_config() {}
+
+#[cfg(feature = "v1")]
/// Routing - Activate config
///
/// Activate a routing config
#[utoipa::path(
post,
- path = "/routing/{algorithm_id}/activate",
+ path = "/routing/{routing_algorithm_id}/activate",
params(
- ("algorithm_id" = String, Path, description = "The unique identifier for a config"),
+ ("routing_algorithm_id" = String, Path, description = "The unique identifier for a config"),
),
responses(
(status = 200, description = "Routing config activated", body = RoutingDictionaryRecord),
@@ -40,15 +64,16 @@ pub async fn routing_create_config() {}
)]
pub async fn routing_link_config() {}
+#[cfg(feature = "v1")]
/// Routing - Retrieve
///
/// Retrieve a routing algorithm
#[utoipa::path(
get,
- path = "/routing/{algorithm_id}",
+ path = "/routing/{routing_algorithm_id}",
params(
- ("algorithm_id" = String, Path, description = "The unique identifier for a config"),
+ ("routing_algorithm_id" = String, Path, description = "The unique identifier for a config"),
),
responses(
(status = 200, description = "Successfully fetched routing config", body = MerchantRoutingAlgorithm),
@@ -62,6 +87,30 @@ pub async fn routing_link_config() {}
)]
pub async fn routing_retrieve_config() {}
+#[cfg(feature = "v2")]
+/// Routing - Retrieve
+///
+/// Retrieve a routing algorithm with its algorithm id
+
+#[utoipa::path(
+ get,
+ path = "/v2/routing_algorithm/{routing_algorithm_id}",
+ params(
+ ("routing_algorithm_id" = String, Path, description = "The unique identifier for a routing algorithm"),
+ ),
+ responses(
+ (status = 200, description = "Successfully fetched routing algorithm", body = MerchantRoutingAlgorithm),
+ (status = 500, description = "Internal server error"),
+ (status = 404, description = "Resource missing"),
+ (status = 403, description = "Forbidden")
+ ),
+ tag = "Routing",
+ operation_id = "Retrieve a routing algorithm with its algorithm id",
+ security(("api_key" = []), ("jwt_key" = []))
+)]
+pub async fn routing_retrieve_config() {}
+
+#[cfg(feature = "v1")]
/// Routing - List
///
/// List all routing configs
@@ -84,6 +133,7 @@ pub async fn routing_retrieve_config() {}
)]
pub async fn list_routing_configs() {}
+#[cfg(feature = "v1")]
/// Routing - Deactivate
///
/// Deactivates a routing config
@@ -104,6 +154,7 @@ pub async fn list_routing_configs() {}
)]
pub async fn routing_unlink_config() {}
+#[cfg(feature = "v1")]
/// Routing - Update Default Config
///
/// Update default fallback config
@@ -123,6 +174,7 @@ pub async fn routing_unlink_config() {}
)]
pub async fn routing_update_default_config() {}
+#[cfg(feature = "v1")]
/// Routing - Retrieve Default Config
///
/// Retrieve default fallback config
@@ -139,6 +191,7 @@ pub async fn routing_update_default_config() {}
)]
pub async fn routing_retrieve_default_config() {}
+#[cfg(feature = "v1")]
/// Routing - Retrieve Config
///
/// Retrieve active config
@@ -160,6 +213,7 @@ pub async fn routing_retrieve_default_config() {}
)]
pub async fn routing_retrieve_linked_config() {}
+#[cfg(feature = "v1")]
/// Routing - Retrieve Default For Profile
///
/// Retrieve default config for profiles
@@ -177,6 +231,7 @@ pub async fn routing_retrieve_linked_config() {}
)]
pub async fn routing_retrieve_default_config_for_profiles() {}
+#[cfg(feature = "v1")]
/// Routing - Update Default For Profile
///
/// Update default config for profiles
diff --git a/crates/router/src/core/routing.rs b/crates/router/src/core/routing.rs
index 2b7f2d18306..640b12c52c2 100644
--- a/crates/router/src/core/routing.rs
+++ b/crates/router/src/core/routing.rs
@@ -424,7 +424,7 @@ pub async fn link_routing_config(
}
#[cfg(all(feature = "v2", feature = "routing_v2",))]
-pub async fn retrieve_active_routing_config(
+pub async fn retrieve_routing_algorithm_from_algorithm_id(
state: SessionState,
merchant_account: domain::MerchantAccount,
key_store: domain::MerchantKeyStore,
@@ -434,9 +434,12 @@ pub async fn retrieve_active_routing_config(
let db = state.store.as_ref();
let key_manager_state = &(&state).into();
- let routing_algorithm =
- RoutingAlgorithmUpdate::fetch_routing_algo(merchant_account.get_id(), &algorithm_id.0, db)
- .await?;
+ let routing_algorithm = RoutingAlgorithmUpdate::fetch_routing_algo(
+ merchant_account.get_id(),
+ &algorithm_id.routing_algorithm_id,
+ db,
+ )
+ .await?;
core_utils::validate_and_get_business_profile(
db,
key_manager_state,
@@ -457,7 +460,7 @@ pub async fn retrieve_active_routing_config(
}
#[cfg(all(any(feature = "v1", feature = "v2"), not(feature = "routing_v2")))]
-pub async fn retrieve_active_routing_config(
+pub async fn retrieve_routing_algorithm_from_algorithm_id(
state: SessionState,
merchant_account: domain::MerchantAccount,
key_store: domain::MerchantKeyStore,
@@ -469,7 +472,7 @@ pub async fn retrieve_active_routing_config(
let routing_algorithm = db
.find_routing_algorithm_by_algorithm_id_merchant_id(
- &algorithm_id.0,
+ &algorithm_id.routing_algorithm_id,
merchant_account.get_id(),
)
.await
diff --git a/crates/router/src/routes/routing.rs b/crates/router/src/routes/routing.rs
index 30edfc187b8..79e8ec11f21 100644
--- a/crates/router/src/routes/routing.rs
+++ b/crates/router/src/routes/routing.rs
@@ -69,12 +69,12 @@ pub async fn routing_link_config(
state,
&req,
path.into_inner(),
- |state, auth: auth::AuthenticationData, algorithm_id, _| {
+ |state, auth: auth::AuthenticationData, algorithm, _| {
routing::link_routing_config(
state,
auth.merchant_account,
auth.key_store,
- algorithm_id.0,
+ algorithm.routing_algorithm_id,
transaction_type,
)
},
@@ -117,7 +117,7 @@ pub async fn routing_link_config(
auth.merchant_account,
auth.key_store,
wrapper.profile_id,
- wrapper.algorithm_id.0,
+ wrapper.algorithm_id.routing_algorithm_id,
transaction_type,
)
},
@@ -149,7 +149,7 @@ pub async fn routing_retrieve_config(
&req,
algorithm_id,
|state, auth: auth::AuthenticationData, algorithm_id, _| {
- routing::retrieve_active_routing_config(
+ routing::retrieve_routing_algorithm_from_algorithm_id(
state,
auth.merchant_account,
auth.key_store,
|
2024-08-25T07:52:07Z
|
## Type of Change
<!-- Put an `x` in the boxes that apply -->
- [ ] Bugfix
- [x] New feature
- [ ] Enhancement
- [ ] Refactoring
- [ ] Dependency updates
- [ ] Documentation
- [ ] CI/CD
## Description
Add open api routes for routing v2
### Additional Changes
- [ ] This PR modifies the API contract
- [ ] This PR modifies the database schema
- [ ] This PR modifies application configuration/environment variables
<!--
Provide links to the files with corresponding changes.
Following are the paths where you can find config files:
1. `config`
2. `crates/router/src/configs`
3. `loadtest/config`
-->
## Motivation and Context
<!--
Why is this change required? What problem does it solve?
If it fixes an open issue, please link to the issue here.
If you don't have an issue, we'd recommend starting with one first so the PR
can focus on the implementation (unless it is an obvious bug or documentation fix
that will have little conversation).
-->
## How did you test it?
- Validated the open-api using this command
`swagger-cli validate ./api-reference-v2/openapi_spec.json`
./api-reference-v2/openapi_spec.json is valid
<img width="1728" alt="openapi" src="https://github.com/user-attachments/assets/5f067b84-edb8-4d38-8418-168b56ec6e3d">
## Checklist
<!-- Put an `x` in the boxes that apply -->
- [ ] I formatted the code `cargo +nightly fmt --all`
- [ ] I addressed lints thrown by `cargo clippy`
- [ ] I reviewed the submitted code
- [ ] I added unit tests for my changes where possible
|
b90ae90c668d4134d526f05d2cc7f988a11ed496
|
|
juspay/hyperswitch
|
juspay__hyperswitch-5708
|
Bug: [FEATURE] Add is_tax_conenctor_enabled boolean in pml response
### Feature Description
Add is_tax_conenctor_enabled boolean in pml response
### Possible Implementation
Get the is_tax_connector_enabled value from business_profile and pass it to pml response
### Have you spent some time checking if this feature request has been raised before?
- [X] I checked and didn't find a similar issue
### Have you read the Contributing Guidelines?
- [X] I have read the [Contributing Guidelines](https://github.com/juspay/hyperswitch/blob/main/docs/CONTRIBUTING.md)
### Are you willing to submit a PR?
Yes, I am willing to submit a PR!
|
diff --git a/api-reference-v2/openapi_spec.json b/api-reference-v2/openapi_spec.json
index 6b9ba4afd01..783d4751bc5 100644
--- a/api-reference-v2/openapi_spec.json
+++ b/api-reference-v2/openapi_spec.json
@@ -11073,7 +11073,8 @@
"payment_methods",
"mandate_payment",
"show_surcharge_breakup_screen",
- "request_external_three_ds_authentication"
+ "request_external_three_ds_authentication",
+ "is_tax_calculation_enabled"
],
"properties": {
"redirect_url": {
@@ -11135,6 +11136,10 @@
"type": "boolean",
"description": "flag that indicates whether to collect billing details from wallets or from the customer",
"nullable": true
+ },
+ "is_tax_calculation_enabled": {
+ "type": "boolean",
+ "description": "flag that indicates whether to calculate tax on the order amount"
}
}
},
@@ -11923,6 +11928,11 @@
"example": "Custom_Order_id_123",
"nullable": true,
"maxLength": 255
+ },
+ "skip_external_tax_calculation": {
+ "type": "boolean",
+ "description": "Whether to calculate tax for this payment intent",
+ "nullable": true
}
}
},
@@ -12288,6 +12298,11 @@
"example": "Custom_Order_id_123",
"nullable": true,
"maxLength": 255
+ },
+ "skip_external_tax_calculation": {
+ "type": "boolean",
+ "description": "Whether to calculate tax for this payment intent",
+ "nullable": true
}
}
},
@@ -13347,6 +13362,11 @@
"example": "Custom_Order_id_123",
"nullable": true,
"maxLength": 255
+ },
+ "skip_external_tax_calculation": {
+ "type": "boolean",
+ "description": "Whether to calculate tax for this payment intent",
+ "nullable": true
}
},
"additionalProperties": false
@@ -14355,6 +14375,11 @@
"example": "Custom_Order_id_123",
"nullable": true,
"maxLength": 255
+ },
+ "skip_external_tax_calculation": {
+ "type": "boolean",
+ "description": "Whether to calculate tax for this payment intent",
+ "nullable": true
}
}
},
diff --git a/crates/api_models/src/payment_methods.rs b/crates/api_models/src/payment_methods.rs
index 2204a7fc584..c6cf6380150 100644
--- a/crates/api_models/src/payment_methods.rs
+++ b/crates/api_models/src/payment_methods.rs
@@ -1482,6 +1482,9 @@ pub struct PaymentMethodListResponse {
/// flag that indicates whether to collect billing details from wallets or from the customer
pub collect_billing_details_from_wallets: Option<bool>,
+
+ /// flag that indicates whether to calculate tax on the order amount
+ pub is_tax_calculation_enabled: bool,
}
#[derive(Eq, PartialEq, Hash, Debug, serde::Deserialize, ToSchema)]
diff --git a/crates/api_models/src/payments.rs b/crates/api_models/src/payments.rs
index d512d487e5b..cd32c045f18 100644
--- a/crates/api_models/src/payments.rs
+++ b/crates/api_models/src/payments.rs
@@ -560,6 +560,9 @@ pub struct PaymentsRequest {
example = "Custom_Order_id_123"
)]
pub merchant_order_reference_id: Option<String>,
+
+ /// Whether to calculate tax for this payment intent
+ pub skip_external_tax_calculation: Option<bool>,
}
/// Checks if the inner values of two options are equal
diff --git a/crates/diesel_models/src/payment_intent.rs b/crates/diesel_models/src/payment_intent.rs
index c80e9e5f4da..b2f314a0fee 100644
--- a/crates/diesel_models/src/payment_intent.rs
+++ b/crates/diesel_models/src/payment_intent.rs
@@ -72,6 +72,7 @@ pub struct PaymentIntent {
pub shipping_cost: Option<MinorUnit>,
pub organization_id: common_utils::id_type::OrganizationId,
pub tax_details: Option<TaxDetails>,
+ pub skip_external_tax_calculation: Option<bool>,
}
#[cfg(all(any(feature = "v1", feature = "v2"), not(feature = "payment_v2")))]
@@ -136,6 +137,7 @@ pub struct PaymentIntent {
pub shipping_cost: Option<MinorUnit>,
pub organization_id: common_utils::id_type::OrganizationId,
pub tax_details: Option<TaxDetails>,
+ pub skip_external_tax_calculation: Option<bool>,
}
#[derive(Clone, Default, Debug, PartialEq, Serialize, Deserialize, diesel::AsExpression)]
@@ -219,6 +221,7 @@ pub struct PaymentIntentNew {
pub shipping_cost: Option<MinorUnit>,
pub organization_id: common_utils::id_type::OrganizationId,
pub tax_details: Option<TaxDetails>,
+ pub skip_external_tax_calculation: Option<bool>,
}
#[derive(Debug, Clone, Serialize, Deserialize)]
diff --git a/crates/diesel_models/src/schema.rs b/crates/diesel_models/src/schema.rs
index 213687431d4..8e6c72eb5ba 100644
--- a/crates/diesel_models/src/schema.rs
+++ b/crates/diesel_models/src/schema.rs
@@ -919,6 +919,7 @@ diesel::table! {
#[max_length = 32]
organization_id -> Varchar,
tax_details -> Nullable<Jsonb>,
+ skip_external_tax_calculation -> Nullable<Bool>,
}
}
diff --git a/crates/diesel_models/src/schema_v2.rs b/crates/diesel_models/src/schema_v2.rs
index de4adf7984f..2deaa3d4ee4 100644
--- a/crates/diesel_models/src/schema_v2.rs
+++ b/crates/diesel_models/src/schema_v2.rs
@@ -899,6 +899,7 @@ diesel::table! {
#[max_length = 32]
organization_id -> Varchar,
tax_details -> Nullable<Jsonb>,
+ skip_external_tax_calculation -> Nullable<Bool>,
}
}
diff --git a/crates/hyperswitch_domain_models/src/business_profile.rs b/crates/hyperswitch_domain_models/src/business_profile.rs
index cfc0d07e0c8..c6b76680d48 100644
--- a/crates/hyperswitch_domain_models/src/business_profile.rs
+++ b/crates/hyperswitch_domain_models/src/business_profile.rs
@@ -659,6 +659,14 @@ impl From<BusinessProfileSetter> for BusinessProfile {
}
impl BusinessProfile {
+ pub fn get_is_tax_connector_enabled(&self) -> bool {
+ let is_tax_connector_enabled = self.is_tax_connector_enabled;
+ match &self.tax_connector_id {
+ Some(_id) => is_tax_connector_enabled,
+ _ => false,
+ }
+ }
+
#[cfg(feature = "v1")]
pub fn get_order_fulfillment_time(&self) -> Option<i64> {
self.intent_fulfillment_time
diff --git a/crates/hyperswitch_domain_models/src/payments.rs b/crates/hyperswitch_domain_models/src/payments.rs
index 1365a7f082c..14d7e43450d 100644
--- a/crates/hyperswitch_domain_models/src/payments.rs
+++ b/crates/hyperswitch_domain_models/src/payments.rs
@@ -71,4 +71,5 @@ pub struct PaymentIntent {
pub is_payment_processor_token_flow: Option<bool>,
pub organization_id: id_type::OrganizationId,
pub tax_details: Option<TaxDetails>,
+ pub skip_external_tax_calculation: Option<bool>,
}
diff --git a/crates/hyperswitch_domain_models/src/payments/payment_attempt.rs b/crates/hyperswitch_domain_models/src/payments/payment_attempt.rs
index 4c2a67ff126..c9854c07857 100644
--- a/crates/hyperswitch_domain_models/src/payments/payment_attempt.rs
+++ b/crates/hyperswitch_domain_models/src/payments/payment_attempt.rs
@@ -550,6 +550,7 @@ impl behaviour::Conversion for PaymentIntent {
organization_id: self.organization_id,
shipping_cost: self.shipping_cost,
tax_details: self.tax_details,
+ skip_external_tax_calculation: self.skip_external_tax_calculation,
})
}
async fn convert_back(
@@ -635,6 +636,7 @@ impl behaviour::Conversion for PaymentIntent {
organization_id: storage_model.organization_id,
shipping_cost: storage_model.shipping_cost,
tax_details: storage_model.tax_details,
+ skip_external_tax_calculation: storage_model.skip_external_tax_calculation,
})
}
.await
@@ -696,6 +698,7 @@ impl behaviour::Conversion for PaymentIntent {
organization_id: self.organization_id,
shipping_cost: self.shipping_cost,
tax_details: self.tax_details,
+ skip_external_tax_calculation: self.skip_external_tax_calculation,
})
}
}
@@ -759,6 +762,7 @@ impl behaviour::Conversion for PaymentIntent {
organization_id: self.organization_id,
shipping_cost: self.shipping_cost,
tax_details: self.tax_details,
+ skip_external_tax_calculation: self.skip_external_tax_calculation,
})
}
@@ -845,6 +849,7 @@ impl behaviour::Conversion for PaymentIntent {
.await?,
is_payment_processor_token_flow: storage_model.is_payment_processor_token_flow,
organization_id: storage_model.organization_id,
+ skip_external_tax_calculation: storage_model.skip_external_tax_calculation,
})
}
.await
@@ -906,6 +911,7 @@ impl behaviour::Conversion for PaymentIntent {
organization_id: self.organization_id,
shipping_cost: self.shipping_cost,
tax_details: self.tax_details,
+ skip_external_tax_calculation: self.skip_external_tax_calculation,
})
}
}
diff --git a/crates/hyperswitch_domain_models/src/payments/payment_intent.rs b/crates/hyperswitch_domain_models/src/payments/payment_intent.rs
index 64403cf3b9c..2057d9ba42f 100644
--- a/crates/hyperswitch_domain_models/src/payments/payment_intent.rs
+++ b/crates/hyperswitch_domain_models/src/payments/payment_intent.rs
@@ -152,6 +152,7 @@ pub struct PaymentIntentNew {
pub shipping_details: Option<Encryptable<Secret<serde_json::Value>>>,
pub is_payment_processor_token_flow: Option<bool>,
pub organization_id: id_type::OrganizationId,
+ pub skip_external_tax_calculation: Option<bool>,
}
#[derive(Debug, Clone, Serialize)]
diff --git a/crates/router/src/core/payment_methods/cards.rs b/crates/router/src/core/payment_methods/cards.rs
index cee4e9d1dd2..c553840347d 100644
--- a/crates/router/src/core/payment_methods/cards.rs
+++ b/crates/router/src/core/payment_methods/cards.rs
@@ -3626,6 +3626,10 @@ pub async fn list_payment_methods(
});
}
let currency = payment_intent.as_ref().and_then(|pi| pi.currency);
+ let skip_external_tax_calculation = payment_intent
+ .as_ref()
+ .and_then(|intent| intent.skip_external_tax_calculation)
+ .unwrap_or(false);
let request_external_three_ds_authentication = payment_intent
.as_ref()
.and_then(|intent| intent.request_external_three_ds_authentication)
@@ -3670,6 +3674,10 @@ pub async fn list_payment_methods(
business_profile.collect_billing_details_from_wallet_connector
}));
+ let is_tax_connector_enabled = business_profile.as_ref().map_or(false, |business_profile| {
+ business_profile.get_is_tax_connector_enabled()
+ });
+
Ok(services::ApplicationResponse::Json(
api::PaymentMethodListResponse {
redirect_url: business_profile
@@ -3710,6 +3718,7 @@ pub async fn list_payment_methods(
request_external_three_ds_authentication,
collect_shipping_details_from_wallets,
collect_billing_details_from_wallets,
+ is_tax_calculation_enabled: is_tax_connector_enabled && !skip_external_tax_calculation,
},
))
}
diff --git a/crates/router/src/core/payments/helpers.rs b/crates/router/src/core/payments/helpers.rs
index fdec36d3b76..70055720d26 100644
--- a/crates/router/src/core/payments/helpers.rs
+++ b/crates/router/src/core/payments/helpers.rs
@@ -3105,6 +3105,7 @@ mod tests {
organization_id: id_type::OrganizationId::default(),
shipping_cost: None,
tax_details: None,
+ skip_external_tax_calculation: None,
};
let req_cs = Some("1".to_string());
assert!(authenticate_client_secret(req_cs.as_ref(), &payment_intent).is_ok());
@@ -3173,6 +3174,7 @@ mod tests {
organization_id: id_type::OrganizationId::default(),
shipping_cost: None,
tax_details: None,
+ skip_external_tax_calculation: None,
};
let req_cs = Some("1".to_string());
assert!(authenticate_client_secret(req_cs.as_ref(), &payment_intent,).is_err())
@@ -3239,6 +3241,7 @@ mod tests {
organization_id: id_type::OrganizationId::default(),
shipping_cost: None,
tax_details: None,
+ skip_external_tax_calculation: None,
};
let req_cs = Some("1".to_string());
assert!(authenticate_client_secret(req_cs.as_ref(), &payment_intent).is_err())
diff --git a/crates/router/src/core/payments/operations/payment_create.rs b/crates/router/src/core/payments/operations/payment_create.rs
index 257a3156bbc..9a662dc589b 100644
--- a/crates/router/src/core/payments/operations/payment_create.rs
+++ b/crates/router/src/core/payments/operations/payment_create.rs
@@ -1283,6 +1283,8 @@ impl PaymentCreate {
.change_context(errors::ApiErrorResponse::InternalServerError)
.attach_printable("Unable to encrypt customer details")?;
+ let skip_external_tax_calculation = request.skip_external_tax_calculation;
+
Ok(storage::PaymentIntent {
payment_id: payment_id.to_owned(),
merchant_id: merchant_account.get_id().to_owned(),
@@ -1338,6 +1340,7 @@ impl PaymentCreate {
organization_id: merchant_account.organization_id.clone(),
shipping_cost: request.shipping_cost,
tax_details: None,
+ skip_external_tax_calculation,
})
}
diff --git a/crates/router/src/utils/user/sample_data.rs b/crates/router/src/utils/user/sample_data.rs
index 07bfe74f1d5..32728fd8fcc 100644
--- a/crates/router/src/utils/user/sample_data.rs
+++ b/crates/router/src/utils/user/sample_data.rs
@@ -250,6 +250,7 @@ pub async fn generate_sample_data(
organization_id: org_id.clone(),
shipping_cost: None,
tax_details: None,
+ skip_external_tax_calculation: None,
};
let payment_attempt = PaymentAttemptBatchNew {
attempt_id: attempt_id.clone(),
diff --git a/migrations/2024-08-28-044317_add_skip_external_tax_calcualtion_in_payment_intent_table/down.sql b/migrations/2024-08-28-044317_add_skip_external_tax_calcualtion_in_payment_intent_table/down.sql
new file mode 100644
index 00000000000..4ca933a4e36
--- /dev/null
+++ b/migrations/2024-08-28-044317_add_skip_external_tax_calcualtion_in_payment_intent_table/down.sql
@@ -0,0 +1,2 @@
+-- This file should undo anything in `up.sql`
+ALTER TABLE payment_intent DROP COLUMN if EXISTS skip_external_tax_calculation;
\ No newline at end of file
diff --git a/migrations/2024-08-28-044317_add_skip_external_tax_calcualtion_in_payment_intent_table/up.sql b/migrations/2024-08-28-044317_add_skip_external_tax_calcualtion_in_payment_intent_table/up.sql
new file mode 100644
index 00000000000..cf185dcdb7a
--- /dev/null
+++ b/migrations/2024-08-28-044317_add_skip_external_tax_calcualtion_in_payment_intent_table/up.sql
@@ -0,0 +1,2 @@
+-- Your SQL goes here
+ALTER TABLE payment_intent ADD COLUMN IF NOT EXISTS skip_external_tax_calculation BOOLEAN;
\ No newline at end of file
|
2024-08-27T07:12:50Z
|
## Type of Change
<!-- Put an `x` in the boxes that apply -->
- [ ] Bugfix
- [x] New feature
- [ ] Enhancement
- [ ] Refactoring
- [ ] Dependency updates
- [ ] Documentation
- [ ] CI/CD
## Description
Added `skip_external_tax_calculation` boolean in payments create request that indicates whether tax to be calculated for this intent or not.
Added `is_tax_calculation_enabled` boolean value in `payment_methods_list` call response that checks both this `skip_external_tax_calculation` and `is_tax_connector_enabled` in business profile.
Payments create request:
```curl
curl --location 'http://localhost:8080/payments' \
--header 'Content-Type: application/json' \
--header 'Accept: application/json' \
--header 'api-key: dev_OcQoFePRNVjYvsA9YGWKITq1BEHtInBKEtW9IRbKyBbOaBjwc6WYGwuxnyBVuhZh' \
--data-raw '{
"amount": 1800,
"currency": "USD",
"confirm": false,
"capture_method": "automatic",
"customer_id": "cus_NwicjmCJbgafjhjfhHr6",
"capture_on": "2022-09-10T10:11:12Z",
"authentication_type": "three_ds",
"email": "guest@example.com",
"name": "John Doe",
"phone": "9123456789",
"phone_country_code": "+65",
"description": "Its my first payment request",
"return_url": "https://duck.com",
"statement_descriptor_name": "Juspay",
"statement_descriptor_suffix": "Router",
"payment_method": "pay_later",
"payment_method_type": "klarna",
"payment_experience": "invoke_sdk_client",
"payment_method_data": {
"pay_later": {
"klarna_sdk": {
"token": "65bfb654-ef2c-6b39-942e-ffdc9a105d3c"
}
}
},
"billing": {
"address": {
"line1": "444, Stelar Enclave",
"line2": "California",
"line3": "Groningen",
"city": "Groningen",
"state": "Groningen",
"zip": "94105",
"country": "US",
"first_name": "joseph",
"last_name": "Doe"
},
"phone": {
"number": "+4901761428434",
"country_code": "+1"
}
},
"shipping": {
"address": {
"line1": "444, Stelar Enclave",
"line2": "California",
"line3": "Groningen",
"city": "Groningen",
"state": "Groningen",
"zip": "94105",
"country": "US",
"first_name": "joseph",
"last_name": "Doe"
},
"phone": {
"number": "446681800",
"country_code": "+41"
}
},
"metadata": {},
"order_details": [
{
"product_name": "Apple iphone 15",
"quantity": 1,
"amount": 180000,
"account_name": "transaction_processing"
}
],
"browser_info": {
"user_agent": "Mozilla\/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit\/537.36 (KHTML, like Gecko) Chrome\/70.0.3538.110 Safari\/537.36",
"accept_header": "text\/html,application\/xhtml+xml,application\/xml;q=0.9,image\/webp,image\/apng,*\/*;q=0.8",
"language": "nl-NL",
"color_depth": 24,
"screen_height": 723,
"screen_width": 1536,
"time_zone": 0,
"java_enabled": true,
"java_script_enabled": true,
"ip_address": "128.0.0.1"
},
"skip_external_tax_calculation": true
}'
```
PML call response:
```json
{
"redirect_url": "https://google.com/success",
"currency": "USD",
"payment_methods": [
{
"payment_method": "pay_later",
"payment_method_types": [
{
"payment_method_type": "klarna",
"payment_experience": [
{
"payment_experience_type": "redirect_to_url",
"eligible_connectors": [
"klarna"
]
},
{
"payment_experience_type": "invoke_sdk_client",
"eligible_connectors": [
"klarna"
]
}
],
"card_networks": null,
"bank_names": null,
"bank_debits": null,
"bank_transfers": null,
"required_fields": {
"billing.address.country": {
"required_field": "payment_method_data.billing.address.country",
"display_name": "country",
"field_type": {
"user_address_country": {
"options": [
"AU",
"AT",
"BE",
"CA",
"CZ",
"DK",
"FI",
"FR",
"DE",
"GR",
"IE",
"IT",
"NL",
"NZ",
"NO",
"PL",
"PT",
"ES",
"SE",
"CH",
"GB",
"US"
]
}
},
"value": "US"
}
},
"surcharge_details": null,
"pm_auth_connector": null
}
]
}
],
"mandate_payment": null,
"merchant_name": "NewAge Retailer",
"show_surcharge_breakup_screen": false,
"payment_type": "normal",
"request_external_three_ds_authentication": false,
"collect_shipping_details_from_wallets": false,
"collect_billing_details_from_wallets": false,
"is_tax_calculation_enabled": false
}
```
We are preventing to update the value of `skip_external_tax_calculation` during payment update
### Additional Changes
- [x] This PR modifies the API contract
- [x] This PR modifies the database schema
- [ ] This PR modifies application configuration/environment variables
<!--
Provide links to the files with corresponding changes.
Following are the paths where you can find config files:
1. `config`
2. `crates/router/src/configs`
3. `loadtest/config`
-->
## Motivation and Context
<!--
Why is this change required? What problem does it solve?
If it fixes an open issue, please link to the issue here.
If you don't have an issue, we'd recommend starting with one first so the PR
can focus on the implementation (unless it is an obvious bug or documentation fix
that will have little conversation).
-->
## How did you test it?
<!--
Did you write an integration/unit/API test to verify the code changes?
Or did you test this change manually (provide relevant screenshots)?
-->
## Checklist
<!-- Put an `x` in the boxes that apply -->
- [x] I formatted the code `cargo +nightly fmt --all`
- [x] I addressed lints thrown by `cargo clippy`
- [x] I reviewed the submitted code
- [ ] I added unit tests for my changes where possible
|
21352cf875e360c808562a15fcbb8d8c6a27ae50
|
|
juspay/hyperswitch
|
juspay__hyperswitch-5694
|
Bug: Add org id to transaction tables
|
diff --git a/crates/analytics/docs/clickhouse/scripts/disputes.sql b/crates/analytics/docs/clickhouse/scripts/disputes.sql
index bb7472a4d54..3bd993d31cf 100644
--- a/crates/analytics/docs/clickhouse/scripts/disputes.sql
+++ b/crates/analytics/docs/clickhouse/scripts/disputes.sql
@@ -20,6 +20,7 @@ CREATE TABLE dispute_queue (
`evidence` Nullable(String),
`profile_id` Nullable(String),
`merchant_connector_id` Nullable(String),
+ `organization_id` String,
`sign_flag` Int8
) ENGINE = Kafka SETTINGS kafka_broker_list = 'kafka0:29092',
kafka_topic_list = 'hyperswitch-dispute-events',
@@ -50,6 +51,7 @@ CREATE TABLE dispute (
`profile_id` Nullable(String),
`merchant_connector_id` Nullable(String),
`inserted_at` DateTime DEFAULT now() CODEC(T64, LZ4),
+ `organization_id` String,
`sign_flag` Int8,
INDEX connectorIndex connector TYPE bloom_filter GRANULARITY 1,
INDEX disputeStatusIndex dispute_status TYPE bloom_filter GRANULARITY 1,
@@ -80,6 +82,7 @@ CREATE MATERIALIZED VIEW dispute_mv TO dispute (
`evidence` Nullable(String),
`profile_id` Nullable(String),
`merchant_connector_id` Nullable(String),
+ `organization_id` String,
`inserted_at` DateTime64(3),
`sign_flag` Int8
) AS
@@ -105,6 +108,7 @@ SELECT
evidence,
profile_id,
merchant_connector_id,
+ organization_id,
now() AS inserted_at,
sign_flag
FROM
diff --git a/crates/analytics/docs/clickhouse/scripts/payment_attempts.sql b/crates/analytics/docs/clickhouse/scripts/payment_attempts.sql
index 223d29c9836..5c1ee8754c9 100644
--- a/crates/analytics/docs/clickhouse/scripts/payment_attempts.sql
+++ b/crates/analytics/docs/clickhouse/scripts/payment_attempts.sql
@@ -40,6 +40,8 @@ CREATE TABLE payment_attempt_queue (
`mandate_data` Nullable(String),
`client_source` LowCardinality(Nullable(String)),
`client_version` LowCardinality(Nullable(String)),
+ `organization_id` String,
+ `profile_id` String,
`sign_flag` Int8
) ENGINE = Kafka SETTINGS kafka_broker_list = 'kafka0:29092',
kafka_topic_list = 'hyperswitch-payment-attempt-events',
@@ -90,6 +92,8 @@ CREATE TABLE payment_attempts (
`inserted_at` DateTime DEFAULT now() CODEC(T64, LZ4),
`client_source` LowCardinality(Nullable(String)),
`client_version` LowCardinality(Nullable(String)),
+ `organization_id` String,
+ `profile_id` String,
`sign_flag` Int8,
INDEX connectorIndex connector TYPE bloom_filter GRANULARITY 1,
INDEX paymentMethodIndex payment_method TYPE bloom_filter GRANULARITY 1,
@@ -143,6 +147,8 @@ CREATE MATERIALIZED VIEW payment_attempt_mv TO payment_attempts (
`inserted_at` DateTime64(3),
`client_source` LowCardinality(Nullable(String)),
`client_version` LowCardinality(Nullable(String)),
+ `organization_id` String,
+ `profile_id` String,
`sign_flag` Int8
) AS
SELECT
@@ -188,6 +194,8 @@ SELECT
now() AS inserted_at,
client_source,
client_version,
+ organization_id,
+ profile_id,
sign_flag
FROM
payment_attempt_queue
diff --git a/crates/analytics/docs/clickhouse/scripts/payment_intents.sql b/crates/analytics/docs/clickhouse/scripts/payment_intents.sql
index 09101e9aa2d..b4d00a858b0 100644
--- a/crates/analytics/docs/clickhouse/scripts/payment_intents.sql
+++ b/crates/analytics/docs/clickhouse/scripts/payment_intents.sql
@@ -23,6 +23,7 @@ CREATE TABLE payment_intents_queue
`modified_at` DateTime CODEC(T64, LZ4),
`created_at` DateTime CODEC(T64, LZ4),
`last_synced` Nullable(DateTime) CODEC(T64, LZ4),
+ `organization_id` String,
`sign_flag` Int8
) ENGINE = Kafka SETTINGS kafka_broker_list = 'kafka0:29092',
kafka_topic_list = 'hyperswitch-payment-intent-events',
@@ -56,6 +57,7 @@ CREATE TABLE payment_intents
`created_at` DateTime DEFAULT now() CODEC(T64, LZ4),
`last_synced` Nullable(DateTime) CODEC(T64, LZ4),
`inserted_at` DateTime DEFAULT now() CODEC(T64, LZ4),
+ `organization_id` String,
`sign_flag` Int8,
INDEX connectorIndex connector_id TYPE bloom_filter GRANULARITY 1,
INDEX currencyIndex currency TYPE bloom_filter GRANULARITY 1,
@@ -93,6 +95,7 @@ CREATE MATERIALIZED VIEW payment_intents_mv TO payment_intents
`created_at` DateTime64(3),
`last_synced` Nullable(DateTime64(3)),
`inserted_at` DateTime64(3),
+ `organization_id` String,
`sign_flag` Int8
) AS
SELECT
@@ -120,5 +123,6 @@ SELECT
created_at,
last_synced,
now() AS inserted_at,
+ organization_id,
sign_flag
FROM payment_intents_queue;
\ No newline at end of file
diff --git a/crates/analytics/docs/clickhouse/scripts/refunds.sql b/crates/analytics/docs/clickhouse/scripts/refunds.sql
index 74c069db853..323caf1adb4 100644
--- a/crates/analytics/docs/clickhouse/scripts/refunds.sql
+++ b/crates/analytics/docs/clickhouse/scripts/refunds.sql
@@ -21,6 +21,8 @@ CREATE TABLE refund_queue (
`refund_error_code` Nullable(String),
`created_at` DateTime,
`modified_at` DateTime,
+ `organization_id` String,
+ `profile_id` String,
`sign_flag` Int8
) ENGINE = Kafka SETTINGS kafka_broker_list = 'kafka0:29092',
kafka_topic_list = 'hyperswitch-refund-events',
@@ -52,6 +54,8 @@ CREATE TABLE refunds (
`created_at` DateTime DEFAULT now() CODEC(T64, LZ4),
`modified_at` DateTime DEFAULT now() CODEC(T64, LZ4),
`inserted_at` DateTime DEFAULT now() CODEC(T64, LZ4),
+ `organization_id` String,
+ `profile_id` String,
`sign_flag` Int8,
INDEX connectorIndex connector TYPE bloom_filter GRANULARITY 1,
INDEX refundTypeIndex refund_type TYPE bloom_filter GRANULARITY 1,
@@ -85,6 +89,8 @@ CREATE MATERIALIZED VIEW refund_mv TO refunds (
`created_at` DateTime64(3),
`modified_at` DateTime64(3),
`inserted_at` DateTime64(3),
+ `organization_id` String,
+ `profile_id` String,
`sign_flag` Int8
) AS
SELECT
@@ -111,6 +117,8 @@ SELECT
created_at,
modified_at,
now() AS inserted_at,
+ organization_id,
+ profile_id,
sign_flag
FROM
refund_queue
diff --git a/crates/diesel_models/src/customers.rs b/crates/diesel_models/src/customers.rs
index 7e4e27a5d38..c0d6639d1ad 100644
--- a/crates/diesel_models/src/customers.rs
+++ b/crates/diesel_models/src/customers.rs
@@ -41,6 +41,7 @@ impl Customer {
#[cfg(all(feature = "v2", feature = "customer_v2"))]
impl Customer {
+ #[allow(clippy::todo)]
pub fn get_customer_id(&self) -> common_utils::id_type::CustomerId {
todo!()
}
diff --git a/crates/diesel_models/src/dispute.rs b/crates/diesel_models/src/dispute.rs
index 45004e10ba5..1c70655406a 100644
--- a/crates/diesel_models/src/dispute.rs
+++ b/crates/diesel_models/src/dispute.rs
@@ -30,6 +30,7 @@ pub struct DisputeNew {
pub profile_id: Option<common_utils::id_type::ProfileId>,
pub merchant_connector_id: Option<common_utils::id_type::MerchantConnectorAccountId>,
pub dispute_amount: i64,
+ pub organization_id: common_utils::id_type::OrganizationId,
}
#[derive(Clone, Debug, PartialEq, Serialize, Identifiable, Queryable, Selectable)]
@@ -59,6 +60,7 @@ pub struct Dispute {
pub profile_id: Option<common_utils::id_type::ProfileId>,
pub merchant_connector_id: Option<common_utils::id_type::MerchantConnectorAccountId>,
pub dispute_amount: i64,
+ pub organization_id: common_utils::id_type::OrganizationId,
}
#[derive(Debug)]
diff --git a/crates/diesel_models/src/payment_attempt.rs b/crates/diesel_models/src/payment_attempt.rs
index ec87b2da2e4..fd769d4dbd2 100644
--- a/crates/diesel_models/src/payment_attempt.rs
+++ b/crates/diesel_models/src/payment_attempt.rs
@@ -1,4 +1,4 @@
-use common_utils::pii;
+use common_utils::{id_type, pii};
use diesel::{AsChangeset, Identifiable, Insertable, Queryable, Selectable};
use serde::{Deserialize, Serialize};
use time::PrimitiveDateTime;
@@ -16,7 +16,7 @@ use crate::schema_v2::payment_attempt;
#[diesel(table_name = payment_attempt, primary_key(attempt_id, merchant_id), check_for_backend(diesel::pg::Pg))]
pub struct PaymentAttempt {
pub payment_id: String,
- pub merchant_id: common_utils::id_type::MerchantId,
+ pub merchant_id: id_type::MerchantId,
pub attempt_id: String,
pub status: storage_enums::AttemptStatus,
pub amount: i64,
@@ -62,7 +62,7 @@ pub struct PaymentAttempt {
pub connector_response_reference_id: Option<String>,
pub amount_capturable: i64,
pub updated_by: String,
- pub merchant_connector_id: Option<common_utils::id_type::MerchantConnectorAccountId>,
+ pub merchant_connector_id: Option<id_type::MerchantConnectorAccountId>,
pub authentication_data: Option<serde_json::Value>,
pub encoded_data: Option<String>,
pub unified_code: Option<String>,
@@ -78,6 +78,9 @@ pub struct PaymentAttempt {
pub client_source: Option<String>,
pub client_version: Option<String>,
pub customer_acceptance: Option<pii::SecretSerdeValue>,
+ pub profile_id: id_type::ProfileId,
+ pub organization_id: id_type::OrganizationId,
+ pub card_network: Option<String>,
}
#[cfg(all(any(feature = "v1", feature = "v2"), not(feature = "payment_v2")))]
@@ -87,7 +90,7 @@ pub struct PaymentAttempt {
#[diesel(table_name = payment_attempt, primary_key(attempt_id, merchant_id), check_for_backend(diesel::pg::Pg))]
pub struct PaymentAttempt {
pub payment_id: String,
- pub merchant_id: common_utils::id_type::MerchantId,
+ pub merchant_id: id_type::MerchantId,
pub attempt_id: String,
pub status: storage_enums::AttemptStatus,
pub amount: i64,
@@ -133,7 +136,7 @@ pub struct PaymentAttempt {
pub connector_response_reference_id: Option<String>,
pub amount_capturable: i64,
pub updated_by: String,
- pub merchant_connector_id: Option<common_utils::id_type::MerchantConnectorAccountId>,
+ pub merchant_connector_id: Option<id_type::MerchantConnectorAccountId>,
pub authentication_data: Option<serde_json::Value>,
pub encoded_data: Option<String>,
pub unified_code: Option<String>,
@@ -149,6 +152,9 @@ pub struct PaymentAttempt {
pub client_source: Option<String>,
pub client_version: Option<String>,
pub customer_acceptance: Option<pii::SecretSerdeValue>,
+ pub profile_id: id_type::ProfileId,
+ pub organization_id: id_type::OrganizationId,
+ pub card_network: Option<String>,
}
impl PaymentAttempt {
@@ -171,7 +177,7 @@ pub struct PaymentListFilters {
#[diesel(table_name = payment_attempt)]
pub struct PaymentAttemptNew {
pub payment_id: String,
- pub merchant_id: common_utils::id_type::MerchantId,
+ pub merchant_id: id_type::MerchantId,
pub attempt_id: String,
pub status: storage_enums::AttemptStatus,
pub amount: i64,
@@ -215,7 +221,7 @@ pub struct PaymentAttemptNew {
pub multiple_capture_count: Option<i16>,
pub amount_capturable: i64,
pub updated_by: String,
- pub merchant_connector_id: Option<common_utils::id_type::MerchantConnectorAccountId>,
+ pub merchant_connector_id: Option<id_type::MerchantConnectorAccountId>,
pub authentication_data: Option<serde_json::Value>,
pub encoded_data: Option<String>,
pub unified_code: Option<String>,
@@ -231,6 +237,9 @@ pub struct PaymentAttemptNew {
pub client_source: Option<String>,
pub client_version: Option<String>,
pub customer_acceptance: Option<pii::SecretSerdeValue>,
+ pub profile_id: id_type::ProfileId,
+ pub organization_id: id_type::OrganizationId,
+ pub card_network: Option<String>,
}
impl PaymentAttemptNew {
@@ -280,7 +289,7 @@ pub enum PaymentAttemptUpdate {
surcharge_amount: Option<i64>,
tax_amount: Option<i64>,
updated_by: String,
- merchant_connector_id: Option<common_utils::id_type::MerchantConnectorAccountId>,
+ merchant_connector_id: Option<id_type::MerchantConnectorAccountId>,
},
AuthenticationTypeUpdate {
authentication_type: storage_enums::AuthenticationType,
@@ -308,7 +317,7 @@ pub enum PaymentAttemptUpdate {
tax_amount: Option<i64>,
fingerprint_id: Option<String>,
updated_by: String,
- merchant_connector_id: Option<common_utils::id_type::MerchantConnectorAccountId>,
+ merchant_connector_id: Option<id_type::MerchantConnectorAccountId>,
payment_method_id: Option<String>,
external_three_ds_authentication_attempted: Option<bool>,
authentication_connector: Option<String>,
@@ -475,7 +484,7 @@ pub struct PaymentAttemptUpdateInternal {
tax_amount: Option<i64>,
amount_capturable: Option<i64>,
updated_by: String,
- merchant_connector_id: Option<Option<common_utils::id_type::MerchantConnectorAccountId>>,
+ merchant_connector_id: Option<Option<id_type::MerchantConnectorAccountId>>,
authentication_data: Option<serde_json::Value>,
encoded_data: Option<String>,
unified_code: Option<Option<String>>,
@@ -489,6 +498,7 @@ pub struct PaymentAttemptUpdateInternal {
client_source: Option<String>,
client_version: Option<String>,
customer_acceptance: Option<pii::SecretSerdeValue>,
+ card_network: Option<String>,
}
impl PaymentAttemptUpdateInternal {
@@ -505,6 +515,15 @@ impl PaymentAttemptUpdateInternal {
.or(source.tax_amount)
.unwrap_or(0),
);
+ update_internal.card_network = update_internal
+ .payment_method_data
+ .as_ref()
+ .and_then(|data| data.as_object())
+ .and_then(|card| card.get("card"))
+ .and_then(|data| data.as_object())
+ .and_then(|card| card.get("card_network"))
+ .and_then(|network| network.as_str())
+ .map(|network| network.to_string());
update_internal
}
}
@@ -558,6 +577,7 @@ impl PaymentAttemptUpdate {
client_source,
client_version,
customer_acceptance,
+ card_network,
} = PaymentAttemptUpdateInternal::from(self).populate_derived_fields(&source);
PaymentAttempt {
amount: amount.unwrap_or(source.amount),
@@ -610,6 +630,7 @@ impl PaymentAttemptUpdate {
client_source: client_source.or(source.client_source),
client_version: client_version.or(source.client_version),
customer_acceptance: customer_acceptance.or(source.customer_acceptance),
+ card_network: card_network.or(source.card_network),
..source
}
}
@@ -685,6 +706,7 @@ impl From<PaymentAttemptUpdate> for PaymentAttemptUpdateInternal {
client_source: None,
client_version: None,
customer_acceptance: None,
+ card_network: None,
},
PaymentAttemptUpdate::AuthenticationTypeUpdate {
authentication_type,
@@ -736,6 +758,7 @@ impl From<PaymentAttemptUpdate> for PaymentAttemptUpdateInternal {
client_source: None,
client_version: None,
customer_acceptance: None,
+ card_network: None,
},
PaymentAttemptUpdate::ConfirmUpdate {
amount,
@@ -815,6 +838,7 @@ impl From<PaymentAttemptUpdate> for PaymentAttemptUpdateInternal {
unified_code: None,
unified_message: None,
charge_id: None,
+ card_network: None,
},
PaymentAttemptUpdate::VoidUpdate {
status,
@@ -867,6 +891,7 @@ impl From<PaymentAttemptUpdate> for PaymentAttemptUpdateInternal {
client_source: None,
client_version: None,
customer_acceptance: None,
+ card_network: None,
},
PaymentAttemptUpdate::RejectUpdate {
status,
@@ -920,6 +945,7 @@ impl From<PaymentAttemptUpdate> for PaymentAttemptUpdateInternal {
client_source: None,
client_version: None,
customer_acceptance: None,
+ card_network: None,
},
PaymentAttemptUpdate::BlocklistUpdate {
status,
@@ -973,6 +999,7 @@ impl From<PaymentAttemptUpdate> for PaymentAttemptUpdateInternal {
client_source: None,
client_version: None,
customer_acceptance: None,
+ card_network: None,
},
PaymentAttemptUpdate::PaymentMethodDetailsUpdate {
payment_method_id,
@@ -1024,6 +1051,7 @@ impl From<PaymentAttemptUpdate> for PaymentAttemptUpdateInternal {
client_source: None,
client_version: None,
customer_acceptance: None,
+ card_network: None,
},
PaymentAttemptUpdate::ResponseUpdate {
status,
@@ -1093,6 +1121,7 @@ impl From<PaymentAttemptUpdate> for PaymentAttemptUpdateInternal {
client_source: None,
client_version: None,
customer_acceptance: None,
+ card_network: None,
},
PaymentAttemptUpdate::ErrorUpdate {
connector,
@@ -1154,6 +1183,7 @@ impl From<PaymentAttemptUpdate> for PaymentAttemptUpdateInternal {
client_source: None,
client_version: None,
customer_acceptance: None,
+ card_network: None,
},
PaymentAttemptUpdate::StatusUpdate { status, updated_by } => Self {
status: Some(status),
@@ -1202,6 +1232,7 @@ impl From<PaymentAttemptUpdate> for PaymentAttemptUpdateInternal {
client_source: None,
client_version: None,
customer_acceptance: None,
+ card_network: None,
},
PaymentAttemptUpdate::UpdateTrackers {
payment_token,
@@ -1259,6 +1290,7 @@ impl From<PaymentAttemptUpdate> for PaymentAttemptUpdateInternal {
client_source: None,
client_version: None,
customer_acceptance: None,
+ card_network: None,
},
PaymentAttemptUpdate::UnresolvedResponseUpdate {
status,
@@ -1317,6 +1349,7 @@ impl From<PaymentAttemptUpdate> for PaymentAttemptUpdateInternal {
client_source: None,
client_version: None,
customer_acceptance: None,
+ card_network: None,
},
PaymentAttemptUpdate::PreprocessingUpdate {
status,
@@ -1373,6 +1406,7 @@ impl From<PaymentAttemptUpdate> for PaymentAttemptUpdateInternal {
client_source: None,
client_version: None,
customer_acceptance: None,
+ card_network: None,
},
PaymentAttemptUpdate::CaptureUpdate {
multiple_capture_count,
@@ -1425,6 +1459,7 @@ impl From<PaymentAttemptUpdate> for PaymentAttemptUpdateInternal {
client_source: None,
client_version: None,
customer_acceptance: None,
+ card_network: None,
},
PaymentAttemptUpdate::AmountToCaptureUpdate {
status,
@@ -1477,6 +1512,7 @@ impl From<PaymentAttemptUpdate> for PaymentAttemptUpdateInternal {
client_source: None,
client_version: None,
customer_acceptance: None,
+ card_network: None,
},
PaymentAttemptUpdate::ConnectorResponse {
authentication_data,
@@ -1532,6 +1568,7 @@ impl From<PaymentAttemptUpdate> for PaymentAttemptUpdateInternal {
client_source: None,
client_version: None,
customer_acceptance: None,
+ card_network: None,
},
PaymentAttemptUpdate::IncrementalAuthorizationAmountUpdate {
amount,
@@ -1583,6 +1620,7 @@ impl From<PaymentAttemptUpdate> for PaymentAttemptUpdateInternal {
client_source: None,
client_version: None,
customer_acceptance: None,
+ card_network: None,
},
PaymentAttemptUpdate::AuthenticationUpdate {
status,
@@ -1637,6 +1675,7 @@ impl From<PaymentAttemptUpdate> for PaymentAttemptUpdateInternal {
client_source: None,
client_version: None,
customer_acceptance: None,
+ card_network: None,
},
PaymentAttemptUpdate::ManualUpdate {
status,
@@ -1694,6 +1733,7 @@ impl From<PaymentAttemptUpdate> for PaymentAttemptUpdateInternal {
client_source: None,
client_version: None,
customer_acceptance: None,
+ card_network: None,
},
}
}
diff --git a/crates/diesel_models/src/payment_intent.rs b/crates/diesel_models/src/payment_intent.rs
index 7bd1652ab56..c96629ea448 100644
--- a/crates/diesel_models/src/payment_intent.rs
+++ b/crates/diesel_models/src/payment_intent.rs
@@ -69,6 +69,7 @@ pub struct PaymentIntent {
pub merchant_order_reference_id: Option<String>,
pub shipping_details: Option<Encryption>,
pub is_payment_processor_token_flow: Option<bool>,
+ pub organization_id: common_utils::id_type::OrganizationId,
}
#[cfg(all(any(feature = "v1", feature = "v2"), not(feature = "payment_v2")))]
@@ -130,6 +131,7 @@ pub struct PaymentIntent {
pub merchant_order_reference_id: Option<String>,
pub shipping_details: Option<Encryption>,
pub is_payment_processor_token_flow: Option<bool>,
+ pub organization_id: common_utils::id_type::OrganizationId,
}
#[derive(
@@ -190,6 +192,7 @@ pub struct PaymentIntentNew {
pub merchant_order_reference_id: Option<String>,
pub shipping_details: Option<Encryption>,
pub is_payment_processor_token_flow: Option<bool>,
+ pub organization_id: common_utils::id_type::OrganizationId,
}
#[derive(Debug, Clone, Serialize, Deserialize)]
diff --git a/crates/diesel_models/src/refund.rs b/crates/diesel_models/src/refund.rs
index 10c1fbb9b29..a0828b31756 100644
--- a/crates/diesel_models/src/refund.rs
+++ b/crates/diesel_models/src/refund.rs
@@ -50,6 +50,7 @@ pub struct Refund {
pub updated_by: String,
pub merchant_connector_id: Option<common_utils::id_type::MerchantConnectorAccountId>,
pub charges: Option<ChargeRefunds>,
+ pub organization_id: common_utils::id_type::OrganizationId,
}
#[derive(
@@ -92,38 +93,7 @@ pub struct RefundNew {
pub updated_by: String,
pub merchant_connector_id: Option<common_utils::id_type::MerchantConnectorAccountId>,
pub charges: Option<ChargeRefunds>,
-}
-
-impl Default for RefundNew {
- fn default() -> Self {
- Self {
- refund_id: Default::default(),
- payment_id: Default::default(),
- merchant_id: Default::default(),
- internal_reference_id: Default::default(),
- external_reference_id: Default::default(),
- connector_transaction_id: Default::default(),
- connector: Default::default(),
- connector_refund_id: Default::default(),
- refund_type: Default::default(),
- total_amount: Default::default(),
- currency: Default::default(),
- refund_amount: Default::default(),
- refund_status: Default::default(),
- sent_to_gateway: Default::default(),
- metadata: Default::default(),
- refund_arn: Default::default(),
- created_at: common_utils::date_time::now(),
- modified_at: common_utils::date_time::now(),
- description: Default::default(),
- attempt_id: Default::default(),
- refund_reason: Default::default(),
- profile_id: Default::default(),
- updated_by: Default::default(),
- merchant_connector_id: Default::default(),
- charges: Default::default(),
- }
- }
+ pub organization_id: common_utils::id_type::OrganizationId,
}
#[derive(Debug, Clone, serde::Serialize, serde::Deserialize)]
diff --git a/crates/diesel_models/src/schema.rs b/crates/diesel_models/src/schema.rs
index 7e6c1b84889..3e4799e42ab 100644
--- a/crates/diesel_models/src/schema.rs
+++ b/crates/diesel_models/src/schema.rs
@@ -375,6 +375,8 @@ diesel::table! {
#[max_length = 32]
merchant_connector_id -> Nullable<Varchar>,
dispute_amount -> Int8,
+ #[max_length = 32]
+ organization_id -> Varchar,
}
}
@@ -831,6 +833,12 @@ diesel::table! {
#[max_length = 64]
client_version -> Nullable<Varchar>,
customer_acceptance -> Nullable<Jsonb>,
+ #[max_length = 64]
+ profile_id -> Varchar,
+ #[max_length = 32]
+ organization_id -> Varchar,
+ #[max_length = 32]
+ card_network -> Nullable<Varchar>,
}
}
@@ -906,6 +914,8 @@ diesel::table! {
merchant_order_reference_id -> Nullable<Varchar>,
shipping_details -> Nullable<Bytea>,
is_payment_processor_token_flow -> Nullable<Bool>,
+ #[max_length = 32]
+ organization_id -> Varchar,
}
}
@@ -1150,6 +1160,8 @@ diesel::table! {
#[max_length = 32]
merchant_connector_id -> Nullable<Varchar>,
charges -> Nullable<Jsonb>,
+ #[max_length = 32]
+ organization_id -> Varchar,
}
}
diff --git a/crates/diesel_models/src/schema_v2.rs b/crates/diesel_models/src/schema_v2.rs
index 818415a277b..013157d5e17 100644
--- a/crates/diesel_models/src/schema_v2.rs
+++ b/crates/diesel_models/src/schema_v2.rs
@@ -385,6 +385,8 @@ diesel::table! {
#[max_length = 32]
merchant_connector_id -> Nullable<Varchar>,
dispute_amount -> Int8,
+ #[max_length = 32]
+ organization_id -> Varchar,
}
}
@@ -810,6 +812,12 @@ diesel::table! {
#[max_length = 64]
client_version -> Nullable<Varchar>,
customer_acceptance -> Nullable<Jsonb>,
+ #[max_length = 64]
+ profile_id -> Varchar,
+ #[max_length = 32]
+ organization_id -> Varchar,
+ #[max_length = 32]
+ card_network -> Nullable<Varchar>,
}
}
@@ -885,6 +893,8 @@ diesel::table! {
merchant_order_reference_id -> Nullable<Varchar>,
shipping_details -> Nullable<Bytea>,
is_payment_processor_token_flow -> Nullable<Bool>,
+ #[max_length = 32]
+ organization_id -> Varchar,
}
}
@@ -1131,6 +1141,8 @@ diesel::table! {
#[max_length = 32]
merchant_connector_id -> Nullable<Varchar>,
charges -> Nullable<Jsonb>,
+ #[max_length = 32]
+ organization_id -> Varchar,
}
}
diff --git a/crates/diesel_models/src/user/sample_data.rs b/crates/diesel_models/src/user/sample_data.rs
index dbdae51c45a..89f8af3d94e 100644
--- a/crates/diesel_models/src/user/sample_data.rs
+++ b/crates/diesel_models/src/user/sample_data.rs
@@ -80,6 +80,8 @@ pub struct PaymentAttemptBatchNew {
pub client_source: Option<String>,
pub client_version: Option<String>,
pub customer_acceptance: Option<common_utils::pii::SecretSerdeValue>,
+ pub profile_id: common_utils::id_type::ProfileId,
+ pub organization_id: common_utils::id_type::OrganizationId,
}
#[allow(dead_code)]
@@ -117,6 +119,15 @@ impl PaymentAttemptBatchNew {
connector_metadata: self.connector_metadata,
payment_experience: self.payment_experience,
payment_method_type: self.payment_method_type,
+ card_network: self
+ .payment_method_data
+ .as_ref()
+ .and_then(|data| data.as_object())
+ .and_then(|card| card.get("card"))
+ .and_then(|v| v.as_object())
+ .and_then(|v| v.get("card_network"))
+ .and_then(|network| network.as_str())
+ .map(|network| network.to_string()),
payment_method_data: self.payment_method_data,
business_sub_label: self.business_sub_label,
straight_through_algorithm: self.straight_through_algorithm,
@@ -144,6 +155,8 @@ impl PaymentAttemptBatchNew {
client_source: self.client_source,
client_version: self.client_version,
customer_acceptance: self.customer_acceptance,
+ profile_id: self.profile_id,
+ organization_id: self.organization_id,
}
}
}
diff --git a/crates/hyperswitch_domain_models/src/payments.rs b/crates/hyperswitch_domain_models/src/payments.rs
index 11a2c3c3164..3873dfcd291 100644
--- a/crates/hyperswitch_domain_models/src/payments.rs
+++ b/crates/hyperswitch_domain_models/src/payments.rs
@@ -67,4 +67,5 @@ pub struct PaymentIntent {
pub merchant_order_reference_id: Option<String>,
pub shipping_details: Option<Encryptable<Secret<serde_json::Value>>>,
pub is_payment_processor_token_flow: Option<bool>,
+ pub organization_id: id_type::OrganizationId,
}
diff --git a/crates/hyperswitch_domain_models/src/payments/payment_attempt.rs b/crates/hyperswitch_domain_models/src/payments/payment_attempt.rs
index 12880172d3d..370b37d5a13 100644
--- a/crates/hyperswitch_domain_models/src/payments/payment_attempt.rs
+++ b/crates/hyperswitch_domain_models/src/payments/payment_attempt.rs
@@ -181,6 +181,8 @@ pub struct PaymentAttempt {
pub client_source: Option<String>,
pub client_version: Option<String>,
pub customer_acceptance: Option<pii::SecretSerdeValue>,
+ pub profile_id: id_type::ProfileId,
+ pub organization_id: id_type::OrganizationId,
}
impl PaymentAttempt {
@@ -206,7 +208,7 @@ pub struct PaymentListFilters {
pub authentication_type: Vec<storage_enums::AuthenticationType>,
}
-#[derive(Clone, Debug, Default, Serialize, Deserialize)]
+#[derive(Clone, Debug, Serialize, Deserialize)]
pub struct PaymentAttemptNew {
pub payment_id: String,
pub merchant_id: id_type::MerchantId,
@@ -271,6 +273,8 @@ pub struct PaymentAttemptNew {
pub client_source: Option<String>,
pub client_version: Option<String>,
pub customer_acceptance: Option<pii::SecretSerdeValue>,
+ pub profile_id: id_type::ProfileId,
+ pub organization_id: id_type::OrganizationId,
}
impl PaymentAttemptNew {
@@ -543,6 +547,7 @@ impl behaviour::Conversion for PaymentIntent {
merchant_order_reference_id: self.merchant_order_reference_id,
shipping_details: self.shipping_details.map(Encryption::from),
is_payment_processor_token_flow: self.is_payment_processor_token_flow,
+ organization_id: self.organization_id,
})
}
async fn convert_back(
@@ -625,6 +630,7 @@ impl behaviour::Conversion for PaymentIntent {
.async_lift(inner_decrypt)
.await?,
is_payment_processor_token_flow: storage_model.is_payment_processor_token_flow,
+ organization_id: storage_model.organization_id,
})
}
.await
@@ -683,6 +689,7 @@ impl behaviour::Conversion for PaymentIntent {
merchant_order_reference_id: self.merchant_order_reference_id,
shipping_details: self.shipping_details.map(Encryption::from),
is_payment_processor_token_flow: self.is_payment_processor_token_flow,
+ organization_id: self.organization_id,
})
}
}
@@ -743,6 +750,7 @@ impl behaviour::Conversion for PaymentIntent {
merchant_order_reference_id: self.merchant_order_reference_id,
shipping_details: self.shipping_details.map(Encryption::from),
is_payment_processor_token_flow: self.is_payment_processor_token_flow,
+ organization_id: self.organization_id,
})
}
@@ -826,6 +834,7 @@ impl behaviour::Conversion for PaymentIntent {
.async_lift(inner_decrypt)
.await?,
is_payment_processor_token_flow: storage_model.is_payment_processor_token_flow,
+ organization_id: storage_model.organization_id,
})
}
.await
@@ -884,6 +893,7 @@ impl behaviour::Conversion for PaymentIntent {
merchant_order_reference_id: self.merchant_order_reference_id,
shipping_details: self.shipping_details.map(Encryption::from),
is_payment_processor_token_flow: self.is_payment_processor_token_flow,
+ organization_id: self.organization_id,
})
}
}
diff --git a/crates/hyperswitch_domain_models/src/payments/payment_intent.rs b/crates/hyperswitch_domain_models/src/payments/payment_intent.rs
index dcb06733cc8..f857e241e11 100644
--- a/crates/hyperswitch_domain_models/src/payments/payment_intent.rs
+++ b/crates/hyperswitch_domain_models/src/payments/payment_intent.rs
@@ -151,6 +151,7 @@ pub struct PaymentIntentNew {
pub billing_details: Option<Encryptable<Secret<serde_json::Value>>>,
pub shipping_details: Option<Encryptable<Secret<serde_json::Value>>>,
pub is_payment_processor_token_flow: Option<bool>,
+ pub organization_id: id_type::OrganizationId,
}
#[derive(Debug, Clone, Serialize)]
diff --git a/crates/router/src/core/payments/helpers.rs b/crates/router/src/core/payments/helpers.rs
index 181e2232d90..ae84d4b0ade 100644
--- a/crates/router/src/core/payments/helpers.rs
+++ b/crates/router/src/core/payments/helpers.rs
@@ -2960,7 +2960,7 @@ mod tests {
feature_metadata: None,
attempt_count: 1,
payment_link_id: None,
- profile_id: None,
+ profile_id: Some(common_utils::generate_profile_id_of_default_length()),
merchant_decision: None,
payment_confirm_source: None,
surcharge_applicable: None,
@@ -2982,6 +2982,7 @@ mod tests {
merchant_order_reference_id: None,
shipping_details: None,
is_payment_processor_token_flow: None,
+ organization_id: id_type::OrganizationId::default(),
};
let req_cs = Some("1".to_string());
assert!(authenticate_client_secret(req_cs.as_ref(), &payment_intent).is_ok());
@@ -3026,7 +3027,7 @@ mod tests {
feature_metadata: None,
attempt_count: 1,
payment_link_id: None,
- profile_id: None,
+ profile_id: Some(common_utils::generate_profile_id_of_default_length()),
merchant_decision: None,
payment_confirm_source: None,
surcharge_applicable: None,
@@ -3047,6 +3048,7 @@ mod tests {
merchant_order_reference_id: None,
shipping_details: None,
is_payment_processor_token_flow: None,
+ organization_id: id_type::OrganizationId::default(),
};
let req_cs = Some("1".to_string());
assert!(authenticate_client_secret(req_cs.as_ref(), &payment_intent,).is_err())
@@ -3088,7 +3090,7 @@ mod tests {
feature_metadata: None,
attempt_count: 1,
payment_link_id: None,
- profile_id: None,
+ profile_id: Some(common_utils::generate_profile_id_of_default_length()),
merchant_decision: None,
payment_confirm_source: None,
surcharge_applicable: None,
@@ -3110,6 +3112,7 @@ mod tests {
merchant_order_reference_id: None,
shipping_details: None,
is_payment_processor_token_flow: None,
+ organization_id: id_type::OrganizationId::default(),
};
let req_cs = Some("1".to_string());
assert!(authenticate_client_secret(req_cs.as_ref(), &payment_intent).is_err())
@@ -3645,6 +3648,8 @@ impl AttemptType {
client_source: old_payment_attempt.client_source,
client_version: old_payment_attempt.client_version,
customer_acceptance: old_payment_attempt.customer_acceptance,
+ organization_id: old_payment_attempt.organization_id,
+ profile_id: old_payment_attempt.profile_id,
}
}
diff --git a/crates/router/src/core/payments/operations/payment_create.rs b/crates/router/src/core/payments/operations/payment_create.rs
index 0ba859f3e17..8ab3a957b06 100644
--- a/crates/router/src/core/payments/operations/payment_create.rs
+++ b/crates/router/src/core/payments/operations/payment_create.rs
@@ -308,6 +308,7 @@ impl<F: Send + Clone> GetTracker<F, PaymentData<F>, api::PaymentsRequest> for Pa
let (payment_attempt_new, additional_payment_data) = Self::make_payment_attempt(
&payment_id,
merchant_id,
+ &merchant_account.organization_id,
money,
payment_method,
payment_method_type,
@@ -874,6 +875,7 @@ impl PaymentCreate {
pub async fn make_payment_attempt(
payment_id: &str,
merchant_id: &common_utils::id_type::MerchantId,
+ organization_id: &common_utils::id_type::OrganizationId,
money: (api::Amount, enums::Currency),
payment_method: Option<enums::PaymentMethod>,
payment_method_type: Option<enums::PaymentMethodType>,
@@ -1065,6 +1067,8 @@ impl PaymentCreate {
.change_context(errors::ApiErrorResponse::InternalServerError)
.attach_printable("Failed to serialize customer_acceptance")?
.map(Secret::new),
+ organization_id: organization_id.clone(),
+ profile_id,
},
additional_pm_data,
))
@@ -1246,6 +1250,7 @@ impl PaymentCreate {
merchant_order_reference_id: request.merchant_order_reference_id.clone(),
shipping_details,
is_payment_processor_token_flow,
+ organization_id: merchant_account.organization_id.clone(),
})
}
diff --git a/crates/router/src/core/payments/retry.rs b/crates/router/src/core/payments/retry.rs
index e67f30a2f79..d655fc42a10 100644
--- a/crates/router/src/core/payments/retry.rs
+++ b/crates/router/src/core/payments/retry.rs
@@ -506,7 +506,6 @@ pub fn make_new_payment_attempt(
amount: old_payment_attempt.amount,
currency: old_payment_attempt.currency,
save_to_locker: old_payment_attempt.save_to_locker,
-
offer_amount: old_payment_attempt.offer_amount,
surcharge_amount: old_payment_attempt.surcharge_amount,
tax_amount: old_payment_attempt.tax_amount,
@@ -521,7 +520,6 @@ pub fn make_new_payment_attempt(
} else {
old_payment_attempt.authentication_type
},
-
amount_to_capture: old_payment_attempt.amount_to_capture,
mandate_id: old_payment_attempt.mandate_id,
browser_info: old_payment_attempt.browser_info,
@@ -531,7 +529,37 @@ pub fn make_new_payment_attempt(
created_at,
modified_at,
last_synced,
- ..storage::PaymentAttemptNew::default()
+ net_amount: Default::default(),
+ error_message: Default::default(),
+ cancellation_reason: Default::default(),
+ error_code: Default::default(),
+ connector_metadata: Default::default(),
+ payment_experience: Default::default(),
+ payment_method_data: Default::default(),
+ business_sub_label: Default::default(),
+ straight_through_algorithm: Default::default(),
+ preprocessing_step_id: Default::default(),
+ mandate_details: Default::default(),
+ error_reason: Default::default(),
+ connector_response_reference_id: Default::default(),
+ multiple_capture_count: Default::default(),
+ amount_capturable: Default::default(),
+ updated_by: Default::default(),
+ authentication_data: Default::default(),
+ encoded_data: Default::default(),
+ merchant_connector_id: Default::default(),
+ unified_code: Default::default(),
+ unified_message: Default::default(),
+ external_three_ds_authentication_attempted: Default::default(),
+ authentication_connector: Default::default(),
+ authentication_id: Default::default(),
+ mandate_data: Default::default(),
+ payment_method_billing_address_id: Default::default(),
+ fingerprint_id: Default::default(),
+ charge_id: Default::default(),
+ customer_acceptance: Default::default(),
+ profile_id: old_payment_attempt.profile_id,
+ organization_id: old_payment_attempt.organization_id,
}
}
diff --git a/crates/router/src/core/refunds.rs b/crates/router/src/core/refunds.rs
index 89450347404..867a2ccff54 100644
--- a/crates/router/src/core/refunds.rs
+++ b/crates/router/src/core/refunds.rs
@@ -798,30 +798,34 @@ pub async fn validate_and_create_refund(
.clone()
.ok_or(errors::ApiErrorResponse::InternalServerError)
.attach_printable("No connector populated in payment attempt")?;
-
- let refund_create_req = storage::RefundNew::default()
- .set_refund_id(refund_id.to_string())
- .set_internal_reference_id(utils::generate_id(consts::ID_LENGTH, "refid"))
- .set_external_reference_id(Some(refund_id.clone()))
- .set_payment_id(req.payment_id)
- .set_merchant_id(merchant_account.get_id().clone())
- .set_connector_transaction_id(connecter_transaction_id.to_string())
- .set_connector(connector)
- .set_refund_type(req.refund_type.unwrap_or_default().foreign_into())
- .set_total_amount(payment_attempt.amount)
- .set_refund_amount(refund_amount)
- .set_currency(currency)
- .set_created_at(common_utils::date_time::now())
- .set_modified_at(common_utils::date_time::now())
- .set_refund_status(enums::RefundStatus::Pending)
- .set_metadata(req.metadata)
- .set_description(req.reason.clone())
- .set_attempt_id(payment_attempt.attempt_id.clone())
- .set_refund_reason(req.reason)
- .set_profile_id(payment_intent.profile_id.clone())
- .set_merchant_connector_id(payment_attempt.merchant_connector_id.clone())
- .set_charges(req.charges)
- .to_owned();
+ let refund_create_req = storage::RefundNew {
+ refund_id: refund_id.to_string(),
+ internal_reference_id: utils::generate_id(consts::ID_LENGTH, "refid"),
+ external_reference_id: Some(refund_id.clone()),
+ payment_id: req.payment_id,
+ merchant_id: merchant_account.get_id().clone(),
+ connector_transaction_id: connecter_transaction_id.to_string(),
+ connector,
+ refund_type: req.refund_type.unwrap_or_default().foreign_into(),
+ total_amount: payment_attempt.amount,
+ refund_amount,
+ currency,
+ created_at: common_utils::date_time::now(),
+ modified_at: common_utils::date_time::now(),
+ refund_status: enums::RefundStatus::Pending,
+ metadata: req.metadata,
+ description: req.reason.clone(),
+ attempt_id: payment_attempt.attempt_id.clone(),
+ refund_reason: req.reason,
+ profile_id: payment_intent.profile_id.clone(),
+ merchant_connector_id: payment_attempt.merchant_connector_id.clone(),
+ charges: req.charges,
+ connector_refund_id: None,
+ sent_to_gateway: Default::default(),
+ refund_arn: None,
+ updated_by: Default::default(),
+ organization_id: merchant_account.organization_id.clone(),
+ };
let refund = match db
.insert_refund(refund_create_req, merchant_account.storage_scheme)
diff --git a/crates/router/src/core/user/sample_data.rs b/crates/router/src/core/user/sample_data.rs
index f5faf68435f..ce7143338f4 100644
--- a/crates/router/src/core/user/sample_data.rs
+++ b/crates/router/src/core/user/sample_data.rs
@@ -19,7 +19,13 @@ pub async fn generate_sample_data_for_user(
req: SampleDataRequest,
_req_state: ReqState,
) -> SampleDataApiResponse<()> {
- let sample_data = generate_sample_data(&state, req, &user_from_token.merchant_id).await?;
+ let sample_data = generate_sample_data(
+ &state,
+ req,
+ &user_from_token.merchant_id,
+ &user_from_token.org_id,
+ )
+ .await?;
let key_store = state
.store
diff --git a/crates/router/src/core/webhooks/incoming.rs b/crates/router/src/core/webhooks/incoming.rs
index 0a0a35c23cc..79d6d5d6b82 100644
--- a/crates/router/src/core/webhooks/incoming.rs
+++ b/crates/router/src/core/webhooks/incoming.rs
@@ -902,6 +902,7 @@ async fn get_or_update_dispute_object(
option_dispute: Option<diesel_models::dispute::Dispute>,
dispute_details: api::disputes::DisputePayload,
merchant_id: &common_utils::id_type::MerchantId,
+ organization_id: &common_utils::id_type::OrganizationId,
payment_attempt: &hyperswitch_domain_models::payments::payment_attempt::PaymentAttempt,
event_type: webhooks::IncomingWebhookEvent,
business_profile: &domain::BusinessProfile,
@@ -935,6 +936,7 @@ async fn get_or_update_dispute_object(
evidence: None,
merchant_connector_id: payment_attempt.merchant_connector_id.clone(),
dispute_amount: dispute_details.amount.parse::<i64>().unwrap_or(0),
+ organization_id: organization_id.clone(),
};
state
.store
@@ -1377,6 +1379,7 @@ async fn disputes_incoming_webhook_flow(
option_dispute,
dispute_details,
merchant_account.get_id(),
+ &merchant_account.organization_id,
&payment_attempt,
event_type,
&business_profile,
diff --git a/crates/router/src/db/dispute.rs b/crates/router/src/db/dispute.rs
index 9d6093bfe3c..686de8c2233 100644
--- a/crates/router/src/db/dispute.rs
+++ b/crates/router/src/db/dispute.rs
@@ -170,6 +170,7 @@ impl DisputeInterface for MockDb {
evidence,
merchant_connector_id: dispute.merchant_connector_id,
dispute_amount: dispute.dispute_amount,
+ organization_id: dispute.organization_id,
};
locked_disputes.push(new_dispute.clone());
@@ -404,9 +405,10 @@ mod tests {
connector_updated_at: Some(datetime!(2019-01-03 0:00)),
connector: "connector".into(),
evidence: Some(Secret::from(Value::String("evidence".into()))),
- profile_id: None,
+ profile_id: Some(common_utils::generate_profile_id_of_default_length()),
merchant_connector_id: None,
dispute_amount: 1040,
+ organization_id: common_utils::id_type::OrganizationId::default(),
}
}
diff --git a/crates/router/src/db/refund.rs b/crates/router/src/db/refund.rs
index 1fa7e28cb81..408c6495609 100644
--- a/crates/router/src/db/refund.rs
+++ b/crates/router/src/db/refund.rs
@@ -398,6 +398,7 @@ mod storage {
updated_by: new.updated_by.clone(),
merchant_connector_id: new.merchant_connector_id.clone(),
charges: new.charges.clone(),
+ organization_id: new.organization_id.clone(),
};
let field = format!(
@@ -859,6 +860,7 @@ impl RefundInterface for MockDb {
updated_by: new.updated_by,
merchant_connector_id: new.merchant_connector_id,
charges: new.charges,
+ organization_id: new.organization_id,
};
refunds.push(refund.clone());
Ok(refund)
diff --git a/crates/router/src/services/kafka/dispute.rs b/crates/router/src/services/kafka/dispute.rs
index 62a4310a640..9374c42cbe4 100644
--- a/crates/router/src/services/kafka/dispute.rs
+++ b/crates/router/src/services/kafka/dispute.rs
@@ -1,3 +1,4 @@
+use common_utils::id_type;
use diesel_models::enums as storage_enums;
use masking::Secret;
use time::OffsetDateTime;
@@ -13,7 +14,7 @@ pub struct KafkaDispute<'a> {
pub dispute_status: &'a storage_enums::DisputeStatus,
pub payment_id: &'a String,
pub attempt_id: &'a String,
- pub merchant_id: &'a common_utils::id_type::MerchantId,
+ pub merchant_id: &'a id_type::MerchantId,
pub connector_status: &'a String,
pub connector_dispute_id: &'a String,
pub connector_reason: Option<&'a String>,
@@ -30,8 +31,9 @@ pub struct KafkaDispute<'a> {
pub modified_at: OffsetDateTime,
pub connector: &'a String,
pub evidence: &'a Secret<serde_json::Value>,
- pub profile_id: Option<&'a common_utils::id_type::ProfileId>,
- pub merchant_connector_id: Option<&'a common_utils::id_type::MerchantConnectorAccountId>,
+ pub profile_id: Option<&'a id_type::ProfileId>,
+ pub merchant_connector_id: Option<&'a id_type::MerchantConnectorAccountId>,
+ pub organization_id: &'a id_type::OrganizationId,
}
impl<'a> KafkaDispute<'a> {
@@ -58,6 +60,7 @@ impl<'a> KafkaDispute<'a> {
evidence: &dispute.evidence,
profile_id: dispute.profile_id.as_ref(),
merchant_connector_id: dispute.merchant_connector_id.as_ref(),
+ organization_id: &dispute.organization_id,
}
}
}
diff --git a/crates/router/src/services/kafka/dispute_event.rs b/crates/router/src/services/kafka/dispute_event.rs
index 9b73cc2e510..ac72af0cd95 100644
--- a/crates/router/src/services/kafka/dispute_event.rs
+++ b/crates/router/src/services/kafka/dispute_event.rs
@@ -33,6 +33,7 @@ pub struct KafkaDisputeEvent<'a> {
pub evidence: &'a Secret<serde_json::Value>,
pub profile_id: Option<&'a common_utils::id_type::ProfileId>,
pub merchant_connector_id: Option<&'a common_utils::id_type::MerchantConnectorAccountId>,
+ pub organization_id: &'a common_utils::id_type::OrganizationId,
}
impl<'a> KafkaDisputeEvent<'a> {
@@ -59,6 +60,7 @@ impl<'a> KafkaDisputeEvent<'a> {
evidence: &dispute.evidence,
profile_id: dispute.profile_id.as_ref(),
merchant_connector_id: dispute.merchant_connector_id.as_ref(),
+ organization_id: &dispute.organization_id,
}
}
}
diff --git a/crates/router/src/services/kafka/payment_attempt.rs b/crates/router/src/services/kafka/payment_attempt.rs
index 08ec50f06b7..b92728196d4 100644
--- a/crates/router/src/services/kafka/payment_attempt.rs
+++ b/crates/router/src/services/kafka/payment_attempt.rs
@@ -1,5 +1,5 @@
// use diesel_models::enums::MandateDetails;
-use common_utils::types::MinorUnit;
+use common_utils::{id_type, types::MinorUnit};
use diesel_models::enums as storage_enums;
use hyperswitch_domain_models::{
mandates::MandateDetails, payments::payment_attempt::PaymentAttempt,
@@ -9,7 +9,7 @@ use time::OffsetDateTime;
#[derive(serde::Serialize, Debug)]
pub struct KafkaPaymentAttempt<'a> {
pub payment_id: &'a String,
- pub merchant_id: &'a common_utils::id_type::MerchantId,
+ pub merchant_id: &'a id_type::MerchantId,
pub attempt_id: &'a String,
pub status: storage_enums::AttemptStatus,
pub amount: MinorUnit,
@@ -47,13 +47,16 @@ pub struct KafkaPaymentAttempt<'a> {
pub error_reason: Option<&'a String>,
pub multiple_capture_count: Option<i16>,
pub amount_capturable: MinorUnit,
- pub merchant_connector_id: Option<&'a common_utils::id_type::MerchantConnectorAccountId>,
+ pub merchant_connector_id: Option<&'a id_type::MerchantConnectorAccountId>,
pub net_amount: MinorUnit,
pub unified_code: Option<&'a String>,
pub unified_message: Option<&'a String>,
pub mandate_data: Option<&'a MandateDetails>,
pub client_source: Option<&'a String>,
pub client_version: Option<&'a String>,
+ pub profile_id: &'a id_type::ProfileId,
+ pub organization_id: &'a id_type::OrganizationId,
+ pub card_network: Option<String>,
}
impl<'a> KafkaPaymentAttempt<'a> {
@@ -100,6 +103,17 @@ impl<'a> KafkaPaymentAttempt<'a> {
mandate_data: attempt.mandate_data.as_ref(),
client_source: attempt.client_source.as_ref(),
client_version: attempt.client_version.as_ref(),
+ profile_id: &attempt.profile_id,
+ organization_id: &attempt.organization_id,
+ card_network: attempt
+ .payment_method_data
+ .as_ref()
+ .and_then(|data| data.as_object())
+ .and_then(|pm| pm.get("card"))
+ .and_then(|data| data.as_object())
+ .and_then(|card| card.get("card_network"))
+ .and_then(|network| network.as_str())
+ .map(|network| network.to_string()),
}
}
}
diff --git a/crates/router/src/services/kafka/payment_attempt_event.rs b/crates/router/src/services/kafka/payment_attempt_event.rs
index c6337a3b5f0..e9f8fbdfc5c 100644
--- a/crates/router/src/services/kafka/payment_attempt_event.rs
+++ b/crates/router/src/services/kafka/payment_attempt_event.rs
@@ -1,5 +1,5 @@
// use diesel_models::enums::MandateDetails;
-use common_utils::types::MinorUnit;
+use common_utils::{id_type, types::MinorUnit};
use diesel_models::enums as storage_enums;
use hyperswitch_domain_models::{
mandates::MandateDetails, payments::payment_attempt::PaymentAttempt,
@@ -10,7 +10,7 @@ use time::OffsetDateTime;
#[derive(serde::Serialize, Debug)]
pub struct KafkaPaymentAttemptEvent<'a> {
pub payment_id: &'a String,
- pub merchant_id: &'a common_utils::id_type::MerchantId,
+ pub merchant_id: &'a id_type::MerchantId,
pub attempt_id: &'a String,
pub status: storage_enums::AttemptStatus,
pub amount: MinorUnit,
@@ -48,13 +48,16 @@ pub struct KafkaPaymentAttemptEvent<'a> {
pub error_reason: Option<&'a String>,
pub multiple_capture_count: Option<i16>,
pub amount_capturable: MinorUnit,
- pub merchant_connector_id: Option<&'a common_utils::id_type::MerchantConnectorAccountId>,
+ pub merchant_connector_id: Option<&'a id_type::MerchantConnectorAccountId>,
pub net_amount: MinorUnit,
pub unified_code: Option<&'a String>,
pub unified_message: Option<&'a String>,
pub mandate_data: Option<&'a MandateDetails>,
pub client_source: Option<&'a String>,
pub client_version: Option<&'a String>,
+ pub profile_id: &'a id_type::ProfileId,
+ pub organization_id: &'a id_type::OrganizationId,
+ pub card_network: Option<String>,
}
impl<'a> KafkaPaymentAttemptEvent<'a> {
@@ -101,6 +104,17 @@ impl<'a> KafkaPaymentAttemptEvent<'a> {
mandate_data: attempt.mandate_data.as_ref(),
client_source: attempt.client_source.as_ref(),
client_version: attempt.client_version.as_ref(),
+ profile_id: &attempt.profile_id,
+ organization_id: &attempt.organization_id,
+ card_network: attempt
+ .payment_method_data
+ .as_ref()
+ .and_then(|data| data.as_object())
+ .and_then(|pm| pm.get("card"))
+ .and_then(|data| data.as_object())
+ .and_then(|card| card.get("card_network"))
+ .and_then(|network| network.as_str())
+ .map(|network| network.to_string()),
}
}
}
diff --git a/crates/router/src/services/kafka/payment_intent.rs b/crates/router/src/services/kafka/payment_intent.rs
index 29aa5632837..31f424b2a28 100644
--- a/crates/router/src/services/kafka/payment_intent.rs
+++ b/crates/router/src/services/kafka/payment_intent.rs
@@ -40,6 +40,7 @@ pub struct KafkaPaymentIntent<'a> {
pub customer_email: Option<HashedString<pii::EmailStrategy>>,
pub feature_metadata: Option<&'a Value>,
pub merchant_order_reference_id: Option<&'a String>,
+ pub organization_id: &'a id_type::OrganizationId,
}
impl<'a> KafkaPaymentIntent<'a> {
@@ -82,6 +83,7 @@ impl<'a> KafkaPaymentIntent<'a> {
.map(|email| HashedString::from(Secret::new(email.to_string()))),
feature_metadata: intent.feature_metadata.as_ref(),
merchant_order_reference_id: intent.merchant_order_reference_id.as_ref(),
+ organization_id: &intent.organization_id,
}
}
}
diff --git a/crates/router/src/services/kafka/payment_intent_event.rs b/crates/router/src/services/kafka/payment_intent_event.rs
index 50d2c48a4bd..f92f3fa9326 100644
--- a/crates/router/src/services/kafka/payment_intent_event.rs
+++ b/crates/router/src/services/kafka/payment_intent_event.rs
@@ -41,6 +41,7 @@ pub struct KafkaPaymentIntentEvent<'a> {
pub customer_email: Option<HashedString<pii::EmailStrategy>>,
pub feature_metadata: Option<&'a Value>,
pub merchant_order_reference_id: Option<&'a String>,
+ pub organization_id: &'a id_type::OrganizationId,
}
impl<'a> KafkaPaymentIntentEvent<'a> {
@@ -83,6 +84,7 @@ impl<'a> KafkaPaymentIntentEvent<'a> {
.map(|email| HashedString::from(Secret::new(email.to_string()))),
feature_metadata: intent.feature_metadata.as_ref(),
merchant_order_reference_id: intent.merchant_order_reference_id.as_ref(),
+ organization_id: &intent.organization_id,
}
}
}
diff --git a/crates/router/src/services/kafka/refund.rs b/crates/router/src/services/kafka/refund.rs
index 1aaf5d2ccb3..09537812e57 100644
--- a/crates/router/src/services/kafka/refund.rs
+++ b/crates/router/src/services/kafka/refund.rs
@@ -1,4 +1,4 @@
-use common_utils::types::MinorUnit;
+use common_utils::{id_type, types::MinorUnit};
use diesel_models::{enums as storage_enums, refund::Refund};
use time::OffsetDateTime;
@@ -7,7 +7,7 @@ pub struct KafkaRefund<'a> {
pub internal_reference_id: &'a String,
pub refund_id: &'a String, //merchant_reference id
pub payment_id: &'a String,
- pub merchant_id: &'a common_utils::id_type::MerchantId,
+ pub merchant_id: &'a id_type::MerchantId,
pub connector_transaction_id: &'a String,
pub connector: &'a String,
pub connector_refund_id: Option<&'a String>,
@@ -28,6 +28,8 @@ pub struct KafkaRefund<'a> {
pub attempt_id: &'a String,
pub refund_reason: Option<&'a String>,
pub refund_error_code: Option<&'a String>,
+ pub profile_id: Option<&'a id_type::ProfileId>,
+ pub organization_id: &'a id_type::OrganizationId,
}
impl<'a> KafkaRefund<'a> {
@@ -55,6 +57,8 @@ impl<'a> KafkaRefund<'a> {
attempt_id: &refund.attempt_id,
refund_reason: refund.refund_reason.as_ref(),
refund_error_code: refund.refund_error_code.as_ref(),
+ profile_id: refund.profile_id.as_ref(),
+ organization_id: &refund.organization_id,
}
}
}
diff --git a/crates/router/src/services/kafka/refund_event.rs b/crates/router/src/services/kafka/refund_event.rs
index 9480220104c..764146f808f 100644
--- a/crates/router/src/services/kafka/refund_event.rs
+++ b/crates/router/src/services/kafka/refund_event.rs
@@ -1,4 +1,4 @@
-use common_utils::types::MinorUnit;
+use common_utils::{id_type, types::MinorUnit};
use diesel_models::{enums as storage_enums, refund::Refund};
use time::OffsetDateTime;
@@ -8,7 +8,7 @@ pub struct KafkaRefundEvent<'a> {
pub internal_reference_id: &'a String,
pub refund_id: &'a String, //merchant_reference id
pub payment_id: &'a String,
- pub merchant_id: &'a common_utils::id_type::MerchantId,
+ pub merchant_id: &'a id_type::MerchantId,
pub connector_transaction_id: &'a String,
pub connector: &'a String,
pub connector_refund_id: Option<&'a String>,
@@ -29,6 +29,8 @@ pub struct KafkaRefundEvent<'a> {
pub attempt_id: &'a String,
pub refund_reason: Option<&'a String>,
pub refund_error_code: Option<&'a String>,
+ pub profile_id: Option<&'a id_type::ProfileId>,
+ pub organization_id: &'a id_type::OrganizationId,
}
impl<'a> KafkaRefundEvent<'a> {
@@ -56,6 +58,8 @@ impl<'a> KafkaRefundEvent<'a> {
attempt_id: &refund.attempt_id,
refund_reason: refund.refund_reason.as_ref(),
refund_error_code: refund.refund_error_code.as_ref(),
+ profile_id: refund.profile_id.as_ref(),
+ organization_id: &refund.organization_id,
}
}
}
diff --git a/crates/router/src/types/storage/payment_attempt.rs b/crates/router/src/types/storage/payment_attempt.rs
index 669427d88c7..6775f9a81a7 100644
--- a/crates/router/src/types/storage/payment_attempt.rs
+++ b/crates/router/src/types/storage/payment_attempt.rs
@@ -129,7 +129,60 @@ mod tests {
connector: Some(connector),
created_at: current_time.into(),
modified_at: current_time.into(),
- ..PaymentAttemptNew::default()
+ merchant_id: Default::default(),
+ attempt_id: Default::default(),
+ status: Default::default(),
+ amount: Default::default(),
+ net_amount: Default::default(),
+ currency: Default::default(),
+ save_to_locker: Default::default(),
+ error_message: Default::default(),
+ offer_amount: Default::default(),
+ surcharge_amount: Default::default(),
+ tax_amount: Default::default(),
+ payment_method_id: Default::default(),
+ payment_method: Default::default(),
+ capture_method: Default::default(),
+ capture_on: Default::default(),
+ confirm: Default::default(),
+ authentication_type: Default::default(),
+ last_synced: Default::default(),
+ cancellation_reason: Default::default(),
+ amount_to_capture: Default::default(),
+ mandate_id: Default::default(),
+ browser_info: Default::default(),
+ payment_token: Default::default(),
+ error_code: Default::default(),
+ connector_metadata: Default::default(),
+ payment_experience: Default::default(),
+ payment_method_type: Default::default(),
+ payment_method_data: Default::default(),
+ business_sub_label: Default::default(),
+ straight_through_algorithm: Default::default(),
+ preprocessing_step_id: Default::default(),
+ mandate_details: Default::default(),
+ error_reason: Default::default(),
+ connector_response_reference_id: Default::default(),
+ multiple_capture_count: Default::default(),
+ amount_capturable: Default::default(),
+ updated_by: Default::default(),
+ authentication_data: Default::default(),
+ encoded_data: Default::default(),
+ merchant_connector_id: Default::default(),
+ unified_code: Default::default(),
+ unified_message: Default::default(),
+ external_three_ds_authentication_attempted: Default::default(),
+ authentication_connector: Default::default(),
+ authentication_id: Default::default(),
+ mandate_data: Default::default(),
+ payment_method_billing_address_id: Default::default(),
+ fingerprint_id: Default::default(),
+ charge_id: Default::default(),
+ client_source: Default::default(),
+ client_version: Default::default(),
+ customer_acceptance: Default::default(),
+ profile_id: common_utils::generate_profile_id_of_default_length(),
+ organization_id: Default::default(),
};
let store = state
@@ -163,7 +216,58 @@ mod tests {
created_at: current_time.into(),
modified_at: current_time.into(),
attempt_id: attempt_id.clone(),
- ..PaymentAttemptNew::default()
+ status: Default::default(),
+ amount: Default::default(),
+ net_amount: Default::default(),
+ currency: Default::default(),
+ save_to_locker: Default::default(),
+ error_message: Default::default(),
+ offer_amount: Default::default(),
+ surcharge_amount: Default::default(),
+ tax_amount: Default::default(),
+ payment_method_id: Default::default(),
+ payment_method: Default::default(),
+ capture_method: Default::default(),
+ capture_on: Default::default(),
+ confirm: Default::default(),
+ authentication_type: Default::default(),
+ last_synced: Default::default(),
+ cancellation_reason: Default::default(),
+ amount_to_capture: Default::default(),
+ mandate_id: Default::default(),
+ browser_info: Default::default(),
+ payment_token: Default::default(),
+ error_code: Default::default(),
+ connector_metadata: Default::default(),
+ payment_experience: Default::default(),
+ payment_method_type: Default::default(),
+ payment_method_data: Default::default(),
+ business_sub_label: Default::default(),
+ straight_through_algorithm: Default::default(),
+ preprocessing_step_id: Default::default(),
+ mandate_details: Default::default(),
+ error_reason: Default::default(),
+ connector_response_reference_id: Default::default(),
+ multiple_capture_count: Default::default(),
+ amount_capturable: Default::default(),
+ updated_by: Default::default(),
+ authentication_data: Default::default(),
+ encoded_data: Default::default(),
+ merchant_connector_id: Default::default(),
+ unified_code: Default::default(),
+ unified_message: Default::default(),
+ external_three_ds_authentication_attempted: Default::default(),
+ authentication_connector: Default::default(),
+ authentication_id: Default::default(),
+ mandate_data: Default::default(),
+ payment_method_billing_address_id: Default::default(),
+ fingerprint_id: Default::default(),
+ charge_id: Default::default(),
+ client_source: Default::default(),
+ client_version: Default::default(),
+ customer_acceptance: Default::default(),
+ profile_id: common_utils::generate_profile_id_of_default_length(),
+ organization_id: Default::default(),
};
let store = state
.stores
@@ -207,10 +311,59 @@ mod tests {
connector: Some(connector),
created_at: current_time.into(),
modified_at: current_time.into(),
- // Adding a mandate_id
mandate_id: Some("man_121212".to_string()),
attempt_id: uuid.clone(),
- ..PaymentAttemptNew::default()
+ status: Default::default(),
+ amount: Default::default(),
+ net_amount: Default::default(),
+ currency: Default::default(),
+ save_to_locker: Default::default(),
+ error_message: Default::default(),
+ offer_amount: Default::default(),
+ surcharge_amount: Default::default(),
+ tax_amount: Default::default(),
+ payment_method_id: Default::default(),
+ payment_method: Default::default(),
+ capture_method: Default::default(),
+ capture_on: Default::default(),
+ confirm: Default::default(),
+ authentication_type: Default::default(),
+ last_synced: Default::default(),
+ cancellation_reason: Default::default(),
+ amount_to_capture: Default::default(),
+ browser_info: Default::default(),
+ payment_token: Default::default(),
+ error_code: Default::default(),
+ connector_metadata: Default::default(),
+ payment_experience: Default::default(),
+ payment_method_type: Default::default(),
+ payment_method_data: Default::default(),
+ business_sub_label: Default::default(),
+ straight_through_algorithm: Default::default(),
+ preprocessing_step_id: Default::default(),
+ mandate_details: Default::default(),
+ error_reason: Default::default(),
+ connector_response_reference_id: Default::default(),
+ multiple_capture_count: Default::default(),
+ amount_capturable: Default::default(),
+ updated_by: Default::default(),
+ authentication_data: Default::default(),
+ encoded_data: Default::default(),
+ merchant_connector_id: Default::default(),
+ unified_code: Default::default(),
+ unified_message: Default::default(),
+ external_three_ds_authentication_attempted: Default::default(),
+ authentication_connector: Default::default(),
+ authentication_id: Default::default(),
+ mandate_data: Default::default(),
+ payment_method_billing_address_id: Default::default(),
+ fingerprint_id: Default::default(),
+ charge_id: Default::default(),
+ client_source: Default::default(),
+ client_version: Default::default(),
+ customer_acceptance: Default::default(),
+ profile_id: common_utils::generate_profile_id_of_default_length(),
+ organization_id: Default::default(),
};
let store = state
.stores
diff --git a/crates/router/src/utils/user/sample_data.rs b/crates/router/src/utils/user/sample_data.rs
index ac9272c86d7..94890a41ad7 100644
--- a/crates/router/src/utils/user/sample_data.rs
+++ b/crates/router/src/utils/user/sample_data.rs
@@ -20,6 +20,7 @@ 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>)>> {
let sample_data_size: usize = req.record.unwrap_or(100);
let key_manager_state = &state.into();
@@ -252,6 +253,7 @@ pub async fn generate_sample_data(
merchant_order_reference_id: Default::default(),
shipping_details: None,
is_payment_processor_token_flow: None,
+ organization_id: org_id.clone(),
};
let payment_attempt = PaymentAttemptBatchNew {
attempt_id: attempt_id.clone(),
@@ -329,6 +331,8 @@ pub async fn generate_sample_data(
client_source: None,
client_version: None,
customer_acceptance: None,
+ profile_id: profile_id.clone(),
+ organization_id: org_id.clone(),
};
let refund = if refunds_count < number_of_refunds && !is_failed_payment {
@@ -364,6 +368,7 @@ pub async fn generate_sample_data(
updated_by: merchant_from_db.storage_scheme.to_string(),
merchant_connector_id: payment_attempt.merchant_connector_id.clone(),
charges: None,
+ organization_id: org_id.clone(),
})
} else {
None
diff --git a/crates/storage_impl/src/mock_db/payment_attempt.rs b/crates/storage_impl/src/mock_db/payment_attempt.rs
index 37e01cbbb5c..67840636de8 100644
--- a/crates/storage_impl/src/mock_db/payment_attempt.rs
+++ b/crates/storage_impl/src/mock_db/payment_attempt.rs
@@ -158,6 +158,8 @@ impl PaymentAttemptInterface for MockDb {
client_source: payment_attempt.client_source,
client_version: payment_attempt.client_version,
customer_acceptance: payment_attempt.customer_acceptance,
+ organization_id: payment_attempt.organization_id,
+ profile_id: payment_attempt.profile_id,
};
payment_attempts.push(payment_attempt.clone());
Ok(payment_attempt)
diff --git a/crates/storage_impl/src/payments/payment_attempt.rs b/crates/storage_impl/src/payments/payment_attempt.rs
index 382abacfa78..63b10cf01bd 100644
--- a/crates/storage_impl/src/payments/payment_attempt.rs
+++ b/crates/storage_impl/src/payments/payment_attempt.rs
@@ -419,6 +419,8 @@ impl<T: DatabaseStore> PaymentAttemptInterface for KVRouterStore<T> {
client_source: payment_attempt.client_source.clone(),
client_version: payment_attempt.client_version.clone(),
customer_acceptance: payment_attempt.customer_acceptance.clone(),
+ organization_id: payment_attempt.organization_id.clone(),
+ profile_id: payment_attempt.profile_id.clone(),
};
let field = format!("pa_{}", created_attempt.attempt_id);
@@ -1189,6 +1191,15 @@ impl DataModelExt for PaymentAttempt {
connector_metadata: self.connector_metadata,
payment_experience: self.payment_experience,
payment_method_type: self.payment_method_type,
+ card_network: self
+ .payment_method_data
+ .as_ref()
+ .and_then(|data| data.as_object())
+ .and_then(|card| card.get("card"))
+ .and_then(|data| data.as_object())
+ .and_then(|card| card.get("card_network"))
+ .and_then(|network| network.as_str())
+ .map(|network| network.to_string()),
payment_method_data: self.payment_method_data,
business_sub_label: self.business_sub_label,
straight_through_algorithm: self.straight_through_algorithm,
@@ -1215,6 +1226,8 @@ impl DataModelExt for PaymentAttempt {
client_source: self.client_source,
client_version: self.client_version,
customer_acceptance: self.customer_acceptance,
+ organization_id: self.organization_id,
+ profile_id: self.profile_id,
}
}
@@ -1282,6 +1295,8 @@ impl DataModelExt for PaymentAttempt {
client_source: storage_model.client_source,
client_version: storage_model.client_version,
customer_acceptance: storage_model.customer_acceptance,
+ organization_id: storage_model.organization_id,
+ profile_id: storage_model.profile_id,
}
}
}
@@ -1330,6 +1345,15 @@ impl DataModelExt for PaymentAttempt {
connector_metadata: self.connector_metadata,
payment_experience: self.payment_experience,
payment_method_type: self.payment_method_type,
+ card_network: self
+ .payment_method_data
+ .as_ref()
+ .and_then(|data| data.as_object())
+ .and_then(|card| card.get("card"))
+ .and_then(|data| data.as_object())
+ .and_then(|card| card.get("card_network"))
+ .and_then(|network| network.as_str())
+ .map(|network| network.to_string()),
payment_method_data: self.payment_method_data,
business_sub_label: self.business_sub_label,
straight_through_algorithm: self.straight_through_algorithm,
@@ -1356,6 +1380,8 @@ impl DataModelExt for PaymentAttempt {
client_source: self.client_source,
client_version: self.client_version,
customer_acceptance: self.customer_acceptance,
+ organization_id: self.organization_id,
+ profile_id: self.profile_id,
}
}
@@ -1423,6 +1449,8 @@ impl DataModelExt for PaymentAttempt {
client_source: storage_model.client_source,
client_version: storage_model.client_version,
customer_acceptance: storage_model.customer_acceptance,
+ organization_id: storage_model.organization_id,
+ profile_id: storage_model.profile_id,
}
}
}
@@ -1471,6 +1499,15 @@ impl DataModelExt for PaymentAttemptNew {
connector_metadata: self.connector_metadata,
payment_experience: self.payment_experience,
payment_method_type: self.payment_method_type,
+ card_network: self
+ .payment_method_data
+ .as_ref()
+ .and_then(|data| data.as_object())
+ .and_then(|card| card.get("card"))
+ .and_then(|value| value.as_object())
+ .and_then(|map| map.get("card_network"))
+ .and_then(|network| network.as_str())
+ .map(|network| network.to_string()),
payment_method_data: self.payment_method_data,
business_sub_label: self.business_sub_label,
straight_through_algorithm: self.straight_through_algorithm,
@@ -1497,6 +1534,8 @@ impl DataModelExt for PaymentAttemptNew {
client_source: self.client_source,
client_version: self.client_version,
customer_acceptance: self.customer_acceptance,
+ organization_id: self.organization_id,
+ profile_id: self.profile_id,
}
}
@@ -1563,6 +1602,8 @@ impl DataModelExt for PaymentAttemptNew {
client_source: storage_model.client_source,
client_version: storage_model.client_version,
customer_acceptance: storage_model.customer_acceptance,
+ organization_id: storage_model.organization_id,
+ profile_id: storage_model.profile_id,
}
}
}
diff --git a/migrations/2024-08-20-112035_add-profile-id-to-txn-tables/down.sql b/migrations/2024-08-20-112035_add-profile-id-to-txn-tables/down.sql
new file mode 100644
index 00000000000..66707bebb4e
--- /dev/null
+++ b/migrations/2024-08-20-112035_add-profile-id-to-txn-tables/down.sql
@@ -0,0 +1,20 @@
+-- This file should undo anything in `up.sql`
+-- Remove profile_id from payment_attempt table
+ALTER TABLE payment_attempt
+DROP COLUMN IF EXISTS profile_id;
+
+-- Remove organization_id from payment_attempt table
+ALTER TABLE payment_attempt
+DROP COLUMN IF EXISTS organization_id;
+
+-- Remove organization_id from payment_intent table
+ALTER TABLE payment_intent
+DROP COLUMN IF EXISTS organization_id;
+
+-- Remove organization_id from refund table
+ALTER TABLE refund
+DROP COLUMN IF EXISTS organization_id;
+
+-- Remove organization_id from dispute table
+ALTER TABLE dispute
+DROP COLUMN IF EXISTS organization_id;
\ No newline at end of file
diff --git a/migrations/2024-08-20-112035_add-profile-id-to-txn-tables/up.sql b/migrations/2024-08-20-112035_add-profile-id-to-txn-tables/up.sql
new file mode 100644
index 00000000000..74f55308fc6
--- /dev/null
+++ b/migrations/2024-08-20-112035_add-profile-id-to-txn-tables/up.sql
@@ -0,0 +1,43 @@
+-- Your SQL goes here
+ALTER TABLE payment_attempt
+ADD COLUMN IF NOT EXISTS profile_id VARCHAR(64) NOT NULL DEFAULT 'default_profile';
+
+-- Add organization_id to payment_attempt table
+ALTER TABLE payment_attempt
+ADD COLUMN IF NOT EXISTS organization_id VARCHAR(32) NOT NULL DEFAULT 'default_org';
+
+-- Add organization_id to payment_intent table
+ALTER TABLE payment_intent
+ADD COLUMN IF NOT EXISTS organization_id VARCHAR(32) NOT NULL DEFAULT 'default_org';
+
+-- Add organization_id to refund table
+ALTER TABLE refund
+ADD COLUMN IF NOT EXISTS organization_id VARCHAR(32) NOT NULL DEFAULT 'default_org';
+
+-- Add organization_id to dispute table
+ALTER TABLE dispute
+ADD COLUMN IF NOT EXISTS organization_id VARCHAR(32) NOT NULL DEFAULT 'default_org';
+
+-- This doesn't work on V2
+-- The below backfill step has to be run after the code deployment
+-- UPDATE payment_attempt pa
+-- SET organization_id = ma.organization_id
+-- FROM merchant_account ma
+-- WHERE pa.merchant_id = ma.merchant_id;
+
+-- UPDATE payment_intent pi
+-- SET organization_id = ma.organization_id
+-- FROM merchant_account ma
+-- WHERE pi.merchant_id = ma.merchant_id;
+
+-- UPDATE refund r
+-- SET organization_id = ma.organization_id
+-- FROM merchant_account ma
+-- WHERE r.merchant_id = ma.merchant_id;
+
+-- UPDATE payment_attempt pa
+-- SET profile_id = pi.profile_id
+-- FROM payment_intent pi
+-- WHERE pa.payment_id = pi.payment_id
+-- AND pa.merchant_id = pi.merchant_id
+-- AND pi.profile_id IS NOT NULL;
diff --git a/migrations/2024-08-26-043046_add-card-network-field-for-pa/down.sql b/migrations/2024-08-26-043046_add-card-network-field-for-pa/down.sql
new file mode 100644
index 00000000000..8dc04221730
--- /dev/null
+++ b/migrations/2024-08-26-043046_add-card-network-field-for-pa/down.sql
@@ -0,0 +1,3 @@
+-- This file should undo anything in `up.sql`
+
+ALTER TABLE payment_attempt DROP COLUMN card_network;
\ No newline at end of file
diff --git a/migrations/2024-08-26-043046_add-card-network-field-for-pa/up.sql b/migrations/2024-08-26-043046_add-card-network-field-for-pa/up.sql
new file mode 100644
index 00000000000..43f29b56d72
--- /dev/null
+++ b/migrations/2024-08-26-043046_add-card-network-field-for-pa/up.sql
@@ -0,0 +1,5 @@
+-- Your SQL goes here
+
+ALTER TABLE payment_attempt ADD COLUMN card_network VARCHAR(32);
+UPDATE payment_attempt
+SET card_network = (payment_method_data -> 'card' -> 'card_network')::VARCHAR(32);
\ No newline at end of file
|
2024-08-26T07:43:24Z
|
## Type of Change
<!-- Put an `x` in the boxes that apply -->
- [ ] Bugfix
- [x] New feature
- [ ] Enhancement
- [ ] Refactoring
- [ ] Dependency updates
- [ ] Documentation
- [ ] CI/CD
## Description
<!-- Describe your changes in detail -->
Add organisation id for
- payment intents
- payment attempts
- refunds
- disputes
add profile id & card network for payment attempts
Add the above fields in clickhouse & kafka as well
### Additional Changes
- [ ] This PR modifies the API contract
- [ ] This PR modifies the database schema
- [ ] This PR modifies application configuration/environment variables
<!--
Provide links to the files with corresponding changes.
Following are the paths where you can find config files:
1. `config`
2. `crates/router/src/configs`
3. `loadtest/config`
-->
## Motivation and Context
<!--
Why is this change required? What problem does it solve?
If it fixes an open issue, please link to the issue here.
If you don't have an issue, we'd recommend starting with one first so the PR
can focus on the implementation (unless it is an obvious bug or documentation fix
that will have little conversation).
-->
Adding these fields to provide better authentication guards
## How did you test it?
<!--
Did you write an integration/unit/API test to verify the code changes?
Or did you test this change manually (provide relevant screenshots)?
-->
<img width="975" alt="image" src="https://github.com/user-attachments/assets/dcb1ff45-4771-4382-9f97-36039abb9ef2">
Check for the added columns in pgweb/grafana
## Checklist
<!-- Put an `x` in the boxes that apply -->
- [ ] I formatted the code `cargo +nightly fmt --all`
- [ ] I addressed lints thrown by `cargo clippy`
- [ ] I reviewed the submitted code
- [ ] I added unit tests for my changes where possible
|
c555a88c6730a1216aa291bc7f7a38e3df08c469
|
|
juspay/hyperswitch
|
juspay__hyperswitch-5689
|
Bug: feat(users_roles): support switch for new user hierarchy
Support switch
- At org level
- At merchant level
- At profile level
- For internal users
Issue new token and set permissions accordingly
|
diff --git a/crates/api_models/src/events/user.rs b/crates/api_models/src/events/user.rs
index 862c361d465..590179c052c 100644
--- a/crates/api_models/src/events/user.rs
+++ b/crates/api_models/src/events/user.rs
@@ -17,10 +17,10 @@ use crate::user::{
GetUserRoleDetailsRequest, GetUserRoleDetailsResponse, InviteUserRequest, ListUsersResponse,
ReInviteUserRequest, RecoveryCodes, ResetPasswordRequest, RotatePasswordRequest,
SendVerifyEmailRequest, SignInResponse, SignUpRequest, SignUpWithMerchantIdRequest,
- SsoSignInRequest, SwitchMerchantIdRequest, TokenOrPayloadResponse, TokenResponse,
- TwoFactorAuthStatusResponse, UpdateUserAccountDetailsRequest,
- UpdateUserAuthenticationMethodRequest, UserFromEmailRequest, UserMerchantCreate,
- VerifyEmailRequest, VerifyRecoveryCodeRequest, VerifyTotpRequest,
+ SsoSignInRequest, SwitchMerchantRequest, SwitchOrganizationRequest, SwitchProfileRequest,
+ TokenOrPayloadResponse, TokenResponse, TwoFactorAuthStatusResponse,
+ UpdateUserAccountDetailsRequest, UpdateUserAuthenticationMethodRequest, UserFromEmailRequest,
+ UserMerchantCreate, VerifyEmailRequest, VerifyRecoveryCodeRequest, VerifyTotpRequest,
};
impl ApiEventMetric for DashboardEntryResponse {
@@ -56,7 +56,9 @@ common_utils::impl_api_event_type!(
GetMetaDataResponse,
GetMetaDataRequest,
SetMetaDataRequest,
- SwitchMerchantIdRequest,
+ SwitchOrganizationRequest,
+ SwitchMerchantRequest,
+ SwitchProfileRequest,
CreateInternalUserRequest,
UserMerchantCreate,
ListUsersResponse,
diff --git a/crates/api_models/src/events/user_role.rs b/crates/api_models/src/events/user_role.rs
index 7e8eaf17e30..5b5da0ec50a 100644
--- a/crates/api_models/src/events/user_role.rs
+++ b/crates/api_models/src/events/user_role.rs
@@ -7,7 +7,7 @@ use crate::user_role::{
UpdateRoleRequest,
},
AcceptInvitationRequest, AuthorizationInfoResponse, DeleteUserRoleRequest,
- MerchantSelectRequest, TransferOrgOwnershipRequest, UpdateUserRoleRequest,
+ MerchantSelectRequest, UpdateUserRoleRequest,
};
common_utils::impl_api_event_type!(
@@ -20,7 +20,6 @@ common_utils::impl_api_event_type!(
MerchantSelectRequest,
AcceptInvitationRequest,
DeleteUserRoleRequest,
- TransferOrgOwnershipRequest,
CreateRoleRequest,
UpdateRoleRequest,
ListRolesResponse,
diff --git a/crates/api_models/src/user.rs b/crates/api_models/src/user.rs
index 1fdf47425e2..2547f082039 100644
--- a/crates/api_models/src/user.rs
+++ b/crates/api_models/src/user.rs
@@ -124,10 +124,20 @@ pub struct AcceptInviteFromEmailRequest {
}
#[derive(Debug, serde::Deserialize, serde::Serialize)]
-pub struct SwitchMerchantIdRequest {
+pub struct SwitchOrganizationRequest {
+ pub org_id: id_type::OrganizationId,
+}
+
+#[derive(Debug, serde::Deserialize, serde::Serialize)]
+pub struct SwitchMerchantRequest {
pub merchant_id: id_type::MerchantId,
}
+#[derive(Debug, serde::Deserialize, serde::Serialize)]
+pub struct SwitchProfileRequest {
+ pub profile_id: id_type::ProfileId,
+}
+
#[derive(serde::Deserialize, Debug, serde::Serialize)]
pub struct CreateInternalUserRequest {
pub name: Secret<String>,
diff --git a/crates/api_models/src/user_role.rs b/crates/api_models/src/user_role.rs
index 5319c81385a..c9f222cb7be 100644
--- a/crates/api_models/src/user_role.rs
+++ b/crates/api_models/src/user_role.rs
@@ -133,8 +133,3 @@ pub struct AcceptInvitationRequest {
pub struct DeleteUserRoleRequest {
pub email: pii::Email,
}
-
-#[derive(Debug, serde::Deserialize, serde::Serialize)]
-pub struct TransferOrgOwnershipRequest {
- pub email: pii::Email,
-}
diff --git a/crates/router/src/core/user.rs b/crates/router/src/core/user.rs
index c3d0dbae04e..9510ddd632d 100644
--- a/crates/router/src/core/user.rs
+++ b/crates/router/src/core/user.rs
@@ -1320,12 +1320,12 @@ pub async fn create_internal_user(
pub async fn switch_merchant_id(
state: SessionState,
- request: user_api::SwitchMerchantIdRequest,
+ request: user_api::SwitchMerchantRequest,
user_from_token: auth::UserFromToken,
) -> UserResponse<user_api::DashboardEntryResponse> {
if user_from_token.merchant_id == request.merchant_id {
return Err(UserErrors::InvalidRoleOperationWithMessage(
- "User switching to same merchant id".to_string(),
+ "User switching to same merchant_id".to_string(),
)
.into());
}
@@ -1375,9 +1375,9 @@ pub async fn switch_merchant_id(
})?
.organization_id;
- let token = utils::user::generate_jwt_auth_token_with_custom_role_attributes(
+ let token = utils::user::generate_jwt_auth_token_with_attributes(
&state,
- &user,
+ user_from_token.user_id,
request.merchant_id.clone(),
org_id.clone(),
user_from_token.role_id.clone(),
@@ -1557,7 +1557,7 @@ pub async fn list_users_for_merchant_account(
.list_user_roles_by_merchant_id(&user_from_token.merchant_id, UserRoleVersion::V1)
.await
.change_context(UserErrors::InternalServerError)
- .attach_printable("No user roles for given merchant id")?
+ .attach_printable("No user roles for given merchant_id")?
.into_iter()
.map(|role| (role.user_id.clone(), role))
.collect();
@@ -1569,7 +1569,7 @@ pub async fn list_users_for_merchant_account(
.find_users_by_user_ids(user_ids)
.await
.change_context(UserErrors::InternalServerError)
- .attach_printable("No users for given merchant id")?;
+ .attach_printable("No users for given merchant_id")?;
let users_and_user_roles: Vec<_> = users
.into_iter()
@@ -2134,7 +2134,7 @@ pub async fn verify_recovery_code(
state: SessionState,
user_token: auth::UserIdFromAuth,
req: user_api::VerifyRecoveryCodeRequest,
-) -> UserResponse<user_api::TokenResponse> {
+) -> UserResponse<()> {
let user_from_db: domain::UserFromStorage = state
.global_store
.find_user_by_id(&user_token.user_id)
@@ -2760,3 +2760,442 @@ pub async fn list_profiles_for_user_in_org_and_merchant_account(
Ok(ApplicationResponse::Json(profiles))
}
+
+pub async fn switch_org_for_user(
+ state: SessionState,
+ request: user_api::SwitchOrganizationRequest,
+ user_from_token: auth::UserFromToken,
+) -> UserResponse<user_api::TokenResponse> {
+ if user_from_token.org_id == request.org_id {
+ return Err(UserErrors::InvalidRoleOperationWithMessage(
+ "User switching to same org".to_string(),
+ )
+ .into());
+ }
+
+ let key_manager_state = &(&state).into();
+ let role_info = roles::RoleInfo::from_role_id(
+ &state,
+ &user_from_token.role_id,
+ &user_from_token.merchant_id,
+ &user_from_token.org_id,
+ )
+ .await
+ .change_context(UserErrors::InternalServerError)
+ .attach_printable("Failed to retrieve role information")?;
+
+ if role_info.get_entity_type() == EntityType::Internal {
+ return Err(UserErrors::InvalidRoleOperationWithMessage(
+ "Org switching not allowed for Internal role".to_string(),
+ )
+ .into());
+ }
+
+ let user_role = state
+ .store
+ .list_user_roles(
+ &user_from_token.user_id,
+ Some(&request.org_id),
+ None,
+ None,
+ None,
+ None,
+ )
+ .await
+ .change_context(UserErrors::InternalServerError)
+ .attach_printable("Failed to list user roles by user_id and org_id")?
+ .into_iter()
+ .find(|role| role.status == UserStatus::Active)
+ .ok_or(UserErrors::InvalidRoleOperationWithMessage(
+ "No user role found for the requested org_id".to_string(),
+ ))?
+ .to_owned();
+
+ let merchant_id = if let Some(merchant_id) = &user_role.merchant_id {
+ merchant_id.clone()
+ } else {
+ state
+ .store
+ .list_merchant_accounts_by_organization_id(
+ key_manager_state,
+ request.org_id.get_string_repr(),
+ )
+ .await
+ .change_context(UserErrors::InternalServerError)
+ .attach_printable("Failed to list merchant accounts by organization_id")?
+ .first()
+ .ok_or(UserErrors::InternalServerError)
+ .attach_printable("No merchant account found for the given organization_id")?
+ .get_id()
+ .clone()
+ };
+
+ let profile_id = if let Some(profile_id) = &user_role.profile_id {
+ profile_id.clone()
+ } else {
+ let merchant_key_store = state
+ .store
+ .get_merchant_key_store_by_merchant_id(
+ key_manager_state,
+ &merchant_id,
+ &state.store.get_master_key().to_vec().into(),
+ )
+ .await
+ .change_context(UserErrors::InternalServerError)
+ .attach_printable("Failed to retrieve merchant key store by merchant_id")?;
+
+ state
+ .store
+ .list_business_profile_by_merchant_id(
+ key_manager_state,
+ &merchant_key_store,
+ &merchant_id,
+ )
+ .await
+ .change_context(UserErrors::InternalServerError)
+ .attach_printable("Failed to list business profiles by merchant_id")?
+ .first()
+ .ok_or(UserErrors::InternalServerError)
+ .attach_printable("No business profile found for the merchant_id")?
+ .profile_id
+ .clone()
+ };
+
+ let token = utils::user::generate_jwt_auth_token_with_attributes(
+ &state,
+ user_from_token.user_id,
+ merchant_id.clone(),
+ request.org_id.clone(),
+ user_role.role_id.clone(),
+ Some(profile_id.clone()),
+ )
+ .await?;
+
+ utils::user_role::set_role_permissions_in_cache_by_role_id_merchant_id_org_id(
+ &state,
+ &user_role.role_id,
+ &merchant_id,
+ &request.org_id,
+ )
+ .await;
+
+ let response = user_api::TokenResponse {
+ token: token.clone(),
+ token_type: common_enums::TokenPurpose::UserInfo,
+ };
+
+ auth::cookies::set_cookie_response(response, token)
+}
+
+pub async fn switch_merchant_for_user_in_org(
+ state: SessionState,
+ request: user_api::SwitchMerchantRequest,
+ user_from_token: auth::UserFromToken,
+) -> UserResponse<user_api::TokenResponse> {
+ if user_from_token.merchant_id == request.merchant_id {
+ return Err(UserErrors::InvalidRoleOperationWithMessage(
+ "User switching to same merchant".to_string(),
+ )
+ .into());
+ }
+
+ let key_manager_state = &(&state).into();
+ let role_info = roles::RoleInfo::from_role_id(
+ &state,
+ &user_from_token.role_id,
+ &user_from_token.merchant_id,
+ &user_from_token.org_id,
+ )
+ .await
+ .change_context(UserErrors::InternalServerError)
+ .attach_printable("Failed to retrieve role information")?;
+
+ let (org_id, merchant_id, profile_id, role_id) = match role_info.get_entity_type() {
+ EntityType::Internal => {
+ let merchant_key_store = state
+ .store
+ .get_merchant_key_store_by_merchant_id(
+ key_manager_state,
+ &request.merchant_id,
+ &state.store.get_master_key().to_vec().into(),
+ )
+ .await
+ .to_not_found_response(UserErrors::MerchantIdNotFound)?;
+
+ let merchant_account = state
+ .store
+ .find_merchant_account_by_merchant_id(
+ key_manager_state,
+ &request.merchant_id,
+ &merchant_key_store,
+ )
+ .await
+ .to_not_found_response(UserErrors::MerchantIdNotFound)?;
+
+ let profile_id = state
+ .store
+ .list_business_profile_by_merchant_id(
+ key_manager_state,
+ &merchant_key_store,
+ &request.merchant_id,
+ )
+ .await
+ .change_context(UserErrors::InternalServerError)
+ .attach_printable("Failed to list business profiles by merchant_id")?
+ .first()
+ .ok_or(UserErrors::InternalServerError)
+ .attach_printable("No business profile found for the given merchant_id")?
+ .profile_id
+ .clone();
+
+ (
+ merchant_account.organization_id,
+ request.merchant_id,
+ profile_id,
+ user_from_token.role_id.clone(),
+ )
+ }
+
+ EntityType::Organization => {
+ let merchant_key_store = state
+ .store
+ .get_merchant_key_store_by_merchant_id(
+ key_manager_state,
+ &request.merchant_id,
+ &state.store.get_master_key().to_vec().into(),
+ )
+ .await
+ .to_not_found_response(UserErrors::MerchantIdNotFound)?;
+
+ let merchant_id = state
+ .store
+ .find_merchant_account_by_merchant_id(
+ key_manager_state,
+ &request.merchant_id,
+ &merchant_key_store,
+ )
+ .await
+ .change_context(UserErrors::MerchantIdNotFound)?
+ .organization_id
+ .eq(&user_from_token.org_id)
+ .then(|| request.merchant_id.clone())
+ .ok_or_else(|| {
+ UserErrors::InvalidRoleOperationWithMessage(
+ "No such merchant_id found for the user in the org".to_string(),
+ )
+ })?;
+
+ let profile_id = state
+ .store
+ .list_business_profile_by_merchant_id(
+ key_manager_state,
+ &merchant_key_store,
+ &merchant_id,
+ )
+ .await
+ .change_context(UserErrors::InternalServerError)
+ .attach_printable("Failed to list business profiles by merchant_id")?
+ .first()
+ .ok_or(UserErrors::InternalServerError)
+ .attach_printable("No business profile found for the merchant_id")?
+ .profile_id
+ .clone();
+
+ (
+ user_from_token.org_id.clone(),
+ merchant_id,
+ profile_id,
+ user_from_token.role_id.clone(),
+ )
+ }
+
+ EntityType::Merchant | EntityType::Profile => {
+ let user_role = state
+ .store
+ .list_user_roles(
+ &user_from_token.user_id,
+ Some(&user_from_token.org_id),
+ Some(&request.merchant_id),
+ None,
+ None,
+ None,
+ )
+ .await
+ .change_context(UserErrors::InternalServerError)
+ .attach_printable(
+ "Failed to list user roles for the given user_id, org_id and merchant_id",
+ )?
+ .into_iter()
+ .find(|role| role.status == UserStatus::Active)
+ .ok_or(UserErrors::InvalidRoleOperationWithMessage(
+ "No user role associated with the requested merchant_id".to_string(),
+ ))?
+ .to_owned();
+
+ let profile_id = if let Some(profile_id) = &user_role.profile_id {
+ profile_id.clone()
+ } else {
+ let merchant_key_store = state
+ .store
+ .get_merchant_key_store_by_merchant_id(
+ key_manager_state,
+ &request.merchant_id,
+ &state.store.get_master_key().to_vec().into(),
+ )
+ .await
+ .change_context(UserErrors::InternalServerError)
+ .attach_printable("Failed to retrieve merchant key store by merchant_id")?;
+
+ state
+ .store
+ .list_business_profile_by_merchant_id(
+ key_manager_state,
+ &merchant_key_store,
+ &request.merchant_id,
+ )
+ .await
+ .change_context(UserErrors::InternalServerError)
+ .attach_printable("Failed to list business profiles for the given merchant_id")?
+ .first()
+ .ok_or(UserErrors::InternalServerError)
+ .attach_printable("No business profile found for the given merchant_id")?
+ .profile_id
+ .clone()
+ };
+ (
+ user_from_token.org_id,
+ request.merchant_id,
+ profile_id,
+ user_role.role_id,
+ )
+ }
+ };
+
+ let token = utils::user::generate_jwt_auth_token_with_attributes(
+ &state,
+ user_from_token.user_id,
+ merchant_id.clone(),
+ org_id.clone(),
+ role_id.clone(),
+ Some(profile_id),
+ )
+ .await?;
+
+ utils::user_role::set_role_permissions_in_cache_by_role_id_merchant_id_org_id(
+ &state,
+ &role_id,
+ &merchant_id,
+ &org_id,
+ )
+ .await;
+
+ let response = user_api::TokenResponse {
+ token: token.clone(),
+ token_type: common_enums::TokenPurpose::UserInfo,
+ };
+
+ auth::cookies::set_cookie_response(response, token)
+}
+
+pub async fn switch_profile_for_user_in_org_and_merchant(
+ state: SessionState,
+ request: user_api::SwitchProfileRequest,
+ user_from_token: auth::UserFromToken,
+) -> UserResponse<user_api::TokenResponse> {
+ if user_from_token.profile_id == Some(request.profile_id.clone()) {
+ return Err(UserErrors::InvalidRoleOperationWithMessage(
+ "User switching to same profile".to_string(),
+ )
+ .into());
+ }
+
+ let key_manager_state = &(&state).into();
+ let role_info = roles::RoleInfo::from_role_id(
+ &state,
+ &user_from_token.role_id,
+ &user_from_token.merchant_id,
+ &user_from_token.org_id,
+ )
+ .await
+ .change_context(UserErrors::InternalServerError)
+ .attach_printable("Failed to retrieve role information")?;
+
+ let (profile_id, role_id) = match role_info.get_entity_type() {
+ EntityType::Internal | EntityType::Organization | EntityType::Merchant => {
+ let merchant_key_store = state
+ .store
+ .get_merchant_key_store_by_merchant_id(
+ key_manager_state,
+ &user_from_token.merchant_id,
+ &state.store.get_master_key().to_vec().into(),
+ )
+ .await
+ .change_context(UserErrors::InternalServerError)
+ .attach_printable("Failed to retrieve merchant key store by merchant_id")?;
+
+ let profile_id = state
+ .store
+ .find_business_profile_by_merchant_id_profile_id(
+ key_manager_state,
+ &merchant_key_store,
+ &user_from_token.merchant_id,
+ &request.profile_id,
+ )
+ .await
+ .change_context(UserErrors::InvalidRoleOperationWithMessage(
+ "No such profile found for the merchant".to_string(),
+ ))?
+ .profile_id;
+ (profile_id, user_from_token.role_id)
+ }
+
+ EntityType::Profile => {
+ let user_role = state
+ .store
+ .list_user_roles(
+ &user_from_token.user_id,
+ Some(&user_from_token.org_id),
+ Some(&user_from_token.merchant_id),
+ Some(&request.profile_id),
+ None,
+ None,
+ )
+ .await
+ .change_context(UserErrors::InternalServerError)
+ .attach_printable("Failed to list user roles for the given user_id, org_id, merchant_id and profile_id")?
+ .into_iter()
+ .find(|role| role.status == UserStatus::Active)
+ .ok_or(UserErrors::InvalidRoleOperationWithMessage(
+ "No user role associated with the profile".to_string(),
+ ))?
+ .to_owned();
+
+ (request.profile_id, user_role.role_id)
+ }
+ };
+
+ let token = utils::user::generate_jwt_auth_token_with_attributes(
+ &state,
+ user_from_token.user_id,
+ user_from_token.merchant_id.clone(),
+ user_from_token.org_id.clone(),
+ role_id.clone(),
+ Some(profile_id),
+ )
+ .await?;
+
+ utils::user_role::set_role_permissions_in_cache_by_role_id_merchant_id_org_id(
+ &state,
+ &role_id,
+ &user_from_token.merchant_id,
+ &user_from_token.org_id,
+ )
+ .await;
+
+ let response = user_api::TokenResponse {
+ token: token.clone(),
+ token_type: common_enums::TokenPurpose::UserInfo,
+ };
+
+ auth::cookies::set_cookie_response(response, token)
+}
diff --git a/crates/router/src/routes/app.rs b/crates/router/src/routes/app.rs
index 06971f381ad..97042485d6b 100644
--- a/crates/router/src/routes/app.rs
+++ b/crates/router/src/routes/app.rs
@@ -1707,6 +1707,19 @@ impl User {
),
);
+ route = route.service(
+ web::scope("/switch")
+ .service(web::resource("/org").route(web::post().to(switch_org_for_user)))
+ .service(
+ web::resource("/merchant")
+ .route(web::post().to(switch_merchant_for_user_in_org)),
+ )
+ .service(
+ web::resource("/profile")
+ .route(web::post().to(switch_profile_for_user_in_org_and_merchant)),
+ ),
+ );
+
// Two factor auth routes
route = route.service(
web::scope("/2fa")
diff --git a/crates/router/src/routes/lock_utils.rs b/crates/router/src/routes/lock_utils.rs
index e08b477d29a..f64fab1f408 100644
--- a/crates/router/src/routes/lock_utils.rs
+++ b/crates/router/src/routes/lock_utils.rs
@@ -212,7 +212,10 @@ impl From<Flow> for ApiIdentifier {
| Flow::GetMultipleDashboardMetadata
| Flow::VerifyPaymentConnector
| Flow::InternalUserSignup
+ | Flow::SwitchOrg
| Flow::SwitchMerchant
+ | Flow::SwitchMerchantV2
+ | Flow::SwitchProfile
| Flow::UserMerchantAccountCreate
| Flow::GenerateSampleData
| Flow::DeleteSampleData
@@ -258,7 +261,6 @@ impl From<Flow> for ApiIdentifier {
| Flow::AcceptInvitation
| Flow::MerchantSelect
| Flow::DeleteUserRole
- | Flow::TransferOrgOwnership
| Flow::CreateRole
| Flow::UpdateRole
| Flow::UserFromEmail => Self::UserRole,
diff --git a/crates/router/src/routes/user.rs b/crates/router/src/routes/user.rs
index 39ec3a24ff2..c52c5d1321c 100644
--- a/crates/router/src/routes/user.rs
+++ b/crates/router/src/routes/user.rs
@@ -240,7 +240,7 @@ pub async fn internal_user_signup(
pub async fn switch_merchant_id(
state: web::Data<AppState>,
http_req: HttpRequest,
- json_payload: web::Json<user_api::SwitchMerchantIdRequest>,
+ json_payload: web::Json<user_api::SwitchMerchantRequest>,
) -> HttpResponse {
let flow = Flow::SwitchMerchant;
Box::pin(api::server_wrap(
@@ -969,3 +969,59 @@ pub async fn list_profiles_for_user_in_org_and_merchant(
))
.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
+}
diff --git a/crates/router/src/utils/user.rs b/crates/router/src/utils/user.rs
index 30a0e1ca788..b2170e7294a 100644
--- a/crates/router/src/utils/user.rs
+++ b/crates/router/src/utils/user.rs
@@ -108,16 +108,16 @@ pub async fn generate_jwt_auth_token_without_profile(
Ok(Secret::new(token))
}
-pub async fn generate_jwt_auth_token_with_custom_role_attributes(
+pub async fn generate_jwt_auth_token_with_attributes(
state: &SessionState,
- user: &UserFromStorage,
+ user_id: String,
merchant_id: id_type::MerchantId,
org_id: id_type::OrganizationId,
role_id: String,
profile_id: Option<id_type::ProfileId>,
) -> UserResult<Secret<String>> {
let token = AuthToken::new_token(
- user.get_user_id().to_string(),
+ user_id,
merchant_id,
role_id,
&state.conf,
diff --git a/crates/router/src/utils/user_role.rs b/crates/router/src/utils/user_role.rs
index 792a79c91eb..1791b5308b4 100644
--- a/crates/router/src/utils/user_role.rs
+++ b/crates/router/src/utils/user_role.rs
@@ -128,6 +128,18 @@ pub async fn set_role_permissions_in_cache_by_user_role(
.is_ok()
}
+pub async fn set_role_permissions_in_cache_by_role_id_merchant_id_org_id(
+ state: &SessionState,
+ role_id: &str,
+ merchant_id: &id_type::MerchantId,
+ org_id: &id_type::OrganizationId,
+) -> bool {
+ set_role_permissions_in_cache_if_required(state, role_id, merchant_id, org_id)
+ .await
+ .map_err(|e| logger::error!("Error setting permissions in cache {:?}", e))
+ .is_ok()
+}
+
pub async fn set_role_permissions_in_cache_if_required(
state: &SessionState,
role_id: &str,
diff --git a/crates/router_env/src/logger/types.rs b/crates/router_env/src/logger/types.rs
index 4fbbfdf5518..88eec0f791a 100644
--- a/crates/router_env/src/logger/types.rs
+++ b/crates/router_env/src/logger/types.rs
@@ -352,8 +352,14 @@ pub enum Flow {
VerifyPaymentConnector,
/// Internal user signup
InternalUserSignup,
+ /// Switch org
+ SwitchOrg,
/// Switch merchant
SwitchMerchant,
+ /// Switch merchant v2
+ SwitchMerchantV2,
+ /// Switch profile
+ SwitchProfile,
/// Get permission info
GetAuthorizationInfo,
/// Get Roles info
@@ -366,8 +372,6 @@ pub enum Flow {
GetRoleFromToken,
/// Update user role
UpdateUserRole,
- /// Transfer organization ownership
- TransferOrgOwnership,
/// Create merchant account for user in a org
UserMerchantAccountCreate,
/// Generate Sample Data
|
2024-08-26T06:46:56Z
|
## Type of Change
<!-- Put an `x` in the boxes that apply -->
- [ ] Bugfix
- [x] New feature
- [ ] Enhancement
- [ ] Refactoring
- [ ] Dependency updates
- [ ] Documentation
- [ ] CI/CD
## Description
Support switch for org, merchant, profile and internal users.
For now switch exist only for merchant.
After new switch, new token will be issued.
### Additional Changes
- [ ] This PR modifies the API contract
- [ ] This PR modifies the database schema
- [ ] This PR modifies application configuration/environment variables
<!--
Provide links to the files with corresponding changes.
Following are the paths where you can find config files:
1. `config`
2. `crates/router/src/configs`
3. `loadtest/config`
-->
## Motivation and Context
Closes #5689
## How did you test it?
For org level switch
```
curl --location 'http://localhost:8080/user/switch/org' \
--header 'Content-Type: application/json' \
--header 'Authorization: Bearer JWT' \
--data '{
"org_id": "some_org_id"
}'
```
For merchant level switch
```
curl --location 'http://localhost:8080/user/switch/merchant' \
--header 'Content-Type: application/json' \
--header 'Authorization: Bearer JWT' \
--data '{
"merchant_id": "some_merchant_id"
}'
```
For profile level switch
```
curl --location 'http://localhost:8080/user/switch/profile' \
--header 'Content-Type: application/json' \
--header 'Authorization: Bearer JWT' \
--data '{
"profile_id": "some_profile_id"
}'
```
Response
```
{
"token": new_token",
"token_type": "user_info"
}
```
If switch happened correctly then we will get new token in response else error accordingly.
## Checklist
<!-- Put an `x` in the boxes that apply -->
- [x] I formatted the code `cargo +nightly fmt --all`
- [x] I addressed lints thrown by `cargo clippy`
- [x] I reviewed the submitted code
- [ ] I added unit tests for my changes where possible
|
4585e16245dd49d8c0b877cda148524afe395009
|
|
juspay/hyperswitch
|
juspay__hyperswitch-5693
|
Bug: [FEATURE] ADD NEXIXPAY CONNECTOR
### Feature Description
Add Nexixpay connector
### Possible Implementation
Add Nexixpay connector
### Have you spent some time checking if this feature request has been raised before?
- [X] I checked and didn't find a similar issue
### Have you read the Contributing Guidelines?
- [X] I have read the [Contributing Guidelines](https://github.com/juspay/hyperswitch/blob/main/docs/CONTRIBUTING.md)
### Are you willing to submit a PR?
Yes, I am willing to submit a PR!
|
diff --git a/config/config.example.toml b/config/config.example.toml
index a8cc36b4dc5..0a88c3896f2 100644
--- a/config/config.example.toml
+++ b/config/config.example.toml
@@ -222,6 +222,7 @@ mollie.secondary_base_url = "https://api.cc.mollie.com/v1/"
multisafepay.base_url = "https://testapi.multisafepay.com/"
netcetera.base_url = "https://{{merchant_endpoint_prefix}}.3ds-server.prev.netcetera-cloud-payment.ch"
nexinets.base_url = "https://apitest.payengine.de/v1"
+nexixpay.base_url = "https://xpaysandbox.nexigroup.com/api/phoenix-0.0/psp/api/v1"
nmi.base_url = "https://secure.nmi.com/"
noon.base_url = "https://api-test.noonpayments.com/"
novalnet.base_url = "https://payport.novalnet.de/v2"
diff --git a/config/deployments/integration_test.toml b/config/deployments/integration_test.toml
index 2ceac401b92..c6cb9ff6c36 100644
--- a/config/deployments/integration_test.toml
+++ b/config/deployments/integration_test.toml
@@ -47,7 +47,6 @@ dummyconnector.base_url = "http://localhost:8080/dummy-connector"
ebanx.base_url = "https://sandbox.ebanxpay.com/"
fiserv.base_url = "https://cert.api.fiservapps.com/"
fiservemea.base_url = "https://prod.emea.api.fiservapps.com/sandbox/ipp/payments-gateway/v2"
-novalnet.base_url = "https://payport.novalnet.de/v2"
forte.base_url = "https://sandbox.forte.net/api/v3"
globalpay.base_url = "https://apis.sandbox.globalpay.com/ucp/"
globepay.base_url = "https://pay.globepay.co/"
@@ -62,9 +61,11 @@ mollie.base_url = "https://api.mollie.com/v2/"
mollie.secondary_base_url = "https://api.cc.mollie.com/v1/"
multisafepay.base_url = "https://testapi.multisafepay.com/"
nexinets.base_url = "https://apitest.payengine.de/v1"
+nexixpay.base_url = "https://xpaysandbox.nexigroup.com/api/phoenix-0.0/psp/api/v1"
nmi.base_url = "https://secure.nmi.com/"
noon.base_url = "https://api-test.noonpayments.com/"
noon.key_mode = "Test"
+novalnet.base_url = "https://payport.novalnet.de/v2"
nuvei.base_url = "https://ppp-test.nuvei.com/"
opayo.base_url = "https://pi-test.sagepay.com/"
opennode.base_url = "https://dev-api.opennode.com"
diff --git a/config/deployments/production.toml b/config/deployments/production.toml
index aa214d04007..67256cf34d7 100644
--- a/config/deployments/production.toml
+++ b/config/deployments/production.toml
@@ -51,7 +51,6 @@ dummyconnector.base_url = "http://localhost:8080/dummy-connector"
ebanx.base_url = "https://sandbox.ebanxpay.com/"
fiserv.base_url = "https://cert.api.fiservapps.com/"
fiservemea.base_url = "https://prod.emea.api.fiservapps.com/ipp/payments-gateway/v2"
-novalnet.base_url = "https://payport.novalnet.de/v2"
forte.base_url = "https://sandbox.forte.net/api/v3"
globalpay.base_url = "https://apis.sandbox.globalpay.com/ucp/"
globepay.base_url = "https://pay.globepay.co/"
@@ -66,9 +65,11 @@ mollie.base_url = "https://api.mollie.com/v2/"
mollie.secondary_base_url = "https://api.cc.mollie.com/v1/"
multisafepay.base_url = "https://testapi.multisafepay.com/"
nexinets.base_url = "https://api.payengine.de/v1"
+nexixpay.base_url = "https://xpay.nexigroup.com/api/phoenix-0.0/psp/api/v1"
nmi.base_url = "https://secure.nmi.com/"
noon.base_url = "https://api.noonpayments.com/"
noon.key_mode = "Live"
+novalnet.base_url = "https://payport.novalnet.de/v2"
nuvei.base_url = "https://ppp-test.nuvei.com/"
opayo.base_url = "https://pi-live.sagepay.com/"
opennode.base_url = "https://api.opennode.com"
diff --git a/config/deployments/sandbox.toml b/config/deployments/sandbox.toml
index b6a235a0018..5496c4ae102 100644
--- a/config/deployments/sandbox.toml
+++ b/config/deployments/sandbox.toml
@@ -51,7 +51,6 @@ dummyconnector.base_url = "http://localhost:8080/dummy-connector"
ebanx.base_url = "https://sandbox.ebanxpay.com/"
fiserv.base_url = "https://cert.api.fiservapps.com/"
fiservemea.base_url = "https://prod.emea.api.fiservapps.com/sandbox/ipp/payments-gateway/v2"
-novalnet.base_url = "https://payport.novalnet.de/v2"
forte.base_url = "https://sandbox.forte.net/api/v3"
globalpay.base_url = "https://apis.sandbox.globalpay.com/ucp/"
globepay.base_url = "https://pay.globepay.co/"
@@ -66,9 +65,11 @@ mollie.base_url = "https://api.mollie.com/v2/"
mollie.secondary_base_url = "https://api.cc.mollie.com/v1/"
multisafepay.base_url = "https://testapi.multisafepay.com/"
nexinets.base_url = "https://apitest.payengine.de/v1"
+nexixpay.base_url = "https://xpaysandbox.nexigroup.com/api/phoenix-0.0/psp/api/v1"
nmi.base_url = "https://secure.nmi.com/"
noon.base_url = "https://api-test.noonpayments.com/"
noon.key_mode = "Test"
+novalnet.base_url = "https://payport.novalnet.de/v2"
nuvei.base_url = "https://ppp-test.nuvei.com/"
opayo.base_url = "https://pi-test.sagepay.com/"
opennode.base_url = "https://dev-api.opennode.com"
diff --git a/config/development.toml b/config/development.toml
index 902c3ed3ad6..401b1487843 100644
--- a/config/development.toml
+++ b/config/development.toml
@@ -131,6 +131,7 @@ cards = [
"multisafepay",
"netcetera",
"nexinets",
+ "nexixpay",
"nmi",
"noon",
"novalnet",
@@ -227,6 +228,7 @@ mollie.secondary_base_url = "https://api.cc.mollie.com/v1/"
multisafepay.base_url = "https://testapi.multisafepay.com/"
netcetera.base_url = "https://{{merchant_endpoint_prefix}}.3ds-server.prev.netcetera-cloud-payment.ch"
nexinets.base_url = "https://apitest.payengine.de/v1"
+nexixpay.base_url = "https://xpaysandbox.nexigroup.com/api/phoenix-0.0/psp/api/v1"
nmi.base_url = "https://secure.nmi.com/"
noon.base_url = "https://api-test.noonpayments.com/"
novalnet.base_url = "https://payport.novalnet.de/v2"
diff --git a/config/docker_compose.toml b/config/docker_compose.toml
index e8d564ac66b..136864c9f98 100644
--- a/config/docker_compose.toml
+++ b/config/docker_compose.toml
@@ -151,6 +151,7 @@ mollie.secondary_base_url = "https://api.cc.mollie.com/v1/"
multisafepay.base_url = "https://testapi.multisafepay.com/"
netcetera.base_url = "https://{{merchant_endpoint_prefix}}.3ds-server.prev.netcetera-cloud-payment.ch"
nexinets.base_url = "https://apitest.payengine.de/v1"
+nexixpay.base_url = "https://xpaysandbox.nexigroup.com/api/phoenix-0.0/psp/api/v1"
nmi.base_url = "https://secure.nmi.com/"
noon.base_url = "https://api-test.noonpayments.com/"
novalnet.base_url = "https://payport.novalnet.de/v2"
@@ -236,6 +237,7 @@ cards = [
"multisafepay",
"netcetera",
"nexinets",
+ "nexixpay",
"nmi",
"noon",
"novalnet",
diff --git a/crates/api_models/src/enums.rs b/crates/api_models/src/enums.rs
index 86d6421c3e2..150d69f1e8d 100644
--- a/crates/api_models/src/enums.rs
+++ b/crates/api_models/src/enums.rs
@@ -47,6 +47,7 @@ pub enum RoutingAlgorithm {
#[strum(serialize_all = "snake_case")]
pub enum Connector {
// Novalnet,
+ // Nexixpay,
// Fiservemea,
Adyenplatform,
#[cfg(feature = "dummy_connector")]
@@ -211,6 +212,7 @@ impl Connector {
Self::Aci
// Add Separate authentication support for connectors
// | Self::Novalnet
+ // | Self::Nexixpay
// | Self::Taxjar
// | Self::Fiservemea
| Self::Adyen
diff --git a/crates/common_enums/src/enums.rs b/crates/common_enums/src/enums.rs
index 617d121c63c..078f490b800 100644
--- a/crates/common_enums/src/enums.rs
+++ b/crates/common_enums/src/enums.rs
@@ -160,6 +160,7 @@ pub enum AttemptStatus {
#[strum(serialize_all = "snake_case")]
/// Connectors eligible for payments routing
pub enum RoutableConnectors {
+ // Nexixpay,
Adyenplatform,
#[cfg(feature = "dummy_connector")]
#[serde(rename = "phonypay")]
diff --git a/crates/hyperswitch_connectors/src/connectors.rs b/crates/hyperswitch_connectors/src/connectors.rs
index dfaffd02662..331f58a4877 100644
--- a/crates/hyperswitch_connectors/src/connectors.rs
+++ b/crates/hyperswitch_connectors/src/connectors.rs
@@ -3,11 +3,12 @@ pub mod bitpay;
pub mod fiserv;
pub mod fiservemea;
pub mod helcim;
+pub mod nexixpay;
pub mod novalnet;
pub mod stax;
pub mod taxjar;
pub use self::{
bambora::Bambora, bitpay::Bitpay, fiserv::Fiserv, fiservemea::Fiservemea, helcim::Helcim,
- novalnet::Novalnet, stax::Stax, taxjar::Taxjar,
+ nexixpay::Nexixpay, novalnet::Novalnet, stax::Stax, taxjar::Taxjar,
};
diff --git a/crates/hyperswitch_connectors/src/connectors/nexixpay.rs b/crates/hyperswitch_connectors/src/connectors/nexixpay.rs
new file mode 100644
index 00000000000..b660445f3ca
--- /dev/null
+++ b/crates/hyperswitch_connectors/src/connectors/nexixpay.rs
@@ -0,0 +1,566 @@
+pub mod transformers;
+
+use common_utils::{
+ errors::CustomResult,
+ ext_traits::BytesExt,
+ request::{Method, Request, RequestBuilder, RequestContent},
+ types::{AmountConvertor, StringMinorUnit, StringMinorUnitForConnector},
+};
+use error_stack::{report, ResultExt};
+use hyperswitch_domain_models::{
+ router_data::{AccessToken, ConnectorAuthType, ErrorResponse, RouterData},
+ router_flow_types::{
+ access_token_auth::AccessTokenAuth,
+ payments::{Authorize, Capture, PSync, PaymentMethodToken, Session, SetupMandate, Void},
+ refunds::{Execute, RSync},
+ },
+ router_request_types::{
+ AccessTokenRequestData, PaymentMethodTokenizationData, PaymentsAuthorizeData,
+ PaymentsCancelData, PaymentsCaptureData, PaymentsSessionData, PaymentsSyncData,
+ RefundsData, SetupMandateRequestData,
+ },
+ router_response_types::{PaymentsResponseData, RefundsResponseData},
+ types::{
+ PaymentsAuthorizeRouterData, PaymentsCaptureRouterData, PaymentsSyncRouterData,
+ RefundSyncRouterData, RefundsRouterData,
+ },
+};
+use hyperswitch_interfaces::{
+ api::{self, ConnectorCommon, ConnectorCommonExt, ConnectorIntegration, ConnectorValidation},
+ configs::Connectors,
+ errors,
+ events::connector_api_logs::ConnectorEvent,
+ types::{self, Response},
+ webhooks,
+};
+use masking::{ExposeInterface, Mask};
+use transformers as nexixpay;
+
+use crate::{constants::headers, types::ResponseRouterData, utils};
+
+#[derive(Clone)]
+pub struct Nexixpay {
+ amount_converter: &'static (dyn AmountConvertor<Output = StringMinorUnit> + Sync),
+}
+
+impl Nexixpay {
+ pub fn new() -> &'static Self {
+ &Self {
+ amount_converter: &StringMinorUnitForConnector,
+ }
+ }
+}
+
+impl api::Payment for Nexixpay {}
+impl api::PaymentSession for Nexixpay {}
+impl api::ConnectorAccessToken for Nexixpay {}
+impl api::MandateSetup for Nexixpay {}
+impl api::PaymentAuthorize for Nexixpay {}
+impl api::PaymentSync for Nexixpay {}
+impl api::PaymentCapture for Nexixpay {}
+impl api::PaymentVoid for Nexixpay {}
+impl api::Refund for Nexixpay {}
+impl api::RefundExecute for Nexixpay {}
+impl api::RefundSync for Nexixpay {}
+impl api::PaymentToken for Nexixpay {}
+
+impl ConnectorIntegration<PaymentMethodToken, PaymentMethodTokenizationData, PaymentsResponseData>
+ for Nexixpay
+{
+ // Not Implemented (R)
+}
+
+impl<Flow, Request, Response> ConnectorCommonExt<Flow, Request, Response> for Nexixpay
+where
+ Self: ConnectorIntegration<Flow, Request, Response>,
+{
+ fn build_headers(
+ &self,
+ req: &RouterData<Flow, Request, Response>,
+ _connectors: &Connectors,
+ ) -> CustomResult<Vec<(String, masking::Maskable<String>)>, errors::ConnectorError> {
+ let mut header = vec![(
+ headers::CONTENT_TYPE.to_string(),
+ self.get_content_type().to_string().into(),
+ )];
+ let mut api_key = self.get_auth_header(&req.connector_auth_type)?;
+ header.append(&mut api_key);
+ Ok(header)
+ }
+}
+
+impl ConnectorCommon for Nexixpay {
+ fn id(&self) -> &'static str {
+ "nexixpay"
+ }
+
+ fn get_currency_unit(&self) -> api::CurrencyUnit {
+ api::CurrencyUnit::Base
+ // TODO! Check connector documentation, on which unit they are processing the currency.
+ // If the connector accepts amount in lower unit ( i.e cents for USD) then return api::CurrencyUnit::Minor,
+ // if connector accepts amount in base unit (i.e dollars for USD) then return api::CurrencyUnit::Base
+ }
+
+ fn common_get_content_type(&self) -> &'static str {
+ "application/json"
+ }
+
+ fn base_url<'a>(&self, connectors: &'a Connectors) -> &'a str {
+ connectors.nexixpay.base_url.as_ref()
+ }
+
+ fn get_auth_header(
+ &self,
+ auth_type: &ConnectorAuthType,
+ ) -> CustomResult<Vec<(String, masking::Maskable<String>)>, errors::ConnectorError> {
+ let auth = nexixpay::NexixpayAuthType::try_from(auth_type)
+ .change_context(errors::ConnectorError::FailedToObtainAuthType)?;
+ Ok(vec![(
+ headers::AUTHORIZATION.to_string(),
+ auth.api_key.expose().into_masked(),
+ )])
+ }
+
+ fn build_error_response(
+ &self,
+ res: Response,
+ event_builder: Option<&mut ConnectorEvent>,
+ ) -> CustomResult<ErrorResponse, errors::ConnectorError> {
+ let response: nexixpay::NexixpayErrorResponse = res
+ .response
+ .parse_struct("NexixpayErrorResponse")
+ .change_context(errors::ConnectorError::ResponseDeserializationFailed)?;
+
+ event_builder.map(|i| i.set_response_body(&response));
+ router_env::logger::info!(connector_response=?response);
+
+ Ok(ErrorResponse {
+ status_code: res.status_code,
+ code: response.code,
+ message: response.message,
+ reason: response.reason,
+ attempt_status: None,
+ connector_transaction_id: None,
+ })
+ }
+}
+
+impl ConnectorValidation for Nexixpay {
+ //TODO: implement functions when support enabled
+}
+
+impl ConnectorIntegration<Session, PaymentsSessionData, PaymentsResponseData> for Nexixpay {
+ //TODO: implement sessions flow
+}
+
+impl ConnectorIntegration<AccessTokenAuth, AccessTokenRequestData, AccessToken> for Nexixpay {}
+
+impl ConnectorIntegration<SetupMandate, SetupMandateRequestData, PaymentsResponseData>
+ for Nexixpay
+{
+}
+
+impl ConnectorIntegration<Authorize, PaymentsAuthorizeData, PaymentsResponseData> for Nexixpay {
+ fn get_headers(
+ &self,
+ req: &PaymentsAuthorizeRouterData,
+ connectors: &Connectors,
+ ) -> CustomResult<Vec<(String, masking::Maskable<String>)>, errors::ConnectorError> {
+ self.build_headers(req, connectors)
+ }
+
+ fn get_content_type(&self) -> &'static str {
+ self.common_get_content_type()
+ }
+
+ fn get_url(
+ &self,
+ _req: &PaymentsAuthorizeRouterData,
+ _connectors: &Connectors,
+ ) -> CustomResult<String, errors::ConnectorError> {
+ Err(errors::ConnectorError::NotImplemented("get_url method".to_string()).into())
+ }
+
+ fn get_request_body(
+ &self,
+ req: &PaymentsAuthorizeRouterData,
+ _connectors: &Connectors,
+ ) -> CustomResult<RequestContent, errors::ConnectorError> {
+ let amount = utils::convert_amount(
+ self.amount_converter,
+ req.request.minor_amount,
+ req.request.currency,
+ )?;
+
+ let connector_router_data = nexixpay::NexixpayRouterData::from((amount, req));
+ let connector_req = nexixpay::NexixpayPaymentsRequest::try_from(&connector_router_data)?;
+ Ok(RequestContent::Json(Box::new(connector_req)))
+ }
+
+ fn build_request(
+ &self,
+ req: &PaymentsAuthorizeRouterData,
+ connectors: &Connectors,
+ ) -> CustomResult<Option<Request>, errors::ConnectorError> {
+ Ok(Some(
+ RequestBuilder::new()
+ .method(Method::Post)
+ .url(&types::PaymentsAuthorizeType::get_url(
+ self, req, connectors,
+ )?)
+ .attach_default_headers()
+ .headers(types::PaymentsAuthorizeType::get_headers(
+ self, req, connectors,
+ )?)
+ .set_body(types::PaymentsAuthorizeType::get_request_body(
+ self, req, connectors,
+ )?)
+ .build(),
+ ))
+ }
+
+ fn handle_response(
+ &self,
+ data: &PaymentsAuthorizeRouterData,
+ event_builder: Option<&mut ConnectorEvent>,
+ res: Response,
+ ) -> CustomResult<PaymentsAuthorizeRouterData, errors::ConnectorError> {
+ let response: nexixpay::NexixpayPaymentsResponse = res
+ .response
+ .parse_struct("Nexixpay PaymentsAuthorizeResponse")
+ .change_context(errors::ConnectorError::ResponseDeserializationFailed)?;
+ event_builder.map(|i| i.set_response_body(&response));
+ router_env::logger::info!(connector_response=?response);
+ RouterData::try_from(ResponseRouterData {
+ response,
+ data: data.clone(),
+ http_code: res.status_code,
+ })
+ }
+
+ fn get_error_response(
+ &self,
+ res: Response,
+ event_builder: Option<&mut ConnectorEvent>,
+ ) -> CustomResult<ErrorResponse, errors::ConnectorError> {
+ self.build_error_response(res, event_builder)
+ }
+}
+
+impl ConnectorIntegration<PSync, PaymentsSyncData, PaymentsResponseData> for Nexixpay {
+ fn get_headers(
+ &self,
+ req: &PaymentsSyncRouterData,
+ connectors: &Connectors,
+ ) -> CustomResult<Vec<(String, masking::Maskable<String>)>, errors::ConnectorError> {
+ self.build_headers(req, connectors)
+ }
+
+ fn get_content_type(&self) -> &'static str {
+ self.common_get_content_type()
+ }
+
+ fn get_url(
+ &self,
+ _req: &PaymentsSyncRouterData,
+ _connectors: &Connectors,
+ ) -> CustomResult<String, errors::ConnectorError> {
+ Err(errors::ConnectorError::NotImplemented("get_url method".to_string()).into())
+ }
+
+ fn build_request(
+ &self,
+ req: &PaymentsSyncRouterData,
+ connectors: &Connectors,
+ ) -> CustomResult<Option<Request>, errors::ConnectorError> {
+ Ok(Some(
+ RequestBuilder::new()
+ .method(Method::Get)
+ .url(&types::PaymentsSyncType::get_url(self, req, connectors)?)
+ .attach_default_headers()
+ .headers(types::PaymentsSyncType::get_headers(self, req, connectors)?)
+ .build(),
+ ))
+ }
+
+ fn handle_response(
+ &self,
+ data: &PaymentsSyncRouterData,
+ event_builder: Option<&mut ConnectorEvent>,
+ res: Response,
+ ) -> CustomResult<PaymentsSyncRouterData, errors::ConnectorError> {
+ let response: nexixpay::NexixpayPaymentsResponse = res
+ .response
+ .parse_struct("nexixpay PaymentsSyncResponse")
+ .change_context(errors::ConnectorError::ResponseDeserializationFailed)?;
+ event_builder.map(|i| i.set_response_body(&response));
+ router_env::logger::info!(connector_response=?response);
+ RouterData::try_from(ResponseRouterData {
+ response,
+ data: data.clone(),
+ http_code: res.status_code,
+ })
+ }
+
+ fn get_error_response(
+ &self,
+ res: Response,
+ event_builder: Option<&mut ConnectorEvent>,
+ ) -> CustomResult<ErrorResponse, errors::ConnectorError> {
+ self.build_error_response(res, event_builder)
+ }
+}
+
+impl ConnectorIntegration<Capture, PaymentsCaptureData, PaymentsResponseData> for Nexixpay {
+ fn get_headers(
+ &self,
+ req: &PaymentsCaptureRouterData,
+ connectors: &Connectors,
+ ) -> CustomResult<Vec<(String, masking::Maskable<String>)>, errors::ConnectorError> {
+ self.build_headers(req, connectors)
+ }
+
+ fn get_content_type(&self) -> &'static str {
+ self.common_get_content_type()
+ }
+
+ fn get_url(
+ &self,
+ _req: &PaymentsCaptureRouterData,
+ _connectors: &Connectors,
+ ) -> CustomResult<String, errors::ConnectorError> {
+ Err(errors::ConnectorError::NotImplemented("get_url method".to_string()).into())
+ }
+
+ fn get_request_body(
+ &self,
+ _req: &PaymentsCaptureRouterData,
+ _connectors: &Connectors,
+ ) -> CustomResult<RequestContent, errors::ConnectorError> {
+ Err(errors::ConnectorError::NotImplemented("get_request_body method".to_string()).into())
+ }
+
+ fn build_request(
+ &self,
+ req: &PaymentsCaptureRouterData,
+ connectors: &Connectors,
+ ) -> CustomResult<Option<Request>, errors::ConnectorError> {
+ Ok(Some(
+ RequestBuilder::new()
+ .method(Method::Post)
+ .url(&types::PaymentsCaptureType::get_url(self, req, connectors)?)
+ .attach_default_headers()
+ .headers(types::PaymentsCaptureType::get_headers(
+ self, req, connectors,
+ )?)
+ .set_body(types::PaymentsCaptureType::get_request_body(
+ self, req, connectors,
+ )?)
+ .build(),
+ ))
+ }
+
+ fn handle_response(
+ &self,
+ data: &PaymentsCaptureRouterData,
+ event_builder: Option<&mut ConnectorEvent>,
+ res: Response,
+ ) -> CustomResult<PaymentsCaptureRouterData, errors::ConnectorError> {
+ let response: nexixpay::NexixpayPaymentsResponse = res
+ .response
+ .parse_struct("Nexixpay PaymentsCaptureResponse")
+ .change_context(errors::ConnectorError::ResponseDeserializationFailed)?;
+ event_builder.map(|i| i.set_response_body(&response));
+ router_env::logger::info!(connector_response=?response);
+ RouterData::try_from(ResponseRouterData {
+ response,
+ data: data.clone(),
+ http_code: res.status_code,
+ })
+ }
+
+ fn get_error_response(
+ &self,
+ res: Response,
+ event_builder: Option<&mut ConnectorEvent>,
+ ) -> CustomResult<ErrorResponse, errors::ConnectorError> {
+ self.build_error_response(res, event_builder)
+ }
+}
+
+impl ConnectorIntegration<Void, PaymentsCancelData, PaymentsResponseData> for Nexixpay {}
+
+impl ConnectorIntegration<Execute, RefundsData, RefundsResponseData> for Nexixpay {
+ fn get_headers(
+ &self,
+ req: &RefundsRouterData<Execute>,
+ connectors: &Connectors,
+ ) -> CustomResult<Vec<(String, masking::Maskable<String>)>, errors::ConnectorError> {
+ self.build_headers(req, connectors)
+ }
+
+ fn get_content_type(&self) -> &'static str {
+ self.common_get_content_type()
+ }
+
+ fn get_url(
+ &self,
+ _req: &RefundsRouterData<Execute>,
+ _connectors: &Connectors,
+ ) -> CustomResult<String, errors::ConnectorError> {
+ Err(errors::ConnectorError::NotImplemented("get_url method".to_string()).into())
+ }
+
+ fn get_request_body(
+ &self,
+ req: &RefundsRouterData<Execute>,
+ _connectors: &Connectors,
+ ) -> CustomResult<RequestContent, errors::ConnectorError> {
+ let refund_amount = utils::convert_amount(
+ self.amount_converter,
+ req.request.minor_refund_amount,
+ req.request.currency,
+ )?;
+
+ let connector_router_data = nexixpay::NexixpayRouterData::from((refund_amount, req));
+ let connector_req = nexixpay::NexixpayRefundRequest::try_from(&connector_router_data)?;
+ Ok(RequestContent::Json(Box::new(connector_req)))
+ }
+
+ fn build_request(
+ &self,
+ req: &RefundsRouterData<Execute>,
+ connectors: &Connectors,
+ ) -> CustomResult<Option<Request>, errors::ConnectorError> {
+ let request = RequestBuilder::new()
+ .method(Method::Post)
+ .url(&types::RefundExecuteType::get_url(self, req, connectors)?)
+ .attach_default_headers()
+ .headers(types::RefundExecuteType::get_headers(
+ self, req, connectors,
+ )?)
+ .set_body(types::RefundExecuteType::get_request_body(
+ self, req, connectors,
+ )?)
+ .build();
+ Ok(Some(request))
+ }
+
+ fn handle_response(
+ &self,
+ data: &RefundsRouterData<Execute>,
+ event_builder: Option<&mut ConnectorEvent>,
+ res: Response,
+ ) -> CustomResult<RefundsRouterData<Execute>, errors::ConnectorError> {
+ let response: nexixpay::RefundResponse = res
+ .response
+ .parse_struct("nexixpay RefundResponse")
+ .change_context(errors::ConnectorError::ResponseDeserializationFailed)?;
+ event_builder.map(|i| i.set_response_body(&response));
+ router_env::logger::info!(connector_response=?response);
+ RouterData::try_from(ResponseRouterData {
+ response,
+ data: data.clone(),
+ http_code: res.status_code,
+ })
+ }
+
+ fn get_error_response(
+ &self,
+ res: Response,
+ event_builder: Option<&mut ConnectorEvent>,
+ ) -> CustomResult<ErrorResponse, errors::ConnectorError> {
+ self.build_error_response(res, event_builder)
+ }
+}
+
+impl ConnectorIntegration<RSync, RefundsData, RefundsResponseData> for Nexixpay {
+ fn get_headers(
+ &self,
+ req: &RefundSyncRouterData,
+ connectors: &Connectors,
+ ) -> CustomResult<Vec<(String, masking::Maskable<String>)>, errors::ConnectorError> {
+ self.build_headers(req, connectors)
+ }
+
+ fn get_content_type(&self) -> &'static str {
+ self.common_get_content_type()
+ }
+
+ fn get_url(
+ &self,
+ _req: &RefundSyncRouterData,
+ _connectors: &Connectors,
+ ) -> CustomResult<String, errors::ConnectorError> {
+ Err(errors::ConnectorError::NotImplemented("get_url method".to_string()).into())
+ }
+
+ fn build_request(
+ &self,
+ req: &RefundSyncRouterData,
+ connectors: &Connectors,
+ ) -> CustomResult<Option<Request>, errors::ConnectorError> {
+ Ok(Some(
+ RequestBuilder::new()
+ .method(Method::Get)
+ .url(&types::RefundSyncType::get_url(self, req, connectors)?)
+ .attach_default_headers()
+ .headers(types::RefundSyncType::get_headers(self, req, connectors)?)
+ .set_body(types::RefundSyncType::get_request_body(
+ self, req, connectors,
+ )?)
+ .build(),
+ ))
+ }
+
+ fn handle_response(
+ &self,
+ data: &RefundSyncRouterData,
+ event_builder: Option<&mut ConnectorEvent>,
+ res: Response,
+ ) -> CustomResult<RefundSyncRouterData, errors::ConnectorError> {
+ let response: nexixpay::RefundResponse = res
+ .response
+ .parse_struct("nexixpay RefundSyncResponse")
+ .change_context(errors::ConnectorError::ResponseDeserializationFailed)?;
+ event_builder.map(|i| i.set_response_body(&response));
+ router_env::logger::info!(connector_response=?response);
+ RouterData::try_from(ResponseRouterData {
+ response,
+ data: data.clone(),
+ http_code: res.status_code,
+ })
+ }
+
+ fn get_error_response(
+ &self,
+ res: Response,
+ event_builder: Option<&mut ConnectorEvent>,
+ ) -> CustomResult<ErrorResponse, errors::ConnectorError> {
+ self.build_error_response(res, event_builder)
+ }
+}
+
+#[async_trait::async_trait]
+impl webhooks::IncomingWebhook for Nexixpay {
+ fn get_webhook_object_reference_id(
+ &self,
+ _request: &webhooks::IncomingWebhookRequestDetails<'_>,
+ ) -> CustomResult<api_models::webhooks::ObjectReferenceId, errors::ConnectorError> {
+ Err(report!(errors::ConnectorError::WebhooksNotImplemented))
+ }
+
+ fn get_webhook_event_type(
+ &self,
+ _request: &webhooks::IncomingWebhookRequestDetails<'_>,
+ ) -> CustomResult<api_models::webhooks::IncomingWebhookEvent, errors::ConnectorError> {
+ Err(report!(errors::ConnectorError::WebhooksNotImplemented))
+ }
+
+ fn get_webhook_resource_object(
+ &self,
+ _request: &webhooks::IncomingWebhookRequestDetails<'_>,
+ ) -> CustomResult<Box<dyn masking::ErasedMaskSerialize>, errors::ConnectorError> {
+ Err(report!(errors::ConnectorError::WebhooksNotImplemented))
+ }
+}
diff --git a/crates/hyperswitch_connectors/src/connectors/nexixpay/transformers.rs b/crates/hyperswitch_connectors/src/connectors/nexixpay/transformers.rs
new file mode 100644
index 00000000000..f0bcb1f249e
--- /dev/null
+++ b/crates/hyperswitch_connectors/src/connectors/nexixpay/transformers.rs
@@ -0,0 +1,228 @@
+use common_enums::enums;
+use common_utils::types::StringMinorUnit;
+use hyperswitch_domain_models::{
+ payment_method_data::PaymentMethodData,
+ router_data::{ConnectorAuthType, RouterData},
+ router_flow_types::refunds::{Execute, RSync},
+ router_request_types::ResponseId,
+ router_response_types::{PaymentsResponseData, RefundsResponseData},
+ types::{PaymentsAuthorizeRouterData, RefundsRouterData},
+};
+use hyperswitch_interfaces::errors;
+use masking::Secret;
+use serde::{Deserialize, Serialize};
+
+use crate::{
+ types::{RefundsResponseRouterData, ResponseRouterData},
+ utils::PaymentsAuthorizeRequestData,
+};
+
+//TODO: Fill the struct with respective fields
+pub struct NexixpayRouterData<T> {
+ pub amount: StringMinorUnit, // The type of amount that a connector accepts, for example, String, i64, f64, etc.
+ pub router_data: T,
+}
+
+impl<T> From<(StringMinorUnit, T)> for NexixpayRouterData<T> {
+ fn from((amount, item): (StringMinorUnit, T)) -> Self {
+ //Todo : use utils to convert the amount to the type of amount that a connector accepts
+ Self {
+ amount,
+ router_data: item,
+ }
+ }
+}
+
+//TODO: Fill the struct with respective fields
+#[derive(Default, Debug, Serialize, PartialEq)]
+pub struct NexixpayPaymentsRequest {
+ amount: StringMinorUnit,
+ card: NexixpayCard,
+}
+
+#[derive(Default, Debug, Serialize, Eq, PartialEq)]
+pub struct NexixpayCard {
+ number: cards::CardNumber,
+ expiry_month: Secret<String>,
+ expiry_year: Secret<String>,
+ cvc: Secret<String>,
+ complete: bool,
+}
+
+impl TryFrom<&NexixpayRouterData<&PaymentsAuthorizeRouterData>> for NexixpayPaymentsRequest {
+ type Error = error_stack::Report<errors::ConnectorError>;
+ fn try_from(
+ item: &NexixpayRouterData<&PaymentsAuthorizeRouterData>,
+ ) -> Result<Self, Self::Error> {
+ match item.router_data.request.payment_method_data.clone() {
+ PaymentMethodData::Card(req_card) => {
+ let card = NexixpayCard {
+ number: req_card.card_number,
+ expiry_month: req_card.card_exp_month,
+ expiry_year: req_card.card_exp_year,
+ cvc: req_card.card_cvc,
+ complete: item.router_data.request.is_auto_capture()?,
+ };
+ Ok(Self {
+ amount: item.amount.clone(),
+ card,
+ })
+ }
+ _ => Err(errors::ConnectorError::NotImplemented("Payment methods".to_string()).into()),
+ }
+ }
+}
+
+//TODO: Fill the struct with respective fields
+// Auth Struct
+pub struct NexixpayAuthType {
+ pub(super) api_key: Secret<String>,
+}
+
+impl TryFrom<&ConnectorAuthType> for NexixpayAuthType {
+ type Error = error_stack::Report<errors::ConnectorError>;
+ fn try_from(auth_type: &ConnectorAuthType) -> Result<Self, Self::Error> {
+ match auth_type {
+ ConnectorAuthType::HeaderKey { api_key } => Ok(Self {
+ api_key: api_key.to_owned(),
+ }),
+ _ => Err(errors::ConnectorError::FailedToObtainAuthType.into()),
+ }
+ }
+}
+// PaymentsResponse
+//TODO: Append the remaining status flags
+#[derive(Debug, Clone, Default, Serialize, Deserialize, PartialEq)]
+#[serde(rename_all = "lowercase")]
+pub enum NexixpayPaymentStatus {
+ Succeeded,
+ Failed,
+ #[default]
+ Processing,
+}
+
+impl From<NexixpayPaymentStatus> for common_enums::AttemptStatus {
+ fn from(item: NexixpayPaymentStatus) -> Self {
+ match item {
+ NexixpayPaymentStatus::Succeeded => Self::Charged,
+ NexixpayPaymentStatus::Failed => Self::Failure,
+ NexixpayPaymentStatus::Processing => Self::Authorizing,
+ }
+ }
+}
+
+//TODO: Fill the struct with respective fields
+#[derive(Default, Debug, Clone, Serialize, Deserialize, PartialEq)]
+pub struct NexixpayPaymentsResponse {
+ status: NexixpayPaymentStatus,
+ id: String,
+}
+
+impl<F, T> TryFrom<ResponseRouterData<F, NexixpayPaymentsResponse, T, PaymentsResponseData>>
+ for RouterData<F, T, PaymentsResponseData>
+{
+ type Error = error_stack::Report<errors::ConnectorError>;
+ fn try_from(
+ item: ResponseRouterData<F, NexixpayPaymentsResponse, T, PaymentsResponseData>,
+ ) -> Result<Self, Self::Error> {
+ Ok(Self {
+ status: common_enums::AttemptStatus::from(item.response.status),
+ response: Ok(PaymentsResponseData::TransactionResponse {
+ resource_id: ResponseId::ConnectorTransactionId(item.response.id),
+ redirection_data: None,
+ mandate_reference: None,
+ connector_metadata: None,
+ network_txn_id: None,
+ connector_response_reference_id: None,
+ incremental_authorization_allowed: None,
+ charge_id: None,
+ }),
+ ..item.data
+ })
+ }
+}
+
+//TODO: Fill the struct with respective fields
+// REFUND :
+// Type definition for RefundRequest
+#[derive(Default, Debug, Serialize)]
+pub struct NexixpayRefundRequest {
+ pub amount: StringMinorUnit,
+}
+
+impl<F> TryFrom<&NexixpayRouterData<&RefundsRouterData<F>>> for NexixpayRefundRequest {
+ type Error = error_stack::Report<errors::ConnectorError>;
+ fn try_from(item: &NexixpayRouterData<&RefundsRouterData<F>>) -> Result<Self, Self::Error> {
+ Ok(Self {
+ amount: item.amount.to_owned(),
+ })
+ }
+}
+
+// Type definition for Refund Response
+
+#[allow(dead_code)]
+#[derive(Debug, Serialize, Default, Deserialize, Clone)]
+pub enum RefundStatus {
+ Succeeded,
+ Failed,
+ #[default]
+ Processing,
+}
+
+impl From<RefundStatus> for enums::RefundStatus {
+ fn from(item: RefundStatus) -> Self {
+ match item {
+ RefundStatus::Succeeded => Self::Success,
+ RefundStatus::Failed => Self::Failure,
+ RefundStatus::Processing => Self::Pending,
+ //TODO: Review mapping
+ }
+ }
+}
+
+//TODO: Fill the struct with respective fields
+#[derive(Default, Debug, Clone, Serialize, Deserialize)]
+pub struct RefundResponse {
+ id: String,
+ status: RefundStatus,
+}
+
+impl TryFrom<RefundsResponseRouterData<Execute, RefundResponse>> for RefundsRouterData<Execute> {
+ type Error = error_stack::Report<errors::ConnectorError>;
+ fn try_from(
+ item: RefundsResponseRouterData<Execute, RefundResponse>,
+ ) -> Result<Self, Self::Error> {
+ Ok(Self {
+ response: Ok(RefundsResponseData {
+ connector_refund_id: item.response.id.to_string(),
+ refund_status: enums::RefundStatus::from(item.response.status),
+ }),
+ ..item.data
+ })
+ }
+}
+
+impl TryFrom<RefundsResponseRouterData<RSync, RefundResponse>> for RefundsRouterData<RSync> {
+ type Error = error_stack::Report<errors::ConnectorError>;
+ fn try_from(
+ item: RefundsResponseRouterData<RSync, RefundResponse>,
+ ) -> Result<Self, Self::Error> {
+ Ok(Self {
+ response: Ok(RefundsResponseData {
+ connector_refund_id: item.response.id.to_string(),
+ refund_status: enums::RefundStatus::from(item.response.status),
+ }),
+ ..item.data
+ })
+ }
+}
+
+//TODO: Fill the struct with respective fields
+#[derive(Default, Debug, Serialize, Deserialize, PartialEq)]
+pub struct NexixpayErrorResponse {
+ pub status_code: u16,
+ pub code: String,
+ pub message: String,
+ pub reason: Option<String>,
+}
diff --git a/crates/hyperswitch_connectors/src/default_implementations.rs b/crates/hyperswitch_connectors/src/default_implementations.rs
index 8da17ae28b0..8283a3e0d62 100644
--- a/crates/hyperswitch_connectors/src/default_implementations.rs
+++ b/crates/hyperswitch_connectors/src/default_implementations.rs
@@ -92,6 +92,7 @@ default_imp_for_authorize_session_token!(
connectors::Fiservemea,
connectors::Helcim,
connectors::Novalnet,
+ connectors::Nexixpay,
connectors::Stax,
connectors::Taxjar
);
@@ -118,6 +119,7 @@ default_imp_for_complete_authorize!(
connectors::Fiservemea,
connectors::Helcim,
connectors::Novalnet,
+ connectors::Nexixpay,
connectors::Stax,
connectors::Taxjar
);
@@ -144,6 +146,7 @@ default_imp_for_incremental_authorization!(
connectors::Fiservemea,
connectors::Helcim,
connectors::Novalnet,
+ connectors::Nexixpay,
connectors::Stax,
connectors::Taxjar
);
@@ -170,6 +173,7 @@ default_imp_for_create_customer!(
connectors::Fiservemea,
connectors::Helcim,
connectors::Novalnet,
+ connectors::Nexixpay,
connectors::Taxjar
);
@@ -196,6 +200,7 @@ default_imp_for_connector_redirect_response!(
connectors::Fiservemea,
connectors::Helcim,
connectors::Novalnet,
+ connectors::Nexixpay,
connectors::Stax,
connectors::Taxjar
);
@@ -222,6 +227,7 @@ default_imp_for_pre_processing_steps!(
connectors::Fiservemea,
connectors::Helcim,
connectors::Novalnet,
+ connectors::Nexixpay,
connectors::Stax,
connectors::Taxjar
);
@@ -248,6 +254,7 @@ default_imp_for_post_processing_steps!(
connectors::Fiservemea,
connectors::Helcim,
connectors::Novalnet,
+ connectors::Nexixpay,
connectors::Stax,
connectors::Taxjar
);
@@ -274,6 +281,7 @@ default_imp_for_approve!(
connectors::Fiservemea,
connectors::Helcim,
connectors::Novalnet,
+ connectors::Nexixpay,
connectors::Stax,
connectors::Taxjar
);
@@ -300,6 +308,7 @@ default_imp_for_reject!(
connectors::Fiservemea,
connectors::Helcim,
connectors::Novalnet,
+ connectors::Nexixpay,
connectors::Stax,
connectors::Taxjar
);
@@ -326,6 +335,7 @@ default_imp_for_webhook_source_verification!(
connectors::Fiservemea,
connectors::Helcim,
connectors::Novalnet,
+ connectors::Nexixpay,
connectors::Stax,
connectors::Taxjar
);
@@ -353,6 +363,7 @@ default_imp_for_accept_dispute!(
connectors::Fiservemea,
connectors::Helcim,
connectors::Novalnet,
+ connectors::Nexixpay,
connectors::Stax,
connectors::Taxjar
);
@@ -379,6 +390,7 @@ default_imp_for_submit_evidence!(
connectors::Fiservemea,
connectors::Helcim,
connectors::Novalnet,
+ connectors::Nexixpay,
connectors::Stax,
connectors::Taxjar
);
@@ -405,6 +417,7 @@ default_imp_for_defend_dispute!(
connectors::Fiservemea,
connectors::Helcim,
connectors::Novalnet,
+ connectors::Nexixpay,
connectors::Stax,
connectors::Taxjar
);
@@ -440,6 +453,7 @@ default_imp_for_file_upload!(
connectors::Fiservemea,
connectors::Helcim,
connectors::Novalnet,
+ connectors::Nexixpay,
connectors::Stax,
connectors::Taxjar
);
@@ -468,6 +482,7 @@ default_imp_for_payouts_create!(
connectors::Fiservemea,
connectors::Helcim,
connectors::Novalnet,
+ connectors::Nexixpay,
connectors::Stax,
connectors::Taxjar
);
@@ -496,6 +511,7 @@ default_imp_for_payouts_retrieve!(
connectors::Fiservemea,
connectors::Helcim,
connectors::Novalnet,
+ connectors::Nexixpay,
connectors::Stax,
connectors::Taxjar
);
@@ -524,6 +540,7 @@ default_imp_for_payouts_eligibility!(
connectors::Fiservemea,
connectors::Helcim,
connectors::Novalnet,
+ connectors::Nexixpay,
connectors::Stax,
connectors::Taxjar
);
@@ -552,6 +569,7 @@ default_imp_for_payouts_fulfill!(
connectors::Fiservemea,
connectors::Helcim,
connectors::Novalnet,
+ connectors::Nexixpay,
connectors::Stax,
connectors::Taxjar
);
@@ -580,6 +598,7 @@ default_imp_for_payouts_cancel!(
connectors::Fiservemea,
connectors::Helcim,
connectors::Novalnet,
+ connectors::Nexixpay,
connectors::Stax,
connectors::Taxjar
);
@@ -608,6 +627,7 @@ default_imp_for_payouts_quote!(
connectors::Fiservemea,
connectors::Helcim,
connectors::Novalnet,
+ connectors::Nexixpay,
connectors::Stax,
connectors::Taxjar
);
@@ -636,6 +656,7 @@ default_imp_for_payouts_recipient!(
connectors::Fiservemea,
connectors::Helcim,
connectors::Novalnet,
+ connectors::Nexixpay,
connectors::Stax,
connectors::Taxjar
);
@@ -664,6 +685,7 @@ default_imp_for_payouts_recipient_account!(
connectors::Fiservemea,
connectors::Helcim,
connectors::Novalnet,
+ connectors::Nexixpay,
connectors::Stax,
connectors::Taxjar
);
@@ -692,6 +714,7 @@ default_imp_for_frm_sale!(
connectors::Fiservemea,
connectors::Helcim,
connectors::Novalnet,
+ connectors::Nexixpay,
connectors::Stax,
connectors::Taxjar
);
@@ -720,6 +743,7 @@ default_imp_for_frm_checkout!(
connectors::Fiservemea,
connectors::Helcim,
connectors::Novalnet,
+ connectors::Nexixpay,
connectors::Stax,
connectors::Taxjar
);
@@ -748,6 +772,7 @@ default_imp_for_frm_transaction!(
connectors::Fiservemea,
connectors::Helcim,
connectors::Novalnet,
+ connectors::Nexixpay,
connectors::Stax,
connectors::Taxjar
);
@@ -776,6 +801,7 @@ default_imp_for_frm_fulfillment!(
connectors::Fiservemea,
connectors::Helcim,
connectors::Novalnet,
+ connectors::Nexixpay,
connectors::Stax,
connectors::Taxjar
);
@@ -804,6 +830,7 @@ default_imp_for_frm_record_return!(
connectors::Fiservemea,
connectors::Helcim,
connectors::Novalnet,
+ connectors::Nexixpay,
connectors::Stax,
connectors::Taxjar
);
@@ -829,6 +856,7 @@ default_imp_for_revoking_mandates!(
connectors::Fiservemea,
connectors::Helcim,
connectors::Novalnet,
+ connectors::Nexixpay,
connectors::Stax,
connectors::Taxjar
);
diff --git a/crates/hyperswitch_connectors/src/default_implementations_v2.rs b/crates/hyperswitch_connectors/src/default_implementations_v2.rs
index 4ebd335ce8f..b837e99c928 100644
--- a/crates/hyperswitch_connectors/src/default_implementations_v2.rs
+++ b/crates/hyperswitch_connectors/src/default_implementations_v2.rs
@@ -187,6 +187,7 @@ default_imp_for_new_connector_integration_payment!(
connectors::Fiservemea,
connectors::Helcim,
connectors::Novalnet,
+ connectors::Nexixpay,
connectors::Stax,
connectors::Taxjar
);
@@ -214,6 +215,7 @@ default_imp_for_new_connector_integration_refund!(
connectors::Fiservemea,
connectors::Helcim,
connectors::Novalnet,
+ connectors::Nexixpay,
connectors::Stax,
connectors::Taxjar
);
@@ -236,6 +238,7 @@ default_imp_for_new_connector_integration_connector_access_token!(
connectors::Fiservemea,
connectors::Helcim,
connectors::Novalnet,
+ connectors::Nexixpay,
connectors::Stax,
connectors::Taxjar
);
@@ -264,6 +267,7 @@ default_imp_for_new_connector_integration_accept_dispute!(
connectors::Fiservemea,
connectors::Helcim,
connectors::Novalnet,
+ connectors::Nexixpay,
connectors::Stax,
connectors::Taxjar
);
@@ -291,6 +295,7 @@ default_imp_for_new_connector_integration_submit_evidence!(
connectors::Fiservemea,
connectors::Helcim,
connectors::Novalnet,
+ connectors::Nexixpay,
connectors::Stax,
connectors::Taxjar
);
@@ -318,6 +323,7 @@ default_imp_for_new_connector_integration_defend_dispute!(
connectors::Fiservemea,
connectors::Helcim,
connectors::Novalnet,
+ connectors::Nexixpay,
connectors::Stax,
connectors::Taxjar
);
@@ -355,6 +361,7 @@ default_imp_for_new_connector_integration_file_upload!(
connectors::Fiservemea,
connectors::Helcim,
connectors::Novalnet,
+ connectors::Nexixpay,
connectors::Stax,
connectors::Taxjar
);
@@ -384,6 +391,7 @@ default_imp_for_new_connector_integration_payouts_create!(
connectors::Fiservemea,
connectors::Helcim,
connectors::Novalnet,
+ connectors::Nexixpay,
connectors::Stax,
connectors::Taxjar
);
@@ -413,6 +421,7 @@ default_imp_for_new_connector_integration_payouts_eligibility!(
connectors::Fiservemea,
connectors::Helcim,
connectors::Novalnet,
+ connectors::Nexixpay,
connectors::Stax,
connectors::Taxjar
);
@@ -442,6 +451,7 @@ default_imp_for_new_connector_integration_payouts_fulfill!(
connectors::Fiservemea,
connectors::Helcim,
connectors::Novalnet,
+ connectors::Nexixpay,
connectors::Stax,
connectors::Taxjar
);
@@ -471,6 +481,7 @@ default_imp_for_new_connector_integration_payouts_cancel!(
connectors::Fiservemea,
connectors::Helcim,
connectors::Novalnet,
+ connectors::Nexixpay,
connectors::Stax,
connectors::Taxjar
);
@@ -500,6 +511,7 @@ default_imp_for_new_connector_integration_payouts_quote!(
connectors::Fiservemea,
connectors::Helcim,
connectors::Novalnet,
+ connectors::Nexixpay,
connectors::Stax,
connectors::Taxjar
);
@@ -529,6 +541,7 @@ default_imp_for_new_connector_integration_payouts_recipient!(
connectors::Fiservemea,
connectors::Helcim,
connectors::Novalnet,
+ connectors::Nexixpay,
connectors::Stax,
connectors::Taxjar
);
@@ -558,6 +571,7 @@ default_imp_for_new_connector_integration_payouts_sync!(
connectors::Fiservemea,
connectors::Helcim,
connectors::Novalnet,
+ connectors::Nexixpay,
connectors::Stax,
connectors::Taxjar
);
@@ -587,6 +601,7 @@ default_imp_for_new_connector_integration_payouts_recipient_account!(
connectors::Fiservemea,
connectors::Helcim,
connectors::Novalnet,
+ connectors::Nexixpay,
connectors::Stax,
connectors::Taxjar
);
@@ -614,6 +629,7 @@ default_imp_for_new_connector_integration_webhook_source_verification!(
connectors::Fiservemea,
connectors::Helcim,
connectors::Novalnet,
+ connectors::Nexixpay,
connectors::Stax,
connectors::Taxjar
);
@@ -643,6 +659,7 @@ default_imp_for_new_connector_integration_frm_sale!(
connectors::Fiservemea,
connectors::Helcim,
connectors::Novalnet,
+ connectors::Nexixpay,
connectors::Stax,
connectors::Taxjar
);
@@ -672,6 +689,7 @@ default_imp_for_new_connector_integration_frm_checkout!(
connectors::Fiservemea,
connectors::Helcim,
connectors::Novalnet,
+ connectors::Nexixpay,
connectors::Stax,
connectors::Taxjar
);
@@ -701,6 +719,7 @@ default_imp_for_new_connector_integration_frm_transaction!(
connectors::Fiservemea,
connectors::Helcim,
connectors::Novalnet,
+ connectors::Nexixpay,
connectors::Stax,
connectors::Taxjar
);
@@ -730,6 +749,7 @@ default_imp_for_new_connector_integration_frm_fulfillment!(
connectors::Fiservemea,
connectors::Helcim,
connectors::Novalnet,
+ connectors::Nexixpay,
connectors::Stax,
connectors::Taxjar
);
@@ -759,6 +779,7 @@ default_imp_for_new_connector_integration_frm_record_return!(
connectors::Fiservemea,
connectors::Helcim,
connectors::Novalnet,
+ connectors::Nexixpay,
connectors::Stax,
connectors::Taxjar
);
@@ -785,6 +806,7 @@ default_imp_for_new_connector_integration_revoking_mandates!(
connectors::Fiservemea,
connectors::Helcim,
connectors::Novalnet,
+ connectors::Nexixpay,
connectors::Stax,
connectors::Taxjar
);
diff --git a/crates/hyperswitch_interfaces/src/configs.rs b/crates/hyperswitch_interfaces/src/configs.rs
index bc59bd037d7..f373b1c86af 100644
--- a/crates/hyperswitch_interfaces/src/configs.rs
+++ b/crates/hyperswitch_interfaces/src/configs.rs
@@ -49,6 +49,7 @@ pub struct Connectors {
pub multisafepay: ConnectorParams,
pub netcetera: ConnectorParams,
pub nexinets: ConnectorParams,
+ pub nexixpay: ConnectorParams,
pub nmi: ConnectorParams,
pub noon: ConnectorParamsWithModeType,
pub novalnet: ConnectorParams,
diff --git a/crates/router/src/connector.rs b/crates/router/src/connector.rs
index 5da8f3a8578..667d53ddf6f 100644
--- a/crates/router/src/connector.rs
+++ b/crates/router/src/connector.rs
@@ -69,8 +69,8 @@ pub mod zsl;
pub use hyperswitch_connectors::connectors::{
bambora, bambora::Bambora, bitpay, bitpay::Bitpay, fiserv, fiserv::Fiserv, fiservemea,
- fiservemea::Fiservemea, helcim, helcim::Helcim, novalnet, novalnet::Novalnet, stax, stax::Stax,
- taxjar, taxjar::Taxjar,
+ fiservemea::Fiservemea, helcim, helcim::Helcim, nexixpay, nexixpay::Nexixpay, novalnet,
+ novalnet::Novalnet, stax, stax::Stax, taxjar, taxjar::Taxjar,
};
#[cfg(feature = "dummy_connector")]
diff --git a/crates/router/src/core/payments/connector_integration_v2_impls.rs b/crates/router/src/core/payments/connector_integration_v2_impls.rs
index bed63c10a8a..27fa4b48176 100644
--- a/crates/router/src/core/payments/connector_integration_v2_impls.rs
+++ b/crates/router/src/core/payments/connector_integration_v2_impls.rs
@@ -1249,6 +1249,7 @@ default_imp_for_new_connector_integration_payouts!(
connector::Multisafepay,
connector::Netcetera,
connector::Nexinets,
+ connector::Nexixpay,
connector::Nmi,
connector::Noon,
connector::Novalnet,
@@ -2095,6 +2096,7 @@ default_imp_for_new_connector_integration_frm!(
connector::Multisafepay,
connector::Netcetera,
connector::Nexinets,
+ connector::Nexixpay,
connector::Nmi,
connector::Noon,
connector::Novalnet,
@@ -2720,6 +2722,7 @@ default_imp_for_new_connector_integration_connector_authentication!(
connector::Multisafepay,
connector::Netcetera,
connector::Nexinets,
+ connector::Nexixpay,
connector::Nmi,
connector::Noon,
connector::Novalnet,
diff --git a/crates/router/src/core/payments/flows.rs b/crates/router/src/core/payments/flows.rs
index aea8748ac67..6cbc320df91 100644
--- a/crates/router/src/core/payments/flows.rs
+++ b/crates/router/src/core/payments/flows.rs
@@ -554,6 +554,7 @@ default_imp_for_connector_request_id!(
connector::Mollie,
connector::Multisafepay,
connector::Netcetera,
+ connector::Nexixpay,
connector::Nmi,
connector::Noon,
connector::Novalnet,
@@ -1209,6 +1210,7 @@ default_imp_for_payouts!(
connector::Multisafepay,
connector::Netcetera,
connector::Nexinets,
+ connector::Nexixpay,
connector::Nmi,
connector::Noon,
connector::Novalnet,
@@ -2229,6 +2231,7 @@ default_imp_for_fraud_check!(
connector::Multisafepay,
connector::Netcetera,
connector::Nexinets,
+ connector::Nexixpay,
connector::Nmi,
connector::Noon,
connector::Novalnet,
@@ -3044,6 +3047,7 @@ default_imp_for_connector_authentication!(
connector::Mollie,
connector::Multisafepay,
connector::Nexinets,
+ connector::Nexixpay,
connector::Nmi,
connector::Noon,
connector::Novalnet,
diff --git a/crates/router/src/types/api.rs b/crates/router/src/types/api.rs
index 0637b98163d..775cc91ebef 100644
--- a/crates/router/src/types/api.rs
+++ b/crates/router/src/types/api.rs
@@ -471,6 +471,9 @@ impl ConnectorData {
enums::Connector::Nexinets => {
Ok(ConnectorEnum::Old(Box::new(&connector::Nexinets)))
}
+ // enums::Connector::Nexixpay => {
+ // Ok(ConnectorEnum::Old(Box::new(&connector::Nexixpay)))
+ // }
enums::Connector::Paypal => {
Ok(ConnectorEnum::Old(Box::new(connector::Paypal::new())))
}
diff --git a/crates/router/src/types/transformers.rs b/crates/router/src/types/transformers.rs
index 11254c5f29a..27e518a64fa 100644
--- a/crates/router/src/types/transformers.rs
+++ b/crates/router/src/types/transformers.rs
@@ -301,6 +301,7 @@ impl ForeignTryFrom<api_enums::Connector> for common_enums::RoutableConnectors {
})?
}
api_enums::Connector::Nexinets => Self::Nexinets,
+ // api_enums::Connector::Nexixpay => Self::Nexixpay,
api_enums::Connector::Nmi => Self::Nmi,
api_enums::Connector::Noon => Self::Noon,
// api_enums::Connector::Novalnet => Self::Novalnet,
diff --git a/crates/router/tests/connectors/main.rs b/crates/router/tests/connectors/main.rs
index 2a400b947dc..9b2b7d9ca04 100644
--- a/crates/router/tests/connectors/main.rs
+++ b/crates/router/tests/connectors/main.rs
@@ -45,6 +45,7 @@ mod mollie;
mod multisafepay;
mod netcetera;
mod nexinets;
+mod nexixpay;
mod nmi;
mod noon;
mod novalnet;
diff --git a/crates/router/tests/connectors/nexixpay.rs b/crates/router/tests/connectors/nexixpay.rs
new file mode 100644
index 00000000000..ebb68dd2898
--- /dev/null
+++ b/crates/router/tests/connectors/nexixpay.rs
@@ -0,0 +1,421 @@
+use hyperswitch_domain_models::payment_method_data::{Card, PaymentMethodData};
+use masking::Secret;
+use router::types::{self, api, storage::enums};
+use test_utils::connector_auth;
+
+use crate::utils::{self, ConnectorActions};
+
+#[derive(Clone, Copy)]
+struct NexixpayTest;
+impl ConnectorActions for NexixpayTest {}
+impl utils::Connector for NexixpayTest {
+ fn get_data(&self) -> api::ConnectorData {
+ use router::connector::Nexixpay;
+ utils::construct_connector_data_old(
+ Box::new(Nexixpay::new()),
+ types::Connector::Plaid,
+ api::GetToken::Connector,
+ None,
+ )
+ }
+
+ fn get_auth_token(&self) -> types::ConnectorAuthType {
+ utils::to_connector_auth_type(
+ connector_auth::ConnectorAuthentication::new()
+ .nexixpay
+ .expect("Missing connector authentication configuration")
+ .into(),
+ )
+ }
+
+ fn get_name(&self) -> String {
+ "nexixpay".to_string()
+ }
+}
+
+static CONNECTOR: NexixpayTest = NexixpayTest {};
+
+fn get_default_payment_info() -> Option<utils::PaymentInfo> {
+ None
+}
+
+fn payment_method_details() -> Option<types::PaymentsAuthorizeData> {
+ None
+}
+
+// Cards Positive Tests
+// Creates a payment using the manual capture flow (Non 3DS).
+#[actix_web::test]
+async fn should_only_authorize_payment() {
+ let response = CONNECTOR
+ .authorize_payment(payment_method_details(), get_default_payment_info())
+ .await
+ .expect("Authorize payment response");
+ assert_eq!(response.status, enums::AttemptStatus::Authorized);
+}
+
+// Captures a payment using the manual capture flow (Non 3DS).
+#[actix_web::test]
+async fn should_capture_authorized_payment() {
+ let response = CONNECTOR
+ .authorize_and_capture_payment(payment_method_details(), None, get_default_payment_info())
+ .await
+ .expect("Capture payment response");
+ assert_eq!(response.status, enums::AttemptStatus::Charged);
+}
+
+// Partially captures a payment using the manual capture flow (Non 3DS).
+#[actix_web::test]
+async fn should_partially_capture_authorized_payment() {
+ let response = CONNECTOR
+ .authorize_and_capture_payment(
+ payment_method_details(),
+ Some(types::PaymentsCaptureData {
+ amount_to_capture: 50,
+ ..utils::PaymentCaptureType::default().0
+ }),
+ get_default_payment_info(),
+ )
+ .await
+ .expect("Capture payment response");
+ assert_eq!(response.status, enums::AttemptStatus::Charged);
+}
+
+// Synchronizes a payment using the manual capture flow (Non 3DS).
+#[actix_web::test]
+async fn should_sync_authorized_payment() {
+ let authorize_response = CONNECTOR
+ .authorize_payment(payment_method_details(), get_default_payment_info())
+ .await
+ .expect("Authorize payment response");
+ let txn_id = utils::get_connector_transaction_id(authorize_response.response);
+ let response = CONNECTOR
+ .psync_retry_till_status_matches(
+ enums::AttemptStatus::Authorized,
+ Some(types::PaymentsSyncData {
+ connector_transaction_id: types::ResponseId::ConnectorTransactionId(
+ txn_id.unwrap(),
+ ),
+ ..Default::default()
+ }),
+ get_default_payment_info(),
+ )
+ .await
+ .expect("PSync response");
+ assert_eq!(response.status, enums::AttemptStatus::Authorized,);
+}
+
+// Voids a payment using the manual capture flow (Non 3DS).
+#[actix_web::test]
+async fn should_void_authorized_payment() {
+ let response = CONNECTOR
+ .authorize_and_void_payment(
+ payment_method_details(),
+ Some(types::PaymentsCancelData {
+ connector_transaction_id: String::from(""),
+ cancellation_reason: Some("requested_by_customer".to_string()),
+ ..Default::default()
+ }),
+ get_default_payment_info(),
+ )
+ .await
+ .expect("Void payment response");
+ assert_eq!(response.status, enums::AttemptStatus::Voided);
+}
+
+// Refunds a payment using the manual capture flow (Non 3DS).
+#[actix_web::test]
+async fn should_refund_manually_captured_payment() {
+ let response = CONNECTOR
+ .capture_payment_and_refund(
+ payment_method_details(),
+ None,
+ None,
+ get_default_payment_info(),
+ )
+ .await
+ .unwrap();
+ assert_eq!(
+ response.response.unwrap().refund_status,
+ enums::RefundStatus::Success,
+ );
+}
+
+// Partially refunds a payment using the manual capture flow (Non 3DS).
+#[actix_web::test]
+async fn should_partially_refund_manually_captured_payment() {
+ let response = CONNECTOR
+ .capture_payment_and_refund(
+ payment_method_details(),
+ None,
+ Some(types::RefundsData {
+ refund_amount: 50,
+ ..utils::PaymentRefundType::default().0
+ }),
+ get_default_payment_info(),
+ )
+ .await
+ .unwrap();
+ assert_eq!(
+ response.response.unwrap().refund_status,
+ enums::RefundStatus::Success,
+ );
+}
+
+// Synchronizes a refund using the manual capture flow (Non 3DS).
+#[actix_web::test]
+async fn should_sync_manually_captured_refund() {
+ let refund_response = CONNECTOR
+ .capture_payment_and_refund(
+ payment_method_details(),
+ None,
+ None,
+ get_default_payment_info(),
+ )
+ .await
+ .unwrap();
+ let response = CONNECTOR
+ .rsync_retry_till_status_matches(
+ enums::RefundStatus::Success,
+ refund_response.response.unwrap().connector_refund_id,
+ None,
+ get_default_payment_info(),
+ )
+ .await
+ .unwrap();
+ assert_eq!(
+ response.response.unwrap().refund_status,
+ enums::RefundStatus::Success,
+ );
+}
+
+// Creates a payment using the automatic capture flow (Non 3DS).
+#[actix_web::test]
+async fn should_make_payment() {
+ let authorize_response = CONNECTOR
+ .make_payment(payment_method_details(), get_default_payment_info())
+ .await
+ .unwrap();
+ assert_eq!(authorize_response.status, enums::AttemptStatus::Charged);
+}
+
+// Synchronizes a payment using the automatic capture flow (Non 3DS).
+#[actix_web::test]
+async fn should_sync_auto_captured_payment() {
+ let authorize_response = CONNECTOR
+ .make_payment(payment_method_details(), get_default_payment_info())
+ .await
+ .unwrap();
+ assert_eq!(authorize_response.status, enums::AttemptStatus::Charged);
+ let txn_id = utils::get_connector_transaction_id(authorize_response.response);
+ assert_ne!(txn_id, None, "Empty connector transaction id");
+ let response = CONNECTOR
+ .psync_retry_till_status_matches(
+ enums::AttemptStatus::Charged,
+ Some(types::PaymentsSyncData {
+ connector_transaction_id: types::ResponseId::ConnectorTransactionId(
+ txn_id.unwrap(),
+ ),
+ capture_method: Some(enums::CaptureMethod::Automatic),
+ ..Default::default()
+ }),
+ get_default_payment_info(),
+ )
+ .await
+ .unwrap();
+ assert_eq!(response.status, enums::AttemptStatus::Charged,);
+}
+
+// Refunds a payment using the automatic capture flow (Non 3DS).
+#[actix_web::test]
+async fn should_refund_auto_captured_payment() {
+ let response = CONNECTOR
+ .make_payment_and_refund(payment_method_details(), None, get_default_payment_info())
+ .await
+ .unwrap();
+ assert_eq!(
+ response.response.unwrap().refund_status,
+ enums::RefundStatus::Success,
+ );
+}
+
+// Partially refunds a payment using the automatic capture flow (Non 3DS).
+#[actix_web::test]
+async fn should_partially_refund_succeeded_payment() {
+ let refund_response = CONNECTOR
+ .make_payment_and_refund(
+ payment_method_details(),
+ Some(types::RefundsData {
+ refund_amount: 50,
+ ..utils::PaymentRefundType::default().0
+ }),
+ get_default_payment_info(),
+ )
+ .await
+ .unwrap();
+ assert_eq!(
+ refund_response.response.unwrap().refund_status,
+ enums::RefundStatus::Success,
+ );
+}
+
+// Creates multiple refunds against a payment using the automatic capture flow (Non 3DS).
+#[actix_web::test]
+async fn should_refund_succeeded_payment_multiple_times() {
+ CONNECTOR
+ .make_payment_and_multiple_refund(
+ payment_method_details(),
+ Some(types::RefundsData {
+ refund_amount: 50,
+ ..utils::PaymentRefundType::default().0
+ }),
+ get_default_payment_info(),
+ )
+ .await;
+}
+
+// Synchronizes a refund using the automatic capture flow (Non 3DS).
+#[actix_web::test]
+async fn should_sync_refund() {
+ let refund_response = CONNECTOR
+ .make_payment_and_refund(payment_method_details(), None, get_default_payment_info())
+ .await
+ .unwrap();
+ let response = CONNECTOR
+ .rsync_retry_till_status_matches(
+ enums::RefundStatus::Success,
+ refund_response.response.unwrap().connector_refund_id,
+ None,
+ get_default_payment_info(),
+ )
+ .await
+ .unwrap();
+ assert_eq!(
+ response.response.unwrap().refund_status,
+ enums::RefundStatus::Success,
+ );
+}
+
+// Cards Negative scenarios
+// Creates a payment with incorrect CVC.
+#[actix_web::test]
+async fn should_fail_payment_for_incorrect_cvc() {
+ let response = CONNECTOR
+ .make_payment(
+ Some(types::PaymentsAuthorizeData {
+ payment_method_data: PaymentMethodData::Card(Card {
+ card_cvc: Secret::new("12345".to_string()),
+ ..utils::CCardType::default().0
+ }),
+ ..utils::PaymentAuthorizeType::default().0
+ }),
+ get_default_payment_info(),
+ )
+ .await
+ .unwrap();
+ assert_eq!(
+ response.response.unwrap_err().message,
+ "Your card's security code is invalid.".to_string(),
+ );
+}
+
+// Creates a payment with incorrect expiry month.
+#[actix_web::test]
+async fn should_fail_payment_for_invalid_exp_month() {
+ let response = CONNECTOR
+ .make_payment(
+ Some(types::PaymentsAuthorizeData {
+ payment_method_data: PaymentMethodData::Card(Card {
+ card_exp_month: Secret::new("20".to_string()),
+ ..utils::CCardType::default().0
+ }),
+ ..utils::PaymentAuthorizeType::default().0
+ }),
+ get_default_payment_info(),
+ )
+ .await
+ .unwrap();
+ assert_eq!(
+ response.response.unwrap_err().message,
+ "Your card's expiration month is invalid.".to_string(),
+ );
+}
+
+// Creates a payment with incorrect expiry year.
+#[actix_web::test]
+async fn should_fail_payment_for_incorrect_expiry_year() {
+ let response = CONNECTOR
+ .make_payment(
+ Some(types::PaymentsAuthorizeData {
+ payment_method_data: PaymentMethodData::Card(Card {
+ card_exp_year: Secret::new("2000".to_string()),
+ ..utils::CCardType::default().0
+ }),
+ ..utils::PaymentAuthorizeType::default().0
+ }),
+ get_default_payment_info(),
+ )
+ .await
+ .unwrap();
+ assert_eq!(
+ response.response.unwrap_err().message,
+ "Your card's expiration year is invalid.".to_string(),
+ );
+}
+
+// Voids a payment using automatic capture flow (Non 3DS).
+#[actix_web::test]
+async fn should_fail_void_payment_for_auto_capture() {
+ let authorize_response = CONNECTOR
+ .make_payment(payment_method_details(), get_default_payment_info())
+ .await
+ .unwrap();
+ assert_eq!(authorize_response.status, enums::AttemptStatus::Charged);
+ let txn_id = utils::get_connector_transaction_id(authorize_response.response);
+ assert_ne!(txn_id, None, "Empty connector transaction id");
+ let void_response = CONNECTOR
+ .void_payment(txn_id.unwrap(), None, get_default_payment_info())
+ .await
+ .unwrap();
+ assert_eq!(
+ void_response.response.unwrap_err().message,
+ "You cannot cancel this PaymentIntent because it has a status of succeeded."
+ );
+}
+
+// Captures a payment using invalid connector payment id.
+#[actix_web::test]
+async fn should_fail_capture_for_invalid_payment() {
+ let capture_response = CONNECTOR
+ .capture_payment("123456789".to_string(), None, get_default_payment_info())
+ .await
+ .unwrap();
+ assert_eq!(
+ capture_response.response.unwrap_err().message,
+ String::from("No such payment_intent: '123456789'")
+ );
+}
+
+// Refunds a payment with refund amount higher than payment amount.
+#[actix_web::test]
+async fn should_fail_for_refund_amount_higher_than_payment_amount() {
+ let response = CONNECTOR
+ .make_payment_and_refund(
+ payment_method_details(),
+ Some(types::RefundsData {
+ refund_amount: 150,
+ ..utils::PaymentRefundType::default().0
+ }),
+ get_default_payment_info(),
+ )
+ .await
+ .unwrap();
+ assert_eq!(
+ response.response.unwrap_err().message,
+ "Refund amount (₹1.50) is greater than charge amount (₹1.00)",
+ );
+}
+
+// Connector dependent test cases goes here
+
+// [#478]: add unit tests for non 3DS, wallets & webhooks in connector tests
diff --git a/crates/router/tests/connectors/sample_auth.toml b/crates/router/tests/connectors/sample_auth.toml
index 6134d1ae036..1fa302c7161 100644
--- a/crates/router/tests/connectors/sample_auth.toml
+++ b/crates/router/tests/connectors/sample_auth.toml
@@ -261,6 +261,9 @@ api_key="API Key"
[fiservemea]
api_key="API Key"
+[nexixpay]
+api_key="API Key"
+
[wellsfargopayout]
api_key = "Consumer Key"
key1 = "Gateway Entity Id"
diff --git a/crates/test_utils/src/connector_auth.rs b/crates/test_utils/src/connector_auth.rs
index 0848b9a9f57..217886e9279 100644
--- a/crates/test_utils/src/connector_auth.rs
+++ b/crates/test_utils/src/connector_auth.rs
@@ -50,6 +50,7 @@ pub struct ConnectorAuthentication {
pub multisafepay: Option<HeaderKey>,
pub netcetera: Option<HeaderKey>,
pub nexinets: Option<BodyKey>,
+ pub nexixpay: Option<HeaderKey>,
pub noon: Option<SignatureKey>,
pub novalnet: Option<HeaderKey>,
pub nmi: Option<HeaderKey>,
diff --git a/loadtest/config/development.toml b/loadtest/config/development.toml
index 347d587014d..efdef8fc88d 100644
--- a/loadtest/config/development.toml
+++ b/loadtest/config/development.toml
@@ -116,10 +116,11 @@ mollie.secondary_base_url = "https://api.cc.mollie.com/v1/"
multisafepay.base_url = "https://testapi.multisafepay.com/"
netcetera.base_url = "https://{{merchant_endpoint_prefix}}.3ds-server.prev.netcetera-cloud-payment.ch"
nexinets.base_url = "https://apitest.payengine.de/v1"
+nexixpay.base_url = "https://xpaysandbox.nexigroup.com/api/phoenix-0.0/psp/api/v1"
nmi.base_url = "https://secure.nmi.com/"
noon.base_url = "https://api-test.noonpayments.com/"
-novalnet.base_url = "https://payport.novalnet.de/v2"
noon.key_mode = "Test"
+novalnet.base_url = "https://payport.novalnet.de/v2"
nuvei.base_url = "https://ppp-test.nuvei.com/"
opayo.base_url = "https://pi-test.sagepay.com/"
opennode.base_url = "https://dev-api.opennode.com"
@@ -201,6 +202,7 @@ cards = [
"multisafepay",
"netcetera",
"nexinets",
+ "nexixpay",
"nmi",
"noon",
"novalnet",
diff --git a/scripts/add_connector.sh b/scripts/add_connector.sh
index 362d0577c69..f9aa336300f 100755
--- a/scripts/add_connector.sh
+++ b/scripts/add_connector.sh
@@ -6,7 +6,7 @@ function find_prev_connector() {
git checkout $self
cp $self $self.tmp
# Add new connector to existing list and sort it
- connectors=(aci adyen adyenplatform airwallex applepay authorizedotnet bambora bamboraapac bankofamerica billwerk bitpay bluesnap boku braintree cashtocode checkout coinbase cryptopay cybersource datatrans dlocal dummyconnector ebanx fiserv fiservemea forte globalpay globepay gocardless gpayments helcim iatapay itaubank klarna mifinity mollie multisafepay netcetera nexinets noon novalnet nuvei opayo opennode paybox payeezy payme payone paypal payu placetopay plaid powertranz prophetpay rapyd razorpay shift4 square stax stripe taxjar threedsecureio trustpay tsys volt wellsfargo wellsfargopayout wise worldline worldpay zsl "$1")
+ connectors=(aci adyen adyenplatform airwallex applepay authorizedotnet bambora bamboraapac bankofamerica billwerk bitpay bluesnap boku braintree cashtocode checkout coinbase cryptopay cybersource datatrans dlocal dummyconnector ebanx fiserv fiservemea forte globalpay globepay gocardless gpayments helcim iatapay itaubank klarna mifinity mollie multisafepay netcetera nexinets nexixpay noon novalnet nuvei opayo opennode paybox payeezy payme payone paypal payu placetopay plaid powertranz prophetpay rapyd razorpay shift4 square stax stripe taxjar threedsecureio trustpay tsys volt wellsfargo wellsfargopayout wise worldline worldpay zsl "$1")
IFS=$'\n' sorted=($(sort <<<"${connectors[*]}")); unset IFS
res=`echo ${sorted[@]}`
sed -i'' -e "s/^ connectors=.*/ connectors=($res \"\$1\")/" $self.tmp
|
2024-08-23T10:56:11Z
|
## Type of Change
<!-- Put an `x` in the boxes that apply -->
- [ ] Bugfix
- [x] New feature
- [ ] Enhancement
- [ ] Refactoring
- [ ] Dependency updates
- [ ] Documentation
- [ ] CI/CD
## Description
<!-- Describe your changes in detail -->
Template code added for new connector Nexi-Xpay
### Additional Changes
- [ ] This PR modifies the API contract
- [ ] This PR modifies the database schema
- [ ] This PR modifies application configuration/environment variables
<!--
Provide links to the files with corresponding changes.
Following are the paths where you can find config files:
1. `config`
2. `crates/router/src/configs`
3. `loadtest/config`
-->
## Motivation and Context
<!--
Why is this change required? What problem does it solve?
If it fixes an open issue, please link to the issue here.
If you don't have an issue, we'd recommend starting with one first so the PR
can focus on the implementation (unless it is an obvious bug or documentation fix
that will have little conversation).
-->
## How did you test it?
<!--
Did you write an integration/unit/API test to verify the code changes?
Or did you test this change manually (provide relevant screenshots)?
-->
## Checklist
<!-- Put an `x` in the boxes that apply -->
- [x] I formatted the code `cargo +nightly fmt --all`
- [x] I addressed lints thrown by `cargo clippy`
- [x] I reviewed the submitted code
- [ ] I added unit tests for my changes where possible
|
4585e16245dd49d8c0b877cda148524afe395009
|
|
juspay/hyperswitch
|
juspay__hyperswitch-5695
|
Bug: Add profile id to transaction tables
Required to provide profile level filters in analytics section
|
diff --git a/crates/analytics/docs/clickhouse/scripts/disputes.sql b/crates/analytics/docs/clickhouse/scripts/disputes.sql
index bb7472a4d54..3bd993d31cf 100644
--- a/crates/analytics/docs/clickhouse/scripts/disputes.sql
+++ b/crates/analytics/docs/clickhouse/scripts/disputes.sql
@@ -20,6 +20,7 @@ CREATE TABLE dispute_queue (
`evidence` Nullable(String),
`profile_id` Nullable(String),
`merchant_connector_id` Nullable(String),
+ `organization_id` String,
`sign_flag` Int8
) ENGINE = Kafka SETTINGS kafka_broker_list = 'kafka0:29092',
kafka_topic_list = 'hyperswitch-dispute-events',
@@ -50,6 +51,7 @@ CREATE TABLE dispute (
`profile_id` Nullable(String),
`merchant_connector_id` Nullable(String),
`inserted_at` DateTime DEFAULT now() CODEC(T64, LZ4),
+ `organization_id` String,
`sign_flag` Int8,
INDEX connectorIndex connector TYPE bloom_filter GRANULARITY 1,
INDEX disputeStatusIndex dispute_status TYPE bloom_filter GRANULARITY 1,
@@ -80,6 +82,7 @@ CREATE MATERIALIZED VIEW dispute_mv TO dispute (
`evidence` Nullable(String),
`profile_id` Nullable(String),
`merchant_connector_id` Nullable(String),
+ `organization_id` String,
`inserted_at` DateTime64(3),
`sign_flag` Int8
) AS
@@ -105,6 +108,7 @@ SELECT
evidence,
profile_id,
merchant_connector_id,
+ organization_id,
now() AS inserted_at,
sign_flag
FROM
diff --git a/crates/analytics/docs/clickhouse/scripts/payment_attempts.sql b/crates/analytics/docs/clickhouse/scripts/payment_attempts.sql
index 223d29c9836..5c1ee8754c9 100644
--- a/crates/analytics/docs/clickhouse/scripts/payment_attempts.sql
+++ b/crates/analytics/docs/clickhouse/scripts/payment_attempts.sql
@@ -40,6 +40,8 @@ CREATE TABLE payment_attempt_queue (
`mandate_data` Nullable(String),
`client_source` LowCardinality(Nullable(String)),
`client_version` LowCardinality(Nullable(String)),
+ `organization_id` String,
+ `profile_id` String,
`sign_flag` Int8
) ENGINE = Kafka SETTINGS kafka_broker_list = 'kafka0:29092',
kafka_topic_list = 'hyperswitch-payment-attempt-events',
@@ -90,6 +92,8 @@ CREATE TABLE payment_attempts (
`inserted_at` DateTime DEFAULT now() CODEC(T64, LZ4),
`client_source` LowCardinality(Nullable(String)),
`client_version` LowCardinality(Nullable(String)),
+ `organization_id` String,
+ `profile_id` String,
`sign_flag` Int8,
INDEX connectorIndex connector TYPE bloom_filter GRANULARITY 1,
INDEX paymentMethodIndex payment_method TYPE bloom_filter GRANULARITY 1,
@@ -143,6 +147,8 @@ CREATE MATERIALIZED VIEW payment_attempt_mv TO payment_attempts (
`inserted_at` DateTime64(3),
`client_source` LowCardinality(Nullable(String)),
`client_version` LowCardinality(Nullable(String)),
+ `organization_id` String,
+ `profile_id` String,
`sign_flag` Int8
) AS
SELECT
@@ -188,6 +194,8 @@ SELECT
now() AS inserted_at,
client_source,
client_version,
+ organization_id,
+ profile_id,
sign_flag
FROM
payment_attempt_queue
diff --git a/crates/analytics/docs/clickhouse/scripts/payment_intents.sql b/crates/analytics/docs/clickhouse/scripts/payment_intents.sql
index 09101e9aa2d..b4d00a858b0 100644
--- a/crates/analytics/docs/clickhouse/scripts/payment_intents.sql
+++ b/crates/analytics/docs/clickhouse/scripts/payment_intents.sql
@@ -23,6 +23,7 @@ CREATE TABLE payment_intents_queue
`modified_at` DateTime CODEC(T64, LZ4),
`created_at` DateTime CODEC(T64, LZ4),
`last_synced` Nullable(DateTime) CODEC(T64, LZ4),
+ `organization_id` String,
`sign_flag` Int8
) ENGINE = Kafka SETTINGS kafka_broker_list = 'kafka0:29092',
kafka_topic_list = 'hyperswitch-payment-intent-events',
@@ -56,6 +57,7 @@ CREATE TABLE payment_intents
`created_at` DateTime DEFAULT now() CODEC(T64, LZ4),
`last_synced` Nullable(DateTime) CODEC(T64, LZ4),
`inserted_at` DateTime DEFAULT now() CODEC(T64, LZ4),
+ `organization_id` String,
`sign_flag` Int8,
INDEX connectorIndex connector_id TYPE bloom_filter GRANULARITY 1,
INDEX currencyIndex currency TYPE bloom_filter GRANULARITY 1,
@@ -93,6 +95,7 @@ CREATE MATERIALIZED VIEW payment_intents_mv TO payment_intents
`created_at` DateTime64(3),
`last_synced` Nullable(DateTime64(3)),
`inserted_at` DateTime64(3),
+ `organization_id` String,
`sign_flag` Int8
) AS
SELECT
@@ -120,5 +123,6 @@ SELECT
created_at,
last_synced,
now() AS inserted_at,
+ organization_id,
sign_flag
FROM payment_intents_queue;
\ No newline at end of file
diff --git a/crates/analytics/docs/clickhouse/scripts/refunds.sql b/crates/analytics/docs/clickhouse/scripts/refunds.sql
index 74c069db853..323caf1adb4 100644
--- a/crates/analytics/docs/clickhouse/scripts/refunds.sql
+++ b/crates/analytics/docs/clickhouse/scripts/refunds.sql
@@ -21,6 +21,8 @@ CREATE TABLE refund_queue (
`refund_error_code` Nullable(String),
`created_at` DateTime,
`modified_at` DateTime,
+ `organization_id` String,
+ `profile_id` String,
`sign_flag` Int8
) ENGINE = Kafka SETTINGS kafka_broker_list = 'kafka0:29092',
kafka_topic_list = 'hyperswitch-refund-events',
@@ -52,6 +54,8 @@ CREATE TABLE refunds (
`created_at` DateTime DEFAULT now() CODEC(T64, LZ4),
`modified_at` DateTime DEFAULT now() CODEC(T64, LZ4),
`inserted_at` DateTime DEFAULT now() CODEC(T64, LZ4),
+ `organization_id` String,
+ `profile_id` String,
`sign_flag` Int8,
INDEX connectorIndex connector TYPE bloom_filter GRANULARITY 1,
INDEX refundTypeIndex refund_type TYPE bloom_filter GRANULARITY 1,
@@ -85,6 +89,8 @@ CREATE MATERIALIZED VIEW refund_mv TO refunds (
`created_at` DateTime64(3),
`modified_at` DateTime64(3),
`inserted_at` DateTime64(3),
+ `organization_id` String,
+ `profile_id` String,
`sign_flag` Int8
) AS
SELECT
@@ -111,6 +117,8 @@ SELECT
created_at,
modified_at,
now() AS inserted_at,
+ organization_id,
+ profile_id,
sign_flag
FROM
refund_queue
diff --git a/crates/diesel_models/src/customers.rs b/crates/diesel_models/src/customers.rs
index 7e4e27a5d38..c0d6639d1ad 100644
--- a/crates/diesel_models/src/customers.rs
+++ b/crates/diesel_models/src/customers.rs
@@ -41,6 +41,7 @@ impl Customer {
#[cfg(all(feature = "v2", feature = "customer_v2"))]
impl Customer {
+ #[allow(clippy::todo)]
pub fn get_customer_id(&self) -> common_utils::id_type::CustomerId {
todo!()
}
diff --git a/crates/diesel_models/src/dispute.rs b/crates/diesel_models/src/dispute.rs
index 45004e10ba5..1c70655406a 100644
--- a/crates/diesel_models/src/dispute.rs
+++ b/crates/diesel_models/src/dispute.rs
@@ -30,6 +30,7 @@ pub struct DisputeNew {
pub profile_id: Option<common_utils::id_type::ProfileId>,
pub merchant_connector_id: Option<common_utils::id_type::MerchantConnectorAccountId>,
pub dispute_amount: i64,
+ pub organization_id: common_utils::id_type::OrganizationId,
}
#[derive(Clone, Debug, PartialEq, Serialize, Identifiable, Queryable, Selectable)]
@@ -59,6 +60,7 @@ pub struct Dispute {
pub profile_id: Option<common_utils::id_type::ProfileId>,
pub merchant_connector_id: Option<common_utils::id_type::MerchantConnectorAccountId>,
pub dispute_amount: i64,
+ pub organization_id: common_utils::id_type::OrganizationId,
}
#[derive(Debug)]
diff --git a/crates/diesel_models/src/payment_attempt.rs b/crates/diesel_models/src/payment_attempt.rs
index ec87b2da2e4..fd769d4dbd2 100644
--- a/crates/diesel_models/src/payment_attempt.rs
+++ b/crates/diesel_models/src/payment_attempt.rs
@@ -1,4 +1,4 @@
-use common_utils::pii;
+use common_utils::{id_type, pii};
use diesel::{AsChangeset, Identifiable, Insertable, Queryable, Selectable};
use serde::{Deserialize, Serialize};
use time::PrimitiveDateTime;
@@ -16,7 +16,7 @@ use crate::schema_v2::payment_attempt;
#[diesel(table_name = payment_attempt, primary_key(attempt_id, merchant_id), check_for_backend(diesel::pg::Pg))]
pub struct PaymentAttempt {
pub payment_id: String,
- pub merchant_id: common_utils::id_type::MerchantId,
+ pub merchant_id: id_type::MerchantId,
pub attempt_id: String,
pub status: storage_enums::AttemptStatus,
pub amount: i64,
@@ -62,7 +62,7 @@ pub struct PaymentAttempt {
pub connector_response_reference_id: Option<String>,
pub amount_capturable: i64,
pub updated_by: String,
- pub merchant_connector_id: Option<common_utils::id_type::MerchantConnectorAccountId>,
+ pub merchant_connector_id: Option<id_type::MerchantConnectorAccountId>,
pub authentication_data: Option<serde_json::Value>,
pub encoded_data: Option<String>,
pub unified_code: Option<String>,
@@ -78,6 +78,9 @@ pub struct PaymentAttempt {
pub client_source: Option<String>,
pub client_version: Option<String>,
pub customer_acceptance: Option<pii::SecretSerdeValue>,
+ pub profile_id: id_type::ProfileId,
+ pub organization_id: id_type::OrganizationId,
+ pub card_network: Option<String>,
}
#[cfg(all(any(feature = "v1", feature = "v2"), not(feature = "payment_v2")))]
@@ -87,7 +90,7 @@ pub struct PaymentAttempt {
#[diesel(table_name = payment_attempt, primary_key(attempt_id, merchant_id), check_for_backend(diesel::pg::Pg))]
pub struct PaymentAttempt {
pub payment_id: String,
- pub merchant_id: common_utils::id_type::MerchantId,
+ pub merchant_id: id_type::MerchantId,
pub attempt_id: String,
pub status: storage_enums::AttemptStatus,
pub amount: i64,
@@ -133,7 +136,7 @@ pub struct PaymentAttempt {
pub connector_response_reference_id: Option<String>,
pub amount_capturable: i64,
pub updated_by: String,
- pub merchant_connector_id: Option<common_utils::id_type::MerchantConnectorAccountId>,
+ pub merchant_connector_id: Option<id_type::MerchantConnectorAccountId>,
pub authentication_data: Option<serde_json::Value>,
pub encoded_data: Option<String>,
pub unified_code: Option<String>,
@@ -149,6 +152,9 @@ pub struct PaymentAttempt {
pub client_source: Option<String>,
pub client_version: Option<String>,
pub customer_acceptance: Option<pii::SecretSerdeValue>,
+ pub profile_id: id_type::ProfileId,
+ pub organization_id: id_type::OrganizationId,
+ pub card_network: Option<String>,
}
impl PaymentAttempt {
@@ -171,7 +177,7 @@ pub struct PaymentListFilters {
#[diesel(table_name = payment_attempt)]
pub struct PaymentAttemptNew {
pub payment_id: String,
- pub merchant_id: common_utils::id_type::MerchantId,
+ pub merchant_id: id_type::MerchantId,
pub attempt_id: String,
pub status: storage_enums::AttemptStatus,
pub amount: i64,
@@ -215,7 +221,7 @@ pub struct PaymentAttemptNew {
pub multiple_capture_count: Option<i16>,
pub amount_capturable: i64,
pub updated_by: String,
- pub merchant_connector_id: Option<common_utils::id_type::MerchantConnectorAccountId>,
+ pub merchant_connector_id: Option<id_type::MerchantConnectorAccountId>,
pub authentication_data: Option<serde_json::Value>,
pub encoded_data: Option<String>,
pub unified_code: Option<String>,
@@ -231,6 +237,9 @@ pub struct PaymentAttemptNew {
pub client_source: Option<String>,
pub client_version: Option<String>,
pub customer_acceptance: Option<pii::SecretSerdeValue>,
+ pub profile_id: id_type::ProfileId,
+ pub organization_id: id_type::OrganizationId,
+ pub card_network: Option<String>,
}
impl PaymentAttemptNew {
@@ -280,7 +289,7 @@ pub enum PaymentAttemptUpdate {
surcharge_amount: Option<i64>,
tax_amount: Option<i64>,
updated_by: String,
- merchant_connector_id: Option<common_utils::id_type::MerchantConnectorAccountId>,
+ merchant_connector_id: Option<id_type::MerchantConnectorAccountId>,
},
AuthenticationTypeUpdate {
authentication_type: storage_enums::AuthenticationType,
@@ -308,7 +317,7 @@ pub enum PaymentAttemptUpdate {
tax_amount: Option<i64>,
fingerprint_id: Option<String>,
updated_by: String,
- merchant_connector_id: Option<common_utils::id_type::MerchantConnectorAccountId>,
+ merchant_connector_id: Option<id_type::MerchantConnectorAccountId>,
payment_method_id: Option<String>,
external_three_ds_authentication_attempted: Option<bool>,
authentication_connector: Option<String>,
@@ -475,7 +484,7 @@ pub struct PaymentAttemptUpdateInternal {
tax_amount: Option<i64>,
amount_capturable: Option<i64>,
updated_by: String,
- merchant_connector_id: Option<Option<common_utils::id_type::MerchantConnectorAccountId>>,
+ merchant_connector_id: Option<Option<id_type::MerchantConnectorAccountId>>,
authentication_data: Option<serde_json::Value>,
encoded_data: Option<String>,
unified_code: Option<Option<String>>,
@@ -489,6 +498,7 @@ pub struct PaymentAttemptUpdateInternal {
client_source: Option<String>,
client_version: Option<String>,
customer_acceptance: Option<pii::SecretSerdeValue>,
+ card_network: Option<String>,
}
impl PaymentAttemptUpdateInternal {
@@ -505,6 +515,15 @@ impl PaymentAttemptUpdateInternal {
.or(source.tax_amount)
.unwrap_or(0),
);
+ update_internal.card_network = update_internal
+ .payment_method_data
+ .as_ref()
+ .and_then(|data| data.as_object())
+ .and_then(|card| card.get("card"))
+ .and_then(|data| data.as_object())
+ .and_then(|card| card.get("card_network"))
+ .and_then(|network| network.as_str())
+ .map(|network| network.to_string());
update_internal
}
}
@@ -558,6 +577,7 @@ impl PaymentAttemptUpdate {
client_source,
client_version,
customer_acceptance,
+ card_network,
} = PaymentAttemptUpdateInternal::from(self).populate_derived_fields(&source);
PaymentAttempt {
amount: amount.unwrap_or(source.amount),
@@ -610,6 +630,7 @@ impl PaymentAttemptUpdate {
client_source: client_source.or(source.client_source),
client_version: client_version.or(source.client_version),
customer_acceptance: customer_acceptance.or(source.customer_acceptance),
+ card_network: card_network.or(source.card_network),
..source
}
}
@@ -685,6 +706,7 @@ impl From<PaymentAttemptUpdate> for PaymentAttemptUpdateInternal {
client_source: None,
client_version: None,
customer_acceptance: None,
+ card_network: None,
},
PaymentAttemptUpdate::AuthenticationTypeUpdate {
authentication_type,
@@ -736,6 +758,7 @@ impl From<PaymentAttemptUpdate> for PaymentAttemptUpdateInternal {
client_source: None,
client_version: None,
customer_acceptance: None,
+ card_network: None,
},
PaymentAttemptUpdate::ConfirmUpdate {
amount,
@@ -815,6 +838,7 @@ impl From<PaymentAttemptUpdate> for PaymentAttemptUpdateInternal {
unified_code: None,
unified_message: None,
charge_id: None,
+ card_network: None,
},
PaymentAttemptUpdate::VoidUpdate {
status,
@@ -867,6 +891,7 @@ impl From<PaymentAttemptUpdate> for PaymentAttemptUpdateInternal {
client_source: None,
client_version: None,
customer_acceptance: None,
+ card_network: None,
},
PaymentAttemptUpdate::RejectUpdate {
status,
@@ -920,6 +945,7 @@ impl From<PaymentAttemptUpdate> for PaymentAttemptUpdateInternal {
client_source: None,
client_version: None,
customer_acceptance: None,
+ card_network: None,
},
PaymentAttemptUpdate::BlocklistUpdate {
status,
@@ -973,6 +999,7 @@ impl From<PaymentAttemptUpdate> for PaymentAttemptUpdateInternal {
client_source: None,
client_version: None,
customer_acceptance: None,
+ card_network: None,
},
PaymentAttemptUpdate::PaymentMethodDetailsUpdate {
payment_method_id,
@@ -1024,6 +1051,7 @@ impl From<PaymentAttemptUpdate> for PaymentAttemptUpdateInternal {
client_source: None,
client_version: None,
customer_acceptance: None,
+ card_network: None,
},
PaymentAttemptUpdate::ResponseUpdate {
status,
@@ -1093,6 +1121,7 @@ impl From<PaymentAttemptUpdate> for PaymentAttemptUpdateInternal {
client_source: None,
client_version: None,
customer_acceptance: None,
+ card_network: None,
},
PaymentAttemptUpdate::ErrorUpdate {
connector,
@@ -1154,6 +1183,7 @@ impl From<PaymentAttemptUpdate> for PaymentAttemptUpdateInternal {
client_source: None,
client_version: None,
customer_acceptance: None,
+ card_network: None,
},
PaymentAttemptUpdate::StatusUpdate { status, updated_by } => Self {
status: Some(status),
@@ -1202,6 +1232,7 @@ impl From<PaymentAttemptUpdate> for PaymentAttemptUpdateInternal {
client_source: None,
client_version: None,
customer_acceptance: None,
+ card_network: None,
},
PaymentAttemptUpdate::UpdateTrackers {
payment_token,
@@ -1259,6 +1290,7 @@ impl From<PaymentAttemptUpdate> for PaymentAttemptUpdateInternal {
client_source: None,
client_version: None,
customer_acceptance: None,
+ card_network: None,
},
PaymentAttemptUpdate::UnresolvedResponseUpdate {
status,
@@ -1317,6 +1349,7 @@ impl From<PaymentAttemptUpdate> for PaymentAttemptUpdateInternal {
client_source: None,
client_version: None,
customer_acceptance: None,
+ card_network: None,
},
PaymentAttemptUpdate::PreprocessingUpdate {
status,
@@ -1373,6 +1406,7 @@ impl From<PaymentAttemptUpdate> for PaymentAttemptUpdateInternal {
client_source: None,
client_version: None,
customer_acceptance: None,
+ card_network: None,
},
PaymentAttemptUpdate::CaptureUpdate {
multiple_capture_count,
@@ -1425,6 +1459,7 @@ impl From<PaymentAttemptUpdate> for PaymentAttemptUpdateInternal {
client_source: None,
client_version: None,
customer_acceptance: None,
+ card_network: None,
},
PaymentAttemptUpdate::AmountToCaptureUpdate {
status,
@@ -1477,6 +1512,7 @@ impl From<PaymentAttemptUpdate> for PaymentAttemptUpdateInternal {
client_source: None,
client_version: None,
customer_acceptance: None,
+ card_network: None,
},
PaymentAttemptUpdate::ConnectorResponse {
authentication_data,
@@ -1532,6 +1568,7 @@ impl From<PaymentAttemptUpdate> for PaymentAttemptUpdateInternal {
client_source: None,
client_version: None,
customer_acceptance: None,
+ card_network: None,
},
PaymentAttemptUpdate::IncrementalAuthorizationAmountUpdate {
amount,
@@ -1583,6 +1620,7 @@ impl From<PaymentAttemptUpdate> for PaymentAttemptUpdateInternal {
client_source: None,
client_version: None,
customer_acceptance: None,
+ card_network: None,
},
PaymentAttemptUpdate::AuthenticationUpdate {
status,
@@ -1637,6 +1675,7 @@ impl From<PaymentAttemptUpdate> for PaymentAttemptUpdateInternal {
client_source: None,
client_version: None,
customer_acceptance: None,
+ card_network: None,
},
PaymentAttemptUpdate::ManualUpdate {
status,
@@ -1694,6 +1733,7 @@ impl From<PaymentAttemptUpdate> for PaymentAttemptUpdateInternal {
client_source: None,
client_version: None,
customer_acceptance: None,
+ card_network: None,
},
}
}
diff --git a/crates/diesel_models/src/payment_intent.rs b/crates/diesel_models/src/payment_intent.rs
index 7bd1652ab56..c96629ea448 100644
--- a/crates/diesel_models/src/payment_intent.rs
+++ b/crates/diesel_models/src/payment_intent.rs
@@ -69,6 +69,7 @@ pub struct PaymentIntent {
pub merchant_order_reference_id: Option<String>,
pub shipping_details: Option<Encryption>,
pub is_payment_processor_token_flow: Option<bool>,
+ pub organization_id: common_utils::id_type::OrganizationId,
}
#[cfg(all(any(feature = "v1", feature = "v2"), not(feature = "payment_v2")))]
@@ -130,6 +131,7 @@ pub struct PaymentIntent {
pub merchant_order_reference_id: Option<String>,
pub shipping_details: Option<Encryption>,
pub is_payment_processor_token_flow: Option<bool>,
+ pub organization_id: common_utils::id_type::OrganizationId,
}
#[derive(
@@ -190,6 +192,7 @@ pub struct PaymentIntentNew {
pub merchant_order_reference_id: Option<String>,
pub shipping_details: Option<Encryption>,
pub is_payment_processor_token_flow: Option<bool>,
+ pub organization_id: common_utils::id_type::OrganizationId,
}
#[derive(Debug, Clone, Serialize, Deserialize)]
diff --git a/crates/diesel_models/src/refund.rs b/crates/diesel_models/src/refund.rs
index 10c1fbb9b29..a0828b31756 100644
--- a/crates/diesel_models/src/refund.rs
+++ b/crates/diesel_models/src/refund.rs
@@ -50,6 +50,7 @@ pub struct Refund {
pub updated_by: String,
pub merchant_connector_id: Option<common_utils::id_type::MerchantConnectorAccountId>,
pub charges: Option<ChargeRefunds>,
+ pub organization_id: common_utils::id_type::OrganizationId,
}
#[derive(
@@ -92,38 +93,7 @@ pub struct RefundNew {
pub updated_by: String,
pub merchant_connector_id: Option<common_utils::id_type::MerchantConnectorAccountId>,
pub charges: Option<ChargeRefunds>,
-}
-
-impl Default for RefundNew {
- fn default() -> Self {
- Self {
- refund_id: Default::default(),
- payment_id: Default::default(),
- merchant_id: Default::default(),
- internal_reference_id: Default::default(),
- external_reference_id: Default::default(),
- connector_transaction_id: Default::default(),
- connector: Default::default(),
- connector_refund_id: Default::default(),
- refund_type: Default::default(),
- total_amount: Default::default(),
- currency: Default::default(),
- refund_amount: Default::default(),
- refund_status: Default::default(),
- sent_to_gateway: Default::default(),
- metadata: Default::default(),
- refund_arn: Default::default(),
- created_at: common_utils::date_time::now(),
- modified_at: common_utils::date_time::now(),
- description: Default::default(),
- attempt_id: Default::default(),
- refund_reason: Default::default(),
- profile_id: Default::default(),
- updated_by: Default::default(),
- merchant_connector_id: Default::default(),
- charges: Default::default(),
- }
- }
+ pub organization_id: common_utils::id_type::OrganizationId,
}
#[derive(Debug, Clone, serde::Serialize, serde::Deserialize)]
diff --git a/crates/diesel_models/src/schema.rs b/crates/diesel_models/src/schema.rs
index 7e6c1b84889..3e4799e42ab 100644
--- a/crates/diesel_models/src/schema.rs
+++ b/crates/diesel_models/src/schema.rs
@@ -375,6 +375,8 @@ diesel::table! {
#[max_length = 32]
merchant_connector_id -> Nullable<Varchar>,
dispute_amount -> Int8,
+ #[max_length = 32]
+ organization_id -> Varchar,
}
}
@@ -831,6 +833,12 @@ diesel::table! {
#[max_length = 64]
client_version -> Nullable<Varchar>,
customer_acceptance -> Nullable<Jsonb>,
+ #[max_length = 64]
+ profile_id -> Varchar,
+ #[max_length = 32]
+ organization_id -> Varchar,
+ #[max_length = 32]
+ card_network -> Nullable<Varchar>,
}
}
@@ -906,6 +914,8 @@ diesel::table! {
merchant_order_reference_id -> Nullable<Varchar>,
shipping_details -> Nullable<Bytea>,
is_payment_processor_token_flow -> Nullable<Bool>,
+ #[max_length = 32]
+ organization_id -> Varchar,
}
}
@@ -1150,6 +1160,8 @@ diesel::table! {
#[max_length = 32]
merchant_connector_id -> Nullable<Varchar>,
charges -> Nullable<Jsonb>,
+ #[max_length = 32]
+ organization_id -> Varchar,
}
}
diff --git a/crates/diesel_models/src/schema_v2.rs b/crates/diesel_models/src/schema_v2.rs
index 818415a277b..013157d5e17 100644
--- a/crates/diesel_models/src/schema_v2.rs
+++ b/crates/diesel_models/src/schema_v2.rs
@@ -385,6 +385,8 @@ diesel::table! {
#[max_length = 32]
merchant_connector_id -> Nullable<Varchar>,
dispute_amount -> Int8,
+ #[max_length = 32]
+ organization_id -> Varchar,
}
}
@@ -810,6 +812,12 @@ diesel::table! {
#[max_length = 64]
client_version -> Nullable<Varchar>,
customer_acceptance -> Nullable<Jsonb>,
+ #[max_length = 64]
+ profile_id -> Varchar,
+ #[max_length = 32]
+ organization_id -> Varchar,
+ #[max_length = 32]
+ card_network -> Nullable<Varchar>,
}
}
@@ -885,6 +893,8 @@ diesel::table! {
merchant_order_reference_id -> Nullable<Varchar>,
shipping_details -> Nullable<Bytea>,
is_payment_processor_token_flow -> Nullable<Bool>,
+ #[max_length = 32]
+ organization_id -> Varchar,
}
}
@@ -1131,6 +1141,8 @@ diesel::table! {
#[max_length = 32]
merchant_connector_id -> Nullable<Varchar>,
charges -> Nullable<Jsonb>,
+ #[max_length = 32]
+ organization_id -> Varchar,
}
}
diff --git a/crates/diesel_models/src/user/sample_data.rs b/crates/diesel_models/src/user/sample_data.rs
index dbdae51c45a..89f8af3d94e 100644
--- a/crates/diesel_models/src/user/sample_data.rs
+++ b/crates/diesel_models/src/user/sample_data.rs
@@ -80,6 +80,8 @@ pub struct PaymentAttemptBatchNew {
pub client_source: Option<String>,
pub client_version: Option<String>,
pub customer_acceptance: Option<common_utils::pii::SecretSerdeValue>,
+ pub profile_id: common_utils::id_type::ProfileId,
+ pub organization_id: common_utils::id_type::OrganizationId,
}
#[allow(dead_code)]
@@ -117,6 +119,15 @@ impl PaymentAttemptBatchNew {
connector_metadata: self.connector_metadata,
payment_experience: self.payment_experience,
payment_method_type: self.payment_method_type,
+ card_network: self
+ .payment_method_data
+ .as_ref()
+ .and_then(|data| data.as_object())
+ .and_then(|card| card.get("card"))
+ .and_then(|v| v.as_object())
+ .and_then(|v| v.get("card_network"))
+ .and_then(|network| network.as_str())
+ .map(|network| network.to_string()),
payment_method_data: self.payment_method_data,
business_sub_label: self.business_sub_label,
straight_through_algorithm: self.straight_through_algorithm,
@@ -144,6 +155,8 @@ impl PaymentAttemptBatchNew {
client_source: self.client_source,
client_version: self.client_version,
customer_acceptance: self.customer_acceptance,
+ profile_id: self.profile_id,
+ organization_id: self.organization_id,
}
}
}
diff --git a/crates/hyperswitch_domain_models/src/payments.rs b/crates/hyperswitch_domain_models/src/payments.rs
index 11a2c3c3164..3873dfcd291 100644
--- a/crates/hyperswitch_domain_models/src/payments.rs
+++ b/crates/hyperswitch_domain_models/src/payments.rs
@@ -67,4 +67,5 @@ pub struct PaymentIntent {
pub merchant_order_reference_id: Option<String>,
pub shipping_details: Option<Encryptable<Secret<serde_json::Value>>>,
pub is_payment_processor_token_flow: Option<bool>,
+ pub organization_id: id_type::OrganizationId,
}
diff --git a/crates/hyperswitch_domain_models/src/payments/payment_attempt.rs b/crates/hyperswitch_domain_models/src/payments/payment_attempt.rs
index 12880172d3d..370b37d5a13 100644
--- a/crates/hyperswitch_domain_models/src/payments/payment_attempt.rs
+++ b/crates/hyperswitch_domain_models/src/payments/payment_attempt.rs
@@ -181,6 +181,8 @@ pub struct PaymentAttempt {
pub client_source: Option<String>,
pub client_version: Option<String>,
pub customer_acceptance: Option<pii::SecretSerdeValue>,
+ pub profile_id: id_type::ProfileId,
+ pub organization_id: id_type::OrganizationId,
}
impl PaymentAttempt {
@@ -206,7 +208,7 @@ pub struct PaymentListFilters {
pub authentication_type: Vec<storage_enums::AuthenticationType>,
}
-#[derive(Clone, Debug, Default, Serialize, Deserialize)]
+#[derive(Clone, Debug, Serialize, Deserialize)]
pub struct PaymentAttemptNew {
pub payment_id: String,
pub merchant_id: id_type::MerchantId,
@@ -271,6 +273,8 @@ pub struct PaymentAttemptNew {
pub client_source: Option<String>,
pub client_version: Option<String>,
pub customer_acceptance: Option<pii::SecretSerdeValue>,
+ pub profile_id: id_type::ProfileId,
+ pub organization_id: id_type::OrganizationId,
}
impl PaymentAttemptNew {
@@ -543,6 +547,7 @@ impl behaviour::Conversion for PaymentIntent {
merchant_order_reference_id: self.merchant_order_reference_id,
shipping_details: self.shipping_details.map(Encryption::from),
is_payment_processor_token_flow: self.is_payment_processor_token_flow,
+ organization_id: self.organization_id,
})
}
async fn convert_back(
@@ -625,6 +630,7 @@ impl behaviour::Conversion for PaymentIntent {
.async_lift(inner_decrypt)
.await?,
is_payment_processor_token_flow: storage_model.is_payment_processor_token_flow,
+ organization_id: storage_model.organization_id,
})
}
.await
@@ -683,6 +689,7 @@ impl behaviour::Conversion for PaymentIntent {
merchant_order_reference_id: self.merchant_order_reference_id,
shipping_details: self.shipping_details.map(Encryption::from),
is_payment_processor_token_flow: self.is_payment_processor_token_flow,
+ organization_id: self.organization_id,
})
}
}
@@ -743,6 +750,7 @@ impl behaviour::Conversion for PaymentIntent {
merchant_order_reference_id: self.merchant_order_reference_id,
shipping_details: self.shipping_details.map(Encryption::from),
is_payment_processor_token_flow: self.is_payment_processor_token_flow,
+ organization_id: self.organization_id,
})
}
@@ -826,6 +834,7 @@ impl behaviour::Conversion for PaymentIntent {
.async_lift(inner_decrypt)
.await?,
is_payment_processor_token_flow: storage_model.is_payment_processor_token_flow,
+ organization_id: storage_model.organization_id,
})
}
.await
@@ -884,6 +893,7 @@ impl behaviour::Conversion for PaymentIntent {
merchant_order_reference_id: self.merchant_order_reference_id,
shipping_details: self.shipping_details.map(Encryption::from),
is_payment_processor_token_flow: self.is_payment_processor_token_flow,
+ organization_id: self.organization_id,
})
}
}
diff --git a/crates/hyperswitch_domain_models/src/payments/payment_intent.rs b/crates/hyperswitch_domain_models/src/payments/payment_intent.rs
index dcb06733cc8..f857e241e11 100644
--- a/crates/hyperswitch_domain_models/src/payments/payment_intent.rs
+++ b/crates/hyperswitch_domain_models/src/payments/payment_intent.rs
@@ -151,6 +151,7 @@ pub struct PaymentIntentNew {
pub billing_details: Option<Encryptable<Secret<serde_json::Value>>>,
pub shipping_details: Option<Encryptable<Secret<serde_json::Value>>>,
pub is_payment_processor_token_flow: Option<bool>,
+ pub organization_id: id_type::OrganizationId,
}
#[derive(Debug, Clone, Serialize)]
diff --git a/crates/router/src/core/payments/helpers.rs b/crates/router/src/core/payments/helpers.rs
index 181e2232d90..ae84d4b0ade 100644
--- a/crates/router/src/core/payments/helpers.rs
+++ b/crates/router/src/core/payments/helpers.rs
@@ -2960,7 +2960,7 @@ mod tests {
feature_metadata: None,
attempt_count: 1,
payment_link_id: None,
- profile_id: None,
+ profile_id: Some(common_utils::generate_profile_id_of_default_length()),
merchant_decision: None,
payment_confirm_source: None,
surcharge_applicable: None,
@@ -2982,6 +2982,7 @@ mod tests {
merchant_order_reference_id: None,
shipping_details: None,
is_payment_processor_token_flow: None,
+ organization_id: id_type::OrganizationId::default(),
};
let req_cs = Some("1".to_string());
assert!(authenticate_client_secret(req_cs.as_ref(), &payment_intent).is_ok());
@@ -3026,7 +3027,7 @@ mod tests {
feature_metadata: None,
attempt_count: 1,
payment_link_id: None,
- profile_id: None,
+ profile_id: Some(common_utils::generate_profile_id_of_default_length()),
merchant_decision: None,
payment_confirm_source: None,
surcharge_applicable: None,
@@ -3047,6 +3048,7 @@ mod tests {
merchant_order_reference_id: None,
shipping_details: None,
is_payment_processor_token_flow: None,
+ organization_id: id_type::OrganizationId::default(),
};
let req_cs = Some("1".to_string());
assert!(authenticate_client_secret(req_cs.as_ref(), &payment_intent,).is_err())
@@ -3088,7 +3090,7 @@ mod tests {
feature_metadata: None,
attempt_count: 1,
payment_link_id: None,
- profile_id: None,
+ profile_id: Some(common_utils::generate_profile_id_of_default_length()),
merchant_decision: None,
payment_confirm_source: None,
surcharge_applicable: None,
@@ -3110,6 +3112,7 @@ mod tests {
merchant_order_reference_id: None,
shipping_details: None,
is_payment_processor_token_flow: None,
+ organization_id: id_type::OrganizationId::default(),
};
let req_cs = Some("1".to_string());
assert!(authenticate_client_secret(req_cs.as_ref(), &payment_intent).is_err())
@@ -3645,6 +3648,8 @@ impl AttemptType {
client_source: old_payment_attempt.client_source,
client_version: old_payment_attempt.client_version,
customer_acceptance: old_payment_attempt.customer_acceptance,
+ organization_id: old_payment_attempt.organization_id,
+ profile_id: old_payment_attempt.profile_id,
}
}
diff --git a/crates/router/src/core/payments/operations/payment_create.rs b/crates/router/src/core/payments/operations/payment_create.rs
index 0ba859f3e17..8ab3a957b06 100644
--- a/crates/router/src/core/payments/operations/payment_create.rs
+++ b/crates/router/src/core/payments/operations/payment_create.rs
@@ -308,6 +308,7 @@ impl<F: Send + Clone> GetTracker<F, PaymentData<F>, api::PaymentsRequest> for Pa
let (payment_attempt_new, additional_payment_data) = Self::make_payment_attempt(
&payment_id,
merchant_id,
+ &merchant_account.organization_id,
money,
payment_method,
payment_method_type,
@@ -874,6 +875,7 @@ impl PaymentCreate {
pub async fn make_payment_attempt(
payment_id: &str,
merchant_id: &common_utils::id_type::MerchantId,
+ organization_id: &common_utils::id_type::OrganizationId,
money: (api::Amount, enums::Currency),
payment_method: Option<enums::PaymentMethod>,
payment_method_type: Option<enums::PaymentMethodType>,
@@ -1065,6 +1067,8 @@ impl PaymentCreate {
.change_context(errors::ApiErrorResponse::InternalServerError)
.attach_printable("Failed to serialize customer_acceptance")?
.map(Secret::new),
+ organization_id: organization_id.clone(),
+ profile_id,
},
additional_pm_data,
))
@@ -1246,6 +1250,7 @@ impl PaymentCreate {
merchant_order_reference_id: request.merchant_order_reference_id.clone(),
shipping_details,
is_payment_processor_token_flow,
+ organization_id: merchant_account.organization_id.clone(),
})
}
diff --git a/crates/router/src/core/payments/retry.rs b/crates/router/src/core/payments/retry.rs
index e67f30a2f79..d655fc42a10 100644
--- a/crates/router/src/core/payments/retry.rs
+++ b/crates/router/src/core/payments/retry.rs
@@ -506,7 +506,6 @@ pub fn make_new_payment_attempt(
amount: old_payment_attempt.amount,
currency: old_payment_attempt.currency,
save_to_locker: old_payment_attempt.save_to_locker,
-
offer_amount: old_payment_attempt.offer_amount,
surcharge_amount: old_payment_attempt.surcharge_amount,
tax_amount: old_payment_attempt.tax_amount,
@@ -521,7 +520,6 @@ pub fn make_new_payment_attempt(
} else {
old_payment_attempt.authentication_type
},
-
amount_to_capture: old_payment_attempt.amount_to_capture,
mandate_id: old_payment_attempt.mandate_id,
browser_info: old_payment_attempt.browser_info,
@@ -531,7 +529,37 @@ pub fn make_new_payment_attempt(
created_at,
modified_at,
last_synced,
- ..storage::PaymentAttemptNew::default()
+ net_amount: Default::default(),
+ error_message: Default::default(),
+ cancellation_reason: Default::default(),
+ error_code: Default::default(),
+ connector_metadata: Default::default(),
+ payment_experience: Default::default(),
+ payment_method_data: Default::default(),
+ business_sub_label: Default::default(),
+ straight_through_algorithm: Default::default(),
+ preprocessing_step_id: Default::default(),
+ mandate_details: Default::default(),
+ error_reason: Default::default(),
+ connector_response_reference_id: Default::default(),
+ multiple_capture_count: Default::default(),
+ amount_capturable: Default::default(),
+ updated_by: Default::default(),
+ authentication_data: Default::default(),
+ encoded_data: Default::default(),
+ merchant_connector_id: Default::default(),
+ unified_code: Default::default(),
+ unified_message: Default::default(),
+ external_three_ds_authentication_attempted: Default::default(),
+ authentication_connector: Default::default(),
+ authentication_id: Default::default(),
+ mandate_data: Default::default(),
+ payment_method_billing_address_id: Default::default(),
+ fingerprint_id: Default::default(),
+ charge_id: Default::default(),
+ customer_acceptance: Default::default(),
+ profile_id: old_payment_attempt.profile_id,
+ organization_id: old_payment_attempt.organization_id,
}
}
diff --git a/crates/router/src/core/refunds.rs b/crates/router/src/core/refunds.rs
index 89450347404..867a2ccff54 100644
--- a/crates/router/src/core/refunds.rs
+++ b/crates/router/src/core/refunds.rs
@@ -798,30 +798,34 @@ pub async fn validate_and_create_refund(
.clone()
.ok_or(errors::ApiErrorResponse::InternalServerError)
.attach_printable("No connector populated in payment attempt")?;
-
- let refund_create_req = storage::RefundNew::default()
- .set_refund_id(refund_id.to_string())
- .set_internal_reference_id(utils::generate_id(consts::ID_LENGTH, "refid"))
- .set_external_reference_id(Some(refund_id.clone()))
- .set_payment_id(req.payment_id)
- .set_merchant_id(merchant_account.get_id().clone())
- .set_connector_transaction_id(connecter_transaction_id.to_string())
- .set_connector(connector)
- .set_refund_type(req.refund_type.unwrap_or_default().foreign_into())
- .set_total_amount(payment_attempt.amount)
- .set_refund_amount(refund_amount)
- .set_currency(currency)
- .set_created_at(common_utils::date_time::now())
- .set_modified_at(common_utils::date_time::now())
- .set_refund_status(enums::RefundStatus::Pending)
- .set_metadata(req.metadata)
- .set_description(req.reason.clone())
- .set_attempt_id(payment_attempt.attempt_id.clone())
- .set_refund_reason(req.reason)
- .set_profile_id(payment_intent.profile_id.clone())
- .set_merchant_connector_id(payment_attempt.merchant_connector_id.clone())
- .set_charges(req.charges)
- .to_owned();
+ let refund_create_req = storage::RefundNew {
+ refund_id: refund_id.to_string(),
+ internal_reference_id: utils::generate_id(consts::ID_LENGTH, "refid"),
+ external_reference_id: Some(refund_id.clone()),
+ payment_id: req.payment_id,
+ merchant_id: merchant_account.get_id().clone(),
+ connector_transaction_id: connecter_transaction_id.to_string(),
+ connector,
+ refund_type: req.refund_type.unwrap_or_default().foreign_into(),
+ total_amount: payment_attempt.amount,
+ refund_amount,
+ currency,
+ created_at: common_utils::date_time::now(),
+ modified_at: common_utils::date_time::now(),
+ refund_status: enums::RefundStatus::Pending,
+ metadata: req.metadata,
+ description: req.reason.clone(),
+ attempt_id: payment_attempt.attempt_id.clone(),
+ refund_reason: req.reason,
+ profile_id: payment_intent.profile_id.clone(),
+ merchant_connector_id: payment_attempt.merchant_connector_id.clone(),
+ charges: req.charges,
+ connector_refund_id: None,
+ sent_to_gateway: Default::default(),
+ refund_arn: None,
+ updated_by: Default::default(),
+ organization_id: merchant_account.organization_id.clone(),
+ };
let refund = match db
.insert_refund(refund_create_req, merchant_account.storage_scheme)
diff --git a/crates/router/src/core/user/sample_data.rs b/crates/router/src/core/user/sample_data.rs
index f5faf68435f..ce7143338f4 100644
--- a/crates/router/src/core/user/sample_data.rs
+++ b/crates/router/src/core/user/sample_data.rs
@@ -19,7 +19,13 @@ pub async fn generate_sample_data_for_user(
req: SampleDataRequest,
_req_state: ReqState,
) -> SampleDataApiResponse<()> {
- let sample_data = generate_sample_data(&state, req, &user_from_token.merchant_id).await?;
+ let sample_data = generate_sample_data(
+ &state,
+ req,
+ &user_from_token.merchant_id,
+ &user_from_token.org_id,
+ )
+ .await?;
let key_store = state
.store
diff --git a/crates/router/src/core/webhooks/incoming.rs b/crates/router/src/core/webhooks/incoming.rs
index 0a0a35c23cc..79d6d5d6b82 100644
--- a/crates/router/src/core/webhooks/incoming.rs
+++ b/crates/router/src/core/webhooks/incoming.rs
@@ -902,6 +902,7 @@ async fn get_or_update_dispute_object(
option_dispute: Option<diesel_models::dispute::Dispute>,
dispute_details: api::disputes::DisputePayload,
merchant_id: &common_utils::id_type::MerchantId,
+ organization_id: &common_utils::id_type::OrganizationId,
payment_attempt: &hyperswitch_domain_models::payments::payment_attempt::PaymentAttempt,
event_type: webhooks::IncomingWebhookEvent,
business_profile: &domain::BusinessProfile,
@@ -935,6 +936,7 @@ async fn get_or_update_dispute_object(
evidence: None,
merchant_connector_id: payment_attempt.merchant_connector_id.clone(),
dispute_amount: dispute_details.amount.parse::<i64>().unwrap_or(0),
+ organization_id: organization_id.clone(),
};
state
.store
@@ -1377,6 +1379,7 @@ async fn disputes_incoming_webhook_flow(
option_dispute,
dispute_details,
merchant_account.get_id(),
+ &merchant_account.organization_id,
&payment_attempt,
event_type,
&business_profile,
diff --git a/crates/router/src/db/dispute.rs b/crates/router/src/db/dispute.rs
index 9d6093bfe3c..686de8c2233 100644
--- a/crates/router/src/db/dispute.rs
+++ b/crates/router/src/db/dispute.rs
@@ -170,6 +170,7 @@ impl DisputeInterface for MockDb {
evidence,
merchant_connector_id: dispute.merchant_connector_id,
dispute_amount: dispute.dispute_amount,
+ organization_id: dispute.organization_id,
};
locked_disputes.push(new_dispute.clone());
@@ -404,9 +405,10 @@ mod tests {
connector_updated_at: Some(datetime!(2019-01-03 0:00)),
connector: "connector".into(),
evidence: Some(Secret::from(Value::String("evidence".into()))),
- profile_id: None,
+ profile_id: Some(common_utils::generate_profile_id_of_default_length()),
merchant_connector_id: None,
dispute_amount: 1040,
+ organization_id: common_utils::id_type::OrganizationId::default(),
}
}
diff --git a/crates/router/src/db/refund.rs b/crates/router/src/db/refund.rs
index 1fa7e28cb81..408c6495609 100644
--- a/crates/router/src/db/refund.rs
+++ b/crates/router/src/db/refund.rs
@@ -398,6 +398,7 @@ mod storage {
updated_by: new.updated_by.clone(),
merchant_connector_id: new.merchant_connector_id.clone(),
charges: new.charges.clone(),
+ organization_id: new.organization_id.clone(),
};
let field = format!(
@@ -859,6 +860,7 @@ impl RefundInterface for MockDb {
updated_by: new.updated_by,
merchant_connector_id: new.merchant_connector_id,
charges: new.charges,
+ organization_id: new.organization_id,
};
refunds.push(refund.clone());
Ok(refund)
diff --git a/crates/router/src/services/kafka/dispute.rs b/crates/router/src/services/kafka/dispute.rs
index 62a4310a640..9374c42cbe4 100644
--- a/crates/router/src/services/kafka/dispute.rs
+++ b/crates/router/src/services/kafka/dispute.rs
@@ -1,3 +1,4 @@
+use common_utils::id_type;
use diesel_models::enums as storage_enums;
use masking::Secret;
use time::OffsetDateTime;
@@ -13,7 +14,7 @@ pub struct KafkaDispute<'a> {
pub dispute_status: &'a storage_enums::DisputeStatus,
pub payment_id: &'a String,
pub attempt_id: &'a String,
- pub merchant_id: &'a common_utils::id_type::MerchantId,
+ pub merchant_id: &'a id_type::MerchantId,
pub connector_status: &'a String,
pub connector_dispute_id: &'a String,
pub connector_reason: Option<&'a String>,
@@ -30,8 +31,9 @@ pub struct KafkaDispute<'a> {
pub modified_at: OffsetDateTime,
pub connector: &'a String,
pub evidence: &'a Secret<serde_json::Value>,
- pub profile_id: Option<&'a common_utils::id_type::ProfileId>,
- pub merchant_connector_id: Option<&'a common_utils::id_type::MerchantConnectorAccountId>,
+ pub profile_id: Option<&'a id_type::ProfileId>,
+ pub merchant_connector_id: Option<&'a id_type::MerchantConnectorAccountId>,
+ pub organization_id: &'a id_type::OrganizationId,
}
impl<'a> KafkaDispute<'a> {
@@ -58,6 +60,7 @@ impl<'a> KafkaDispute<'a> {
evidence: &dispute.evidence,
profile_id: dispute.profile_id.as_ref(),
merchant_connector_id: dispute.merchant_connector_id.as_ref(),
+ organization_id: &dispute.organization_id,
}
}
}
diff --git a/crates/router/src/services/kafka/dispute_event.rs b/crates/router/src/services/kafka/dispute_event.rs
index 9b73cc2e510..ac72af0cd95 100644
--- a/crates/router/src/services/kafka/dispute_event.rs
+++ b/crates/router/src/services/kafka/dispute_event.rs
@@ -33,6 +33,7 @@ pub struct KafkaDisputeEvent<'a> {
pub evidence: &'a Secret<serde_json::Value>,
pub profile_id: Option<&'a common_utils::id_type::ProfileId>,
pub merchant_connector_id: Option<&'a common_utils::id_type::MerchantConnectorAccountId>,
+ pub organization_id: &'a common_utils::id_type::OrganizationId,
}
impl<'a> KafkaDisputeEvent<'a> {
@@ -59,6 +60,7 @@ impl<'a> KafkaDisputeEvent<'a> {
evidence: &dispute.evidence,
profile_id: dispute.profile_id.as_ref(),
merchant_connector_id: dispute.merchant_connector_id.as_ref(),
+ organization_id: &dispute.organization_id,
}
}
}
diff --git a/crates/router/src/services/kafka/payment_attempt.rs b/crates/router/src/services/kafka/payment_attempt.rs
index 08ec50f06b7..b92728196d4 100644
--- a/crates/router/src/services/kafka/payment_attempt.rs
+++ b/crates/router/src/services/kafka/payment_attempt.rs
@@ -1,5 +1,5 @@
// use diesel_models::enums::MandateDetails;
-use common_utils::types::MinorUnit;
+use common_utils::{id_type, types::MinorUnit};
use diesel_models::enums as storage_enums;
use hyperswitch_domain_models::{
mandates::MandateDetails, payments::payment_attempt::PaymentAttempt,
@@ -9,7 +9,7 @@ use time::OffsetDateTime;
#[derive(serde::Serialize, Debug)]
pub struct KafkaPaymentAttempt<'a> {
pub payment_id: &'a String,
- pub merchant_id: &'a common_utils::id_type::MerchantId,
+ pub merchant_id: &'a id_type::MerchantId,
pub attempt_id: &'a String,
pub status: storage_enums::AttemptStatus,
pub amount: MinorUnit,
@@ -47,13 +47,16 @@ pub struct KafkaPaymentAttempt<'a> {
pub error_reason: Option<&'a String>,
pub multiple_capture_count: Option<i16>,
pub amount_capturable: MinorUnit,
- pub merchant_connector_id: Option<&'a common_utils::id_type::MerchantConnectorAccountId>,
+ pub merchant_connector_id: Option<&'a id_type::MerchantConnectorAccountId>,
pub net_amount: MinorUnit,
pub unified_code: Option<&'a String>,
pub unified_message: Option<&'a String>,
pub mandate_data: Option<&'a MandateDetails>,
pub client_source: Option<&'a String>,
pub client_version: Option<&'a String>,
+ pub profile_id: &'a id_type::ProfileId,
+ pub organization_id: &'a id_type::OrganizationId,
+ pub card_network: Option<String>,
}
impl<'a> KafkaPaymentAttempt<'a> {
@@ -100,6 +103,17 @@ impl<'a> KafkaPaymentAttempt<'a> {
mandate_data: attempt.mandate_data.as_ref(),
client_source: attempt.client_source.as_ref(),
client_version: attempt.client_version.as_ref(),
+ profile_id: &attempt.profile_id,
+ organization_id: &attempt.organization_id,
+ card_network: attempt
+ .payment_method_data
+ .as_ref()
+ .and_then(|data| data.as_object())
+ .and_then(|pm| pm.get("card"))
+ .and_then(|data| data.as_object())
+ .and_then(|card| card.get("card_network"))
+ .and_then(|network| network.as_str())
+ .map(|network| network.to_string()),
}
}
}
diff --git a/crates/router/src/services/kafka/payment_attempt_event.rs b/crates/router/src/services/kafka/payment_attempt_event.rs
index c6337a3b5f0..e9f8fbdfc5c 100644
--- a/crates/router/src/services/kafka/payment_attempt_event.rs
+++ b/crates/router/src/services/kafka/payment_attempt_event.rs
@@ -1,5 +1,5 @@
// use diesel_models::enums::MandateDetails;
-use common_utils::types::MinorUnit;
+use common_utils::{id_type, types::MinorUnit};
use diesel_models::enums as storage_enums;
use hyperswitch_domain_models::{
mandates::MandateDetails, payments::payment_attempt::PaymentAttempt,
@@ -10,7 +10,7 @@ use time::OffsetDateTime;
#[derive(serde::Serialize, Debug)]
pub struct KafkaPaymentAttemptEvent<'a> {
pub payment_id: &'a String,
- pub merchant_id: &'a common_utils::id_type::MerchantId,
+ pub merchant_id: &'a id_type::MerchantId,
pub attempt_id: &'a String,
pub status: storage_enums::AttemptStatus,
pub amount: MinorUnit,
@@ -48,13 +48,16 @@ pub struct KafkaPaymentAttemptEvent<'a> {
pub error_reason: Option<&'a String>,
pub multiple_capture_count: Option<i16>,
pub amount_capturable: MinorUnit,
- pub merchant_connector_id: Option<&'a common_utils::id_type::MerchantConnectorAccountId>,
+ pub merchant_connector_id: Option<&'a id_type::MerchantConnectorAccountId>,
pub net_amount: MinorUnit,
pub unified_code: Option<&'a String>,
pub unified_message: Option<&'a String>,
pub mandate_data: Option<&'a MandateDetails>,
pub client_source: Option<&'a String>,
pub client_version: Option<&'a String>,
+ pub profile_id: &'a id_type::ProfileId,
+ pub organization_id: &'a id_type::OrganizationId,
+ pub card_network: Option<String>,
}
impl<'a> KafkaPaymentAttemptEvent<'a> {
@@ -101,6 +104,17 @@ impl<'a> KafkaPaymentAttemptEvent<'a> {
mandate_data: attempt.mandate_data.as_ref(),
client_source: attempt.client_source.as_ref(),
client_version: attempt.client_version.as_ref(),
+ profile_id: &attempt.profile_id,
+ organization_id: &attempt.organization_id,
+ card_network: attempt
+ .payment_method_data
+ .as_ref()
+ .and_then(|data| data.as_object())
+ .and_then(|pm| pm.get("card"))
+ .and_then(|data| data.as_object())
+ .and_then(|card| card.get("card_network"))
+ .and_then(|network| network.as_str())
+ .map(|network| network.to_string()),
}
}
}
diff --git a/crates/router/src/services/kafka/payment_intent.rs b/crates/router/src/services/kafka/payment_intent.rs
index 29aa5632837..31f424b2a28 100644
--- a/crates/router/src/services/kafka/payment_intent.rs
+++ b/crates/router/src/services/kafka/payment_intent.rs
@@ -40,6 +40,7 @@ pub struct KafkaPaymentIntent<'a> {
pub customer_email: Option<HashedString<pii::EmailStrategy>>,
pub feature_metadata: Option<&'a Value>,
pub merchant_order_reference_id: Option<&'a String>,
+ pub organization_id: &'a id_type::OrganizationId,
}
impl<'a> KafkaPaymentIntent<'a> {
@@ -82,6 +83,7 @@ impl<'a> KafkaPaymentIntent<'a> {
.map(|email| HashedString::from(Secret::new(email.to_string()))),
feature_metadata: intent.feature_metadata.as_ref(),
merchant_order_reference_id: intent.merchant_order_reference_id.as_ref(),
+ organization_id: &intent.organization_id,
}
}
}
diff --git a/crates/router/src/services/kafka/payment_intent_event.rs b/crates/router/src/services/kafka/payment_intent_event.rs
index 50d2c48a4bd..f92f3fa9326 100644
--- a/crates/router/src/services/kafka/payment_intent_event.rs
+++ b/crates/router/src/services/kafka/payment_intent_event.rs
@@ -41,6 +41,7 @@ pub struct KafkaPaymentIntentEvent<'a> {
pub customer_email: Option<HashedString<pii::EmailStrategy>>,
pub feature_metadata: Option<&'a Value>,
pub merchant_order_reference_id: Option<&'a String>,
+ pub organization_id: &'a id_type::OrganizationId,
}
impl<'a> KafkaPaymentIntentEvent<'a> {
@@ -83,6 +84,7 @@ impl<'a> KafkaPaymentIntentEvent<'a> {
.map(|email| HashedString::from(Secret::new(email.to_string()))),
feature_metadata: intent.feature_metadata.as_ref(),
merchant_order_reference_id: intent.merchant_order_reference_id.as_ref(),
+ organization_id: &intent.organization_id,
}
}
}
diff --git a/crates/router/src/services/kafka/refund.rs b/crates/router/src/services/kafka/refund.rs
index 1aaf5d2ccb3..09537812e57 100644
--- a/crates/router/src/services/kafka/refund.rs
+++ b/crates/router/src/services/kafka/refund.rs
@@ -1,4 +1,4 @@
-use common_utils::types::MinorUnit;
+use common_utils::{id_type, types::MinorUnit};
use diesel_models::{enums as storage_enums, refund::Refund};
use time::OffsetDateTime;
@@ -7,7 +7,7 @@ pub struct KafkaRefund<'a> {
pub internal_reference_id: &'a String,
pub refund_id: &'a String, //merchant_reference id
pub payment_id: &'a String,
- pub merchant_id: &'a common_utils::id_type::MerchantId,
+ pub merchant_id: &'a id_type::MerchantId,
pub connector_transaction_id: &'a String,
pub connector: &'a String,
pub connector_refund_id: Option<&'a String>,
@@ -28,6 +28,8 @@ pub struct KafkaRefund<'a> {
pub attempt_id: &'a String,
pub refund_reason: Option<&'a String>,
pub refund_error_code: Option<&'a String>,
+ pub profile_id: Option<&'a id_type::ProfileId>,
+ pub organization_id: &'a id_type::OrganizationId,
}
impl<'a> KafkaRefund<'a> {
@@ -55,6 +57,8 @@ impl<'a> KafkaRefund<'a> {
attempt_id: &refund.attempt_id,
refund_reason: refund.refund_reason.as_ref(),
refund_error_code: refund.refund_error_code.as_ref(),
+ profile_id: refund.profile_id.as_ref(),
+ organization_id: &refund.organization_id,
}
}
}
diff --git a/crates/router/src/services/kafka/refund_event.rs b/crates/router/src/services/kafka/refund_event.rs
index 9480220104c..764146f808f 100644
--- a/crates/router/src/services/kafka/refund_event.rs
+++ b/crates/router/src/services/kafka/refund_event.rs
@@ -1,4 +1,4 @@
-use common_utils::types::MinorUnit;
+use common_utils::{id_type, types::MinorUnit};
use diesel_models::{enums as storage_enums, refund::Refund};
use time::OffsetDateTime;
@@ -8,7 +8,7 @@ pub struct KafkaRefundEvent<'a> {
pub internal_reference_id: &'a String,
pub refund_id: &'a String, //merchant_reference id
pub payment_id: &'a String,
- pub merchant_id: &'a common_utils::id_type::MerchantId,
+ pub merchant_id: &'a id_type::MerchantId,
pub connector_transaction_id: &'a String,
pub connector: &'a String,
pub connector_refund_id: Option<&'a String>,
@@ -29,6 +29,8 @@ pub struct KafkaRefundEvent<'a> {
pub attempt_id: &'a String,
pub refund_reason: Option<&'a String>,
pub refund_error_code: Option<&'a String>,
+ pub profile_id: Option<&'a id_type::ProfileId>,
+ pub organization_id: &'a id_type::OrganizationId,
}
impl<'a> KafkaRefundEvent<'a> {
@@ -56,6 +58,8 @@ impl<'a> KafkaRefundEvent<'a> {
attempt_id: &refund.attempt_id,
refund_reason: refund.refund_reason.as_ref(),
refund_error_code: refund.refund_error_code.as_ref(),
+ profile_id: refund.profile_id.as_ref(),
+ organization_id: &refund.organization_id,
}
}
}
diff --git a/crates/router/src/types/storage/payment_attempt.rs b/crates/router/src/types/storage/payment_attempt.rs
index 669427d88c7..6775f9a81a7 100644
--- a/crates/router/src/types/storage/payment_attempt.rs
+++ b/crates/router/src/types/storage/payment_attempt.rs
@@ -129,7 +129,60 @@ mod tests {
connector: Some(connector),
created_at: current_time.into(),
modified_at: current_time.into(),
- ..PaymentAttemptNew::default()
+ merchant_id: Default::default(),
+ attempt_id: Default::default(),
+ status: Default::default(),
+ amount: Default::default(),
+ net_amount: Default::default(),
+ currency: Default::default(),
+ save_to_locker: Default::default(),
+ error_message: Default::default(),
+ offer_amount: Default::default(),
+ surcharge_amount: Default::default(),
+ tax_amount: Default::default(),
+ payment_method_id: Default::default(),
+ payment_method: Default::default(),
+ capture_method: Default::default(),
+ capture_on: Default::default(),
+ confirm: Default::default(),
+ authentication_type: Default::default(),
+ last_synced: Default::default(),
+ cancellation_reason: Default::default(),
+ amount_to_capture: Default::default(),
+ mandate_id: Default::default(),
+ browser_info: Default::default(),
+ payment_token: Default::default(),
+ error_code: Default::default(),
+ connector_metadata: Default::default(),
+ payment_experience: Default::default(),
+ payment_method_type: Default::default(),
+ payment_method_data: Default::default(),
+ business_sub_label: Default::default(),
+ straight_through_algorithm: Default::default(),
+ preprocessing_step_id: Default::default(),
+ mandate_details: Default::default(),
+ error_reason: Default::default(),
+ connector_response_reference_id: Default::default(),
+ multiple_capture_count: Default::default(),
+ amount_capturable: Default::default(),
+ updated_by: Default::default(),
+ authentication_data: Default::default(),
+ encoded_data: Default::default(),
+ merchant_connector_id: Default::default(),
+ unified_code: Default::default(),
+ unified_message: Default::default(),
+ external_three_ds_authentication_attempted: Default::default(),
+ authentication_connector: Default::default(),
+ authentication_id: Default::default(),
+ mandate_data: Default::default(),
+ payment_method_billing_address_id: Default::default(),
+ fingerprint_id: Default::default(),
+ charge_id: Default::default(),
+ client_source: Default::default(),
+ client_version: Default::default(),
+ customer_acceptance: Default::default(),
+ profile_id: common_utils::generate_profile_id_of_default_length(),
+ organization_id: Default::default(),
};
let store = state
@@ -163,7 +216,58 @@ mod tests {
created_at: current_time.into(),
modified_at: current_time.into(),
attempt_id: attempt_id.clone(),
- ..PaymentAttemptNew::default()
+ status: Default::default(),
+ amount: Default::default(),
+ net_amount: Default::default(),
+ currency: Default::default(),
+ save_to_locker: Default::default(),
+ error_message: Default::default(),
+ offer_amount: Default::default(),
+ surcharge_amount: Default::default(),
+ tax_amount: Default::default(),
+ payment_method_id: Default::default(),
+ payment_method: Default::default(),
+ capture_method: Default::default(),
+ capture_on: Default::default(),
+ confirm: Default::default(),
+ authentication_type: Default::default(),
+ last_synced: Default::default(),
+ cancellation_reason: Default::default(),
+ amount_to_capture: Default::default(),
+ mandate_id: Default::default(),
+ browser_info: Default::default(),
+ payment_token: Default::default(),
+ error_code: Default::default(),
+ connector_metadata: Default::default(),
+ payment_experience: Default::default(),
+ payment_method_type: Default::default(),
+ payment_method_data: Default::default(),
+ business_sub_label: Default::default(),
+ straight_through_algorithm: Default::default(),
+ preprocessing_step_id: Default::default(),
+ mandate_details: Default::default(),
+ error_reason: Default::default(),
+ connector_response_reference_id: Default::default(),
+ multiple_capture_count: Default::default(),
+ amount_capturable: Default::default(),
+ updated_by: Default::default(),
+ authentication_data: Default::default(),
+ encoded_data: Default::default(),
+ merchant_connector_id: Default::default(),
+ unified_code: Default::default(),
+ unified_message: Default::default(),
+ external_three_ds_authentication_attempted: Default::default(),
+ authentication_connector: Default::default(),
+ authentication_id: Default::default(),
+ mandate_data: Default::default(),
+ payment_method_billing_address_id: Default::default(),
+ fingerprint_id: Default::default(),
+ charge_id: Default::default(),
+ client_source: Default::default(),
+ client_version: Default::default(),
+ customer_acceptance: Default::default(),
+ profile_id: common_utils::generate_profile_id_of_default_length(),
+ organization_id: Default::default(),
};
let store = state
.stores
@@ -207,10 +311,59 @@ mod tests {
connector: Some(connector),
created_at: current_time.into(),
modified_at: current_time.into(),
- // Adding a mandate_id
mandate_id: Some("man_121212".to_string()),
attempt_id: uuid.clone(),
- ..PaymentAttemptNew::default()
+ status: Default::default(),
+ amount: Default::default(),
+ net_amount: Default::default(),
+ currency: Default::default(),
+ save_to_locker: Default::default(),
+ error_message: Default::default(),
+ offer_amount: Default::default(),
+ surcharge_amount: Default::default(),
+ tax_amount: Default::default(),
+ payment_method_id: Default::default(),
+ payment_method: Default::default(),
+ capture_method: Default::default(),
+ capture_on: Default::default(),
+ confirm: Default::default(),
+ authentication_type: Default::default(),
+ last_synced: Default::default(),
+ cancellation_reason: Default::default(),
+ amount_to_capture: Default::default(),
+ browser_info: Default::default(),
+ payment_token: Default::default(),
+ error_code: Default::default(),
+ connector_metadata: Default::default(),
+ payment_experience: Default::default(),
+ payment_method_type: Default::default(),
+ payment_method_data: Default::default(),
+ business_sub_label: Default::default(),
+ straight_through_algorithm: Default::default(),
+ preprocessing_step_id: Default::default(),
+ mandate_details: Default::default(),
+ error_reason: Default::default(),
+ connector_response_reference_id: Default::default(),
+ multiple_capture_count: Default::default(),
+ amount_capturable: Default::default(),
+ updated_by: Default::default(),
+ authentication_data: Default::default(),
+ encoded_data: Default::default(),
+ merchant_connector_id: Default::default(),
+ unified_code: Default::default(),
+ unified_message: Default::default(),
+ external_three_ds_authentication_attempted: Default::default(),
+ authentication_connector: Default::default(),
+ authentication_id: Default::default(),
+ mandate_data: Default::default(),
+ payment_method_billing_address_id: Default::default(),
+ fingerprint_id: Default::default(),
+ charge_id: Default::default(),
+ client_source: Default::default(),
+ client_version: Default::default(),
+ customer_acceptance: Default::default(),
+ profile_id: common_utils::generate_profile_id_of_default_length(),
+ organization_id: Default::default(),
};
let store = state
.stores
diff --git a/crates/router/src/utils/user/sample_data.rs b/crates/router/src/utils/user/sample_data.rs
index ac9272c86d7..94890a41ad7 100644
--- a/crates/router/src/utils/user/sample_data.rs
+++ b/crates/router/src/utils/user/sample_data.rs
@@ -20,6 +20,7 @@ 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>)>> {
let sample_data_size: usize = req.record.unwrap_or(100);
let key_manager_state = &state.into();
@@ -252,6 +253,7 @@ pub async fn generate_sample_data(
merchant_order_reference_id: Default::default(),
shipping_details: None,
is_payment_processor_token_flow: None,
+ organization_id: org_id.clone(),
};
let payment_attempt = PaymentAttemptBatchNew {
attempt_id: attempt_id.clone(),
@@ -329,6 +331,8 @@ pub async fn generate_sample_data(
client_source: None,
client_version: None,
customer_acceptance: None,
+ profile_id: profile_id.clone(),
+ organization_id: org_id.clone(),
};
let refund = if refunds_count < number_of_refunds && !is_failed_payment {
@@ -364,6 +368,7 @@ pub async fn generate_sample_data(
updated_by: merchant_from_db.storage_scheme.to_string(),
merchant_connector_id: payment_attempt.merchant_connector_id.clone(),
charges: None,
+ organization_id: org_id.clone(),
})
} else {
None
diff --git a/crates/storage_impl/src/mock_db/payment_attempt.rs b/crates/storage_impl/src/mock_db/payment_attempt.rs
index 37e01cbbb5c..67840636de8 100644
--- a/crates/storage_impl/src/mock_db/payment_attempt.rs
+++ b/crates/storage_impl/src/mock_db/payment_attempt.rs
@@ -158,6 +158,8 @@ impl PaymentAttemptInterface for MockDb {
client_source: payment_attempt.client_source,
client_version: payment_attempt.client_version,
customer_acceptance: payment_attempt.customer_acceptance,
+ organization_id: payment_attempt.organization_id,
+ profile_id: payment_attempt.profile_id,
};
payment_attempts.push(payment_attempt.clone());
Ok(payment_attempt)
diff --git a/crates/storage_impl/src/payments/payment_attempt.rs b/crates/storage_impl/src/payments/payment_attempt.rs
index 382abacfa78..63b10cf01bd 100644
--- a/crates/storage_impl/src/payments/payment_attempt.rs
+++ b/crates/storage_impl/src/payments/payment_attempt.rs
@@ -419,6 +419,8 @@ impl<T: DatabaseStore> PaymentAttemptInterface for KVRouterStore<T> {
client_source: payment_attempt.client_source.clone(),
client_version: payment_attempt.client_version.clone(),
customer_acceptance: payment_attempt.customer_acceptance.clone(),
+ organization_id: payment_attempt.organization_id.clone(),
+ profile_id: payment_attempt.profile_id.clone(),
};
let field = format!("pa_{}", created_attempt.attempt_id);
@@ -1189,6 +1191,15 @@ impl DataModelExt for PaymentAttempt {
connector_metadata: self.connector_metadata,
payment_experience: self.payment_experience,
payment_method_type: self.payment_method_type,
+ card_network: self
+ .payment_method_data
+ .as_ref()
+ .and_then(|data| data.as_object())
+ .and_then(|card| card.get("card"))
+ .and_then(|data| data.as_object())
+ .and_then(|card| card.get("card_network"))
+ .and_then(|network| network.as_str())
+ .map(|network| network.to_string()),
payment_method_data: self.payment_method_data,
business_sub_label: self.business_sub_label,
straight_through_algorithm: self.straight_through_algorithm,
@@ -1215,6 +1226,8 @@ impl DataModelExt for PaymentAttempt {
client_source: self.client_source,
client_version: self.client_version,
customer_acceptance: self.customer_acceptance,
+ organization_id: self.organization_id,
+ profile_id: self.profile_id,
}
}
@@ -1282,6 +1295,8 @@ impl DataModelExt for PaymentAttempt {
client_source: storage_model.client_source,
client_version: storage_model.client_version,
customer_acceptance: storage_model.customer_acceptance,
+ organization_id: storage_model.organization_id,
+ profile_id: storage_model.profile_id,
}
}
}
@@ -1330,6 +1345,15 @@ impl DataModelExt for PaymentAttempt {
connector_metadata: self.connector_metadata,
payment_experience: self.payment_experience,
payment_method_type: self.payment_method_type,
+ card_network: self
+ .payment_method_data
+ .as_ref()
+ .and_then(|data| data.as_object())
+ .and_then(|card| card.get("card"))
+ .and_then(|data| data.as_object())
+ .and_then(|card| card.get("card_network"))
+ .and_then(|network| network.as_str())
+ .map(|network| network.to_string()),
payment_method_data: self.payment_method_data,
business_sub_label: self.business_sub_label,
straight_through_algorithm: self.straight_through_algorithm,
@@ -1356,6 +1380,8 @@ impl DataModelExt for PaymentAttempt {
client_source: self.client_source,
client_version: self.client_version,
customer_acceptance: self.customer_acceptance,
+ organization_id: self.organization_id,
+ profile_id: self.profile_id,
}
}
@@ -1423,6 +1449,8 @@ impl DataModelExt for PaymentAttempt {
client_source: storage_model.client_source,
client_version: storage_model.client_version,
customer_acceptance: storage_model.customer_acceptance,
+ organization_id: storage_model.organization_id,
+ profile_id: storage_model.profile_id,
}
}
}
@@ -1471,6 +1499,15 @@ impl DataModelExt for PaymentAttemptNew {
connector_metadata: self.connector_metadata,
payment_experience: self.payment_experience,
payment_method_type: self.payment_method_type,
+ card_network: self
+ .payment_method_data
+ .as_ref()
+ .and_then(|data| data.as_object())
+ .and_then(|card| card.get("card"))
+ .and_then(|value| value.as_object())
+ .and_then(|map| map.get("card_network"))
+ .and_then(|network| network.as_str())
+ .map(|network| network.to_string()),
payment_method_data: self.payment_method_data,
business_sub_label: self.business_sub_label,
straight_through_algorithm: self.straight_through_algorithm,
@@ -1497,6 +1534,8 @@ impl DataModelExt for PaymentAttemptNew {
client_source: self.client_source,
client_version: self.client_version,
customer_acceptance: self.customer_acceptance,
+ organization_id: self.organization_id,
+ profile_id: self.profile_id,
}
}
@@ -1563,6 +1602,8 @@ impl DataModelExt for PaymentAttemptNew {
client_source: storage_model.client_source,
client_version: storage_model.client_version,
customer_acceptance: storage_model.customer_acceptance,
+ organization_id: storage_model.organization_id,
+ profile_id: storage_model.profile_id,
}
}
}
diff --git a/migrations/2024-08-20-112035_add-profile-id-to-txn-tables/down.sql b/migrations/2024-08-20-112035_add-profile-id-to-txn-tables/down.sql
new file mode 100644
index 00000000000..66707bebb4e
--- /dev/null
+++ b/migrations/2024-08-20-112035_add-profile-id-to-txn-tables/down.sql
@@ -0,0 +1,20 @@
+-- This file should undo anything in `up.sql`
+-- Remove profile_id from payment_attempt table
+ALTER TABLE payment_attempt
+DROP COLUMN IF EXISTS profile_id;
+
+-- Remove organization_id from payment_attempt table
+ALTER TABLE payment_attempt
+DROP COLUMN IF EXISTS organization_id;
+
+-- Remove organization_id from payment_intent table
+ALTER TABLE payment_intent
+DROP COLUMN IF EXISTS organization_id;
+
+-- Remove organization_id from refund table
+ALTER TABLE refund
+DROP COLUMN IF EXISTS organization_id;
+
+-- Remove organization_id from dispute table
+ALTER TABLE dispute
+DROP COLUMN IF EXISTS organization_id;
\ No newline at end of file
diff --git a/migrations/2024-08-20-112035_add-profile-id-to-txn-tables/up.sql b/migrations/2024-08-20-112035_add-profile-id-to-txn-tables/up.sql
new file mode 100644
index 00000000000..74f55308fc6
--- /dev/null
+++ b/migrations/2024-08-20-112035_add-profile-id-to-txn-tables/up.sql
@@ -0,0 +1,43 @@
+-- Your SQL goes here
+ALTER TABLE payment_attempt
+ADD COLUMN IF NOT EXISTS profile_id VARCHAR(64) NOT NULL DEFAULT 'default_profile';
+
+-- Add organization_id to payment_attempt table
+ALTER TABLE payment_attempt
+ADD COLUMN IF NOT EXISTS organization_id VARCHAR(32) NOT NULL DEFAULT 'default_org';
+
+-- Add organization_id to payment_intent table
+ALTER TABLE payment_intent
+ADD COLUMN IF NOT EXISTS organization_id VARCHAR(32) NOT NULL DEFAULT 'default_org';
+
+-- Add organization_id to refund table
+ALTER TABLE refund
+ADD COLUMN IF NOT EXISTS organization_id VARCHAR(32) NOT NULL DEFAULT 'default_org';
+
+-- Add organization_id to dispute table
+ALTER TABLE dispute
+ADD COLUMN IF NOT EXISTS organization_id VARCHAR(32) NOT NULL DEFAULT 'default_org';
+
+-- This doesn't work on V2
+-- The below backfill step has to be run after the code deployment
+-- UPDATE payment_attempt pa
+-- SET organization_id = ma.organization_id
+-- FROM merchant_account ma
+-- WHERE pa.merchant_id = ma.merchant_id;
+
+-- UPDATE payment_intent pi
+-- SET organization_id = ma.organization_id
+-- FROM merchant_account ma
+-- WHERE pi.merchant_id = ma.merchant_id;
+
+-- UPDATE refund r
+-- SET organization_id = ma.organization_id
+-- FROM merchant_account ma
+-- WHERE r.merchant_id = ma.merchant_id;
+
+-- UPDATE payment_attempt pa
+-- SET profile_id = pi.profile_id
+-- FROM payment_intent pi
+-- WHERE pa.payment_id = pi.payment_id
+-- AND pa.merchant_id = pi.merchant_id
+-- AND pi.profile_id IS NOT NULL;
diff --git a/migrations/2024-08-26-043046_add-card-network-field-for-pa/down.sql b/migrations/2024-08-26-043046_add-card-network-field-for-pa/down.sql
new file mode 100644
index 00000000000..8dc04221730
--- /dev/null
+++ b/migrations/2024-08-26-043046_add-card-network-field-for-pa/down.sql
@@ -0,0 +1,3 @@
+-- This file should undo anything in `up.sql`
+
+ALTER TABLE payment_attempt DROP COLUMN card_network;
\ No newline at end of file
diff --git a/migrations/2024-08-26-043046_add-card-network-field-for-pa/up.sql b/migrations/2024-08-26-043046_add-card-network-field-for-pa/up.sql
new file mode 100644
index 00000000000..43f29b56d72
--- /dev/null
+++ b/migrations/2024-08-26-043046_add-card-network-field-for-pa/up.sql
@@ -0,0 +1,5 @@
+-- Your SQL goes here
+
+ALTER TABLE payment_attempt ADD COLUMN card_network VARCHAR(32);
+UPDATE payment_attempt
+SET card_network = (payment_method_data -> 'card' -> 'card_network')::VARCHAR(32);
\ No newline at end of file
|
2024-08-26T07:43:24Z
|
## Type of Change
<!-- Put an `x` in the boxes that apply -->
- [ ] Bugfix
- [x] New feature
- [ ] Enhancement
- [ ] Refactoring
- [ ] Dependency updates
- [ ] Documentation
- [ ] CI/CD
## Description
<!-- Describe your changes in detail -->
Add organisation id for
- payment intents
- payment attempts
- refunds
- disputes
add profile id & card network for payment attempts
Add the above fields in clickhouse & kafka as well
### Additional Changes
- [ ] This PR modifies the API contract
- [ ] This PR modifies the database schema
- [ ] This PR modifies application configuration/environment variables
<!--
Provide links to the files with corresponding changes.
Following are the paths where you can find config files:
1. `config`
2. `crates/router/src/configs`
3. `loadtest/config`
-->
## Motivation and Context
<!--
Why is this change required? What problem does it solve?
If it fixes an open issue, please link to the issue here.
If you don't have an issue, we'd recommend starting with one first so the PR
can focus on the implementation (unless it is an obvious bug or documentation fix
that will have little conversation).
-->
Adding these fields to provide better authentication guards
## How did you test it?
<!--
Did you write an integration/unit/API test to verify the code changes?
Or did you test this change manually (provide relevant screenshots)?
-->
<img width="975" alt="image" src="https://github.com/user-attachments/assets/dcb1ff45-4771-4382-9f97-36039abb9ef2">
Check for the added columns in pgweb/grafana
## Checklist
<!-- Put an `x` in the boxes that apply -->
- [ ] I formatted the code `cargo +nightly fmt --all`
- [ ] I addressed lints thrown by `cargo clippy`
- [ ] I reviewed the submitted code
- [ ] I added unit tests for my changes where possible
|
c555a88c6730a1216aa291bc7f7a38e3df08c469
|
|
juspay/hyperswitch
|
juspay__hyperswitch-5680
|
Bug: REFACTOR: check the authenticity of profile_id being used for all the routing routes
After this refactor goes in, we will have an auth layer verifying the autheticity of profile being sent in the request at max there can be 4 cases:
1. profile_id not present in the request: provide the requested details for the profile present in auth headers
2. profile_id not present in the auth_layer: provide the details requested no change in behaviour
3. same profile_id present in both the places(request as well as the auth_layer): provide the details for the profiles
4. mismatch between the profiles in both the layers: Throw unauthorized error.
|
diff --git a/crates/api_models/src/routing.rs b/crates/api_models/src/routing.rs
index 1416e985523..7b7a59bc866 100644
--- a/crates/api_models/src/routing.rs
+++ b/crates/api_models/src/routing.rs
@@ -57,18 +57,18 @@ pub struct ProfileDefaultRoutingConfig {
pub connectors: Vec<RoutableConnectorChoice>,
}
-#[derive(Debug, serde::Deserialize, serde::Serialize)]
+#[derive(Clone, Debug, serde::Deserialize, serde::Serialize)]
pub struct RoutingRetrieveQuery {
pub limit: Option<u16>,
pub offset: Option<u8>,
}
-#[derive(Debug, serde::Deserialize, serde::Serialize)]
+#[derive(Clone, Debug, serde::Deserialize, serde::Serialize)]
pub struct RoutingRetrieveLinkQuery {
pub profile_id: Option<common_utils::id_type::ProfileId>,
}
-#[derive(Debug, serde::Deserialize, serde::Serialize)]
+#[derive(Clone, Debug, serde::Deserialize, serde::Serialize)]
pub struct RoutingRetrieveLinkQueryWrapper {
pub routing_query: RoutingRetrieveQuery,
pub profile_id: common_utils::id_type::ProfileId,
diff --git a/crates/router/src/core/routing.rs b/crates/router/src/core/routing.rs
index 512f97b8c9e..9efe2cd6ab2 100644
--- a/crates/router/src/core/routing.rs
+++ b/crates/router/src/core/routing.rs
@@ -84,12 +84,13 @@ impl RoutingAlgorithmUpdate {
pub async fn retrieve_merchant_routing_dictionary(
state: SessionState,
merchant_account: domain::MerchantAccount,
+ profile_id_list: Option<Vec<common_utils::id_type::ProfileId>>,
query_params: RoutingRetrieveQuery,
transaction_type: &enums::TransactionType,
) -> RouterResponse<routing_types::RoutingKind> {
metrics::ROUTING_MERCHANT_DICTIONARY_RETRIEVE.add(&metrics::CONTEXT, 1, &[]);
- let routing_metadata = state
+ let routing_metadata: Vec<diesel_models::routing_algorithm::RoutingProfileMetadata> = state
.store
.list_routing_algorithm_metadata_by_merchant_id_transaction_type(
merchant_account.get_id(),
@@ -99,6 +100,9 @@ pub async fn retrieve_merchant_routing_dictionary(
)
.await
.to_not_found_response(errors::ApiErrorResponse::ResourceIdNotFound)?;
+ let routing_metadata =
+ super::utils::filter_objects_based_on_profile_id_list(profile_id_list, routing_metadata);
+
let result = routing_metadata
.into_iter()
.map(ForeignInto::foreign_into)
@@ -115,6 +119,7 @@ pub async fn create_routing_algorithm_under_profile(
state: SessionState,
merchant_account: domain::MerchantAccount,
key_store: domain::MerchantKeyStore,
+ authentication_profile_id: Option<common_utils::id_type::ProfileId>,
request: routing_types::RoutingConfigRequest,
transaction_type: &enums::TransactionType,
) -> RouterResponse<routing_types::RoutingDictionaryRecord> {
@@ -132,6 +137,8 @@ pub async fn create_routing_algorithm_under_profile(
.await?
.get_required_value("BusinessProfile")?;
+ core_utils::validate_profile_id_from_auth_layer(authentication_profile_id, &business_profile)?;
+
let all_mcas = helpers::MerchantConnectorAccounts::get_all_mcas(
merchant_account.get_id(),
&key_store,
@@ -182,6 +189,7 @@ pub async fn create_routing_algorithm_under_profile(
state: SessionState,
merchant_account: domain::MerchantAccount,
key_store: domain::MerchantKeyStore,
+ authentication_profile_id: Option<common_utils::id_type::ProfileId>,
request: routing_types::RoutingConfigRequest,
transaction_type: &enums::TransactionType,
) -> RouterResponse<routing_types::RoutingDictionaryRecord> {
@@ -221,14 +229,17 @@ pub async fn create_routing_algorithm_under_profile(
})
.attach_printable("Profile_id not provided")?;
- core_utils::validate_and_get_business_profile(
+ let business_profile = core_utils::validate_and_get_business_profile(
db,
key_manager_state,
&key_store,
Some(&profile_id),
merchant_account.get_id(),
)
- .await?;
+ .await?
+ .get_required_value("BusinessProfile")?;
+
+ core_utils::validate_profile_id_from_auth_layer(authentication_profile_id, &business_profile)?;
helpers::validate_connectors_in_routing_config(
&state,
@@ -345,6 +356,7 @@ pub async fn link_routing_config(
state: SessionState,
merchant_account: domain::MerchantAccount,
key_store: domain::MerchantKeyStore,
+ authentication_profile_id: Option<common_utils::id_type::ProfileId>,
algorithm_id: common_utils::id_type::RoutingId,
transaction_type: &enums::TransactionType,
) -> RouterResponse<routing_types::RoutingDictionaryRecord> {
@@ -373,6 +385,8 @@ pub async fn link_routing_config(
id: routing_algorithm.profile_id.get_string_repr().to_owned(),
})?;
+ core_utils::validate_profile_id_from_auth_layer(authentication_profile_id, &business_profile)?;
+
let mut routing_ref: routing_types::RoutingAlgorithmRef = business_profile
.routing_algorithm
.clone()
@@ -421,6 +435,7 @@ pub async fn retrieve_routing_algorithm_from_algorithm_id(
state: SessionState,
merchant_account: domain::MerchantAccount,
key_store: domain::MerchantKeyStore,
+ authentication_profile_id: Option<common_utils::id_type::ProfileId>,
algorithm_id: common_utils::id_type::RoutingId,
) -> RouterResponse<routing_types::MerchantRoutingAlgorithm> {
metrics::ROUTING_RETRIEVE_CONFIG.add(&metrics::CONTEXT, 1, &[]);
@@ -430,7 +445,7 @@ pub async fn retrieve_routing_algorithm_from_algorithm_id(
let routing_algorithm =
RoutingAlgorithmUpdate::fetch_routing_algo(merchant_account.get_id(), &algorithm_id, db)
.await?;
- core_utils::validate_and_get_business_profile(
+ let business_profile = core_utils::validate_and_get_business_profile(
db,
key_manager_state,
&key_store,
@@ -441,6 +456,8 @@ pub async fn retrieve_routing_algorithm_from_algorithm_id(
.get_required_value("BusinessProfile")
.change_context(errors::ApiErrorResponse::ResourceIdNotFound)?;
+ core_utils::validate_profile_id_from_auth_layer(authentication_profile_id, &business_profile)?;
+
let response = routing_types::MerchantRoutingAlgorithm::foreign_try_from(routing_algorithm.0)
.change_context(errors::ApiErrorResponse::InternalServerError)
.attach_printable("unable to parse routing algorithm")?;
@@ -454,6 +471,7 @@ pub async fn retrieve_routing_algorithm_from_algorithm_id(
state: SessionState,
merchant_account: domain::MerchantAccount,
key_store: domain::MerchantKeyStore,
+ authentication_profile_id: Option<common_utils::id_type::ProfileId>,
algorithm_id: common_utils::id_type::RoutingId,
) -> RouterResponse<routing_types::MerchantRoutingAlgorithm> {
metrics::ROUTING_RETRIEVE_CONFIG.add(&metrics::CONTEXT, 1, &[]);
@@ -468,7 +486,7 @@ pub async fn retrieve_routing_algorithm_from_algorithm_id(
.await
.to_not_found_response(errors::ApiErrorResponse::ResourceIdNotFound)?;
- core_utils::validate_and_get_business_profile(
+ let business_profile = core_utils::validate_and_get_business_profile(
db,
key_manager_state,
&key_store,
@@ -479,6 +497,8 @@ pub async fn retrieve_routing_algorithm_from_algorithm_id(
.get_required_value("BusinessProfile")
.change_context(errors::ApiErrorResponse::ResourceIdNotFound)?;
+ core_utils::validate_profile_id_from_auth_layer(authentication_profile_id, &business_profile)?;
+
let response = routing_types::MerchantRoutingAlgorithm::foreign_try_from(routing_algorithm)
.change_context(errors::ApiErrorResponse::InternalServerError)
.attach_printable("unable to parse routing algorithm")?;
@@ -554,9 +574,11 @@ pub async fn unlink_routing_config(
merchant_account: domain::MerchantAccount,
key_store: domain::MerchantKeyStore,
request: routing_types::RoutingConfigRequest,
+ authentication_profile_id: Option<common_utils::id_type::ProfileId>,
transaction_type: &enums::TransactionType,
) -> RouterResponse<routing_types::RoutingDictionaryRecord> {
metrics::ROUTING_UNLINK_CONFIG.add(&metrics::CONTEXT, 1, &[]);
+
let db = state.store.as_ref();
let key_manager_state = &(&state).into();
@@ -567,6 +589,7 @@ pub async fn unlink_routing_config(
field_name: "profile_id",
})
.attach_printable("Profile_id not provided")?;
+
let business_profile = core_utils::validate_and_get_business_profile(
db,
key_manager_state,
@@ -575,8 +598,13 @@ pub async fn unlink_routing_config(
merchant_account.get_id(),
)
.await?;
+
match business_profile {
Some(business_profile) => {
+ core_utils::validate_profile_id_from_auth_layer(
+ authentication_profile_id,
+ &business_profile,
+ )?;
let routing_algo_ref: routing_types::RoutingAlgorithmRef = match transaction_type {
enums::TransactionType::Payment => business_profile.routing_algorithm.clone(),
#[cfg(feature = "payouts")]
@@ -880,6 +908,7 @@ pub async fn retrieve_linked_routing_config(
state: SessionState,
merchant_account: domain::MerchantAccount,
key_store: domain::MerchantKeyStore,
+ authentication_profile_id: Option<common_utils::id_type::ProfileId>,
query_params: routing_types::RoutingRetrieveLinkQuery,
transaction_type: &enums::TransactionType,
) -> RouterResponse<routing_types::LinkedRoutingConfigRetrieveResponse> {
@@ -902,13 +931,18 @@ pub async fn retrieve_linked_routing_config(
id: profile_id.get_string_repr().to_owned(),
})?
} else {
- db.list_business_profile_by_merchant_id(
- key_manager_state,
- &key_store,
- merchant_account.get_id(),
+ let business_profile = db
+ .list_business_profile_by_merchant_id(
+ key_manager_state,
+ &key_store,
+ merchant_account.get_id(),
+ )
+ .await
+ .to_not_found_response(errors::ApiErrorResponse::ResourceIdNotFound)?;
+ core_utils::filter_objects_based_on_profile_id_list(
+ authentication_profile_id.map(|profile_id| vec![profile_id]),
+ business_profile.clone(),
)
- .await
- .to_not_found_response(errors::ApiErrorResponse::ResourceIdNotFound)?
};
let mut active_algorithms = Vec::new();
@@ -1007,6 +1041,7 @@ pub async fn update_default_routing_config_for_profile(
transaction_type: &enums::TransactionType,
) -> RouterResponse<routing_types::ProfileDefaultRoutingConfig> {
metrics::ROUTING_UPDATE_CONFIG_FOR_PROFILE.add(&metrics::CONTEXT, 1, &[]);
+
let db = state.store.as_ref();
let key_manager_state = &(&state).into();
diff --git a/crates/router/src/core/utils.rs b/crates/router/src/core/utils.rs
index 2fcf8a24773..41e87a19337 100644
--- a/crates/router/src/core/utils.rs
+++ b/crates/router/src/core/utils.rs
@@ -1368,16 +1368,29 @@ impl GetProfileId for diesel_models::Refund {
}
}
-#[cfg(feature = "payouts")]
-impl GetProfileId for storage::Payouts {
+#[cfg(all(any(feature = "v1", feature = "v2"), not(feature = "routing_v2")))]
+impl GetProfileId for api_models::routing::RoutingConfigRequest {
+ fn get_profile_id(&self) -> Option<&common_utils::id_type::ProfileId> {
+ self.profile_id.as_ref()
+ }
+}
+
+#[cfg(all(feature = "v2", feature = "routing_v2"))]
+impl GetProfileId for api_models::routing::RoutingConfigRequest {
fn get_profile_id(&self) -> Option<&common_utils::id_type::ProfileId> {
Some(&self.profile_id)
}
}
-#[cfg(feature = "payouts")]
-impl<T, F> GetProfileId for (storage::Payouts, T, F) {
+
+impl GetProfileId for api_models::routing::RoutingRetrieveLinkQuery {
fn get_profile_id(&self) -> Option<&common_utils::id_type::ProfileId> {
- self.0.get_profile_id()
+ self.profile_id.as_ref()
+ }
+}
+
+impl GetProfileId for diesel_models::routing_algorithm::RoutingProfileMetadata {
+ fn get_profile_id(&self) -> Option<&common_utils::id_type::ProfileId> {
+ Some(&self.profile_id)
}
}
@@ -1387,6 +1400,19 @@ impl GetProfileId for domain::BusinessProfile {
}
}
+#[cfg(feature = "payouts")]
+impl GetProfileId for storage::Payouts {
+ fn get_profile_id(&self) -> Option<&common_utils::id_type::ProfileId> {
+ Some(&self.profile_id)
+ }
+}
+#[cfg(feature = "payouts")]
+impl<T, F> GetProfileId for (storage::Payouts, T, F) {
+ fn get_profile_id(&self) -> Option<&common_utils::id_type::ProfileId> {
+ self.0.get_profile_id()
+ }
+}
+
/// Filter Objects based on profile ids
pub(super) fn filter_objects_based_on_profile_id_list<T: GetProfileId>(
profile_id_list_auth_layer: Option<Vec<common_utils::id_type::ProfileId>>,
diff --git a/crates/router/src/routes/app.rs b/crates/router/src/routes/app.rs
index c78caa9e781..bd05740acae 100644
--- a/crates/router/src/routes/app.rs
+++ b/crates/router/src/routes/app.rs
@@ -711,6 +711,17 @@ impl Routing {
)
})),
)
+ .service(web::resource("/list/{profile_id}").route(web::get().to(
+ |state, req, path, query: web::Query<RoutingRetrieveQuery>| {
+ routing::list_routing_configs_for_profile(
+ state,
+ req,
+ query,
+ path,
+ &TransactionType::Payment,
+ )
+ },
+ )))
.service(
web::resource("/default")
.route(web::get().to(|state, req| {
diff --git a/crates/router/src/routes/routing.rs b/crates/router/src/routes/routing.rs
index aefc91f759c..b68d09deeb2 100644
--- a/crates/router/src/routes/routing.rs
+++ b/crates/router/src/routes/routing.rs
@@ -34,6 +34,7 @@ pub async fn routing_create_config(
state,
auth.merchant_account,
auth.key_store,
+ auth.profile_id,
payload,
transaction_type,
)
@@ -74,6 +75,7 @@ pub async fn routing_link_config(
state,
auth.merchant_account,
auth.key_store,
+ auth.profile_id,
algorithm,
transaction_type,
)
@@ -110,7 +112,7 @@ pub async fn routing_link_config(
flow,
state,
&req,
- wrapper,
+ wrapper.clone(),
|state, auth: auth::AuthenticationData, wrapper, _| {
routing::link_routing_config_under_profile(
state,
@@ -124,11 +126,17 @@ pub async fn routing_link_config(
#[cfg(not(feature = "release"))]
auth::auth_type(
&auth::ApiKeyAuth,
- &auth::JWTAuth(Permission::RoutingWrite),
+ &auth::JWTAuthProfileFromRoute {
+ profile_id: routing_payload_wrapper.profile_id,
+ required_permission: Permission::RoutingWrite,
+ },
req.headers(),
),
#[cfg(feature = "release")]
- &auth::JWTAuth(Permission::RoutingWrite),
+ &auth::JWTAuthProfileFromRoute {
+ profile_id: wrapper.profile_id,
+ required_permission: Permission::RoutingWrite,
+ },
api_locking::LockAction::NotApplicable,
))
.await
@@ -153,6 +161,7 @@ pub async fn routing_retrieve_config(
state,
auth.merchant_account,
auth.key_store,
+ auth.profile_id,
algorithm_id,
)
},
@@ -187,6 +196,7 @@ pub async fn list_routing_configs(
routing::retrieve_merchant_routing_dictionary(
state,
auth.merchant_account,
+ None,
query_params,
transaction_type,
)
@@ -204,6 +214,50 @@ pub async fn list_routing_configs(
.await
}
+#[cfg(feature = "olap")]
+#[instrument(skip_all)]
+pub async fn list_routing_configs_for_profile(
+ state: web::Data<AppState>,
+ req: HttpRequest,
+ query: web::Query<RoutingRetrieveQuery>,
+ path: web::Path<common_utils::id_type::ProfileId>,
+ transaction_type: &enums::TransactionType,
+) -> impl Responder {
+ let flow = Flow::RoutingRetrieveDictionary;
+ let path = path.into_inner();
+ 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.merchant_account,
+ auth.profile_id.map(|profile_id| vec![profile_id]),
+ query_params,
+ transaction_type,
+ )
+ },
+ #[cfg(not(feature = "release"))]
+ auth::auth_type(
+ &auth::HeaderAuth(auth::ApiKeyAuth),
+ &auth::JWTAuthProfileFromRoute {
+ profile_id: path,
+ required_permission: Permission::RoutingRead,
+ },
+ req.headers(),
+ ),
+ #[cfg(feature = "release")]
+ &auth::JWTAuthProfileFromRoute {
+ profile_id: path,
+ required_permission: Permission::RoutingRead,
+ },
+ api_locking::LockAction::NotApplicable,
+ ))
+ .await
+}
+
#[cfg(all(feature = "olap", feature = "v2", feature = "routing_v2"))]
#[instrument(skip_all)]
pub async fn routing_unlink_config(
@@ -213,11 +267,12 @@ pub async fn routing_unlink_config(
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.into_inner(),
+ path.clone(),
|state, auth: auth::AuthenticationData, path, _| {
routing::unlink_routing_config_under_profile(
state,
@@ -230,11 +285,17 @@ pub async fn routing_unlink_config(
#[cfg(not(feature = "release"))]
auth::auth_type(
&auth::ApiKeyAuth,
- &auth::JWTAuth(Permission::RoutingWrite),
+ &auth::JWTAuthProfileFromRoute {
+ profile_id: path,
+ required_permission: Permission::RoutingWrite,
+ },
req.headers(),
),
#[cfg(feature = "release")]
- &auth::JWTAuth(Permission::RoutingWrite),
+ &auth::JWTAuthProfileFromRoute {
+ profile_id: path,
+ required_permission: Permission::RoutingWrite,
+ },
api_locking::LockAction::NotApplicable,
))
.await
@@ -264,6 +325,7 @@ pub async fn routing_unlink_config(
auth.merchant_account,
auth.key_store,
payload_req,
+ auth.profile_id,
transaction_type,
)
},
@@ -374,11 +436,12 @@ pub async fn routing_retrieve_default_config(
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.into_inner(),
+ path.clone(),
|state, auth: auth::AuthenticationData, profile_id, _| {
routing::retrieve_default_fallback_algorithm_for_profile(
state,
@@ -390,11 +453,17 @@ pub async fn routing_retrieve_default_config(
#[cfg(not(feature = "release"))]
auth::auth_type(
&auth::HeaderAuth(auth::ApiKeyAuth),
- &auth::JWTAuth(Permission::RoutingRead),
+ &auth::JWTAuthProfileFromRoute {
+ profile_id: path,
+ required_permission: Permission::RoutingRead,
+ },
req.headers(),
),
#[cfg(feature = "release")]
- &auth::JWTAuth(Permission::RoutingRead),
+ &auth::JWTAuthProfileFromRoute {
+ profile_id: path,
+ required_permission: Permission::RoutingRead,
+ },
api_locking::LockAction::NotApplicable,
))
.await
@@ -636,31 +705,68 @@ pub async fn routing_retrieve_linked_config(
) -> impl Responder {
use crate::services::authentication::AuthenticationData;
let flow = Flow::RoutingRetrieveActiveConfig;
- Box::pin(oss_api::server_wrap(
- flow,
- state,
- &req,
- query.into_inner(),
- |state, auth: AuthenticationData, query_params, _| {
- routing::retrieve_linked_routing_config(
- state,
- auth.merchant_account,
- auth.key_store,
- query_params,
- transaction_type,
- )
- },
- #[cfg(not(feature = "release"))]
- auth::auth_type(
- &auth::HeaderAuth(auth::ApiKeyAuth),
+ 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, _| {
+ routing::retrieve_linked_routing_config(
+ state,
+ auth.merchant_account,
+ auth.key_store,
+ auth.profile_id,
+ query_params,
+ transaction_type,
+ )
+ },
+ #[cfg(not(feature = "release"))]
+ auth::auth_type(
+ &auth::HeaderAuth(auth::ApiKeyAuth),
+ &auth::JWTAuthProfileFromRoute {
+ profile_id,
+ required_permission: Permission::RoutingRead,
+ },
+ req.headers(),
+ ),
+ #[cfg(feature = "release")]
+ &auth::JWTAuthProfileFromRoute {
+ profile_id,
+ required_permission: Permission::RoutingRead,
+ },
+ api_locking::LockAction::NotApplicable,
+ ))
+ .await
+ } else {
+ Box::pin(oss_api::server_wrap(
+ flow,
+ state,
+ &req,
+ query.clone(),
+ |state, auth: AuthenticationData, query_params, _| {
+ routing::retrieve_linked_routing_config(
+ state,
+ auth.merchant_account,
+ auth.key_store,
+ auth.profile_id,
+ query_params,
+ transaction_type,
+ )
+ },
+ #[cfg(not(feature = "release"))]
+ auth::auth_type(
+ &auth::HeaderAuth(auth::ApiKeyAuth),
+ &auth::JWTAuth(Permission::RoutingRead),
+ req.headers(),
+ ),
+ #[cfg(feature = "release")]
&auth::JWTAuth(Permission::RoutingRead),
- req.headers(),
- ),
- #[cfg(feature = "release")]
- &auth::JWTAuth(Permission::RoutingRead),
- api_locking::LockAction::NotApplicable,
- ))
- .await
+ api_locking::LockAction::NotApplicable,
+ ))
+ .await
+ }
}
#[cfg(all(
@@ -687,7 +793,7 @@ pub async fn routing_retrieve_linked_config(
flow,
state,
&req,
- wrapper,
+ wrapper.clone(),
|state, auth: AuthenticationData, wrapper, _| {
routing::retrieve_routing_config_under_profile(
state,
@@ -701,11 +807,17 @@ pub async fn routing_retrieve_linked_config(
#[cfg(not(feature = "release"))]
auth::auth_type(
&auth::HeaderAuth(auth::ApiKeyAuth),
- &auth::JWTAuth(Permission::RoutingRead),
+ &auth::JWTAuthProfileFromRoute {
+ profile_id: wrapper.profile_id,
+ required_permission: Permission::RoutingRead,
+ },
req.headers(),
),
#[cfg(feature = "release")]
- &auth::JWTAuth(Permission::RoutingRead),
+ &auth::JWTAuthProfileFromRoute {
+ profile_id: wrapper.profile_id,
+ required_permission: Permission::RoutingRead,
+ },
api_locking::LockAction::NotApplicable,
))
.await
@@ -765,7 +877,7 @@ pub async fn routing_update_default_config_for_profile(
Flow::RoutingUpdateDefaultConfig,
state,
&req,
- routing_payload_wrapper,
+ routing_payload_wrapper.clone(),
|state, auth: auth::AuthenticationData, wrapper, _| {
routing::update_default_routing_config_for_profile(
state,
@@ -779,11 +891,17 @@ pub async fn routing_update_default_config_for_profile(
#[cfg(not(feature = "release"))]
auth::auth_type(
&auth::HeaderAuth(auth::ApiKeyAuth),
- &auth::JWTAuth(Permission::RoutingWrite),
+ &auth::JWTAuthProfileFromRoute {
+ profile_id: routing_payload_wrapper.profile_id,
+ required_permission: Permission::RoutingWrite,
+ },
req.headers(),
),
#[cfg(feature = "release")]
- &auth::JWTAuth(Permission::RoutingWrite),
+ &auth::JWTAuthProfileFromRoute {
+ profile_id: routing_payload_wrapper.profile_id,
+ required_permission: Permission::RoutingWrite,
+ },
api_locking::LockAction::NotApplicable,
))
.await
diff --git a/crates/router/src/services/authentication.rs b/crates/router/src/services/authentication.rs
index a84f3a5a0e3..4f9a222db5e 100644
--- a/crates/router/src/services/authentication.rs
+++ b/crates/router/src/services/authentication.rs
@@ -1329,7 +1329,6 @@ where
))
}
}
-
pub struct JWTAuthMerchantAndProfileFromRoute {
pub merchant_id: id_type::MerchantId,
pub profile_id: id_type::ProfileId,
@@ -1404,6 +1403,87 @@ where
}
}
+pub struct JWTAuthProfileFromRoute {
+ pub profile_id: id_type::ProfileId,
+ pub required_permission: Permission,
+}
+
+#[async_trait]
+impl<A> AuthenticateAndFetch<AuthenticationData, A> for JWTAuthProfileFromRoute
+where
+ A: SessionStateInfo + Sync,
+{
+ async fn authenticate_and_fetch(
+ &self,
+ request_headers: &HeaderMap,
+ state: &A,
+ ) -> RouterResult<(AuthenticationData, AuthenticationType)> {
+ let payload = parse_jwt_payload::<A, AuthToken>(request_headers, state).await?;
+ if payload.check_in_blacklist(state).await? {
+ return Err(errors::ApiErrorResponse::InvalidJwtToken.into());
+ }
+
+ let permissions = authorization::get_permissions(state, &payload).await?;
+ authorization::check_authorization(&self.required_permission, &permissions)?;
+ let key_manager_state = &(&state.session_state()).into();
+ let key_store = state
+ .store()
+ .get_merchant_key_store_by_merchant_id(
+ key_manager_state,
+ &payload.merchant_id,
+ &state.store().get_master_key().to_vec().into(),
+ )
+ .await
+ .to_not_found_response(errors::ApiErrorResponse::InvalidJwtToken)
+ .attach_printable("Failed to fetch merchant key store for the merchant id")?;
+
+ let merchant = state
+ .store()
+ .find_merchant_account_by_merchant_id(
+ key_manager_state,
+ &payload.merchant_id,
+ &key_store,
+ )
+ .await
+ .to_not_found_response(errors::ApiErrorResponse::InvalidJwtToken)
+ .attach_printable("Failed to fetch merchant account for the merchant id")?;
+
+ if let Some(ref payload_profile_id) = payload.profile_id {
+ if *payload_profile_id != self.profile_id {
+ return Err(report!(errors::ApiErrorResponse::InvalidJwtToken));
+ } else {
+ // if both of them are same then proceed with the profile id present in the request
+ let auth = AuthenticationData {
+ merchant_account: merchant,
+ key_store,
+ profile_id: Some(self.profile_id.clone()),
+ };
+ Ok((
+ auth.clone(),
+ AuthenticationType::MerchantJwt {
+ merchant_id: auth.merchant_account.get_id().clone(),
+ user_id: Some(payload.user_id),
+ },
+ ))
+ }
+ } else {
+ // if profile_id is not present in the auth_layer itself then no change in behaviour
+ let auth = AuthenticationData {
+ merchant_account: merchant,
+ key_store,
+ profile_id: payload.profile_id,
+ };
+ Ok((
+ auth.clone(),
+ AuthenticationType::MerchantJwt {
+ merchant_id: auth.merchant_account.get_id().clone(),
+ user_id: Some(payload.user_id),
+ },
+ ))
+ }
+ }
+}
+
pub async fn parse_jwt_payload<A, T>(headers: &HeaderMap, state: &A) -> RouterResult<T>
where
T: serde::de::DeserializeOwned,
|
2024-08-20T08:17:36Z
|
## Type of Change
<!-- Put an `x` in the boxes that apply -->
- [ ] Bugfix
- [ ] New feature
- [ ] Enhancement
- [x] Refactoring
- [ ] Dependency updates
- [ ] Documentation
- [ ] CI/CD
## Description
<!-- Describe your changes in detail -->
This change will ensure that the profile id being sent in params, belongs to the merchant using them.
### Additional Changes
- [ ] This PR modifies the API contract
- [ ] This PR modifies the database schema
- [ ] This PR modifies application configuration/environment variables
## How did you test it?
<!--
Did you write an integration/unit/API test to verify the code changes?
Or did you test this change manually (provide relevant screenshots)?
-->
Cannot be tested right now because currently we are not including profile_id in JWT.
Was able to compile the code.
## Checklist
<!-- Put an `x` in the boxes that apply -->
- [x] I formatted the code `cargo +nightly fmt --all`
- [x] I addressed lints thrown by `cargo clippy`
- [x] I reviewed the submitted code
- [ ] I added unit tests for my changes where possible
|
e3a9fb16c518d09313d00a23ece70a26d4728f63
|
|
juspay/hyperswitch
|
juspay__hyperswitch-5663
|
Bug: [FEATURE] Update MCA Update to process additional merchant data for open banking connectors
### Feature Description
Currently, we only accept `additional_merchant_data` in the MCA create req, we need to accept it in update req as well and and add the logic for processing the data in the MCA update core.
### Possible Implementation
Need to update the relevant api_models and core logic
### Have you spent some time checking if this feature request has been raised before?
- [X] I checked and didn't find a similar issue
### Have you read the Contributing Guidelines?
- [X] I have read the [Contributing Guidelines](https://github.com/juspay/hyperswitch/blob/main/docs/CONTRIBUTING.md)
### Are you willing to submit a PR?
Yes, I am willing to submit a PR!
|
diff --git a/api-reference-v2/openapi_spec.json b/api-reference-v2/openapi_spec.json
index 458e1ae9ff0..b68a5c91c8b 100644
--- a/api-reference-v2/openapi_spec.json
+++ b/api-reference-v2/openapi_spec.json
@@ -7766,6 +7766,14 @@
"example": "y3oqhf46pyzuxjbcn2giaqnb44",
"maxLength": 64,
"minLength": 1
+ },
+ "additional_merchant_data": {
+ "allOf": [
+ {
+ "$ref": "#/components/schemas/AdditionalMerchantData"
+ }
+ ],
+ "nullable": true
}
},
"additionalProperties": false
diff --git a/crates/api_models/src/admin.rs b/crates/api_models/src/admin.rs
index b073c219517..e4f61fc2e41 100644
--- a/crates/api_models/src/admin.rs
+++ b/crates/api_models/src/admin.rs
@@ -1555,6 +1555,10 @@ pub struct MerchantConnectorUpdate {
#[schema(value_type = ConnectorStatus, example = "inactive")]
pub status: Option<api_enums::ConnectorStatus>,
+
+ /// In case the merchant needs to store any additional sensitive data
+ #[schema(value_type = Option<AdditionalMerchantData>)]
+ pub additional_merchant_data: Option<AdditionalMerchantData>,
}
/// 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."
@@ -1636,6 +1640,10 @@ pub struct MerchantConnectorUpdate {
/// The identifier for the Merchant Account
#[schema(value_type = String, max_length = 64, min_length = 1, example = "y3oqhf46pyzuxjbcn2giaqnb44")]
pub merchant_id: id_type::MerchantId,
+
+ /// In case the merchant needs to store any additional sensitive data
+ #[schema(value_type = Option<AdditionalMerchantData>)]
+ pub additional_merchant_data: Option<AdditionalMerchantData>,
}
#[cfg(all(feature = "v2", feature = "merchant_connector_account_v2"))]
diff --git a/crates/diesel_models/src/merchant_connector_account.rs b/crates/diesel_models/src/merchant_connector_account.rs
index 876240f44a3..19fe880f3aa 100644
--- a/crates/diesel_models/src/merchant_connector_account.rs
+++ b/crates/diesel_models/src/merchant_connector_account.rs
@@ -203,6 +203,7 @@ pub struct MerchantConnectorAccountUpdateInternal {
pub pm_auth_config: Option<pii::SecretSerdeValue>,
pub status: Option<storage_enums::ConnectorStatus>,
pub connector_wallets_details: Option<Encryption>,
+ pub additional_merchant_data: Option<Encryption>,
}
#[cfg(all(feature = "v2", feature = "merchant_connector_account_v2"))]
@@ -224,6 +225,7 @@ pub struct MerchantConnectorAccountUpdateInternal {
pub pm_auth_config: Option<pii::SecretSerdeValue>,
pub status: Option<storage_enums::ConnectorStatus>,
pub connector_wallets_details: Option<Encryption>,
+ pub additional_merchant_data: Option<Encryption>,
}
#[cfg(all(
diff --git a/crates/hyperswitch_domain_models/src/merchant_connector_account.rs b/crates/hyperswitch_domain_models/src/merchant_connector_account.rs
index 9e2f6918b43..d763531f3bd 100644
--- a/crates/hyperswitch_domain_models/src/merchant_connector_account.rs
+++ b/crates/hyperswitch_domain_models/src/merchant_connector_account.rs
@@ -109,6 +109,7 @@ pub enum MerchantConnectorAccountUpdate {
connector_label: Option<String>,
status: Option<enums::ConnectorStatus>,
connector_wallets_details: Option<Encryptable<pii::SecretSerdeValue>>,
+ additional_merchant_data: Option<Encryptable<pii::SecretSerdeValue>>,
},
ConnectorWalletDetailsUpdate {
connector_wallets_details: Encryptable<pii::SecretSerdeValue>,
@@ -131,6 +132,7 @@ pub enum MerchantConnectorAccountUpdate {
connector_label: Option<String>,
status: Option<enums::ConnectorStatus>,
connector_wallets_details: Option<Encryptable<pii::SecretSerdeValue>>,
+ additional_merchant_data: Option<Encryptable<pii::SecretSerdeValue>>,
},
ConnectorWalletDetailsUpdate {
connector_wallets_details: Encryptable<pii::SecretSerdeValue>,
@@ -453,6 +455,7 @@ impl From<MerchantConnectorAccountUpdate> for MerchantConnectorAccountUpdateInte
connector_label,
status,
connector_wallets_details,
+ additional_merchant_data,
} => Self {
connector_type,
connector_name,
@@ -471,6 +474,7 @@ impl From<MerchantConnectorAccountUpdate> for MerchantConnectorAccountUpdateInte
connector_label,
status,
connector_wallets_details: connector_wallets_details.map(Encryption::from),
+ additional_merchant_data: additional_merchant_data.map(Encryption::from),
},
MerchantConnectorAccountUpdate::ConnectorWalletDetailsUpdate {
connector_wallets_details,
@@ -492,6 +496,7 @@ impl From<MerchantConnectorAccountUpdate> for MerchantConnectorAccountUpdateInte
applepay_verified_domains: None,
pm_auth_config: None,
status: None,
+ additional_merchant_data: None,
},
}
}
@@ -514,6 +519,7 @@ impl From<MerchantConnectorAccountUpdate> for MerchantConnectorAccountUpdateInte
connector_label,
status,
connector_wallets_details,
+ additional_merchant_data,
} => Self {
connector_type,
connector_account_details: connector_account_details.map(Encryption::from),
@@ -528,6 +534,7 @@ impl From<MerchantConnectorAccountUpdate> for MerchantConnectorAccountUpdateInte
connector_label,
status,
connector_wallets_details: connector_wallets_details.map(Encryption::from),
+ additional_merchant_data: additional_merchant_data.map(Encryption::from),
},
MerchantConnectorAccountUpdate::ConnectorWalletDetailsUpdate {
connector_wallets_details,
@@ -545,6 +552,7 @@ impl From<MerchantConnectorAccountUpdate> for MerchantConnectorAccountUpdateInte
applepay_verified_domains: None,
pm_auth_config: None,
status: None,
+ additional_merchant_data: None,
},
}
}
diff --git a/crates/router/src/core/admin.rs b/crates/router/src/core/admin.rs
index 1f5fb068408..da497c77f16 100644
--- a/crates/router/src/core/admin.rs
+++ b/crates/router/src/core/admin.rs
@@ -2027,6 +2027,30 @@ impl MerchantConnectorAccountUpdateBridge for api_models::admin::MerchantConnect
pm_auth_config_validation.validate_pm_auth_config().await?;
+ let merchant_recipient_data = if let Some(data) = &self.additional_merchant_data {
+ Some(
+ process_open_banking_connectors(
+ state,
+ merchant_account.get_id(),
+ &auth,
+ &self.connector_type,
+ &connector_enum,
+ types::AdditionalMerchantData::foreign_from(data.clone()),
+ )
+ .await?,
+ )
+ } else {
+ None
+ }
+ .map(|data| {
+ serde_json::to_value(types::AdditionalMerchantData::OpenBankingRecipientData(
+ data,
+ ))
+ })
+ .transpose()
+ .change_context(errors::ApiErrorResponse::InternalServerError)
+ .attach_printable("Failed to serialize MerchantRecipientData")?;
+
Ok(storage::MerchantConnectorAccountUpdate::Update {
connector_type: Some(self.connector_type),
connector_label: self.connector_label.clone(),
@@ -2061,6 +2085,23 @@ impl MerchantConnectorAccountUpdateBridge for api_models::admin::MerchantConnect
applepay_verified_domains: None,
pm_auth_config: self.pm_auth_config,
status: Some(connector_status),
+ additional_merchant_data: if let Some(mcd) = merchant_recipient_data {
+ Some(
+ domain_types::crypto_operation(
+ key_manager_state,
+ type_name!(domain::MerchantConnectorAccount),
+ domain_types::CryptoOperation::Encrypt(Secret::new(mcd)),
+ km_types::Identifier::Merchant(key_store.merchant_id.clone()),
+ key_store.key.peek(),
+ )
+ .await
+ .and_then(|val| val.try_into_operation())
+ .change_context(errors::ApiErrorResponse::InternalServerError)
+ .attach_printable("Unable to encrypt additional_merchant_data")?,
+ )
+ } else {
+ None
+ },
connector_wallets_details: helpers::get_encrypted_apple_pay_connector_wallets_details(
state, &key_store, &metadata,
)
@@ -2163,6 +2204,30 @@ impl MerchantConnectorAccountUpdateBridge for api_models::admin::MerchantConnect
}
}
+ let merchant_recipient_data = if let Some(data) = &self.additional_merchant_data {
+ Some(
+ process_open_banking_connectors(
+ state,
+ merchant_account.get_id(),
+ &auth,
+ &self.connector_type,
+ &connector_enum,
+ types::AdditionalMerchantData::foreign_from(data.clone()),
+ )
+ .await?,
+ )
+ } else {
+ None
+ }
+ .map(|data| {
+ serde_json::to_value(types::AdditionalMerchantData::OpenBankingRecipientData(
+ data,
+ ))
+ })
+ .transpose()
+ .change_context(errors::ApiErrorResponse::InternalServerError)
+ .attach_printable("Failed to serialize MerchantRecipientData")?;
+
Ok(storage::MerchantConnectorAccountUpdate::Update {
connector_type: Some(self.connector_type),
connector_name: None,
@@ -2200,6 +2265,23 @@ impl MerchantConnectorAccountUpdateBridge for api_models::admin::MerchantConnect
applepay_verified_domains: None,
pm_auth_config: self.pm_auth_config,
status: Some(connector_status),
+ additional_merchant_data: if let Some(mcd) = merchant_recipient_data {
+ Some(
+ domain_types::crypto_operation(
+ key_manager_state,
+ type_name!(domain::MerchantConnectorAccount),
+ domain_types::CryptoOperation::Encrypt(Secret::new(mcd)),
+ km_types::Identifier::Merchant(key_store.merchant_id.clone()),
+ key_store.key.peek(),
+ )
+ .await
+ .and_then(|val| val.try_into_operation())
+ .change_context(errors::ApiErrorResponse::InternalServerError)
+ .attach_printable("Unable to encrypt additional_merchant_data")?,
+ )
+ } else {
+ None
+ },
connector_wallets_details: helpers::get_encrypted_apple_pay_connector_wallets_details(
state, &key_store, &metadata,
)
@@ -2297,7 +2379,7 @@ impl MerchantConnectorAccountCreateBridge for api::MerchantConnectorCreate {
})
.transpose()
.change_context(errors::ApiErrorResponse::InternalServerError)
- .attach_printable("Failed to get MerchantRecipientData")?;
+ .attach_printable("Failed to serialize MerchantRecipientData")?;
Ok(domain::MerchantConnectorAccount {
merchant_id: business_profile.merchant_id.clone(),
connector_type: self.connector_type,
@@ -2346,7 +2428,7 @@ impl MerchantConnectorAccountCreateBridge for api::MerchantConnectorCreate {
key_manager_state,
type_name!(domain::MerchantConnectorAccount),
domain_types::CryptoOperation::Encrypt(Secret::new(mcd)),
- identifier,
+ km_types::Identifier::Merchant(key_store.merchant_id.clone()),
key_store.key.peek(),
)
.await
@@ -2463,7 +2545,7 @@ impl MerchantConnectorAccountCreateBridge for api::MerchantConnectorCreate {
})
.transpose()
.change_context(errors::ApiErrorResponse::InternalServerError)
- .attach_printable("Failed to get MerchantRecipientData")?;
+ .attach_printable("Failed to serialize MerchantRecipientData")?;
Ok(domain::MerchantConnectorAccount {
merchant_id: business_profile.merchant_id.clone(),
connector_type: self.connector_type,
diff --git a/crates/router/src/core/connector_onboarding/paypal.rs b/crates/router/src/core/connector_onboarding/paypal.rs
index 13b2bf16cdb..f967f2aece3 100644
--- a/crates/router/src/core/connector_onboarding/paypal.rs
+++ b/crates/router/src/core/connector_onboarding/paypal.rs
@@ -164,6 +164,7 @@ pub async fn update_mca(
connector_webhook_details: None,
pm_auth_config: None,
test_mode: None,
+ additional_merchant_data: None,
};
#[cfg(all(feature = "v2", feature = "merchant_connector_account_v2"))]
let request = MerchantConnectorUpdate {
@@ -178,6 +179,7 @@ pub async fn update_mca(
connector_webhook_details: None,
pm_auth_config: None,
merchant_id: merchant_id.clone(),
+ additional_merchant_data: None,
};
let mca_response =
admin::update_connector(state.clone(), &merchant_id, None, &connector_id, request).await?;
diff --git a/crates/router/src/core/verification/utils.rs b/crates/router/src/core/verification/utils.rs
index dd0aa3edef4..012f04299da 100644
--- a/crates/router/src/core/verification/utils.rs
+++ b/crates/router/src/core/verification/utils.rs
@@ -87,6 +87,7 @@ pub async fn check_existence_and_add_domain_to_db(
connector_label: None,
status: None,
connector_wallets_details: None,
+ additional_merchant_data: None,
};
#[cfg(all(feature = "v2", feature = "merchant_connector_account_v2"))]
let updated_mca = storage::MerchantConnectorAccountUpdate::Update {
@@ -102,6 +103,7 @@ pub async fn check_existence_and_add_domain_to_db(
connector_label: None,
status: None,
connector_wallets_details: None,
+ additional_merchant_data: None,
};
state
.store
|
2024-08-21T10:05:35Z
|
## Type of Change
<!-- Put an `x` in the boxes that apply -->
- [x] Bugfix
- [ ] New feature
- [ ] Enhancement
- [ ] Refactoring
- [ ] Dependency updates
- [ ] Documentation
- [ ] CI/CD
## Description
<!-- Describe your changes in detail -->
This PR does -
- In the PIS flow, in merchant connector update, we didn't collect `additional_merchant_data` in the update req, have fixed that. Have also added relevant logic in MCA update core to process the data collected.
### Additional Changes
- [ ] This PR modifies the API contract
- [ ] This PR modifies the database schema
- [ ] This PR modifies application configuration/environment variables
<!--
Provide links to the files with corresponding changes.
Following are the paths where you can find config files:
1. `config`
2. `crates/router/src/configs`
3. `loadtest/config`
-->
## Motivation and Context
<!--
Why is this change required? What problem does it solve?
If it fixes an open issue, please link to the issue here.
If you don't have an issue, we'd recommend starting with one first so the PR
can focus on the implementation (unless it is an obvious bug or documentation fix
that will have little conversation).
-->
## How did you test it?
<!--
Did you write an integration/unit/API test to verify the code changes?
Or did you test this change manually (provide relevant screenshots)?
-->
1. MCA create for Plaid -
```
curl --location --request POST 'http://localhost:8080/account/merchant_1724231900/connectors' \
--header 'api-key: test_admin' \
--header 'Content-Type: application/json' \
--data-raw '{
"connector_type": "payment_processor",
"connector_name": "plaid",
"connector_account_details": {
"auth_type": "BodyKey",
"api_key": "something",
"key1": "something"
},
"test_mode": false,
"disabled": false,
"payment_methods_enabled": [
{
"payment_method": "open_banking",
"payment_method_types": [
{
"payment_method_type": "open_banking_pis",
"maximum_amount": 68607706,
"recurring_enabled": true,
"installment_payment_enabled": true,
"payment_experience": "redirect_to_url",
"accepted_currencies": {
"type": "enable_only",
"list": [
"EUR",
"GBP"
]
},
"minimum_amount": 0
}
]
}
],
"metadata": {
"city": "NY",
"unit": "246"
}
}'
```
2. Update MCA with `additional_merchant_data`
```
curl --location --request POST 'http://localhost:8080/account/merchant_1724231900/connectors/mca_HaQGes1t8LKrBYOF6OGj' \
--header 'Content-Type: application/json' \
--header 'Accept: application/json' \
--header 'api-key: dev_cZOhqwgSt6Dl6A95YW10eWHV6LI9h2mdQ9JtDB8kxMJ4YCjFEwf0g5O2WfDnrgrW' \
--data-raw '{
"connector_type": "payment_processor",
"additional_merchant_data": {
"open_banking_recipient_data": {
"account_data": {
"iban": {
"iban": "IT38R7004962566080427G36725",
"name": "merchant_name"
}
}
}
}
}'
```
Resposne -
```
{
"connector_type": "payment_processor",
"connector_name": "plaid",
"connector_label": "plaid_GB_default",
"merchant_connector_id": "mca_HaQGes1t8LKrBYOF6OGj",
"profile_id": "pro_iWX6p7sOYZnOE10swzA2",
"connector_account_details": {
"auth_type": "BodyKey",
"api_key": "something",
"key1": "something"
},
"payment_methods_enabled": [
{
"payment_method": "open_banking",
"payment_method_types": [
{
"payment_method_type": "open_banking_pis",
"payment_experience": "redirect_to_url",
"card_networks": null,
"accepted_currencies": {
"type": "enable_only",
"list": [
"EUR",
"GBP"
]
},
"accepted_countries": null,
"minimum_amount": 0,
"maximum_amount": 68607706,
"recurring_enabled": true,
"installment_payment_enabled": true
}
]
}
],
"connector_webhook_details": null,
"metadata": {
"city": "NY",
"unit": "246"
},
"test_mode": false,
"disabled": false,
"frm_configs": null,
"business_country": null,
"business_label": null,
"business_sub_label": null,
"applepay_verified_domains": null,
"pm_auth_config": null,
"status": "active",
"additional_merchant_data": {
"open_banking_recipient_data": {
"account_data": {
"iban": {
"iban": "IT38R7004962566080427G36725",
"name": "merchant_name",
"connector_recipient_id": "recipient-id-sandbox-3fafd4a5-269e-4ebc-9f9b-6f18c8f91a73"
}
}
}
}
}
```
## Checklist
<!-- Put an `x` in the boxes that apply -->
- [x] I formatted the code `cargo +nightly fmt --all`
- [x] I addressed lints thrown by `cargo clippy`
- [ ] I reviewed the submitted code
- [ ] I added unit tests for my changes where possible
|
b60ced02ffba21624a9491a63fcde1c04cfa0b06
|
|
juspay/hyperswitch
|
juspay__hyperswitch-5659
|
Bug: feat(user): list apis
Create new apis to list for user:
- orgs
- merchant accounts
- profiles.
|
diff --git a/crates/api_models/src/user.rs b/crates/api_models/src/user.rs
index 03e59db1e86..9867aba7b39 100644
--- a/crates/api_models/src/user.rs
+++ b/crates/api_models/src/user.rs
@@ -390,3 +390,21 @@ pub struct UserKeyTransferRequest {
pub struct UserTransferKeyResponse {
pub total_transferred: usize,
}
+
+#[derive(Debug, serde::Serialize)]
+pub struct ListOrgsForUserResponse {
+ pub org_id: id_type::OrganizationId,
+ pub org_name: Option<String>,
+}
+
+#[derive(Debug, serde::Serialize)]
+pub struct ListMerchantsForUserInOrgResponse {
+ pub merchant_id: id_type::MerchantId,
+ pub merchant_name: OptionalEncryptableName,
+}
+
+#[derive(Debug, serde::Serialize)]
+pub struct ListProfilesForUserInOrgAndMerchantAccountResponse {
+ pub profile_id: String,
+ pub profile_name: String,
+}
diff --git a/crates/diesel_models/src/query/user_role.rs b/crates/diesel_models/src/query/user_role.rs
index b7f79a4438f..b4789b3c169 100644
--- a/crates/diesel_models/src/query/user_role.rs
+++ b/crates/diesel_models/src/query/user_role.rs
@@ -1,9 +1,14 @@
+use async_bb8_diesel::AsyncRunQueryDsl;
use common_utils::id_type;
-use diesel::{associations::HasTable, BoolExpressionMethods, ExpressionMethods};
+use diesel::{
+ associations::HasTable, debug_query, pg::Pg, result::Error as DieselError,
+ BoolExpressionMethods, ExpressionMethods, QueryDsl,
+};
+use error_stack::{report, ResultExt};
use crate::{
- enums::UserRoleVersion, query::generics, schema::user_roles::dsl, user_role::*, PgPooledConn,
- StorageResult,
+ enums::UserRoleVersion, errors, query::generics, schema::user_roles::dsl, user_role::*,
+ PgPooledConn, StorageResult,
};
impl UserRoleNew {
@@ -179,4 +184,55 @@ impl UserRole {
generics::generic_delete_one_with_result::<<Self as HasTable>::Table, _, _>(conn, predicate)
.await
}
+
+ pub async fn generic_user_roles_list(
+ conn: &PgPooledConn,
+ user_id: String,
+ org_id: Option<id_type::OrganizationId>,
+ merchant_id: Option<id_type::MerchantId>,
+ profile_id: Option<String>,
+ entity_id: Option<String>,
+ version: Option<UserRoleVersion>,
+ ) -> StorageResult<Vec<Self>> {
+ let mut query = <Self as HasTable>::table()
+ .filter(dsl::user_id.eq(user_id))
+ .into_boxed();
+
+ if let Some(org_id) = org_id {
+ query = query.filter(dsl::org_id.eq(org_id));
+ }
+
+ if let Some(merchant_id) = merchant_id {
+ query = query.filter(dsl::merchant_id.eq(merchant_id));
+ }
+
+ if let Some(profile_id) = profile_id {
+ query = query.filter(dsl::profile_id.eq(profile_id));
+ }
+
+ if let Some(entity_id) = entity_id {
+ query = query.filter(dsl::entity_id.eq(entity_id));
+ }
+
+ if let Some(version) = version {
+ query = query.filter(dsl::version.eq(version));
+ }
+
+ router_env::logger::debug!(query = %debug_query::<Pg,_>(&query).to_string());
+
+ match generics::db_metrics::track_database_call::<Self, _, _>(
+ query.get_results_async(conn),
+ generics::db_metrics::DatabaseOperation::Filter,
+ )
+ .await
+ {
+ Ok(value) => Ok(value),
+ Err(err) => match err {
+ DieselError::NotFound => {
+ Err(report!(err)).change_context(errors::DatabaseError::NotFound)
+ }
+ _ => Err(report!(err)).change_context(errors::DatabaseError::Others),
+ },
+ }
+ }
}
diff --git a/crates/router/src/core/user.rs b/crates/router/src/core/user.rs
index 671d3ee1535..c3d0dbae04e 100644
--- a/crates/router/src/core/user.rs
+++ b/crates/router/src/core/user.rs
@@ -1,14 +1,16 @@
-use std::collections::HashMap;
+use std::collections::{HashMap, HashSet};
use api_models::{
payments::RedirectionResponse,
user::{self as user_api, InviteMultipleUserResponse},
};
+use common_enums::EntityType;
use common_utils::{type_name, types::keymanager::Identifier};
#[cfg(feature = "email")]
use diesel_models::user_role::UserRoleUpdate;
use diesel_models::{
enums::{TotpStatus, UserRoleVersion, UserStatus},
+ organization::OrganizationBridge,
user as storage_user,
user_authentication_method::{UserAuthenticationMethodNew, UserAuthenticationMethodUpdate},
user_role::UserRoleNew,
@@ -2563,3 +2565,198 @@ pub async fn terminate_auth_select(
token,
)
}
+
+pub async fn list_orgs_for_user(
+ state: SessionState,
+ user_from_token: auth::UserFromToken,
+) -> UserResponse<Vec<user_api::ListOrgsForUserResponse>> {
+ let orgs = state
+ .store
+ .list_user_roles(
+ user_from_token.user_id.as_str(),
+ None,
+ None,
+ None,
+ None,
+ None,
+ )
+ .await
+ .change_context(UserErrors::InternalServerError)?
+ .into_iter()
+ .filter_map(|user_role| {
+ (user_role.status == UserStatus::Active)
+ .then_some(user_role.org_id)
+ .flatten()
+ })
+ .collect::<HashSet<_>>();
+
+ let resp = futures::future::try_join_all(
+ orgs.iter()
+ .map(|org_id| state.store.find_organization_by_org_id(org_id)),
+ )
+ .await
+ .change_context(UserErrors::InternalServerError)?
+ .into_iter()
+ .map(|org| user_api::ListOrgsForUserResponse {
+ org_id: org.get_organization_id(),
+ org_name: org.get_organization_name(),
+ })
+ .collect();
+
+ Ok(ApplicationResponse::Json(resp))
+}
+
+pub async fn list_merchants_for_user_in_org(
+ state: SessionState,
+ user_from_token: auth::UserFromToken,
+) -> UserResponse<Vec<user_api::ListMerchantsForUserInOrgResponse>> {
+ let role_info = roles::RoleInfo::from_role_id(
+ &state,
+ &user_from_token.role_id,
+ &user_from_token.merchant_id,
+ &user_from_token.org_id,
+ )
+ .await
+ .change_context(UserErrors::InternalServerError)?;
+ let merchant_accounts = if role_info.get_entity_type() == EntityType::Organization {
+ state
+ .store
+ .list_merchant_accounts_by_organization_id(
+ &(&state).into(),
+ user_from_token.org_id.get_string_repr(),
+ )
+ .await
+ .change_context(UserErrors::InternalServerError)?
+ .into_iter()
+ .map(
+ |merchant_account| user_api::ListMerchantsForUserInOrgResponse {
+ merchant_name: merchant_account.merchant_name.clone(),
+ merchant_id: merchant_account.get_id().to_owned(),
+ },
+ )
+ .collect()
+ } else {
+ let merchant_ids = state
+ .store
+ .list_user_roles(
+ user_from_token.user_id.as_str(),
+ Some(&user_from_token.org_id),
+ None,
+ None,
+ None,
+ None,
+ )
+ .await
+ .change_context(UserErrors::InternalServerError)?
+ .into_iter()
+ .filter_map(|user_role| {
+ (user_role.status == UserStatus::Active)
+ .then_some(user_role.merchant_id)
+ .flatten()
+ })
+ .collect::<HashSet<_>>()
+ .into_iter()
+ .collect();
+ state
+ .store
+ .list_multiple_merchant_accounts(&(&state).into(), merchant_ids)
+ .await
+ .change_context(UserErrors::InternalServerError)?
+ .into_iter()
+ .map(
+ |merchant_account| user_api::ListMerchantsForUserInOrgResponse {
+ merchant_name: merchant_account.merchant_name.clone(),
+ merchant_id: merchant_account.get_id().to_owned(),
+ },
+ )
+ .collect()
+ };
+
+ Ok(ApplicationResponse::Json(merchant_accounts))
+}
+
+pub async fn list_profiles_for_user_in_org_and_merchant_account(
+ state: SessionState,
+ user_from_token: auth::UserFromToken,
+) -> UserResponse<Vec<user_api::ListProfilesForUserInOrgAndMerchantAccountResponse>> {
+ let role_info = roles::RoleInfo::from_role_id(
+ &state,
+ &user_from_token.role_id,
+ &user_from_token.merchant_id,
+ &user_from_token.org_id,
+ )
+ .await
+ .change_context(UserErrors::InternalServerError)?;
+
+ let key_manager_state = &(&state).into();
+ let key_store = state
+ .store
+ .get_merchant_key_store_by_merchant_id(
+ key_manager_state,
+ &user_from_token.merchant_id,
+ &state.store.get_master_key().to_vec().into(),
+ )
+ .await
+ .change_context(UserErrors::InternalServerError)?;
+ let user_role_level = role_info.get_entity_type();
+ let profiles =
+ if user_role_level == EntityType::Organization || user_role_level == EntityType::Merchant {
+ state
+ .store
+ .list_business_profile_by_merchant_id(
+ key_manager_state,
+ &key_store,
+ &user_from_token.merchant_id,
+ )
+ .await
+ .change_context(UserErrors::InternalServerError)?
+ .into_iter()
+ .map(
+ |profile| user_api::ListProfilesForUserInOrgAndMerchantAccountResponse {
+ profile_id: profile.profile_id,
+ profile_name: profile.profile_name,
+ },
+ )
+ .collect()
+ } else {
+ let profile_ids = state
+ .store
+ .list_user_roles(
+ user_from_token.user_id.as_str(),
+ Some(&user_from_token.org_id),
+ Some(&user_from_token.merchant_id),
+ None,
+ None,
+ None,
+ )
+ .await
+ .change_context(UserErrors::InternalServerError)?
+ .into_iter()
+ .filter_map(|user_role| {
+ (user_role.status == UserStatus::Active)
+ .then_some(user_role.profile_id)
+ .flatten()
+ })
+ .collect::<HashSet<_>>();
+
+ futures::future::try_join_all(profile_ids.iter().map(|profile_id| {
+ state.store.find_business_profile_by_profile_id(
+ key_manager_state,
+ &key_store,
+ profile_id,
+ )
+ }))
+ .await
+ .change_context(UserErrors::InternalServerError)?
+ .into_iter()
+ .map(
+ |profile| user_api::ListProfilesForUserInOrgAndMerchantAccountResponse {
+ profile_id: profile.profile_id,
+ profile_name: profile.profile_name,
+ },
+ )
+ .collect()
+ };
+
+ Ok(ApplicationResponse::Json(profiles))
+}
diff --git a/crates/router/src/db/kafka_store.rs b/crates/router/src/db/kafka_store.rs
index c22f327983a..cb3f6db144e 100644
--- a/crates/router/src/db/kafka_store.rs
+++ b/crates/router/src/db/kafka_store.rs
@@ -2871,6 +2871,20 @@ impl UserRoleInterface for KafkaStore {
.list_user_roles_by_merchant_id(merchant_id, version)
.await
}
+
+ async fn list_user_roles(
+ &self,
+ user_id: &str,
+ org_id: Option<&id_type::OrganizationId>,
+ merchant_id: Option<&id_type::MerchantId>,
+ profile_id: Option<&String>,
+ entity_id: Option<&String>,
+ version: Option<enums::UserRoleVersion>,
+ ) -> CustomResult<Vec<storage::UserRole>, errors::StorageError> {
+ self.diesel_store
+ .list_user_roles(user_id, org_id, merchant_id, profile_id, entity_id, version)
+ .await
+ }
}
#[async_trait::async_trait]
diff --git a/crates/router/src/db/user_role.rs b/crates/router/src/db/user_role.rs
index a93aeb1ce34..f028437b346 100644
--- a/crates/router/src/db/user_role.rs
+++ b/crates/router/src/db/user_role.rs
@@ -69,6 +69,16 @@ pub trait UserRoleInterface {
profile_id: Option<&String>,
version: enums::UserRoleVersion,
) -> CustomResult<storage::UserRole, errors::StorageError>;
+
+ async fn list_user_roles(
+ &self,
+ user_id: &str,
+ org_id: Option<&id_type::OrganizationId>,
+ merchant_id: Option<&id_type::MerchantId>,
+ profile_id: Option<&String>,
+ entity_id: Option<&String>,
+ version: Option<enums::UserRoleVersion>,
+ ) -> CustomResult<Vec<storage::UserRole>, errors::StorageError>;
}
#[async_trait::async_trait]
@@ -206,6 +216,29 @@ impl UserRoleInterface for Store {
.await
.map_err(|error| report!(errors::StorageError::from(error)))
}
+
+ async fn list_user_roles(
+ &self,
+ user_id: &str,
+ org_id: Option<&id_type::OrganizationId>,
+ merchant_id: Option<&id_type::MerchantId>,
+ profile_id: Option<&String>,
+ entity_id: Option<&String>,
+ version: Option<enums::UserRoleVersion>,
+ ) -> CustomResult<Vec<storage::UserRole>, errors::StorageError> {
+ let conn = connection::pg_connection_read(self).await?;
+ storage::UserRole::generic_user_roles_list(
+ &conn,
+ user_id.to_owned(),
+ org_id.cloned(),
+ merchant_id.cloned(),
+ profile_id.cloned(),
+ entity_id.cloned(),
+ version,
+ )
+ .await
+ .map_err(|error| report!(errors::StorageError::from(error)))
+ }
}
#[async_trait::async_trait]
@@ -471,4 +504,51 @@ impl UserRoleInterface for MockDb {
.into()),
}
}
+
+ async fn list_user_roles(
+ &self,
+ user_id: &str,
+ org_id: Option<&id_type::OrganizationId>,
+ merchant_id: Option<&id_type::MerchantId>,
+ profile_id: Option<&String>,
+ entity_id: Option<&String>,
+ version: Option<enums::UserRoleVersion>,
+ ) -> CustomResult<Vec<storage::UserRole>, errors::StorageError> {
+ let user_roles = self.user_roles.lock().await;
+
+ let filtered_roles: Vec<_> = user_roles
+ .iter()
+ .filter_map(|role| {
+ let mut filter_condition = role.user_id == user_id;
+
+ role.org_id
+ .as_ref()
+ .zip(org_id)
+ .inspect(|(role_org_id, org_id)| {
+ filter_condition = filter_condition && role_org_id == org_id
+ });
+ role.merchant_id.as_ref().zip(merchant_id).inspect(
+ |(role_merchant_id, merchant_id)| {
+ filter_condition = filter_condition && role_merchant_id == merchant_id
+ },
+ );
+ role.profile_id.as_ref().zip(profile_id).inspect(
+ |(role_profile_id, profile_id)| {
+ filter_condition = filter_condition && role_profile_id == profile_id
+ },
+ );
+ role.entity_id
+ .as_ref()
+ .zip(entity_id)
+ .inspect(|(role_entity_id, entity_id)| {
+ filter_condition = filter_condition && role_entity_id == entity_id
+ });
+ version.inspect(|ver| filter_condition = filter_condition && ver == &role.version);
+
+ filter_condition.then(|| role.to_owned())
+ })
+ .collect();
+
+ Ok(filtered_roles)
+ }
}
diff --git a/crates/router/src/routes/app.rs b/crates/router/src/routes/app.rs
index 25e13ba417e..3ec877bdd9f 100644
--- a/crates/router/src/routes/app.rs
+++ b/crates/router/src/routes/app.rs
@@ -1632,6 +1632,18 @@ impl User {
.service(web::resource("/transfer").route(web::post().to(transfer_user_key))),
);
+ route = route.service(
+ web::scope("/list")
+ .service(web::resource("/org").route(web::get().to(list_orgs_for_user)))
+ .service(
+ web::resource("/merchant").route(web::get().to(list_merchants_for_user_in_org)),
+ )
+ .service(
+ web::resource("/profile")
+ .route(web::get().to(list_profiles_for_user_in_org_and_merchant)),
+ ),
+ );
+
// Two factor auth routes
route = route.service(
web::scope("/2fa")
diff --git a/crates/router/src/routes/lock_utils.rs b/crates/router/src/routes/lock_utils.rs
index b08451a870e..e08b477d29a 100644
--- a/crates/router/src/routes/lock_utils.rs
+++ b/crates/router/src/routes/lock_utils.rs
@@ -244,6 +244,9 @@ impl From<Flow> for ApiIdentifier {
| Flow::UserTransferKey
| Flow::GetSsoAuthUrl
| Flow::SignInWithSso
+ | Flow::ListOrgForUser
+ | Flow::ListMerchantsForUserInOrg
+ | Flow::ListProfileForUserInOrgAndMerchant
| Flow::AuthSelect => Self::User,
Flow::ListRoles
diff --git a/crates/router/src/routes/user.rs b/crates/router/src/routes/user.rs
index 39839e423ea..39ec3a24ff2 100644
--- a/crates/router/src/routes/user.rs
+++ b/crates/router/src/routes/user.rs
@@ -914,3 +914,58 @@ pub async fn transfer_user_key(
))
.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
+}
diff --git a/crates/router_env/src/logger/types.rs b/crates/router_env/src/logger/types.rs
index d1e552275ce..4fbbfdf5518 100644
--- a/crates/router_env/src/logger/types.rs
+++ b/crates/router_env/src/logger/types.rs
@@ -456,6 +456,12 @@ pub enum Flow {
SignInWithSso,
/// Auth Select
AuthSelect,
+ /// List Orgs for user
+ ListOrgForUser,
+ /// List Merchants for user in org
+ ListMerchantsForUserInOrg,
+ /// List Profile for user in org and merchant
+ ListProfileForUserInOrgAndMerchant,
/// List initial webhook delivery attempts
WebhookEventInitialDeliveryAttemptList,
/// List delivery attempts for a webhook event
|
2024-08-21T19:18:51Z
|
## Type of Change
<!-- Put an `x` in the boxes that apply -->
- [ ] Bugfix
- [X] New feature
- [ ] Enhancement
- [ ] Refactoring
- [ ] Dependency updates
- [ ] Documentation
- [ ] CI/CD
## Description
New APIs list:
- orgs for a user.
- merchant accounts for a user in current organisation.
- profile id for a user in current merchant account.
<!-- Describe your changes in detail -->
### Additional Changes
- [X] This PR modifies the API contract
- [ ] This PR modifies the database schema
- [ ] This PR modifies application configuration/environment variables
<!--
Provide links to the files with corresponding changes.
Following are the paths where you can find config files:
1. `config`
2. `crates/router/src/configs`
3. `loadtest/config`
-->
## Motivation and Context
Need new list apis for dashboard frontend.
This would allow user to see the list of all the orgs, merchant accounts (in select org) & profile ids (in select merchant account).
<!--
Why is this change required? What problem does it solve?
If it fixes an open issue, please link to the issue here.
If you don't have an issue, we'd recommend starting with one first so the PR
can focus on the implementation (unless it is an obvious bug or documentation fix
that will have little conversation).
-->
## How did you test it?
List orgs
```sh
curl --location 'localhost:8080/user/list/org' \
--header 'Authorization: Bearer <JWT>' \
```
response example
```json
[
{
"org_id": "org_t4ryeBxwt9RKu8jlsTWq",
"org_name": "Juspay"
},
{
"org_id": "org_t4ryeBxwt9RKu8jlsTWq2",
"org_name": "Juspay2"
}
]
```
List merchants
```sh
curl --location 'localhost:8080/user/list/merchant' \
--header 'Authorization: Bearer <JWT>' \
```
response example
```json
[
{
"merchant_id": "juspay",
"merchant_name": "Juspay"
},
{
"merchant_id": "merchant_1724247367",
"merchant_name": "Juspay"
}
]
```
List profile
```sh
curl --location 'localhost:8080/user/list/profile' \
--header 'Authorization: Bearer <JWT>' \
```
response example
```json
[
{
"profile_id": "pro_S2E1iXeSzluIrIqH7DNi",
"profile_name": "default"
},
{
"profile_id": "pro_S2E1iXeSzluIrIqH7DNi2",
"profile_name": "profile2"
}
]
```
<!--
Did you write an integration/unit/API test to verify the code changes?
Or did you test this change manually (provide relevant screenshots)?
-->
## Checklist
<!-- Put an `x` in the boxes that apply -->
- [X] I formatted the code `cargo +nightly fmt --all`
- [X] I addressed lints thrown by `cargo clippy`
- [X] I reviewed the submitted code
- [ ] I added unit tests for my changes where possible
|
ca72fedae82194abb7216854c7dd61c64d57b1d6
|
|
juspay/hyperswitch
|
juspay__hyperswitch-5683
|
Bug: [FEATURE] Add template code for Novalnet
### Feature Description
Add template code for Novalnet
### Possible Implementation
Add template code for Novalnet
### Have you spent some time checking if this feature request has been raised before?
- [X] I checked and didn't find a similar issue
### Have you read the Contributing Guidelines?
- [X] I have read the [Contributing Guidelines](https://github.com/juspay/hyperswitch/blob/main/docs/CONTRIBUTING.md)
### Are you willing to submit a PR?
Yes, I am willing to submit a PR!
|
diff --git a/config/config.example.toml b/config/config.example.toml
index ebadc9edae7..d71846dab6f 100644
--- a/config/config.example.toml
+++ b/config/config.example.toml
@@ -223,6 +223,7 @@ netcetera.base_url = "https://{{merchant_endpoint_prefix}}.3ds-server.prev.netce
nexinets.base_url = "https://apitest.payengine.de/v1"
nmi.base_url = "https://secure.nmi.com/"
noon.base_url = "https://api-test.noonpayments.com/"
+novalnet.base_url = "https://payport.novalnet.de/v2"
noon.key_mode = "Test"
nuvei.base_url = "https://ppp-test.nuvei.com/"
opayo.base_url = "https://pi-test.sagepay.com/"
diff --git a/config/deployments/integration_test.toml b/config/deployments/integration_test.toml
index 84652e11b0a..dc95ef11234 100644
--- a/config/deployments/integration_test.toml
+++ b/config/deployments/integration_test.toml
@@ -46,6 +46,7 @@ dummyconnector.base_url = "http://localhost:8080/dummy-connector"
ebanx.base_url = "https://sandbox.ebanxpay.com/"
fiserv.base_url = "https://cert.api.fiservapps.com/"
fiservemea.base_url = "https://prod.emea.api.fiservapps.com/sandbox/ipp/payments-gateway/v2"
+novalnet.base_url = "https://payport.novalnet.de/v2"
forte.base_url = "https://sandbox.forte.net/api/v3"
globalpay.base_url = "https://apis.sandbox.globalpay.com/ucp/"
globepay.base_url = "https://pay.globepay.co/"
diff --git a/config/deployments/production.toml b/config/deployments/production.toml
index bac5ec206e6..259a84e8651 100644
--- a/config/deployments/production.toml
+++ b/config/deployments/production.toml
@@ -50,6 +50,7 @@ dummyconnector.base_url = "http://localhost:8080/dummy-connector"
ebanx.base_url = "https://sandbox.ebanxpay.com/"
fiserv.base_url = "https://cert.api.fiservapps.com/"
fiservemea.base_url = "https://prod.emea.api.fiservapps.com/ipp/payments-gateway/v2"
+novalnet.base_url = "https://payport.novalnet.de/v2"
forte.base_url = "https://sandbox.forte.net/api/v3"
globalpay.base_url = "https://apis.sandbox.globalpay.com/ucp/"
globepay.base_url = "https://pay.globepay.co/"
diff --git a/config/deployments/sandbox.toml b/config/deployments/sandbox.toml
index 669daa10162..b5d385850f7 100644
--- a/config/deployments/sandbox.toml
+++ b/config/deployments/sandbox.toml
@@ -50,6 +50,7 @@ dummyconnector.base_url = "http://localhost:8080/dummy-connector"
ebanx.base_url = "https://sandbox.ebanxpay.com/"
fiserv.base_url = "https://cert.api.fiservapps.com/"
fiservemea.base_url = "https://prod.emea.api.fiservapps.com/sandbox/ipp/payments-gateway/v2"
+novalnet.base_url = "https://payport.novalnet.de/v2"
forte.base_url = "https://sandbox.forte.net/api/v3"
globalpay.base_url = "https://apis.sandbox.globalpay.com/ucp/"
globepay.base_url = "https://pay.globepay.co/"
diff --git a/config/development.toml b/config/development.toml
index 8facb9e803b..dc5f66e4293 100644
--- a/config/development.toml
+++ b/config/development.toml
@@ -133,6 +133,7 @@ cards = [
"nexinets",
"nmi",
"noon",
+ "novalnet",
"nuvei",
"opayo",
"opennode",
@@ -227,6 +228,7 @@ netcetera.base_url = "https://{{merchant_endpoint_prefix}}.3ds-server.prev.netce
nexinets.base_url = "https://apitest.payengine.de/v1"
nmi.base_url = "https://secure.nmi.com/"
noon.base_url = "https://api-test.noonpayments.com/"
+novalnet.base_url = "https://payport.novalnet.de/v2"
noon.key_mode = "Test"
nuvei.base_url = "https://ppp-test.nuvei.com/"
opayo.base_url = "https://pi-test.sagepay.com/"
diff --git a/config/docker_compose.toml b/config/docker_compose.toml
index 41f9cf6cfaf..4435488cd7e 100644
--- a/config/docker_compose.toml
+++ b/config/docker_compose.toml
@@ -152,6 +152,7 @@ netcetera.base_url = "https://{{merchant_endpoint_prefix}}.3ds-server.prev.netce
nexinets.base_url = "https://apitest.payengine.de/v1"
nmi.base_url = "https://secure.nmi.com/"
noon.base_url = "https://api-test.noonpayments.com/"
+novalnet.base_url = "https://payport.novalnet.de/v2"
noon.key_mode = "Test"
nuvei.base_url = "https://ppp-test.nuvei.com/"
opayo.base_url = "https://pi-test.sagepay.com/"
@@ -236,6 +237,7 @@ cards = [
"nexinets",
"nmi",
"noon",
+ "novalnet",
"nuvei",
"opayo",
"opennode",
diff --git a/crates/api_models/src/enums.rs b/crates/api_models/src/enums.rs
index a7738133ca0..86d6421c3e2 100644
--- a/crates/api_models/src/enums.rs
+++ b/crates/api_models/src/enums.rs
@@ -46,6 +46,7 @@ pub enum RoutingAlgorithm {
#[serde(rename_all = "snake_case")]
#[strum(serialize_all = "snake_case")]
pub enum Connector {
+ // Novalnet,
// Fiservemea,
Adyenplatform,
#[cfg(feature = "dummy_connector")]
@@ -209,6 +210,7 @@ impl Connector {
| Self::DummyConnector7 => false,
Self::Aci
// Add Separate authentication support for connectors
+ // | Self::Novalnet
// | Self::Taxjar
// | Self::Fiservemea
| Self::Adyen
diff --git a/crates/common_enums/src/enums.rs b/crates/common_enums/src/enums.rs
index 8df5885e7b6..617d121c63c 100644
--- a/crates/common_enums/src/enums.rs
+++ b/crates/common_enums/src/enums.rs
@@ -225,6 +225,7 @@ pub enum RoutableConnectors {
Nexinets,
Nmi,
Noon,
+ // Novalnet,
Nuvei,
// Opayo, added as template code for future usage
Opennode,
diff --git a/crates/hyperswitch_connectors/src/connectors.rs b/crates/hyperswitch_connectors/src/connectors.rs
index ae0fa945799..dfaffd02662 100644
--- a/crates/hyperswitch_connectors/src/connectors.rs
+++ b/crates/hyperswitch_connectors/src/connectors.rs
@@ -3,10 +3,11 @@ pub mod bitpay;
pub mod fiserv;
pub mod fiservemea;
pub mod helcim;
+pub mod novalnet;
pub mod stax;
pub mod taxjar;
pub use self::{
bambora::Bambora, bitpay::Bitpay, fiserv::Fiserv, fiservemea::Fiservemea, helcim::Helcim,
- stax::Stax, taxjar::Taxjar,
+ novalnet::Novalnet, stax::Stax, taxjar::Taxjar,
};
diff --git a/crates/hyperswitch_connectors/src/connectors/novalnet.rs b/crates/hyperswitch_connectors/src/connectors/novalnet.rs
new file mode 100644
index 00000000000..83a8015e73c
--- /dev/null
+++ b/crates/hyperswitch_connectors/src/connectors/novalnet.rs
@@ -0,0 +1,566 @@
+pub mod transformers;
+
+use common_utils::{
+ errors::CustomResult,
+ ext_traits::BytesExt,
+ request::{Method, Request, RequestBuilder, RequestContent},
+ types::{AmountConvertor, StringMinorUnit, StringMinorUnitForConnector},
+};
+use error_stack::{report, ResultExt};
+use hyperswitch_domain_models::{
+ router_data::{AccessToken, ConnectorAuthType, ErrorResponse, RouterData},
+ router_flow_types::{
+ access_token_auth::AccessTokenAuth,
+ payments::{Authorize, Capture, PSync, PaymentMethodToken, Session, SetupMandate, Void},
+ refunds::{Execute, RSync},
+ },
+ router_request_types::{
+ AccessTokenRequestData, PaymentMethodTokenizationData, PaymentsAuthorizeData,
+ PaymentsCancelData, PaymentsCaptureData, PaymentsSessionData, PaymentsSyncData,
+ RefundsData, SetupMandateRequestData,
+ },
+ router_response_types::{PaymentsResponseData, RefundsResponseData},
+ types::{
+ PaymentsAuthorizeRouterData, PaymentsCaptureRouterData, PaymentsSyncRouterData,
+ RefundSyncRouterData, RefundsRouterData,
+ },
+};
+use hyperswitch_interfaces::{
+ api::{self, ConnectorCommon, ConnectorCommonExt, ConnectorIntegration, ConnectorValidation},
+ configs::Connectors,
+ errors,
+ events::connector_api_logs::ConnectorEvent,
+ types::{self, Response},
+ webhooks,
+};
+use masking::{ExposeInterface, Mask};
+use transformers as novalnet;
+
+use crate::{constants::headers, types::ResponseRouterData, utils};
+
+#[derive(Clone)]
+pub struct Novalnet {
+ amount_converter: &'static (dyn AmountConvertor<Output = StringMinorUnit> + Sync),
+}
+
+impl Novalnet {
+ pub fn new() -> &'static Self {
+ &Self {
+ amount_converter: &StringMinorUnitForConnector,
+ }
+ }
+}
+
+impl api::Payment for Novalnet {}
+impl api::PaymentSession for Novalnet {}
+impl api::ConnectorAccessToken for Novalnet {}
+impl api::MandateSetup for Novalnet {}
+impl api::PaymentAuthorize for Novalnet {}
+impl api::PaymentSync for Novalnet {}
+impl api::PaymentCapture for Novalnet {}
+impl api::PaymentVoid for Novalnet {}
+impl api::Refund for Novalnet {}
+impl api::RefundExecute for Novalnet {}
+impl api::RefundSync for Novalnet {}
+impl api::PaymentToken for Novalnet {}
+
+impl ConnectorIntegration<PaymentMethodToken, PaymentMethodTokenizationData, PaymentsResponseData>
+ for Novalnet
+{
+ // Not Implemented (R)
+}
+
+impl<Flow, Request, Response> ConnectorCommonExt<Flow, Request, Response> for Novalnet
+where
+ Self: ConnectorIntegration<Flow, Request, Response>,
+{
+ fn build_headers(
+ &self,
+ req: &RouterData<Flow, Request, Response>,
+ _connectors: &Connectors,
+ ) -> CustomResult<Vec<(String, masking::Maskable<String>)>, errors::ConnectorError> {
+ let mut header = vec![(
+ headers::CONTENT_TYPE.to_string(),
+ self.get_content_type().to_string().into(),
+ )];
+ let mut api_key = self.get_auth_header(&req.connector_auth_type)?;
+ header.append(&mut api_key);
+ Ok(header)
+ }
+}
+
+impl ConnectorCommon for Novalnet {
+ fn id(&self) -> &'static str {
+ "novalnet"
+ }
+
+ fn get_currency_unit(&self) -> api::CurrencyUnit {
+ api::CurrencyUnit::Base
+ // TODO! Check connector documentation, on which unit they are processing the currency.
+ // If the connector accepts amount in lower unit ( i.e cents for USD) then return api::CurrencyUnit::Minor,
+ // if connector accepts amount in base unit (i.e dollars for USD) then return api::CurrencyUnit::Base
+ }
+
+ fn common_get_content_type(&self) -> &'static str {
+ "application/json"
+ }
+
+ fn base_url<'a>(&self, connectors: &'a Connectors) -> &'a str {
+ connectors.novalnet.base_url.as_ref()
+ }
+
+ fn get_auth_header(
+ &self,
+ auth_type: &ConnectorAuthType,
+ ) -> CustomResult<Vec<(String, masking::Maskable<String>)>, errors::ConnectorError> {
+ let auth = novalnet::NovalnetAuthType::try_from(auth_type)
+ .change_context(errors::ConnectorError::FailedToObtainAuthType)?;
+ Ok(vec![(
+ headers::AUTHORIZATION.to_string(),
+ auth.api_key.expose().into_masked(),
+ )])
+ }
+
+ fn build_error_response(
+ &self,
+ res: Response,
+ event_builder: Option<&mut ConnectorEvent>,
+ ) -> CustomResult<ErrorResponse, errors::ConnectorError> {
+ let response: novalnet::NovalnetErrorResponse = res
+ .response
+ .parse_struct("NovalnetErrorResponse")
+ .change_context(errors::ConnectorError::ResponseDeserializationFailed)?;
+
+ event_builder.map(|i| i.set_response_body(&response));
+ router_env::logger::info!(connector_response=?response);
+
+ Ok(ErrorResponse {
+ status_code: res.status_code,
+ code: response.code,
+ message: response.message,
+ reason: response.reason,
+ attempt_status: None,
+ connector_transaction_id: None,
+ })
+ }
+}
+
+impl ConnectorValidation for Novalnet {
+ //TODO: implement functions when support enabled
+}
+
+impl ConnectorIntegration<Session, PaymentsSessionData, PaymentsResponseData> for Novalnet {
+ //TODO: implement sessions flow
+}
+
+impl ConnectorIntegration<AccessTokenAuth, AccessTokenRequestData, AccessToken> for Novalnet {}
+
+impl ConnectorIntegration<SetupMandate, SetupMandateRequestData, PaymentsResponseData>
+ for Novalnet
+{
+}
+
+impl ConnectorIntegration<Authorize, PaymentsAuthorizeData, PaymentsResponseData> for Novalnet {
+ fn get_headers(
+ &self,
+ req: &PaymentsAuthorizeRouterData,
+ connectors: &Connectors,
+ ) -> CustomResult<Vec<(String, masking::Maskable<String>)>, errors::ConnectorError> {
+ self.build_headers(req, connectors)
+ }
+
+ fn get_content_type(&self) -> &'static str {
+ self.common_get_content_type()
+ }
+
+ fn get_url(
+ &self,
+ _req: &PaymentsAuthorizeRouterData,
+ _connectors: &Connectors,
+ ) -> CustomResult<String, errors::ConnectorError> {
+ Err(errors::ConnectorError::NotImplemented("get_url method".to_string()).into())
+ }
+
+ fn get_request_body(
+ &self,
+ req: &PaymentsAuthorizeRouterData,
+ _connectors: &Connectors,
+ ) -> CustomResult<RequestContent, errors::ConnectorError> {
+ let amount = utils::convert_amount(
+ self.amount_converter,
+ req.request.minor_amount,
+ req.request.currency,
+ )?;
+
+ let connector_router_data = novalnet::NovalnetRouterData::from((amount, req));
+ let connector_req = novalnet::NovalnetPaymentsRequest::try_from(&connector_router_data)?;
+ Ok(RequestContent::Json(Box::new(connector_req)))
+ }
+
+ fn build_request(
+ &self,
+ req: &PaymentsAuthorizeRouterData,
+ connectors: &Connectors,
+ ) -> CustomResult<Option<Request>, errors::ConnectorError> {
+ Ok(Some(
+ RequestBuilder::new()
+ .method(Method::Post)
+ .url(&types::PaymentsAuthorizeType::get_url(
+ self, req, connectors,
+ )?)
+ .attach_default_headers()
+ .headers(types::PaymentsAuthorizeType::get_headers(
+ self, req, connectors,
+ )?)
+ .set_body(types::PaymentsAuthorizeType::get_request_body(
+ self, req, connectors,
+ )?)
+ .build(),
+ ))
+ }
+
+ fn handle_response(
+ &self,
+ data: &PaymentsAuthorizeRouterData,
+ event_builder: Option<&mut ConnectorEvent>,
+ res: Response,
+ ) -> CustomResult<PaymentsAuthorizeRouterData, errors::ConnectorError> {
+ let response: novalnet::NovalnetPaymentsResponse = res
+ .response
+ .parse_struct("Novalnet PaymentsAuthorizeResponse")
+ .change_context(errors::ConnectorError::ResponseDeserializationFailed)?;
+ event_builder.map(|i| i.set_response_body(&response));
+ router_env::logger::info!(connector_response=?response);
+ RouterData::try_from(ResponseRouterData {
+ response,
+ data: data.clone(),
+ http_code: res.status_code,
+ })
+ }
+
+ fn get_error_response(
+ &self,
+ res: Response,
+ event_builder: Option<&mut ConnectorEvent>,
+ ) -> CustomResult<ErrorResponse, errors::ConnectorError> {
+ self.build_error_response(res, event_builder)
+ }
+}
+
+impl ConnectorIntegration<PSync, PaymentsSyncData, PaymentsResponseData> for Novalnet {
+ fn get_headers(
+ &self,
+ req: &PaymentsSyncRouterData,
+ connectors: &Connectors,
+ ) -> CustomResult<Vec<(String, masking::Maskable<String>)>, errors::ConnectorError> {
+ self.build_headers(req, connectors)
+ }
+
+ fn get_content_type(&self) -> &'static str {
+ self.common_get_content_type()
+ }
+
+ fn get_url(
+ &self,
+ _req: &PaymentsSyncRouterData,
+ _connectors: &Connectors,
+ ) -> CustomResult<String, errors::ConnectorError> {
+ Err(errors::ConnectorError::NotImplemented("get_url method".to_string()).into())
+ }
+
+ fn build_request(
+ &self,
+ req: &PaymentsSyncRouterData,
+ connectors: &Connectors,
+ ) -> CustomResult<Option<Request>, errors::ConnectorError> {
+ Ok(Some(
+ RequestBuilder::new()
+ .method(Method::Get)
+ .url(&types::PaymentsSyncType::get_url(self, req, connectors)?)
+ .attach_default_headers()
+ .headers(types::PaymentsSyncType::get_headers(self, req, connectors)?)
+ .build(),
+ ))
+ }
+
+ fn handle_response(
+ &self,
+ data: &PaymentsSyncRouterData,
+ event_builder: Option<&mut ConnectorEvent>,
+ res: Response,
+ ) -> CustomResult<PaymentsSyncRouterData, errors::ConnectorError> {
+ let response: novalnet::NovalnetPaymentsResponse = res
+ .response
+ .parse_struct("novalnet PaymentsSyncResponse")
+ .change_context(errors::ConnectorError::ResponseDeserializationFailed)?;
+ event_builder.map(|i| i.set_response_body(&response));
+ router_env::logger::info!(connector_response=?response);
+ RouterData::try_from(ResponseRouterData {
+ response,
+ data: data.clone(),
+ http_code: res.status_code,
+ })
+ }
+
+ fn get_error_response(
+ &self,
+ res: Response,
+ event_builder: Option<&mut ConnectorEvent>,
+ ) -> CustomResult<ErrorResponse, errors::ConnectorError> {
+ self.build_error_response(res, event_builder)
+ }
+}
+
+impl ConnectorIntegration<Capture, PaymentsCaptureData, PaymentsResponseData> for Novalnet {
+ fn get_headers(
+ &self,
+ req: &PaymentsCaptureRouterData,
+ connectors: &Connectors,
+ ) -> CustomResult<Vec<(String, masking::Maskable<String>)>, errors::ConnectorError> {
+ self.build_headers(req, connectors)
+ }
+
+ fn get_content_type(&self) -> &'static str {
+ self.common_get_content_type()
+ }
+
+ fn get_url(
+ &self,
+ _req: &PaymentsCaptureRouterData,
+ _connectors: &Connectors,
+ ) -> CustomResult<String, errors::ConnectorError> {
+ Err(errors::ConnectorError::NotImplemented("get_url method".to_string()).into())
+ }
+
+ fn get_request_body(
+ &self,
+ _req: &PaymentsCaptureRouterData,
+ _connectors: &Connectors,
+ ) -> CustomResult<RequestContent, errors::ConnectorError> {
+ Err(errors::ConnectorError::NotImplemented("get_request_body method".to_string()).into())
+ }
+
+ fn build_request(
+ &self,
+ req: &PaymentsCaptureRouterData,
+ connectors: &Connectors,
+ ) -> CustomResult<Option<Request>, errors::ConnectorError> {
+ Ok(Some(
+ RequestBuilder::new()
+ .method(Method::Post)
+ .url(&types::PaymentsCaptureType::get_url(self, req, connectors)?)
+ .attach_default_headers()
+ .headers(types::PaymentsCaptureType::get_headers(
+ self, req, connectors,
+ )?)
+ .set_body(types::PaymentsCaptureType::get_request_body(
+ self, req, connectors,
+ )?)
+ .build(),
+ ))
+ }
+
+ fn handle_response(
+ &self,
+ data: &PaymentsCaptureRouterData,
+ event_builder: Option<&mut ConnectorEvent>,
+ res: Response,
+ ) -> CustomResult<PaymentsCaptureRouterData, errors::ConnectorError> {
+ let response: novalnet::NovalnetPaymentsResponse = res
+ .response
+ .parse_struct("Novalnet PaymentsCaptureResponse")
+ .change_context(errors::ConnectorError::ResponseDeserializationFailed)?;
+ event_builder.map(|i| i.set_response_body(&response));
+ router_env::logger::info!(connector_response=?response);
+ RouterData::try_from(ResponseRouterData {
+ response,
+ data: data.clone(),
+ http_code: res.status_code,
+ })
+ }
+
+ fn get_error_response(
+ &self,
+ res: Response,
+ event_builder: Option<&mut ConnectorEvent>,
+ ) -> CustomResult<ErrorResponse, errors::ConnectorError> {
+ self.build_error_response(res, event_builder)
+ }
+}
+
+impl ConnectorIntegration<Void, PaymentsCancelData, PaymentsResponseData> for Novalnet {}
+
+impl ConnectorIntegration<Execute, RefundsData, RefundsResponseData> for Novalnet {
+ fn get_headers(
+ &self,
+ req: &RefundsRouterData<Execute>,
+ connectors: &Connectors,
+ ) -> CustomResult<Vec<(String, masking::Maskable<String>)>, errors::ConnectorError> {
+ self.build_headers(req, connectors)
+ }
+
+ fn get_content_type(&self) -> &'static str {
+ self.common_get_content_type()
+ }
+
+ fn get_url(
+ &self,
+ _req: &RefundsRouterData<Execute>,
+ _connectors: &Connectors,
+ ) -> CustomResult<String, errors::ConnectorError> {
+ Err(errors::ConnectorError::NotImplemented("get_url method".to_string()).into())
+ }
+
+ fn get_request_body(
+ &self,
+ req: &RefundsRouterData<Execute>,
+ _connectors: &Connectors,
+ ) -> CustomResult<RequestContent, errors::ConnectorError> {
+ let refund_amount = utils::convert_amount(
+ self.amount_converter,
+ req.request.minor_refund_amount,
+ req.request.currency,
+ )?;
+
+ let connector_router_data = novalnet::NovalnetRouterData::from((refund_amount, req));
+ let connector_req = novalnet::NovalnetRefundRequest::try_from(&connector_router_data)?;
+ Ok(RequestContent::Json(Box::new(connector_req)))
+ }
+
+ fn build_request(
+ &self,
+ req: &RefundsRouterData<Execute>,
+ connectors: &Connectors,
+ ) -> CustomResult<Option<Request>, errors::ConnectorError> {
+ let request = RequestBuilder::new()
+ .method(Method::Post)
+ .url(&types::RefundExecuteType::get_url(self, req, connectors)?)
+ .attach_default_headers()
+ .headers(types::RefundExecuteType::get_headers(
+ self, req, connectors,
+ )?)
+ .set_body(types::RefundExecuteType::get_request_body(
+ self, req, connectors,
+ )?)
+ .build();
+ Ok(Some(request))
+ }
+
+ fn handle_response(
+ &self,
+ data: &RefundsRouterData<Execute>,
+ event_builder: Option<&mut ConnectorEvent>,
+ res: Response,
+ ) -> CustomResult<RefundsRouterData<Execute>, errors::ConnectorError> {
+ let response: novalnet::RefundResponse = res
+ .response
+ .parse_struct("novalnet RefundResponse")
+ .change_context(errors::ConnectorError::ResponseDeserializationFailed)?;
+ event_builder.map(|i| i.set_response_body(&response));
+ router_env::logger::info!(connector_response=?response);
+ RouterData::try_from(ResponseRouterData {
+ response,
+ data: data.clone(),
+ http_code: res.status_code,
+ })
+ }
+
+ fn get_error_response(
+ &self,
+ res: Response,
+ event_builder: Option<&mut ConnectorEvent>,
+ ) -> CustomResult<ErrorResponse, errors::ConnectorError> {
+ self.build_error_response(res, event_builder)
+ }
+}
+
+impl ConnectorIntegration<RSync, RefundsData, RefundsResponseData> for Novalnet {
+ fn get_headers(
+ &self,
+ req: &RefundSyncRouterData,
+ connectors: &Connectors,
+ ) -> CustomResult<Vec<(String, masking::Maskable<String>)>, errors::ConnectorError> {
+ self.build_headers(req, connectors)
+ }
+
+ fn get_content_type(&self) -> &'static str {
+ self.common_get_content_type()
+ }
+
+ fn get_url(
+ &self,
+ _req: &RefundSyncRouterData,
+ _connectors: &Connectors,
+ ) -> CustomResult<String, errors::ConnectorError> {
+ Err(errors::ConnectorError::NotImplemented("get_url method".to_string()).into())
+ }
+
+ fn build_request(
+ &self,
+ req: &RefundSyncRouterData,
+ connectors: &Connectors,
+ ) -> CustomResult<Option<Request>, errors::ConnectorError> {
+ Ok(Some(
+ RequestBuilder::new()
+ .method(Method::Get)
+ .url(&types::RefundSyncType::get_url(self, req, connectors)?)
+ .attach_default_headers()
+ .headers(types::RefundSyncType::get_headers(self, req, connectors)?)
+ .set_body(types::RefundSyncType::get_request_body(
+ self, req, connectors,
+ )?)
+ .build(),
+ ))
+ }
+
+ fn handle_response(
+ &self,
+ data: &RefundSyncRouterData,
+ event_builder: Option<&mut ConnectorEvent>,
+ res: Response,
+ ) -> CustomResult<RefundSyncRouterData, errors::ConnectorError> {
+ let response: novalnet::RefundResponse = res
+ .response
+ .parse_struct("novalnet RefundSyncResponse")
+ .change_context(errors::ConnectorError::ResponseDeserializationFailed)?;
+ event_builder.map(|i| i.set_response_body(&response));
+ router_env::logger::info!(connector_response=?response);
+ RouterData::try_from(ResponseRouterData {
+ response,
+ data: data.clone(),
+ http_code: res.status_code,
+ })
+ }
+
+ fn get_error_response(
+ &self,
+ res: Response,
+ event_builder: Option<&mut ConnectorEvent>,
+ ) -> CustomResult<ErrorResponse, errors::ConnectorError> {
+ self.build_error_response(res, event_builder)
+ }
+}
+
+#[async_trait::async_trait]
+impl webhooks::IncomingWebhook for Novalnet {
+ fn get_webhook_object_reference_id(
+ &self,
+ _request: &webhooks::IncomingWebhookRequestDetails<'_>,
+ ) -> CustomResult<api_models::webhooks::ObjectReferenceId, errors::ConnectorError> {
+ Err(report!(errors::ConnectorError::WebhooksNotImplemented))
+ }
+
+ fn get_webhook_event_type(
+ &self,
+ _request: &webhooks::IncomingWebhookRequestDetails<'_>,
+ ) -> CustomResult<api_models::webhooks::IncomingWebhookEvent, errors::ConnectorError> {
+ Err(report!(errors::ConnectorError::WebhooksNotImplemented))
+ }
+
+ fn get_webhook_resource_object(
+ &self,
+ _request: &webhooks::IncomingWebhookRequestDetails<'_>,
+ ) -> CustomResult<Box<dyn masking::ErasedMaskSerialize>, errors::ConnectorError> {
+ Err(report!(errors::ConnectorError::WebhooksNotImplemented))
+ }
+}
diff --git a/crates/hyperswitch_connectors/src/connectors/novalnet/transformers.rs b/crates/hyperswitch_connectors/src/connectors/novalnet/transformers.rs
new file mode 100644
index 00000000000..de63e9b48c0
--- /dev/null
+++ b/crates/hyperswitch_connectors/src/connectors/novalnet/transformers.rs
@@ -0,0 +1,228 @@
+use common_enums::enums;
+use common_utils::types::StringMinorUnit;
+use hyperswitch_domain_models::{
+ payment_method_data::PaymentMethodData,
+ router_data::{ConnectorAuthType, RouterData},
+ router_flow_types::refunds::{Execute, RSync},
+ router_request_types::ResponseId,
+ router_response_types::{PaymentsResponseData, RefundsResponseData},
+ types::{PaymentsAuthorizeRouterData, RefundsRouterData},
+};
+use hyperswitch_interfaces::errors;
+use masking::Secret;
+use serde::{Deserialize, Serialize};
+
+use crate::{
+ types::{RefundsResponseRouterData, ResponseRouterData},
+ utils::PaymentsAuthorizeRequestData,
+};
+
+//TODO: Fill the struct with respective fields
+pub struct NovalnetRouterData<T> {
+ pub amount: StringMinorUnit, // The type of amount that a connector accepts, for example, String, i64, f64, etc.
+ pub router_data: T,
+}
+
+impl<T> From<(StringMinorUnit, T)> for NovalnetRouterData<T> {
+ fn from((amount, item): (StringMinorUnit, T)) -> Self {
+ //Todo : use utils to convert the amount to the type of amount that a connector accepts
+ Self {
+ amount,
+ router_data: item,
+ }
+ }
+}
+
+//TODO: Fill the struct with respective fields
+#[derive(Default, Debug, Serialize, PartialEq)]
+pub struct NovalnetPaymentsRequest {
+ amount: StringMinorUnit,
+ card: NovalnetCard,
+}
+
+#[derive(Default, Debug, Serialize, Eq, PartialEq)]
+pub struct NovalnetCard {
+ number: cards::CardNumber,
+ expiry_month: Secret<String>,
+ expiry_year: Secret<String>,
+ cvc: Secret<String>,
+ complete: bool,
+}
+
+impl TryFrom<&NovalnetRouterData<&PaymentsAuthorizeRouterData>> for NovalnetPaymentsRequest {
+ type Error = error_stack::Report<errors::ConnectorError>;
+ fn try_from(
+ item: &NovalnetRouterData<&PaymentsAuthorizeRouterData>,
+ ) -> Result<Self, Self::Error> {
+ match item.router_data.request.payment_method_data.clone() {
+ PaymentMethodData::Card(req_card) => {
+ let card = NovalnetCard {
+ number: req_card.card_number,
+ expiry_month: req_card.card_exp_month,
+ expiry_year: req_card.card_exp_year,
+ cvc: req_card.card_cvc,
+ complete: item.router_data.request.is_auto_capture()?,
+ };
+ Ok(Self {
+ amount: item.amount.clone(),
+ card,
+ })
+ }
+ _ => Err(errors::ConnectorError::NotImplemented("Payment methods".to_string()).into()),
+ }
+ }
+}
+
+//TODO: Fill the struct with respective fields
+// Auth Struct
+pub struct NovalnetAuthType {
+ pub(super) api_key: Secret<String>,
+}
+
+impl TryFrom<&ConnectorAuthType> for NovalnetAuthType {
+ type Error = error_stack::Report<errors::ConnectorError>;
+ fn try_from(auth_type: &ConnectorAuthType) -> Result<Self, Self::Error> {
+ match auth_type {
+ ConnectorAuthType::HeaderKey { api_key } => Ok(Self {
+ api_key: api_key.to_owned(),
+ }),
+ _ => Err(errors::ConnectorError::FailedToObtainAuthType.into()),
+ }
+ }
+}
+// PaymentsResponse
+//TODO: Append the remaining status flags
+#[derive(Debug, Clone, Default, Serialize, Deserialize, PartialEq)]
+#[serde(rename_all = "lowercase")]
+pub enum NovalnetPaymentStatus {
+ Succeeded,
+ Failed,
+ #[default]
+ Processing,
+}
+
+impl From<NovalnetPaymentStatus> for common_enums::AttemptStatus {
+ fn from(item: NovalnetPaymentStatus) -> Self {
+ match item {
+ NovalnetPaymentStatus::Succeeded => Self::Charged,
+ NovalnetPaymentStatus::Failed => Self::Failure,
+ NovalnetPaymentStatus::Processing => Self::Authorizing,
+ }
+ }
+}
+
+//TODO: Fill the struct with respective fields
+#[derive(Default, Debug, Clone, Serialize, Deserialize, PartialEq)]
+pub struct NovalnetPaymentsResponse {
+ status: NovalnetPaymentStatus,
+ id: String,
+}
+
+impl<F, T> TryFrom<ResponseRouterData<F, NovalnetPaymentsResponse, T, PaymentsResponseData>>
+ for RouterData<F, T, PaymentsResponseData>
+{
+ type Error = error_stack::Report<errors::ConnectorError>;
+ fn try_from(
+ item: ResponseRouterData<F, NovalnetPaymentsResponse, T, PaymentsResponseData>,
+ ) -> Result<Self, Self::Error> {
+ Ok(Self {
+ status: common_enums::AttemptStatus::from(item.response.status),
+ response: Ok(PaymentsResponseData::TransactionResponse {
+ resource_id: ResponseId::ConnectorTransactionId(item.response.id),
+ redirection_data: None,
+ mandate_reference: None,
+ connector_metadata: None,
+ network_txn_id: None,
+ connector_response_reference_id: None,
+ incremental_authorization_allowed: None,
+ charge_id: None,
+ }),
+ ..item.data
+ })
+ }
+}
+
+//TODO: Fill the struct with respective fields
+// REFUND :
+// Type definition for RefundRequest
+#[derive(Default, Debug, Serialize)]
+pub struct NovalnetRefundRequest {
+ pub amount: StringMinorUnit,
+}
+
+impl<F> TryFrom<&NovalnetRouterData<&RefundsRouterData<F>>> for NovalnetRefundRequest {
+ type Error = error_stack::Report<errors::ConnectorError>;
+ fn try_from(item: &NovalnetRouterData<&RefundsRouterData<F>>) -> Result<Self, Self::Error> {
+ Ok(Self {
+ amount: item.amount.to_owned(),
+ })
+ }
+}
+
+// Type definition for Refund Response
+
+#[allow(dead_code)]
+#[derive(Debug, Serialize, Default, Deserialize, Clone)]
+pub enum RefundStatus {
+ Succeeded,
+ Failed,
+ #[default]
+ Processing,
+}
+
+impl From<RefundStatus> for enums::RefundStatus {
+ fn from(item: RefundStatus) -> Self {
+ match item {
+ RefundStatus::Succeeded => Self::Success,
+ RefundStatus::Failed => Self::Failure,
+ RefundStatus::Processing => Self::Pending,
+ //TODO: Review mapping
+ }
+ }
+}
+
+//TODO: Fill the struct with respective fields
+#[derive(Default, Debug, Clone, Serialize, Deserialize)]
+pub struct RefundResponse {
+ id: String,
+ status: RefundStatus,
+}
+
+impl TryFrom<RefundsResponseRouterData<Execute, RefundResponse>> for RefundsRouterData<Execute> {
+ type Error = error_stack::Report<errors::ConnectorError>;
+ fn try_from(
+ item: RefundsResponseRouterData<Execute, RefundResponse>,
+ ) -> Result<Self, Self::Error> {
+ Ok(Self {
+ response: Ok(RefundsResponseData {
+ connector_refund_id: item.response.id.to_string(),
+ refund_status: enums::RefundStatus::from(item.response.status),
+ }),
+ ..item.data
+ })
+ }
+}
+
+impl TryFrom<RefundsResponseRouterData<RSync, RefundResponse>> for RefundsRouterData<RSync> {
+ type Error = error_stack::Report<errors::ConnectorError>;
+ fn try_from(
+ item: RefundsResponseRouterData<RSync, RefundResponse>,
+ ) -> Result<Self, Self::Error> {
+ Ok(Self {
+ response: Ok(RefundsResponseData {
+ connector_refund_id: item.response.id.to_string(),
+ refund_status: enums::RefundStatus::from(item.response.status),
+ }),
+ ..item.data
+ })
+ }
+}
+
+//TODO: Fill the struct with respective fields
+#[derive(Default, Debug, Serialize, Deserialize, PartialEq)]
+pub struct NovalnetErrorResponse {
+ pub status_code: u16,
+ pub code: String,
+ pub message: String,
+ pub reason: Option<String>,
+}
diff --git a/crates/hyperswitch_connectors/src/default_implementations.rs b/crates/hyperswitch_connectors/src/default_implementations.rs
index 9165a1cba53..8da17ae28b0 100644
--- a/crates/hyperswitch_connectors/src/default_implementations.rs
+++ b/crates/hyperswitch_connectors/src/default_implementations.rs
@@ -91,6 +91,7 @@ default_imp_for_authorize_session_token!(
connectors::Fiserv,
connectors::Fiservemea,
connectors::Helcim,
+ connectors::Novalnet,
connectors::Stax,
connectors::Taxjar
);
@@ -116,6 +117,7 @@ default_imp_for_complete_authorize!(
connectors::Fiserv,
connectors::Fiservemea,
connectors::Helcim,
+ connectors::Novalnet,
connectors::Stax,
connectors::Taxjar
);
@@ -141,6 +143,7 @@ default_imp_for_incremental_authorization!(
connectors::Fiserv,
connectors::Fiservemea,
connectors::Helcim,
+ connectors::Novalnet,
connectors::Stax,
connectors::Taxjar
);
@@ -166,6 +169,7 @@ default_imp_for_create_customer!(
connectors::Fiserv,
connectors::Fiservemea,
connectors::Helcim,
+ connectors::Novalnet,
connectors::Taxjar
);
@@ -191,6 +195,7 @@ default_imp_for_connector_redirect_response!(
connectors::Fiserv,
connectors::Fiservemea,
connectors::Helcim,
+ connectors::Novalnet,
connectors::Stax,
connectors::Taxjar
);
@@ -216,6 +221,7 @@ default_imp_for_pre_processing_steps!(
connectors::Fiserv,
connectors::Fiservemea,
connectors::Helcim,
+ connectors::Novalnet,
connectors::Stax,
connectors::Taxjar
);
@@ -241,6 +247,7 @@ default_imp_for_post_processing_steps!(
connectors::Fiserv,
connectors::Fiservemea,
connectors::Helcim,
+ connectors::Novalnet,
connectors::Stax,
connectors::Taxjar
);
@@ -266,6 +273,7 @@ default_imp_for_approve!(
connectors::Fiserv,
connectors::Fiservemea,
connectors::Helcim,
+ connectors::Novalnet,
connectors::Stax,
connectors::Taxjar
);
@@ -291,6 +299,7 @@ default_imp_for_reject!(
connectors::Fiserv,
connectors::Fiservemea,
connectors::Helcim,
+ connectors::Novalnet,
connectors::Stax,
connectors::Taxjar
);
@@ -316,6 +325,7 @@ default_imp_for_webhook_source_verification!(
connectors::Fiserv,
connectors::Fiservemea,
connectors::Helcim,
+ connectors::Novalnet,
connectors::Stax,
connectors::Taxjar
);
@@ -342,6 +352,7 @@ default_imp_for_accept_dispute!(
connectors::Fiserv,
connectors::Fiservemea,
connectors::Helcim,
+ connectors::Novalnet,
connectors::Stax,
connectors::Taxjar
);
@@ -367,6 +378,7 @@ default_imp_for_submit_evidence!(
connectors::Fiserv,
connectors::Fiservemea,
connectors::Helcim,
+ connectors::Novalnet,
connectors::Stax,
connectors::Taxjar
);
@@ -392,6 +404,7 @@ default_imp_for_defend_dispute!(
connectors::Fiserv,
connectors::Fiservemea,
connectors::Helcim,
+ connectors::Novalnet,
connectors::Stax,
connectors::Taxjar
);
@@ -426,6 +439,7 @@ default_imp_for_file_upload!(
connectors::Fiserv,
connectors::Fiservemea,
connectors::Helcim,
+ connectors::Novalnet,
connectors::Stax,
connectors::Taxjar
);
@@ -453,6 +467,7 @@ default_imp_for_payouts_create!(
connectors::Fiserv,
connectors::Fiservemea,
connectors::Helcim,
+ connectors::Novalnet,
connectors::Stax,
connectors::Taxjar
);
@@ -480,6 +495,7 @@ default_imp_for_payouts_retrieve!(
connectors::Fiserv,
connectors::Fiservemea,
connectors::Helcim,
+ connectors::Novalnet,
connectors::Stax,
connectors::Taxjar
);
@@ -507,6 +523,7 @@ default_imp_for_payouts_eligibility!(
connectors::Fiserv,
connectors::Fiservemea,
connectors::Helcim,
+ connectors::Novalnet,
connectors::Stax,
connectors::Taxjar
);
@@ -534,6 +551,7 @@ default_imp_for_payouts_fulfill!(
connectors::Fiserv,
connectors::Fiservemea,
connectors::Helcim,
+ connectors::Novalnet,
connectors::Stax,
connectors::Taxjar
);
@@ -561,6 +579,7 @@ default_imp_for_payouts_cancel!(
connectors::Fiserv,
connectors::Fiservemea,
connectors::Helcim,
+ connectors::Novalnet,
connectors::Stax,
connectors::Taxjar
);
@@ -588,6 +607,7 @@ default_imp_for_payouts_quote!(
connectors::Fiserv,
connectors::Fiservemea,
connectors::Helcim,
+ connectors::Novalnet,
connectors::Stax,
connectors::Taxjar
);
@@ -615,6 +635,7 @@ default_imp_for_payouts_recipient!(
connectors::Fiserv,
connectors::Fiservemea,
connectors::Helcim,
+ connectors::Novalnet,
connectors::Stax,
connectors::Taxjar
);
@@ -642,6 +663,7 @@ default_imp_for_payouts_recipient_account!(
connectors::Fiserv,
connectors::Fiservemea,
connectors::Helcim,
+ connectors::Novalnet,
connectors::Stax,
connectors::Taxjar
);
@@ -669,6 +691,7 @@ default_imp_for_frm_sale!(
connectors::Fiserv,
connectors::Fiservemea,
connectors::Helcim,
+ connectors::Novalnet,
connectors::Stax,
connectors::Taxjar
);
@@ -696,6 +719,7 @@ default_imp_for_frm_checkout!(
connectors::Fiserv,
connectors::Fiservemea,
connectors::Helcim,
+ connectors::Novalnet,
connectors::Stax,
connectors::Taxjar
);
@@ -723,6 +747,7 @@ default_imp_for_frm_transaction!(
connectors::Fiserv,
connectors::Fiservemea,
connectors::Helcim,
+ connectors::Novalnet,
connectors::Stax,
connectors::Taxjar
);
@@ -750,6 +775,7 @@ default_imp_for_frm_fulfillment!(
connectors::Fiserv,
connectors::Fiservemea,
connectors::Helcim,
+ connectors::Novalnet,
connectors::Stax,
connectors::Taxjar
);
@@ -777,6 +803,7 @@ default_imp_for_frm_record_return!(
connectors::Fiserv,
connectors::Fiservemea,
connectors::Helcim,
+ connectors::Novalnet,
connectors::Stax,
connectors::Taxjar
);
@@ -801,6 +828,7 @@ default_imp_for_revoking_mandates!(
connectors::Fiserv,
connectors::Fiservemea,
connectors::Helcim,
+ connectors::Novalnet,
connectors::Stax,
connectors::Taxjar
);
diff --git a/crates/hyperswitch_connectors/src/default_implementations_v2.rs b/crates/hyperswitch_connectors/src/default_implementations_v2.rs
index c9a1cfde745..4ebd335ce8f 100644
--- a/crates/hyperswitch_connectors/src/default_implementations_v2.rs
+++ b/crates/hyperswitch_connectors/src/default_implementations_v2.rs
@@ -186,6 +186,7 @@ default_imp_for_new_connector_integration_payment!(
connectors::Fiserv,
connectors::Fiservemea,
connectors::Helcim,
+ connectors::Novalnet,
connectors::Stax,
connectors::Taxjar
);
@@ -212,6 +213,7 @@ default_imp_for_new_connector_integration_refund!(
connectors::Fiserv,
connectors::Fiservemea,
connectors::Helcim,
+ connectors::Novalnet,
connectors::Stax,
connectors::Taxjar
);
@@ -233,6 +235,7 @@ default_imp_for_new_connector_integration_connector_access_token!(
connectors::Fiserv,
connectors::Fiservemea,
connectors::Helcim,
+ connectors::Novalnet,
connectors::Stax,
connectors::Taxjar
);
@@ -260,6 +263,7 @@ default_imp_for_new_connector_integration_accept_dispute!(
connectors::Fiserv,
connectors::Fiservemea,
connectors::Helcim,
+ connectors::Novalnet,
connectors::Stax,
connectors::Taxjar
);
@@ -286,6 +290,7 @@ default_imp_for_new_connector_integration_submit_evidence!(
connectors::Fiserv,
connectors::Fiservemea,
connectors::Helcim,
+ connectors::Novalnet,
connectors::Stax,
connectors::Taxjar
);
@@ -312,6 +317,7 @@ default_imp_for_new_connector_integration_defend_dispute!(
connectors::Fiserv,
connectors::Fiservemea,
connectors::Helcim,
+ connectors::Novalnet,
connectors::Stax,
connectors::Taxjar
);
@@ -348,6 +354,7 @@ default_imp_for_new_connector_integration_file_upload!(
connectors::Fiserv,
connectors::Fiservemea,
connectors::Helcim,
+ connectors::Novalnet,
connectors::Stax,
connectors::Taxjar
);
@@ -376,6 +383,7 @@ default_imp_for_new_connector_integration_payouts_create!(
connectors::Fiserv,
connectors::Fiservemea,
connectors::Helcim,
+ connectors::Novalnet,
connectors::Stax,
connectors::Taxjar
);
@@ -404,6 +412,7 @@ default_imp_for_new_connector_integration_payouts_eligibility!(
connectors::Fiserv,
connectors::Fiservemea,
connectors::Helcim,
+ connectors::Novalnet,
connectors::Stax,
connectors::Taxjar
);
@@ -432,6 +441,7 @@ default_imp_for_new_connector_integration_payouts_fulfill!(
connectors::Fiserv,
connectors::Fiservemea,
connectors::Helcim,
+ connectors::Novalnet,
connectors::Stax,
connectors::Taxjar
);
@@ -460,6 +470,7 @@ default_imp_for_new_connector_integration_payouts_cancel!(
connectors::Fiserv,
connectors::Fiservemea,
connectors::Helcim,
+ connectors::Novalnet,
connectors::Stax,
connectors::Taxjar
);
@@ -488,6 +499,7 @@ default_imp_for_new_connector_integration_payouts_quote!(
connectors::Fiserv,
connectors::Fiservemea,
connectors::Helcim,
+ connectors::Novalnet,
connectors::Stax,
connectors::Taxjar
);
@@ -516,6 +528,7 @@ default_imp_for_new_connector_integration_payouts_recipient!(
connectors::Fiserv,
connectors::Fiservemea,
connectors::Helcim,
+ connectors::Novalnet,
connectors::Stax,
connectors::Taxjar
);
@@ -544,6 +557,7 @@ default_imp_for_new_connector_integration_payouts_sync!(
connectors::Fiserv,
connectors::Fiservemea,
connectors::Helcim,
+ connectors::Novalnet,
connectors::Stax,
connectors::Taxjar
);
@@ -572,6 +586,7 @@ default_imp_for_new_connector_integration_payouts_recipient_account!(
connectors::Fiserv,
connectors::Fiservemea,
connectors::Helcim,
+ connectors::Novalnet,
connectors::Stax,
connectors::Taxjar
);
@@ -598,6 +613,7 @@ default_imp_for_new_connector_integration_webhook_source_verification!(
connectors::Fiserv,
connectors::Fiservemea,
connectors::Helcim,
+ connectors::Novalnet,
connectors::Stax,
connectors::Taxjar
);
@@ -626,6 +642,7 @@ default_imp_for_new_connector_integration_frm_sale!(
connectors::Fiserv,
connectors::Fiservemea,
connectors::Helcim,
+ connectors::Novalnet,
connectors::Stax,
connectors::Taxjar
);
@@ -654,6 +671,7 @@ default_imp_for_new_connector_integration_frm_checkout!(
connectors::Fiserv,
connectors::Fiservemea,
connectors::Helcim,
+ connectors::Novalnet,
connectors::Stax,
connectors::Taxjar
);
@@ -682,6 +700,7 @@ default_imp_for_new_connector_integration_frm_transaction!(
connectors::Fiserv,
connectors::Fiservemea,
connectors::Helcim,
+ connectors::Novalnet,
connectors::Stax,
connectors::Taxjar
);
@@ -710,6 +729,7 @@ default_imp_for_new_connector_integration_frm_fulfillment!(
connectors::Fiserv,
connectors::Fiservemea,
connectors::Helcim,
+ connectors::Novalnet,
connectors::Stax,
connectors::Taxjar
);
@@ -738,6 +758,7 @@ default_imp_for_new_connector_integration_frm_record_return!(
connectors::Fiserv,
connectors::Fiservemea,
connectors::Helcim,
+ connectors::Novalnet,
connectors::Stax,
connectors::Taxjar
);
@@ -763,6 +784,7 @@ default_imp_for_new_connector_integration_revoking_mandates!(
connectors::Fiserv,
connectors::Fiservemea,
connectors::Helcim,
+ connectors::Novalnet,
connectors::Stax,
connectors::Taxjar
);
diff --git a/crates/hyperswitch_interfaces/src/configs.rs b/crates/hyperswitch_interfaces/src/configs.rs
index 2a30df3b2cb..2139a68d275 100644
--- a/crates/hyperswitch_interfaces/src/configs.rs
+++ b/crates/hyperswitch_interfaces/src/configs.rs
@@ -54,6 +54,7 @@ pub struct Connectors {
pub nexinets: ConnectorParams,
pub nmi: ConnectorParams,
pub noon: ConnectorParamsWithModeType,
+ pub novalnet: ConnectorParams,
pub nuvei: ConnectorParams,
pub opayo: ConnectorParams,
pub opennode: ConnectorParams,
diff --git a/crates/router/src/connector.rs b/crates/router/src/connector.rs
index eb83e2c4ba6..5da8f3a8578 100644
--- a/crates/router/src/connector.rs
+++ b/crates/router/src/connector.rs
@@ -69,7 +69,8 @@ pub mod zsl;
pub use hyperswitch_connectors::connectors::{
bambora, bambora::Bambora, bitpay, bitpay::Bitpay, fiserv, fiserv::Fiserv, fiservemea,
- fiservemea::Fiservemea, helcim, helcim::Helcim, stax, stax::Stax, taxjar, taxjar::Taxjar,
+ fiservemea::Fiservemea, helcim, helcim::Helcim, novalnet, novalnet::Novalnet, stax, stax::Stax,
+ taxjar, taxjar::Taxjar,
};
#[cfg(feature = "dummy_connector")]
diff --git a/crates/router/src/core/payments/connector_integration_v2_impls.rs b/crates/router/src/core/payments/connector_integration_v2_impls.rs
index 3ccd5f2577a..bed63c10a8a 100644
--- a/crates/router/src/core/payments/connector_integration_v2_impls.rs
+++ b/crates/router/src/core/payments/connector_integration_v2_impls.rs
@@ -1251,6 +1251,7 @@ default_imp_for_new_connector_integration_payouts!(
connector::Nexinets,
connector::Nmi,
connector::Noon,
+ connector::Novalnet,
connector::Nuvei,
connector::Opayo,
connector::Opennode,
@@ -2096,6 +2097,7 @@ default_imp_for_new_connector_integration_frm!(
connector::Nexinets,
connector::Nmi,
connector::Noon,
+ connector::Novalnet,
connector::Nuvei,
connector::Opayo,
connector::Opennode,
@@ -2720,6 +2722,7 @@ default_imp_for_new_connector_integration_connector_authentication!(
connector::Nexinets,
connector::Nmi,
connector::Noon,
+ connector::Novalnet,
connector::Nuvei,
connector::Opayo,
connector::Opennode,
diff --git a/crates/router/src/core/payments/flows.rs b/crates/router/src/core/payments/flows.rs
index 228c7e208cc..fb9f9907c5a 100644
--- a/crates/router/src/core/payments/flows.rs
+++ b/crates/router/src/core/payments/flows.rs
@@ -556,6 +556,7 @@ default_imp_for_connector_request_id!(
connector::Netcetera,
connector::Nmi,
connector::Noon,
+ connector::Novalnet,
connector::Nuvei,
connector::Opayo,
connector::Opennode,
@@ -1214,6 +1215,7 @@ default_imp_for_payouts!(
connector::Nexinets,
connector::Nmi,
connector::Noon,
+ connector::Novalnet,
connector::Nuvei,
connector::Opayo,
connector::Opennode,
@@ -2233,6 +2235,7 @@ default_imp_for_fraud_check!(
connector::Nexinets,
connector::Nmi,
connector::Noon,
+ connector::Novalnet,
connector::Nuvei,
connector::Opayo,
connector::Opennode,
@@ -3047,6 +3050,7 @@ default_imp_for_connector_authentication!(
connector::Nexinets,
connector::Nmi,
connector::Noon,
+ connector::Novalnet,
connector::Nuvei,
connector::Opayo,
connector::Opennode,
diff --git a/crates/router/src/types/api.rs b/crates/router/src/types/api.rs
index 513e4fa1ee2..0637b98163d 100644
--- a/crates/router/src/types/api.rs
+++ b/crates/router/src/types/api.rs
@@ -416,6 +416,7 @@ impl ConnectorData {
enums::Connector::Mollie => Ok(ConnectorEnum::Old(Box::new(&connector::Mollie))),
enums::Connector::Nmi => Ok(ConnectorEnum::Old(Box::new(connector::Nmi::new()))),
enums::Connector::Noon => Ok(ConnectorEnum::Old(Box::new(connector::Noon::new()))),
+ // enums::Connector::Novalnet => Ok(ConnectorEnum::Old(Box::new(connector::Novalnet))),
enums::Connector::Nuvei => Ok(ConnectorEnum::Old(Box::new(&connector::Nuvei))),
enums::Connector::Opennode => {
Ok(ConnectorEnum::Old(Box::new(&connector::Opennode)))
diff --git a/crates/router/src/types/transformers.rs b/crates/router/src/types/transformers.rs
index 67af63b154e..be9c17bc8aa 100644
--- a/crates/router/src/types/transformers.rs
+++ b/crates/router/src/types/transformers.rs
@@ -269,6 +269,7 @@ impl ForeignTryFrom<api_enums::Connector> for common_enums::RoutableConnectors {
api_enums::Connector::Nexinets => Self::Nexinets,
api_enums::Connector::Nmi => Self::Nmi,
api_enums::Connector::Noon => Self::Noon,
+ // api_enums::Connector::Novalnet => Self::Novalnet,
api_enums::Connector::Nuvei => Self::Nuvei,
api_enums::Connector::Opennode => Self::Opennode,
api_enums::Connector::Paybox => Self::Paybox,
diff --git a/crates/router/tests/connectors/main.rs b/crates/router/tests/connectors/main.rs
index e0fa3964b27..2a400b947dc 100644
--- a/crates/router/tests/connectors/main.rs
+++ b/crates/router/tests/connectors/main.rs
@@ -47,6 +47,7 @@ mod netcetera;
mod nexinets;
mod nmi;
mod noon;
+mod novalnet;
mod nuvei;
#[cfg(feature = "dummy_connector")]
mod opayo;
diff --git a/crates/router/tests/connectors/novalnet.rs b/crates/router/tests/connectors/novalnet.rs
new file mode 100644
index 00000000000..2337cae383c
--- /dev/null
+++ b/crates/router/tests/connectors/novalnet.rs
@@ -0,0 +1,420 @@
+use hyperswitch_domain_models::payment_method_data::{Card, PaymentMethodData};
+use masking::Secret;
+use router::types::{self, api, storage::enums};
+use test_utils::connector_auth;
+
+use crate::utils::{self, ConnectorActions};
+
+#[derive(Clone, Copy)]
+struct NovalnetTest;
+impl ConnectorActions for NovalnetTest {}
+impl utils::Connector for NovalnetTest {
+ fn get_data(&self) -> api::ConnectorData {
+ use router::connector::Novalnet;
+ utils::construct_connector_data_old(
+ Box::new(Novalnet::new()),
+ types::Connector::Plaid,
+ api::GetToken::Connector,
+ None,
+ )
+ }
+ fn get_auth_token(&self) -> types::ConnectorAuthType {
+ utils::to_connector_auth_type(
+ connector_auth::ConnectorAuthentication::new()
+ .novalnet
+ .expect("Missing connector authentication configuration")
+ .into(),
+ )
+ }
+
+ fn get_name(&self) -> String {
+ "novalnet".to_string()
+ }
+}
+
+static CONNECTOR: NovalnetTest = NovalnetTest {};
+
+fn get_default_payment_info() -> Option<utils::PaymentInfo> {
+ None
+}
+
+fn payment_method_details() -> Option<types::PaymentsAuthorizeData> {
+ None
+}
+
+// Cards Positive Tests
+// Creates a payment using the manual capture flow (Non 3DS).
+#[actix_web::test]
+async fn should_only_authorize_payment() {
+ let response = CONNECTOR
+ .authorize_payment(payment_method_details(), get_default_payment_info())
+ .await
+ .expect("Authorize payment response");
+ assert_eq!(response.status, enums::AttemptStatus::Authorized);
+}
+
+// Captures a payment using the manual capture flow (Non 3DS).
+#[actix_web::test]
+async fn should_capture_authorized_payment() {
+ let response = CONNECTOR
+ .authorize_and_capture_payment(payment_method_details(), None, get_default_payment_info())
+ .await
+ .expect("Capture payment response");
+ assert_eq!(response.status, enums::AttemptStatus::Charged);
+}
+
+// Partially captures a payment using the manual capture flow (Non 3DS).
+#[actix_web::test]
+async fn should_partially_capture_authorized_payment() {
+ let response = CONNECTOR
+ .authorize_and_capture_payment(
+ payment_method_details(),
+ Some(types::PaymentsCaptureData {
+ amount_to_capture: 50,
+ ..utils::PaymentCaptureType::default().0
+ }),
+ get_default_payment_info(),
+ )
+ .await
+ .expect("Capture payment response");
+ assert_eq!(response.status, enums::AttemptStatus::Charged);
+}
+
+// Synchronizes a payment using the manual capture flow (Non 3DS).
+#[actix_web::test]
+async fn should_sync_authorized_payment() {
+ let authorize_response = CONNECTOR
+ .authorize_payment(payment_method_details(), get_default_payment_info())
+ .await
+ .expect("Authorize payment response");
+ let txn_id = utils::get_connector_transaction_id(authorize_response.response);
+ let response = CONNECTOR
+ .psync_retry_till_status_matches(
+ enums::AttemptStatus::Authorized,
+ Some(types::PaymentsSyncData {
+ connector_transaction_id: types::ResponseId::ConnectorTransactionId(
+ txn_id.unwrap(),
+ ),
+ ..Default::default()
+ }),
+ get_default_payment_info(),
+ )
+ .await
+ .expect("PSync response");
+ assert_eq!(response.status, enums::AttemptStatus::Authorized,);
+}
+
+// Voids a payment using the manual capture flow (Non 3DS).
+#[actix_web::test]
+async fn should_void_authorized_payment() {
+ let response = CONNECTOR
+ .authorize_and_void_payment(
+ payment_method_details(),
+ Some(types::PaymentsCancelData {
+ connector_transaction_id: String::from(""),
+ cancellation_reason: Some("requested_by_customer".to_string()),
+ ..Default::default()
+ }),
+ get_default_payment_info(),
+ )
+ .await
+ .expect("Void payment response");
+ assert_eq!(response.status, enums::AttemptStatus::Voided);
+}
+
+// Refunds a payment using the manual capture flow (Non 3DS).
+#[actix_web::test]
+async fn should_refund_manually_captured_payment() {
+ let response = CONNECTOR
+ .capture_payment_and_refund(
+ payment_method_details(),
+ None,
+ None,
+ get_default_payment_info(),
+ )
+ .await
+ .unwrap();
+ assert_eq!(
+ response.response.unwrap().refund_status,
+ enums::RefundStatus::Success,
+ );
+}
+
+// Partially refunds a payment using the manual capture flow (Non 3DS).
+#[actix_web::test]
+async fn should_partially_refund_manually_captured_payment() {
+ let response = CONNECTOR
+ .capture_payment_and_refund(
+ payment_method_details(),
+ None,
+ Some(types::RefundsData {
+ refund_amount: 50,
+ ..utils::PaymentRefundType::default().0
+ }),
+ get_default_payment_info(),
+ )
+ .await
+ .unwrap();
+ assert_eq!(
+ response.response.unwrap().refund_status,
+ enums::RefundStatus::Success,
+ );
+}
+
+// Synchronizes a refund using the manual capture flow (Non 3DS).
+#[actix_web::test]
+async fn should_sync_manually_captured_refund() {
+ let refund_response = CONNECTOR
+ .capture_payment_and_refund(
+ payment_method_details(),
+ None,
+ None,
+ get_default_payment_info(),
+ )
+ .await
+ .unwrap();
+ let response = CONNECTOR
+ .rsync_retry_till_status_matches(
+ enums::RefundStatus::Success,
+ refund_response.response.unwrap().connector_refund_id,
+ None,
+ get_default_payment_info(),
+ )
+ .await
+ .unwrap();
+ assert_eq!(
+ response.response.unwrap().refund_status,
+ enums::RefundStatus::Success,
+ );
+}
+
+// Creates a payment using the automatic capture flow (Non 3DS).
+#[actix_web::test]
+async fn should_make_payment() {
+ let authorize_response = CONNECTOR
+ .make_payment(payment_method_details(), get_default_payment_info())
+ .await
+ .unwrap();
+ assert_eq!(authorize_response.status, enums::AttemptStatus::Charged);
+}
+
+// Synchronizes a payment using the automatic capture flow (Non 3DS).
+#[actix_web::test]
+async fn should_sync_auto_captured_payment() {
+ let authorize_response = CONNECTOR
+ .make_payment(payment_method_details(), get_default_payment_info())
+ .await
+ .unwrap();
+ assert_eq!(authorize_response.status, enums::AttemptStatus::Charged);
+ let txn_id = utils::get_connector_transaction_id(authorize_response.response);
+ assert_ne!(txn_id, None, "Empty connector transaction id");
+ let response = CONNECTOR
+ .psync_retry_till_status_matches(
+ enums::AttemptStatus::Charged,
+ Some(types::PaymentsSyncData {
+ connector_transaction_id: types::ResponseId::ConnectorTransactionId(
+ txn_id.unwrap(),
+ ),
+ capture_method: Some(enums::CaptureMethod::Automatic),
+ ..Default::default()
+ }),
+ get_default_payment_info(),
+ )
+ .await
+ .unwrap();
+ assert_eq!(response.status, enums::AttemptStatus::Charged,);
+}
+
+// Refunds a payment using the automatic capture flow (Non 3DS).
+#[actix_web::test]
+async fn should_refund_auto_captured_payment() {
+ let response = CONNECTOR
+ .make_payment_and_refund(payment_method_details(), None, get_default_payment_info())
+ .await
+ .unwrap();
+ assert_eq!(
+ response.response.unwrap().refund_status,
+ enums::RefundStatus::Success,
+ );
+}
+
+// Partially refunds a payment using the automatic capture flow (Non 3DS).
+#[actix_web::test]
+async fn should_partially_refund_succeeded_payment() {
+ let refund_response = CONNECTOR
+ .make_payment_and_refund(
+ payment_method_details(),
+ Some(types::RefundsData {
+ refund_amount: 50,
+ ..utils::PaymentRefundType::default().0
+ }),
+ get_default_payment_info(),
+ )
+ .await
+ .unwrap();
+ assert_eq!(
+ refund_response.response.unwrap().refund_status,
+ enums::RefundStatus::Success,
+ );
+}
+
+// Creates multiple refunds against a payment using the automatic capture flow (Non 3DS).
+#[actix_web::test]
+async fn should_refund_succeeded_payment_multiple_times() {
+ CONNECTOR
+ .make_payment_and_multiple_refund(
+ payment_method_details(),
+ Some(types::RefundsData {
+ refund_amount: 50,
+ ..utils::PaymentRefundType::default().0
+ }),
+ get_default_payment_info(),
+ )
+ .await;
+}
+
+// Synchronizes a refund using the automatic capture flow (Non 3DS).
+#[actix_web::test]
+async fn should_sync_refund() {
+ let refund_response = CONNECTOR
+ .make_payment_and_refund(payment_method_details(), None, get_default_payment_info())
+ .await
+ .unwrap();
+ let response = CONNECTOR
+ .rsync_retry_till_status_matches(
+ enums::RefundStatus::Success,
+ refund_response.response.unwrap().connector_refund_id,
+ None,
+ get_default_payment_info(),
+ )
+ .await
+ .unwrap();
+ assert_eq!(
+ response.response.unwrap().refund_status,
+ enums::RefundStatus::Success,
+ );
+}
+
+// Cards Negative scenarios
+// Creates a payment with incorrect CVC.
+#[actix_web::test]
+async fn should_fail_payment_for_incorrect_cvc() {
+ let response = CONNECTOR
+ .make_payment(
+ Some(types::PaymentsAuthorizeData {
+ payment_method_data: PaymentMethodData::Card(Card {
+ card_cvc: Secret::new("12345".to_string()),
+ ..utils::CCardType::default().0
+ }),
+ ..utils::PaymentAuthorizeType::default().0
+ }),
+ get_default_payment_info(),
+ )
+ .await
+ .unwrap();
+ assert_eq!(
+ response.response.unwrap_err().message,
+ "Your card's security code is invalid.".to_string(),
+ );
+}
+
+// Creates a payment with incorrect expiry month.
+#[actix_web::test]
+async fn should_fail_payment_for_invalid_exp_month() {
+ let response = CONNECTOR
+ .make_payment(
+ Some(types::PaymentsAuthorizeData {
+ payment_method_data: PaymentMethodData::Card(Card {
+ card_exp_month: Secret::new("20".to_string()),
+ ..utils::CCardType::default().0
+ }),
+ ..utils::PaymentAuthorizeType::default().0
+ }),
+ get_default_payment_info(),
+ )
+ .await
+ .unwrap();
+ assert_eq!(
+ response.response.unwrap_err().message,
+ "Your card's expiration month is invalid.".to_string(),
+ );
+}
+
+// Creates a payment with incorrect expiry year.
+#[actix_web::test]
+async fn should_fail_payment_for_incorrect_expiry_year() {
+ let response = CONNECTOR
+ .make_payment(
+ Some(types::PaymentsAuthorizeData {
+ payment_method_data: PaymentMethodData::Card(Card {
+ card_exp_year: Secret::new("2000".to_string()),
+ ..utils::CCardType::default().0
+ }),
+ ..utils::PaymentAuthorizeType::default().0
+ }),
+ get_default_payment_info(),
+ )
+ .await
+ .unwrap();
+ assert_eq!(
+ response.response.unwrap_err().message,
+ "Your card's expiration year is invalid.".to_string(),
+ );
+}
+
+// Voids a payment using automatic capture flow (Non 3DS).
+#[actix_web::test]
+async fn should_fail_void_payment_for_auto_capture() {
+ let authorize_response = CONNECTOR
+ .make_payment(payment_method_details(), get_default_payment_info())
+ .await
+ .unwrap();
+ assert_eq!(authorize_response.status, enums::AttemptStatus::Charged);
+ let txn_id = utils::get_connector_transaction_id(authorize_response.response);
+ assert_ne!(txn_id, None, "Empty connector transaction id");
+ let void_response = CONNECTOR
+ .void_payment(txn_id.unwrap(), None, get_default_payment_info())
+ .await
+ .unwrap();
+ assert_eq!(
+ void_response.response.unwrap_err().message,
+ "You cannot cancel this PaymentIntent because it has a status of succeeded."
+ );
+}
+
+// Captures a payment using invalid connector payment id.
+#[actix_web::test]
+async fn should_fail_capture_for_invalid_payment() {
+ let capture_response = CONNECTOR
+ .capture_payment("123456789".to_string(), None, get_default_payment_info())
+ .await
+ .unwrap();
+ assert_eq!(
+ capture_response.response.unwrap_err().message,
+ String::from("No such payment_intent: '123456789'")
+ );
+}
+
+// Refunds a payment with refund amount higher than payment amount.
+#[actix_web::test]
+async fn should_fail_for_refund_amount_higher_than_payment_amount() {
+ let response = CONNECTOR
+ .make_payment_and_refund(
+ payment_method_details(),
+ Some(types::RefundsData {
+ refund_amount: 150,
+ ..utils::PaymentRefundType::default().0
+ }),
+ get_default_payment_info(),
+ )
+ .await
+ .unwrap();
+ assert_eq!(
+ response.response.unwrap_err().message,
+ "Refund amount (₹1.50) is greater than charge amount (₹1.00)",
+ );
+}
+
+// Connector dependent test cases goes here
+
+// [#478]: add unit tests for non 3DS, wallets & webhooks in connector tests
diff --git a/crates/router/tests/connectors/sample_auth.toml b/crates/router/tests/connectors/sample_auth.toml
index 0bf4d96d19f..6134d1ae036 100644
--- a/crates/router/tests/connectors/sample_auth.toml
+++ b/crates/router/tests/connectors/sample_auth.toml
@@ -267,4 +267,7 @@ key1 = "Gateway Entity Id"
api_secret = "Consumer Secret"
[taxjar]
-api_key = "API Key"
\ No newline at end of file
+api_key = "API Key"
+
+[novalnet]
+api_key="API Key"
\ No newline at end of file
diff --git a/crates/test_utils/src/connector_auth.rs b/crates/test_utils/src/connector_auth.rs
index b13be3075aa..0848b9a9f57 100644
--- a/crates/test_utils/src/connector_auth.rs
+++ b/crates/test_utils/src/connector_auth.rs
@@ -51,6 +51,7 @@ pub struct ConnectorAuthentication {
pub netcetera: Option<HeaderKey>,
pub nexinets: Option<BodyKey>,
pub noon: Option<SignatureKey>,
+ pub novalnet: Option<HeaderKey>,
pub nmi: Option<HeaderKey>,
pub nuvei: Option<SignatureKey>,
pub opayo: Option<HeaderKey>,
diff --git a/loadtest/config/development.toml b/loadtest/config/development.toml
index 9e5c8a3f0ce..d2025311dc1 100644
--- a/loadtest/config/development.toml
+++ b/loadtest/config/development.toml
@@ -117,6 +117,7 @@ netcetera.base_url = "https://{{merchant_endpoint_prefix}}.3ds-server.prev.netce
nexinets.base_url = "https://apitest.payengine.de/v1"
nmi.base_url = "https://secure.nmi.com/"
noon.base_url = "https://api-test.noonpayments.com/"
+novalnet.base_url = "https://payport.novalnet.de/v2"
noon.key_mode = "Test"
nuvei.base_url = "https://ppp-test.nuvei.com/"
opayo.base_url = "https://pi-test.sagepay.com/"
@@ -201,6 +202,7 @@ cards = [
"nexinets",
"nmi",
"noon",
+ "novalnet",
"nuvei",
"opayo",
"opennode",
diff --git a/scripts/add_connector.sh b/scripts/add_connector.sh
index 3e5fc1c3d9d..362d0577c69 100755
--- a/scripts/add_connector.sh
+++ b/scripts/add_connector.sh
@@ -6,7 +6,7 @@ function find_prev_connector() {
git checkout $self
cp $self $self.tmp
# Add new connector to existing list and sort it
- connectors=(aci adyen adyenplatform airwallex applepay authorizedotnet bambora bamboraapac bankofamerica billwerk bitpay bluesnap boku braintree cashtocode checkout coinbase cryptopay cybersource datatrans dlocal dummyconnector ebanx fiserv fiservemea forte globalpay globepay gocardless gpayments helcim iatapay itaubank klarna mifinity mollie multisafepay netcetera nexinets noon nuvei opayo opennode paybox payeezy payme payone paypal payu placetopay plaid powertranz prophetpay rapyd razorpay shift4 square stax stripe taxjar threedsecureio trustpay tsys volt wellsfargo wellsfargopayout wise worldline worldpay zsl "$1")
+ connectors=(aci adyen adyenplatform airwallex applepay authorizedotnet bambora bamboraapac bankofamerica billwerk bitpay bluesnap boku braintree cashtocode checkout coinbase cryptopay cybersource datatrans dlocal dummyconnector ebanx fiserv fiservemea forte globalpay globepay gocardless gpayments helcim iatapay itaubank klarna mifinity mollie multisafepay netcetera nexinets noon novalnet nuvei opayo opennode paybox payeezy payme payone paypal payu placetopay plaid powertranz prophetpay rapyd razorpay shift4 square stax stripe taxjar threedsecureio trustpay tsys volt wellsfargo wellsfargopayout wise worldline worldpay zsl "$1")
IFS=$'\n' sorted=($(sort <<<"${connectors[*]}")); unset IFS
res=`echo ${sorted[@]}`
sed -i'' -e "s/^ connectors=.*/ connectors=($res \"\$1\")/" $self.tmp
|
2024-08-22T12:18:40Z
|
## Type of Change
<!-- Put an `x` in the boxes that apply -->
- [ ] Bugfix
- [x] New feature
- [ ] Enhancement
- [ ] Refactoring
- [ ] Dependency updates
- [ ] Documentation
- [ ] CI/CD
## Description
Template code added for new connector Novalnet
https://developer.novalnet.com/onlinepayments/api
### Additional Changes
- [ ] This PR modifies the API contract
- [ ] This PR modifies the database schema
- [ ] This PR modifies application configuration/environment variables
<!--
Provide links to the files with corresponding changes.
Following are the paths where you can find config files:
1. `config`
2. `crates/router/src/configs`
3. `loadtest/config`
-->
## Motivation and Context
<!--
Why is this change required? What problem does it solve?
If it fixes an open issue, please link to the issue here.
If you don't have an issue, we'd recommend starting with one first so the PR
can focus on the implementation (unless it is an obvious bug or documentation fix
that will have little conversation).
-->
## How did you test it?
<!--
Did you write an integration/unit/API test to verify the code changes?
Or did you test this change manually (provide relevant screenshots)?
-->
## Checklist
<!-- Put an `x` in the boxes that apply -->
- [x] I formatted the code `cargo +nightly fmt --all`
- [x] I addressed lints thrown by `cargo clippy`
- [x] I reviewed the submitted code
- [ ] I added unit tests for my changes where possible
|
ad9f91b37cc39c8fb594b48ac60c5e945a0f561f
|
|
juspay/hyperswitch
|
juspay__hyperswitch-5671
|
Bug: [FEATURE] [FISERVEMEA] Integrate card payments
### Feature Description
Integrate card payments for new connector Fiserv-EMEA
https://docs.fiserv.dev/
### Possible Implementation
Integrate card payments for new connector Fiserv-EMEA
https://docs.fiserv.dev/
### Have you spent some time checking if this feature request has been raised before?
- [X] I checked and didn't find a similar issue
### Have you read the Contributing Guidelines?
- [X] I have read the [Contributing Guidelines](https://github.com/juspay/hyperswitch/blob/main/docs/CONTRIBUTING.md)
### Are you willing to submit a PR?
Yes, I am willing to submit a PR!
|
diff --git a/api-reference-v2/openapi_spec.json b/api-reference-v2/openapi_spec.json
index 5c57891d103..7b9cf0e48c8 100644
--- a/api-reference-v2/openapi_spec.json
+++ b/api-reference-v2/openapi_spec.json
@@ -4738,6 +4738,7 @@
"dlocal",
"ebanx",
"fiserv",
+ "fiservemea",
"forte",
"globalpay",
"globepay",
@@ -16776,6 +16777,7 @@
"dlocal",
"ebanx",
"fiserv",
+ "fiservemea",
"forte",
"globalpay",
"globepay",
diff --git a/config/config.example.toml b/config/config.example.toml
index 0a88c3896f2..229dabfeefc 100644
--- a/config/config.example.toml
+++ b/config/config.example.toml
@@ -206,7 +206,7 @@ dlocal.base_url = "https://sandbox.dlocal.com/"
dummyconnector.base_url = "http://localhost:8080/dummy-connector"
ebanx.base_url = "https://sandbox.ebanxpay.com/"
fiserv.base_url = "https://cert.api.fiservapps.com/"
-fiservemea.base_url = "https://prod.emea.api.fiservapps.com/sandbox/ipp/payments-gateway/v2"
+fiservemea.base_url = "https://prod.emea.api.fiservapps.com/sandbox"
forte.base_url = "https://sandbox.forte.net/api/v3"
globalpay.base_url = "https://apis.sandbox.globalpay.com/ucp/"
globepay.base_url = "https://pay.globepay.co/"
diff --git a/config/deployments/integration_test.toml b/config/deployments/integration_test.toml
index c6cb9ff6c36..3d91e2dfda3 100644
--- a/config/deployments/integration_test.toml
+++ b/config/deployments/integration_test.toml
@@ -46,7 +46,7 @@ dlocal.base_url = "https://sandbox.dlocal.com/"
dummyconnector.base_url = "http://localhost:8080/dummy-connector"
ebanx.base_url = "https://sandbox.ebanxpay.com/"
fiserv.base_url = "https://cert.api.fiservapps.com/"
-fiservemea.base_url = "https://prod.emea.api.fiservapps.com/sandbox/ipp/payments-gateway/v2"
+fiservemea.base_url = "https://prod.emea.api.fiservapps.com/sandbox"
forte.base_url = "https://sandbox.forte.net/api/v3"
globalpay.base_url = "https://apis.sandbox.globalpay.com/ucp/"
globepay.base_url = "https://pay.globepay.co/"
diff --git a/config/deployments/production.toml b/config/deployments/production.toml
index 67256cf34d7..e33b4ece805 100644
--- a/config/deployments/production.toml
+++ b/config/deployments/production.toml
@@ -50,7 +50,7 @@ dlocal.base_url = "https://sandbox.dlocal.com/"
dummyconnector.base_url = "http://localhost:8080/dummy-connector"
ebanx.base_url = "https://sandbox.ebanxpay.com/"
fiserv.base_url = "https://cert.api.fiservapps.com/"
-fiservemea.base_url = "https://prod.emea.api.fiservapps.com/ipp/payments-gateway/v2"
+fiservemea.base_url = "https://prod.emea.api.fiservapps.com"
forte.base_url = "https://sandbox.forte.net/api/v3"
globalpay.base_url = "https://apis.sandbox.globalpay.com/ucp/"
globepay.base_url = "https://pay.globepay.co/"
diff --git a/config/deployments/sandbox.toml b/config/deployments/sandbox.toml
index 5496c4ae102..af249369a12 100644
--- a/config/deployments/sandbox.toml
+++ b/config/deployments/sandbox.toml
@@ -50,7 +50,7 @@ dlocal.base_url = "https://sandbox.dlocal.com/"
dummyconnector.base_url = "http://localhost:8080/dummy-connector"
ebanx.base_url = "https://sandbox.ebanxpay.com/"
fiserv.base_url = "https://cert.api.fiservapps.com/"
-fiservemea.base_url = "https://prod.emea.api.fiservapps.com/sandbox/ipp/payments-gateway/v2"
+fiservemea.base_url = "https://prod.emea.api.fiservapps.com/sandbox"
forte.base_url = "https://sandbox.forte.net/api/v3"
globalpay.base_url = "https://apis.sandbox.globalpay.com/ucp/"
globepay.base_url = "https://pay.globepay.co/"
diff --git a/config/development.toml b/config/development.toml
index 401b1487843..87f952508e8 100644
--- a/config/development.toml
+++ b/config/development.toml
@@ -212,7 +212,7 @@ dlocal.base_url = "https://sandbox.dlocal.com/"
dummyconnector.base_url = "http://localhost:8080/dummy-connector"
ebanx.base_url = "https://sandbox.ebanxpay.com/"
fiserv.base_url = "https://cert.api.fiservapps.com/"
-fiservemea.base_url = "https://prod.emea.api.fiservapps.com/sandbox/ipp/payments-gateway/v2"
+fiservemea.base_url = "https://prod.emea.api.fiservapps.com/sandbox"
forte.base_url = "https://sandbox.forte.net/api/v3"
globalpay.base_url = "https://apis.sandbox.globalpay.com/ucp/"
globepay.base_url = "https://pay.globepay.co/"
diff --git a/config/docker_compose.toml b/config/docker_compose.toml
index 136864c9f98..6bf009c19f7 100644
--- a/config/docker_compose.toml
+++ b/config/docker_compose.toml
@@ -135,7 +135,7 @@ dlocal.base_url = "https://sandbox.dlocal.com/"
dummyconnector.base_url = "http://localhost:8080/dummy-connector"
ebanx.base_url = "https://sandbox.ebanxpay.com/"
fiserv.base_url = "https://cert.api.fiservapps.com/"
-fiservemea.base_url = "https://prod.emea.api.fiservapps.com/sandbox/ipp/payments-gateway/v2"
+fiservemea.base_url = "https://prod.emea.api.fiservapps.com/sandbox"
forte.base_url = "https://sandbox.forte.net/api/v3"
globalpay.base_url = "https://apis.sandbox.globalpay.com/ucp/"
globepay.base_url = "https://pay.globepay.co/"
diff --git a/crates/api_models/src/enums.rs b/crates/api_models/src/enums.rs
index 150d69f1e8d..b154341fb8b 100644
--- a/crates/api_models/src/enums.rs
+++ b/crates/api_models/src/enums.rs
@@ -48,7 +48,6 @@ pub enum RoutingAlgorithm {
pub enum Connector {
// Novalnet,
// Nexixpay,
- // Fiservemea,
Adyenplatform,
#[cfg(feature = "dummy_connector")]
#[serde(rename = "phonypay")]
@@ -99,6 +98,7 @@ pub enum Connector {
Dlocal,
Ebanx,
Fiserv,
+ Fiservemea,
Forte,
Globalpay,
Globepay,
@@ -214,7 +214,6 @@ impl Connector {
// | Self::Novalnet
// | Self::Nexixpay
// | Self::Taxjar
- // | Self::Fiservemea
| Self::Adyen
| Self::Adyenplatform
| Self::Airwallex
@@ -233,6 +232,7 @@ impl Connector {
| Self::Dlocal
| Self::Ebanx
| Self::Fiserv
+ | Self::Fiservemea
| Self::Forte
| Self::Globalpay
| Self::Globepay
diff --git a/crates/common_enums/src/enums.rs b/crates/common_enums/src/enums.rs
index 078f490b800..dd935b9a50e 100644
--- a/crates/common_enums/src/enums.rs
+++ b/crates/common_enums/src/enums.rs
@@ -211,7 +211,7 @@ pub enum RoutableConnectors {
Dlocal,
Ebanx,
Fiserv,
- // Fiservemea,
+ Fiservemea,
Forte,
Globalpay,
Globepay,
diff --git a/crates/connector_configs/src/connector.rs b/crates/connector_configs/src/connector.rs
index 51713f6166f..0bd69623599 100644
--- a/crates/connector_configs/src/connector.rs
+++ b/crates/connector_configs/src/connector.rs
@@ -161,6 +161,7 @@ pub struct ConnectorConfig {
pub dlocal: Option<ConnectorTomlConfig>,
pub ebanx_payout: Option<ConnectorTomlConfig>,
pub fiserv: Option<ConnectorTomlConfig>,
+ pub fiservemea: Option<ConnectorTomlConfig>,
pub forte: Option<ConnectorTomlConfig>,
pub globalpay: Option<ConnectorTomlConfig>,
pub globepay: Option<ConnectorTomlConfig>,
@@ -308,6 +309,7 @@ impl ConnectorConfig {
Connector::Dlocal => Ok(connector_data.dlocal),
Connector::Ebanx => Ok(connector_data.ebanx_payout),
Connector::Fiserv => Ok(connector_data.fiserv),
+ Connector::Fiservemea => Ok(connector_data.fiservemea),
Connector::Forte => Ok(connector_data.forte),
Connector::Globalpay => Ok(connector_data.globalpay),
Connector::Globepay => Ok(connector_data.globepay),
diff --git a/crates/connector_configs/toml/development.toml b/crates/connector_configs/toml/development.toml
index 4a2f09be69e..c4becca74ee 100644
--- a/crates/connector_configs/toml/development.toml
+++ b/crates/connector_configs/toml/development.toml
@@ -1455,6 +1455,47 @@ type="Text"
[fiserv.connector_webhook_details]
merchant_secret="Source verification key"
+[fiservemea]
+[[fiservemea.credit]]
+ payment_method_type = "Mastercard"
+[[fiservemea.credit]]
+ payment_method_type = "Visa"
+[[fiservemea.credit]]
+ payment_method_type = "Interac"
+[[fiservemea.credit]]
+ payment_method_type = "AmericanExpress"
+[[fiservemea.credit]]
+ payment_method_type = "JCB"
+[[fiservemea.credit]]
+ payment_method_type = "DinersClub"
+[[fiservemea.credit]]
+ payment_method_type = "Discover"
+[[fiservemea.credit]]
+ payment_method_type = "CartesBancaires"
+[[fiservemea.credit]]
+ payment_method_type = "UnionPay"
+[[fiservemea.debit]]
+ payment_method_type = "Mastercard"
+[[fiservemea.debit]]
+ payment_method_type = "Visa"
+[[fiservemea.debit]]
+ payment_method_type = "Interac"
+[[fiservemea.debit]]
+ payment_method_type = "AmericanExpress"
+[[fiservemea.debit]]
+ payment_method_type = "JCB"
+[[fiservemea.debit]]
+ payment_method_type = "DinersClub"
+[[fiservemea.debit]]
+ payment_method_type = "Discover"
+[[fiservemea.debit]]
+ payment_method_type = "CartesBancaires"
+[[fiservemea.debit]]
+ payment_method_type = "UnionPay"
+[fiservemea.connector_auth.BodyKey]
+api_key="API Key"
+key1="Secret Key"
+
[forte]
[[forte.credit]]
payment_method_type = "Mastercard"
@@ -2954,7 +2995,7 @@ merchant_secret="Source verification key"
payment_method_type = "CartesBancaires"
[[square.debit]]
payment_method_type = "UnionPay"
-[square_payout.connector_auth.BodyKey]
+[square.connector_auth.BodyKey]
api_key = "Square API Key"
key1 = "Square Client Id"
[square.connector_webhook_details]
diff --git a/crates/connector_configs/toml/production.toml b/crates/connector_configs/toml/production.toml
index ea7aafed858..52cee886c3d 100644
--- a/crates/connector_configs/toml/production.toml
+++ b/crates/connector_configs/toml/production.toml
@@ -1221,6 +1221,47 @@ placeholder="Enter Terminal ID"
required=true
type="Text"
+[fiservemea]
+[[fiservemea.credit]]
+ payment_method_type = "Mastercard"
+[[fiservemea.credit]]
+ payment_method_type = "Visa"
+[[fiservemea.credit]]
+ payment_method_type = "Interac"
+[[fiservemea.credit]]
+ payment_method_type = "AmericanExpress"
+[[fiservemea.credit]]
+ payment_method_type = "JCB"
+[[fiservemea.credit]]
+ payment_method_type = "DinersClub"
+[[fiservemea.credit]]
+ payment_method_type = "Discover"
+[[fiservemea.credit]]
+ payment_method_type = "CartesBancaires"
+[[fiservemea.credit]]
+ payment_method_type = "UnionPay"
+[[fiservemea.debit]]
+ payment_method_type = "Mastercard"
+[[fiservemea.debit]]
+ payment_method_type = "Visa"
+[[fiservemea.debit]]
+ payment_method_type = "Interac"
+[[fiservemea.debit]]
+ payment_method_type = "AmericanExpress"
+[[fiservemea.debit]]
+ payment_method_type = "JCB"
+[[fiservemea.debit]]
+ payment_method_type = "DinersClub"
+[[fiservemea.debit]]
+ payment_method_type = "Discover"
+[[fiservemea.debit]]
+ payment_method_type = "CartesBancaires"
+[[fiservemea.debit]]
+ payment_method_type = "UnionPay"
+[fiservemea.connector_auth.BodyKey]
+api_key="API Key"
+key1="Secret Key"
+
[forte]
[[forte.credit]]
payment_method_type = "Mastercard"
diff --git a/crates/connector_configs/toml/sandbox.toml b/crates/connector_configs/toml/sandbox.toml
index 21b4c0a4120..5ad65ab514e 100644
--- a/crates/connector_configs/toml/sandbox.toml
+++ b/crates/connector_configs/toml/sandbox.toml
@@ -1453,6 +1453,47 @@ placeholder="Enter Terminal ID"
required=true
type="Text"
+[fiservemea]
+[[fiservemea.credit]]
+ payment_method_type = "Mastercard"
+[[fiservemea.credit]]
+ payment_method_type = "Visa"
+[[fiservemea.credit]]
+ payment_method_type = "Interac"
+[[fiservemea.credit]]
+ payment_method_type = "AmericanExpress"
+[[fiservemea.credit]]
+ payment_method_type = "JCB"
+[[fiservemea.credit]]
+ payment_method_type = "DinersClub"
+[[fiservemea.credit]]
+ payment_method_type = "Discover"
+[[fiservemea.credit]]
+ payment_method_type = "CartesBancaires"
+[[fiservemea.credit]]
+ payment_method_type = "UnionPay"
+[[fiservemea.debit]]
+ payment_method_type = "Mastercard"
+[[fiservemea.debit]]
+ payment_method_type = "Visa"
+[[fiservemea.debit]]
+ payment_method_type = "Interac"
+[[fiservemea.debit]]
+ payment_method_type = "AmericanExpress"
+[[fiservemea.debit]]
+ payment_method_type = "JCB"
+[[fiservemea.debit]]
+ payment_method_type = "DinersClub"
+[[fiservemea.debit]]
+ payment_method_type = "Discover"
+[[fiservemea.debit]]
+ payment_method_type = "CartesBancaires"
+[[fiservemea.debit]]
+ payment_method_type = "UnionPay"
+[fiservemea.connector_auth.BodyKey]
+api_key="API Key"
+key1="Secret Key"
+
[forte]
[[forte.credit]]
payment_method_type = "Mastercard"
@@ -2947,7 +2988,7 @@ merchant_secret="Source verification key"
payment_method_type = "CartesBancaires"
[[square.debit]]
payment_method_type = "UnionPay"
-[square_payout.connector_auth.BodyKey]
+[square.connector_auth.BodyKey]
api_key = "Square API Key"
key1 = "Square Client Id"
[square.connector_webhook_details]
diff --git a/crates/hyperswitch_connectors/src/connectors/fiservemea.rs b/crates/hyperswitch_connectors/src/connectors/fiservemea.rs
index 83674893724..a7eed07d30c 100644
--- a/crates/hyperswitch_connectors/src/connectors/fiservemea.rs
+++ b/crates/hyperswitch_connectors/src/connectors/fiservemea.rs
@@ -1,14 +1,16 @@
pub mod transformers;
+use base64::Engine;
+use common_enums::enums;
use common_utils::{
errors::CustomResult,
ext_traits::BytesExt,
request::{Method, Request, RequestBuilder, RequestContent},
- types::{AmountConvertor, StringMinorUnit, StringMinorUnitForConnector},
+ types::{AmountConvertor, StringMajorUnit, StringMajorUnitForConnector},
};
use error_stack::{report, ResultExt};
use hyperswitch_domain_models::{
- router_data::{AccessToken, ConnectorAuthType, ErrorResponse, RouterData},
+ router_data::{AccessToken, ErrorResponse, RouterData},
router_flow_types::{
access_token_auth::AccessTokenAuth,
payments::{Authorize, Capture, PSync, PaymentMethodToken, Session, SetupMandate, Void},
@@ -21,34 +23,60 @@ use hyperswitch_domain_models::{
},
router_response_types::{PaymentsResponseData, RefundsResponseData},
types::{
- PaymentsAuthorizeRouterData, PaymentsCaptureRouterData, PaymentsSyncRouterData,
- RefundSyncRouterData, RefundsRouterData,
+ PaymentsAuthorizeRouterData, PaymentsCancelRouterData, PaymentsCaptureRouterData,
+ PaymentsSyncRouterData, RefundSyncRouterData, RefundsRouterData,
},
};
use hyperswitch_interfaces::{
api::{self, ConnectorCommon, ConnectorCommonExt, ConnectorIntegration, ConnectorValidation},
configs::Connectors,
- errors,
+ consts, errors,
events::connector_api_logs::ConnectorEvent,
types::{self, Response},
webhooks,
};
-use masking::{ExposeInterface, Mask};
+use masking::{ExposeInterface, Mask, PeekInterface};
+use ring::hmac;
+use time::OffsetDateTime;
use transformers as fiservemea;
+use uuid::Uuid;
-use crate::{constants::headers, types::ResponseRouterData, utils};
+use crate::{
+ constants::headers,
+ types::ResponseRouterData,
+ utils::{self, RefundsRequestData as _},
+};
#[derive(Clone)]
pub struct Fiservemea {
- amount_converter: &'static (dyn AmountConvertor<Output = StringMinorUnit> + Sync),
+ amount_converter: &'static (dyn AmountConvertor<Output = StringMajorUnit> + Sync),
}
impl Fiservemea {
pub fn new() -> &'static Self {
&Self {
- amount_converter: &StringMinorUnitForConnector,
+ amount_converter: &StringMajorUnitForConnector,
}
}
+
+ pub fn generate_authorization_signature(
+ &self,
+ auth: fiservemea::FiservemeaAuthType,
+ request_id: &str,
+ payload: &str,
+ timestamp: i128,
+ ) -> CustomResult<String, errors::ConnectorError> {
+ let fiservemea::FiservemeaAuthType {
+ api_key,
+ secret_key,
+ } = auth;
+ let raw_signature = format!("{}{request_id}{timestamp}{payload}", api_key.peek());
+
+ let key = hmac::Key::new(hmac::HMAC_SHA256, secret_key.expose().as_bytes());
+ let signature_value = common_utils::consts::BASE64_ENGINE
+ .encode(hmac::sign(&key, raw_signature.as_bytes()).as_ref());
+ Ok(signature_value)
+ }
}
impl api::Payment for Fiservemea {}
@@ -64,10 +92,28 @@ impl api::RefundExecute for Fiservemea {}
impl api::RefundSync for Fiservemea {}
impl api::PaymentToken for Fiservemea {}
+impl ConnectorIntegration<Session, PaymentsSessionData, PaymentsResponseData> for Fiservemea {}
+
+impl ConnectorIntegration<AccessTokenAuth, AccessTokenRequestData, AccessToken> for Fiservemea {}
+
+impl ConnectorIntegration<SetupMandate, SetupMandateRequestData, PaymentsResponseData>
+ for Fiservemea
+{
+ fn build_request(
+ &self,
+ _req: &RouterData<SetupMandate, SetupMandateRequestData, PaymentsResponseData>,
+ _connectors: &Connectors,
+ ) -> CustomResult<Option<Request>, errors::ConnectorError> {
+ Err(
+ errors::ConnectorError::NotImplemented("Setup Mandate flow for Fiservemea".to_string())
+ .into(),
+ )
+ }
+}
+
impl ConnectorIntegration<PaymentMethodToken, PaymentMethodTokenizationData, PaymentsResponseData>
for Fiservemea
{
- // Not Implemented (R)
}
impl<Flow, Request, Response> ConnectorCommonExt<Flow, Request, Response> for Fiservemea
@@ -77,15 +123,42 @@ where
fn build_headers(
&self,
req: &RouterData<Flow, Request, Response>,
- _connectors: &Connectors,
+ connectors: &Connectors,
) -> CustomResult<Vec<(String, masking::Maskable<String>)>, errors::ConnectorError> {
- let mut header = vec![(
- headers::CONTENT_TYPE.to_string(),
- self.get_content_type().to_string().into(),
- )];
- let mut api_key = self.get_auth_header(&req.connector_auth_type)?;
- header.append(&mut api_key);
- Ok(header)
+ let timestamp = OffsetDateTime::now_utc().unix_timestamp_nanos() / 1_000_000;
+ let auth: fiservemea::FiservemeaAuthType =
+ fiservemea::FiservemeaAuthType::try_from(&req.connector_auth_type)?;
+
+ let client_request_id = Uuid::new_v4().to_string();
+ let http_method = self.get_http_method();
+ let hmac = match http_method {
+ Method::Get => self
+ .generate_authorization_signature(auth.clone(), &client_request_id, "", timestamp)
+ .change_context(errors::ConnectorError::RequestEncodingFailed)?,
+ Method::Post | Method::Put | Method::Delete | Method::Patch => {
+ let fiserv_req = self.get_request_body(req, connectors)?;
+ self.generate_authorization_signature(
+ auth.clone(),
+ &client_request_id,
+ fiserv_req.get_inner_value().peek(),
+ timestamp,
+ )
+ .change_context(errors::ConnectorError::RequestEncodingFailed)?
+ }
+ };
+ let headers = vec![
+ (
+ headers::CONTENT_TYPE.to_string(),
+ types::PaymentsAuthorizeType::get_content_type(self)
+ .to_string()
+ .into(),
+ ),
+ ("Client-Request-Id".to_string(), client_request_id.into()),
+ (headers::API_KEY.to_string(), auth.api_key.expose().into()),
+ (headers::TIMESTAMP.to_string(), timestamp.to_string().into()),
+ (headers::MESSAGE_SIGNATURE.to_string(), hmac.into_masked()),
+ ];
+ Ok(headers)
}
}
@@ -96,9 +169,6 @@ impl ConnectorCommon for Fiservemea {
fn get_currency_unit(&self) -> api::CurrencyUnit {
api::CurrencyUnit::Base
- // TODO! Check connector documentation, on which unit they are processing the currency.
- // If the connector accepts amount in lower unit ( i.e cents for USD) then return api::CurrencyUnit::Minor,
- // if connector accepts amount in base unit (i.e dollars for USD) then return api::CurrencyUnit::Base
}
fn common_get_content_type(&self) -> &'static str {
@@ -109,18 +179,6 @@ impl ConnectorCommon for Fiservemea {
connectors.fiservemea.base_url.as_ref()
}
- fn get_auth_header(
- &self,
- auth_type: &ConnectorAuthType,
- ) -> CustomResult<Vec<(String, masking::Maskable<String>)>, errors::ConnectorError> {
- let auth = fiservemea::FiservemeaAuthType::try_from(auth_type)
- .change_context(errors::ConnectorError::FailedToObtainAuthType)?;
- Ok(vec![(
- headers::AUTHORIZATION.to_string(),
- auth.api_key.expose().into_masked(),
- )])
- }
-
fn build_error_response(
&self,
res: Response,
@@ -134,30 +192,74 @@ impl ConnectorCommon for Fiservemea {
event_builder.map(|i| i.set_response_body(&response));
router_env::logger::info!(connector_response=?response);
- Ok(ErrorResponse {
- status_code: res.status_code,
- code: response.code,
- message: response.message,
- reason: response.reason,
- attempt_status: None,
- connector_transaction_id: None,
- })
+ match response.error {
+ Some(error) => {
+ let details = error.details.map(|details| {
+ details
+ .iter()
+ .map(|detail| {
+ format!(
+ "{}: {}",
+ detail
+ .field
+ .clone()
+ .unwrap_or("No Field Provided".to_string()),
+ detail
+ .message
+ .clone()
+ .unwrap_or("No Message Provided".to_string())
+ )
+ })
+ .collect::<Vec<String>>()
+ .join(", ")
+ });
+ Ok(ErrorResponse {
+ status_code: res.status_code,
+ code: error.code.unwrap_or(consts::NO_ERROR_CODE.to_string()),
+ message: response
+ .response_type
+ .unwrap_or(consts::NO_ERROR_MESSAGE.to_string()),
+ reason: match details {
+ Some(details) => Some(format!(
+ "{} {}",
+ error.message.unwrap_or("".to_string()),
+ details
+ )),
+ None => error.message,
+ },
+ attempt_status: None,
+ connector_transaction_id: None,
+ })
+ }
+ None => Ok(ErrorResponse {
+ status_code: res.status_code,
+ code: consts::NO_ERROR_CODE.to_string(),
+ message: response
+ .response_type
+ .clone()
+ .unwrap_or(consts::NO_ERROR_MESSAGE.to_string()),
+ reason: response.response_type,
+ attempt_status: None,
+ connector_transaction_id: None,
+ }),
+ }
}
}
impl ConnectorValidation for Fiservemea {
- //TODO: implement functions when support enabled
-}
-
-impl ConnectorIntegration<Session, PaymentsSessionData, PaymentsResponseData> for Fiservemea {
- //TODO: implement sessions flow
-}
-
-impl ConnectorIntegration<AccessTokenAuth, AccessTokenRequestData, AccessToken> for Fiservemea {}
-
-impl ConnectorIntegration<SetupMandate, SetupMandateRequestData, PaymentsResponseData>
- for Fiservemea
-{
+ fn validate_capture_method(
+ &self,
+ capture_method: Option<enums::CaptureMethod>,
+ _pmt: Option<enums::PaymentMethodType>,
+ ) -> CustomResult<(), errors::ConnectorError> {
+ let capture_method = capture_method.unwrap_or_default();
+ match capture_method {
+ enums::CaptureMethod::Automatic | enums::CaptureMethod::Manual => Ok(()),
+ enums::CaptureMethod::ManualMultiple | enums::CaptureMethod::Scheduled => Err(
+ utils::construct_not_implemented_error_report(capture_method, self.id()),
+ ),
+ }
+ }
}
impl ConnectorIntegration<Authorize, PaymentsAuthorizeData, PaymentsResponseData> for Fiservemea {
@@ -176,9 +278,12 @@ impl ConnectorIntegration<Authorize, PaymentsAuthorizeData, PaymentsResponseData
fn get_url(
&self,
_req: &PaymentsAuthorizeRouterData,
- _connectors: &Connectors,
+ connectors: &Connectors,
) -> CustomResult<String, errors::ConnectorError> {
- Err(errors::ConnectorError::NotImplemented("get_url method".to_string()).into())
+ Ok(format!(
+ "{}/ipp/payments-gateway/v2/payments",
+ self.base_url(connectors)
+ ))
}
fn get_request_body(
@@ -261,12 +366,24 @@ impl ConnectorIntegration<PSync, PaymentsSyncData, PaymentsResponseData> for Fis
self.common_get_content_type()
}
+ fn get_http_method(&self) -> Method {
+ Method::Get
+ }
+
fn get_url(
&self,
- _req: &PaymentsSyncRouterData,
- _connectors: &Connectors,
+ req: &PaymentsSyncRouterData,
+ connectors: &Connectors,
) -> CustomResult<String, errors::ConnectorError> {
- Err(errors::ConnectorError::NotImplemented("get_url method".to_string()).into())
+ let connector_payment_id = req
+ .request
+ .connector_transaction_id
+ .get_connector_transaction_id()
+ .change_context(errors::ConnectorError::MissingConnectorTransactionID)?;
+ Ok(format!(
+ "{}/ipp/payments-gateway/v2/payments/{connector_payment_id}",
+ self.base_url(connectors)
+ ))
}
fn build_request(
@@ -327,18 +444,30 @@ impl ConnectorIntegration<Capture, PaymentsCaptureData, PaymentsResponseData> fo
fn get_url(
&self,
- _req: &PaymentsCaptureRouterData,
- _connectors: &Connectors,
+ req: &PaymentsCaptureRouterData,
+ connectors: &Connectors,
) -> CustomResult<String, errors::ConnectorError> {
- Err(errors::ConnectorError::NotImplemented("get_url method".to_string()).into())
+ let connector_payment_id = req.request.connector_transaction_id.clone();
+ Ok(format!(
+ "{}/ipp/payments-gateway/v2/payments/{connector_payment_id}",
+ self.base_url(connectors)
+ ))
}
fn get_request_body(
&self,
- _req: &PaymentsCaptureRouterData,
+ req: &PaymentsCaptureRouterData,
_connectors: &Connectors,
) -> CustomResult<RequestContent, errors::ConnectorError> {
- Err(errors::ConnectorError::NotImplemented("get_request_body method".to_string()).into())
+ let amount = utils::convert_amount(
+ self.amount_converter,
+ req.request.minor_amount_to_capture,
+ req.request.currency,
+ )?;
+
+ let connector_router_data = fiservemea::FiservemeaRouterData::from((amount, req));
+ let connector_req = fiservemea::FiservemeaCaptureRequest::try_from(&connector_router_data)?;
+ Ok(RequestContent::Json(Box::new(connector_req)))
}
fn build_request(
@@ -389,7 +518,85 @@ impl ConnectorIntegration<Capture, PaymentsCaptureData, PaymentsResponseData> fo
}
}
-impl ConnectorIntegration<Void, PaymentsCancelData, PaymentsResponseData> for Fiservemea {}
+impl ConnectorIntegration<Void, PaymentsCancelData, PaymentsResponseData> for Fiservemea {
+ fn get_headers(
+ &self,
+ req: &PaymentsCancelRouterData,
+ connectors: &Connectors,
+ ) -> CustomResult<Vec<(String, masking::Maskable<String>)>, errors::ConnectorError> {
+ self.build_headers(req, connectors)
+ }
+
+ fn get_content_type(&self) -> &'static str {
+ self.common_get_content_type()
+ }
+
+ fn get_url(
+ &self,
+ req: &PaymentsCancelRouterData,
+ connectors: &Connectors,
+ ) -> CustomResult<String, errors::ConnectorError> {
+ let connector_payment_id = req.request.connector_transaction_id.clone();
+ Ok(format!(
+ "{}/ipp/payments-gateway/v2/payments/{connector_payment_id}",
+ self.base_url(connectors)
+ ))
+ }
+
+ fn get_request_body(
+ &self,
+ req: &PaymentsCancelRouterData,
+ _connectors: &Connectors,
+ ) -> CustomResult<RequestContent, errors::ConnectorError> {
+ let connector_req = fiservemea::FiservemeaVoidRequest::try_from(req)?;
+ Ok(RequestContent::Json(Box::new(connector_req)))
+ }
+
+ fn build_request(
+ &self,
+ req: &PaymentsCancelRouterData,
+ connectors: &Connectors,
+ ) -> CustomResult<Option<Request>, errors::ConnectorError> {
+ Ok(Some(
+ RequestBuilder::new()
+ .method(Method::Post)
+ .url(&types::PaymentsVoidType::get_url(self, req, connectors)?)
+ .attach_default_headers()
+ .headers(types::PaymentsVoidType::get_headers(self, req, connectors)?)
+ .set_body(types::PaymentsVoidType::get_request_body(
+ self, req, connectors,
+ )?)
+ .build(),
+ ))
+ }
+
+ fn handle_response(
+ &self,
+ data: &PaymentsCancelRouterData,
+ event_builder: Option<&mut ConnectorEvent>,
+ res: Response,
+ ) -> CustomResult<PaymentsCancelRouterData, errors::ConnectorError> {
+ let response: fiservemea::FiservemeaPaymentsResponse = res
+ .response
+ .parse_struct("Fiservemea PaymentsCaptureResponse")
+ .change_context(errors::ConnectorError::ResponseDeserializationFailed)?;
+ event_builder.map(|i| i.set_response_body(&response));
+ router_env::logger::info!(connector_response=?response);
+ RouterData::try_from(ResponseRouterData {
+ response,
+ data: data.clone(),
+ http_code: res.status_code,
+ })
+ }
+
+ fn get_error_response(
+ &self,
+ res: Response,
+ event_builder: Option<&mut ConnectorEvent>,
+ ) -> CustomResult<ErrorResponse, errors::ConnectorError> {
+ self.build_error_response(res, event_builder)
+ }
+}
impl ConnectorIntegration<Execute, RefundsData, RefundsResponseData> for Fiservemea {
fn get_headers(
@@ -406,10 +613,14 @@ impl ConnectorIntegration<Execute, RefundsData, RefundsResponseData> for Fiserve
fn get_url(
&self,
- _req: &RefundsRouterData<Execute>,
- _connectors: &Connectors,
+ req: &RefundsRouterData<Execute>,
+ connectors: &Connectors,
) -> CustomResult<String, errors::ConnectorError> {
- Err(errors::ConnectorError::NotImplemented("get_url method".to_string()).into())
+ let connector_payment_id = req.request.connector_transaction_id.clone();
+ Ok(format!(
+ "{}/ipp/payments-gateway/v2/payments/{connector_payment_id}",
+ self.base_url(connectors)
+ ))
}
fn get_request_body(
@@ -453,7 +664,7 @@ impl ConnectorIntegration<Execute, RefundsData, RefundsResponseData> for Fiserve
event_builder: Option<&mut ConnectorEvent>,
res: Response,
) -> CustomResult<RefundsRouterData<Execute>, errors::ConnectorError> {
- let response: fiservemea::RefundResponse = res
+ let response: fiservemea::FiservemeaPaymentsResponse = res
.response
.parse_struct("fiservemea RefundResponse")
.change_context(errors::ConnectorError::ResponseDeserializationFailed)?;
@@ -488,12 +699,20 @@ impl ConnectorIntegration<RSync, RefundsData, RefundsResponseData> for Fiserveme
self.common_get_content_type()
}
+ fn get_http_method(&self) -> Method {
+ Method::Get
+ }
+
fn get_url(
&self,
- _req: &RefundSyncRouterData,
- _connectors: &Connectors,
+ req: &RefundSyncRouterData,
+ connectors: &Connectors,
) -> CustomResult<String, errors::ConnectorError> {
- Err(errors::ConnectorError::NotImplemented("get_url method".to_string()).into())
+ let connector_payment_id = req.request.get_connector_refund_id()?;
+ Ok(format!(
+ "{}/ipp/payments-gateway/v2/payments/{connector_payment_id}",
+ self.base_url(connectors)
+ ))
}
fn build_request(
@@ -520,7 +739,7 @@ impl ConnectorIntegration<RSync, RefundsData, RefundsResponseData> for Fiserveme
event_builder: Option<&mut ConnectorEvent>,
res: Response,
) -> CustomResult<RefundSyncRouterData, errors::ConnectorError> {
- let response: fiservemea::RefundResponse = res
+ let response: fiservemea::FiservemeaPaymentsResponse = res
.response
.parse_struct("fiservemea RefundSyncResponse")
.change_context(errors::ConnectorError::ResponseDeserializationFailed)?;
diff --git a/crates/hyperswitch_connectors/src/connectors/fiservemea/transformers.rs b/crates/hyperswitch_connectors/src/connectors/fiservemea/transformers.rs
index e6307b4bdf5..fdec3d0e1eb 100644
--- a/crates/hyperswitch_connectors/src/connectors/fiservemea/transformers.rs
+++ b/crates/hyperswitch_connectors/src/connectors/fiservemea/transformers.rs
@@ -1,12 +1,15 @@
use common_enums::enums;
-use common_utils::types::StringMinorUnit;
+use common_utils::types::StringMajorUnit;
use hyperswitch_domain_models::{
payment_method_data::PaymentMethodData,
router_data::{ConnectorAuthType, RouterData},
router_flow_types::refunds::{Execute, RSync},
router_request_types::ResponseId,
router_response_types::{PaymentsResponseData, RefundsResponseData},
- types::{PaymentsAuthorizeRouterData, RefundsRouterData},
+ types::{
+ PaymentsAuthorizeRouterData, PaymentsCancelRouterData, PaymentsCaptureRouterData,
+ RefundsRouterData,
+ },
};
use hyperswitch_interfaces::errors;
use masking::Secret;
@@ -14,17 +17,17 @@ use serde::{Deserialize, Serialize};
use crate::{
types::{RefundsResponseRouterData, ResponseRouterData},
- utils::PaymentsAuthorizeRequestData,
+ utils::CardData as _,
};
//TODO: Fill the struct with respective fields
pub struct FiservemeaRouterData<T> {
- pub amount: StringMinorUnit, // The type of amount that a connector accepts, for example, String, i64, f64, etc.
+ pub amount: StringMajorUnit, // The type of amount that a connector accepts, for example, String, i64, f64, etc.
pub router_data: T,
}
-impl<T> From<(StringMinorUnit, T)> for FiservemeaRouterData<T> {
- fn from((amount, item): (StringMinorUnit, T)) -> Self {
+impl<T> From<(StringMajorUnit, T)> for FiservemeaRouterData<T> {
+ fn from((amount, item): (StringMajorUnit, T)) -> Self {
//Todo : use utils to convert the amount to the type of amount that a connector accepts
Self {
amount,
@@ -33,20 +36,56 @@ impl<T> From<(StringMinorUnit, T)> for FiservemeaRouterData<T> {
}
}
-//TODO: Fill the struct with respective fields
-#[derive(Default, Debug, Serialize, PartialEq)]
-pub struct FiservemeaPaymentsRequest {
- amount: StringMinorUnit,
- card: FiservemeaCard,
+#[derive(Debug, Serialize)]
+pub struct FiservemeaTransactionAmount {
+ total: StringMajorUnit,
+ currency: common_enums::Currency,
+}
+
+#[derive(Debug, Serialize, Deserialize)]
+#[serde(rename_all = "camelCase")]
+pub struct FiservemeaOrder {
+ order_id: String,
+}
+
+#[derive(Debug, Serialize)]
+pub enum FiservemeaRequestType {
+ PaymentCardSaleTransaction,
+ PaymentCardPreAuthTransaction,
+ PostAuthTransaction,
+ VoidPreAuthTransactions,
+ ReturnTransaction,
+}
+
+#[derive(Debug, Serialize, Deserialize)]
+#[serde(rename_all = "camelCase")]
+pub struct FiservemeaExpiryDate {
+ month: Secret<String>,
+ year: Secret<String>,
}
-#[derive(Default, Debug, Serialize, Eq, PartialEq)]
-pub struct FiservemeaCard {
+#[derive(Debug, Serialize)]
+#[serde(rename_all = "camelCase")]
+pub struct FiservemeaPaymentCard {
number: cards::CardNumber,
- expiry_month: Secret<String>,
- expiry_year: Secret<String>,
- cvc: Secret<String>,
- complete: bool,
+ expiry_date: FiservemeaExpiryDate,
+ security_code: Secret<String>,
+}
+
+#[derive(Debug, Serialize)]
+#[serde(rename_all = "camelCase")]
+pub enum FiservemeaPaymentMethods {
+ PaymentCard(FiservemeaPaymentCard),
+}
+
+#[derive(Debug, Serialize)]
+#[serde(rename_all = "camelCase")]
+pub struct FiservemeaPaymentsRequest {
+ request_type: FiservemeaRequestType,
+ merchant_transaction_id: String,
+ transaction_amount: FiservemeaTransactionAmount,
+ order: FiservemeaOrder,
+ payment_method: FiservemeaPaymentMethods,
}
impl TryFrom<&FiservemeaRouterData<&PaymentsAuthorizeRouterData>> for FiservemeaPaymentsRequest {
@@ -56,66 +95,262 @@ impl TryFrom<&FiservemeaRouterData<&PaymentsAuthorizeRouterData>> for Fiservemea
) -> Result<Self, Self::Error> {
match item.router_data.request.payment_method_data.clone() {
PaymentMethodData::Card(req_card) => {
- let card = FiservemeaCard {
- number: req_card.card_number,
- expiry_month: req_card.card_exp_month,
- expiry_year: req_card.card_exp_year,
- cvc: req_card.card_cvc,
- complete: item.router_data.request.is_auto_capture()?,
+ let card = FiservemeaPaymentCard {
+ number: req_card.card_number.clone(),
+ expiry_date: FiservemeaExpiryDate {
+ month: req_card.card_exp_month.clone(),
+ year: req_card.get_card_expiry_year_2_digit()?,
+ },
+ security_code: req_card.card_cvc,
+ };
+ let request_type = if item.router_data.request.capture_method
+ == Some(enums::CaptureMethod::Automatic)
+ {
+ FiservemeaRequestType::PaymentCardSaleTransaction
+ } else {
+ FiservemeaRequestType::PaymentCardPreAuthTransaction
};
Ok(Self {
- amount: item.amount.clone(),
- card,
+ request_type,
+ merchant_transaction_id: item
+ .router_data
+ .request
+ .merchant_order_reference_id
+ .clone()
+ .unwrap_or(item.router_data.connector_request_reference_id.clone()),
+ transaction_amount: FiservemeaTransactionAmount {
+ total: item.amount.clone(),
+ currency: item.router_data.request.currency,
+ },
+ order: FiservemeaOrder {
+ order_id: item.router_data.connector_request_reference_id.clone(),
+ },
+ payment_method: FiservemeaPaymentMethods::PaymentCard(card),
})
}
- _ => Err(errors::ConnectorError::NotImplemented("Payment methods".to_string()).into()),
+ _ => Err(errors::ConnectorError::NotImplemented(
+ "Selected payment method through fiservemea".to_string(),
+ )
+ .into()),
}
}
}
-//TODO: Fill the struct with respective fields
// Auth Struct
+#[derive(Clone)]
pub struct FiservemeaAuthType {
pub(super) api_key: Secret<String>,
+ pub(super) secret_key: Secret<String>,
}
impl TryFrom<&ConnectorAuthType> for FiservemeaAuthType {
type Error = error_stack::Report<errors::ConnectorError>;
fn try_from(auth_type: &ConnectorAuthType) -> Result<Self, Self::Error> {
match auth_type {
- ConnectorAuthType::HeaderKey { api_key } => Ok(Self {
+ ConnectorAuthType::BodyKey { api_key, key1 } => Ok(Self {
api_key: api_key.to_owned(),
+ secret_key: key1.to_owned(),
}),
_ => Err(errors::ConnectorError::FailedToObtainAuthType.into()),
}
}
}
+
// PaymentsResponse
-//TODO: Append the remaining status flags
-#[derive(Debug, Clone, Default, Serialize, Deserialize, PartialEq)]
-#[serde(rename_all = "lowercase")]
+#[derive(Debug, Serialize, Deserialize)]
+pub enum ResponseType {
+ BadRequest,
+ Unauthenticated,
+ Unauthorized,
+ NotFound,
+ GatewayDeclined,
+ EndpointDeclined,
+ ServerError,
+ EndpointCommunicationError,
+ UnsupportedMediaType,
+}
+
+#[derive(Debug, Serialize, Deserialize)]
+#[serde(rename_all = "camelCase")]
+pub enum FiservemeaResponseType {
+ TransactionResponse,
+ ErrorResponse,
+}
+
+#[derive(Debug, Serialize, Deserialize, PartialEq)]
+#[serde(rename_all = "SCREAMING_SNAKE_CASE")]
+pub enum FiservemeaTransactionType {
+ Sale,
+ Preauth,
+ Credit,
+ ForcedTicket,
+ Void,
+ Return,
+ Postauth,
+ PayerAuth,
+ Disbursement,
+}
+
+#[derive(Debug, Serialize, Deserialize)]
+#[serde(rename_all = "UPPERCASE")]
+pub enum FiservemeaTransactionOrigin {
+ Ecom,
+ Moto,
+ Mail,
+ Phone,
+ Retail,
+}
+
+#[derive(Debug, Serialize, Deserialize)]
+#[serde(rename_all = "SCREAMING_SNAKE_CASE")]
pub enum FiservemeaPaymentStatus {
- Succeeded,
+ Approved,
+ Waiting,
+ Partial,
+ ValidationFailed,
+ ProcessingFailed,
+ Declined,
+}
+
+#[derive(Debug, Serialize, Deserialize)]
+#[serde(rename_all = "SCREAMING_SNAKE_CASE")]
+pub enum FiservemeaPaymentResult {
+ Approved,
+ Declined,
Failed,
- #[default]
- Processing,
+ Waiting,
+ Partial,
+ Fraud,
}
-impl From<FiservemeaPaymentStatus> for common_enums::AttemptStatus {
- fn from(item: FiservemeaPaymentStatus) -> Self {
- match item {
- FiservemeaPaymentStatus::Succeeded => Self::Charged,
- FiservemeaPaymentStatus::Failed => Self::Failure,
- FiservemeaPaymentStatus::Processing => Self::Authorizing,
- }
+#[derive(Debug, Serialize, Deserialize)]
+#[serde(rename_all = "camelCase")]
+pub struct FiservemeaPaymentCardResponse {
+ expiry_date: Option<FiservemeaExpiryDate>,
+ bin: Option<String>,
+ last4: Option<String>,
+ brand: Option<String>,
+}
+
+#[derive(Debug, Serialize, Deserialize)]
+#[serde(rename_all = "camelCase")]
+pub struct FiservemeaPaymentMethodDetails {
+ payment_card: Option<FiservemeaPaymentCardResponse>,
+ payment_method_type: Option<String>,
+ payment_method_brand: Option<String>,
+}
+
+#[derive(Debug, Serialize, Deserialize)]
+#[serde(rename_all = "camelCase")]
+pub struct Components {
+ subtotal: Option<f64>,
+}
+
+#[derive(Debug, Serialize, Deserialize)]
+#[serde(rename_all = "camelCase")]
+pub struct AmountDetails {
+ total: Option<f64>,
+ currency: Option<common_enums::Currency>,
+ components: Option<Components>,
+}
+
+#[derive(Debug, Serialize, Deserialize)]
+#[serde(rename_all = "camelCase")]
+pub struct AvsResponse {
+ street_match: Option<String>,
+ postal_code_match: Option<String>,
+}
+
+#[derive(Debug, Serialize, Deserialize)]
+#[serde(rename_all = "camelCase")]
+pub struct Processor {
+ reference_number: Option<String>,
+ authorization_code: Option<String>,
+ response_code: Option<String>,
+ response_message: Option<String>,
+ avs_response: Option<AvsResponse>,
+ security_code_response: Option<String>,
+}
+
+fn map_status(
+ fiservemea_status: Option<FiservemeaPaymentStatus>,
+ fiservemea_result: Option<FiservemeaPaymentResult>,
+ transaction_type: FiservemeaTransactionType,
+) -> common_enums::AttemptStatus {
+ match fiservemea_status {
+ Some(status) => match status {
+ FiservemeaPaymentStatus::Approved => match transaction_type {
+ FiservemeaTransactionType::Preauth => common_enums::AttemptStatus::Authorized,
+ FiservemeaTransactionType::Void => common_enums::AttemptStatus::Voided,
+ FiservemeaTransactionType::Sale | FiservemeaTransactionType::Postauth => {
+ common_enums::AttemptStatus::Charged
+ }
+ FiservemeaTransactionType::Credit
+ | FiservemeaTransactionType::ForcedTicket
+ | FiservemeaTransactionType::Return
+ | FiservemeaTransactionType::PayerAuth
+ | FiservemeaTransactionType::Disbursement => common_enums::AttemptStatus::Failure,
+ },
+ FiservemeaPaymentStatus::Waiting => common_enums::AttemptStatus::Pending,
+ FiservemeaPaymentStatus::Partial => common_enums::AttemptStatus::PartialCharged,
+ FiservemeaPaymentStatus::ValidationFailed
+ | FiservemeaPaymentStatus::ProcessingFailed
+ | FiservemeaPaymentStatus::Declined => common_enums::AttemptStatus::Failure,
+ },
+ None => match fiservemea_result {
+ Some(result) => match result {
+ FiservemeaPaymentResult::Approved => match transaction_type {
+ FiservemeaTransactionType::Preauth => common_enums::AttemptStatus::Authorized,
+ FiservemeaTransactionType::Void => common_enums::AttemptStatus::Voided,
+ FiservemeaTransactionType::Sale | FiservemeaTransactionType::Postauth => {
+ common_enums::AttemptStatus::Charged
+ }
+ FiservemeaTransactionType::Credit
+ | FiservemeaTransactionType::ForcedTicket
+ | FiservemeaTransactionType::Return
+ | FiservemeaTransactionType::PayerAuth
+ | FiservemeaTransactionType::Disbursement => {
+ common_enums::AttemptStatus::Failure
+ }
+ },
+ FiservemeaPaymentResult::Waiting => common_enums::AttemptStatus::Pending,
+ FiservemeaPaymentResult::Partial => common_enums::AttemptStatus::PartialCharged,
+ FiservemeaPaymentResult::Declined
+ | FiservemeaPaymentResult::Failed
+ | FiservemeaPaymentResult::Fraud => common_enums::AttemptStatus::Failure,
+ },
+ None => common_enums::AttemptStatus::Pending,
+ },
}
}
-//TODO: Fill the struct with respective fields
-#[derive(Default, Debug, Clone, Serialize, Deserialize, PartialEq)]
+#[derive(Debug, Serialize, Deserialize)]
+#[serde(rename_all = "camelCase")]
pub struct FiservemeaPaymentsResponse {
- status: FiservemeaPaymentStatus,
- id: String,
+ response_type: Option<ResponseType>,
+ #[serde(rename = "type")]
+ fiservemea_type: Option<FiservemeaResponseType>,
+ client_request_id: Option<String>,
+ api_trace_id: Option<String>,
+ ipg_transaction_id: String,
+ order_id: Option<String>,
+ transaction_type: FiservemeaTransactionType,
+ transaction_origin: Option<FiservemeaTransactionOrigin>,
+ payment_method_details: Option<FiservemeaPaymentMethodDetails>,
+ country: Option<Secret<String>>,
+ terminal_id: Option<String>,
+ merchant_id: Option<String>,
+ merchant_transaction_id: Option<String>,
+ transaction_time: Option<i64>,
+ approved_amount: Option<AmountDetails>,
+ transaction_amount: Option<AmountDetails>,
+ transaction_status: Option<FiservemeaPaymentStatus>, // FiservEMEA Docs mention that this field is deprecated. We are using it for now because transaction_result is not present in the response.
+ transaction_result: Option<FiservemeaPaymentResult>,
+ approval_code: Option<String>,
+ error_message: Option<String>,
+ transaction_state: Option<String>,
+ scheme_transaction_id: Option<String>,
+ processor: Option<Processor>,
}
impl<F, T> TryFrom<ResponseRouterData<F, FiservemeaPaymentsResponse, T, PaymentsResponseData>>
@@ -126,14 +361,18 @@ impl<F, T> TryFrom<ResponseRouterData<F, FiservemeaPaymentsResponse, T, Payments
item: ResponseRouterData<F, FiservemeaPaymentsResponse, T, PaymentsResponseData>,
) -> Result<Self, Self::Error> {
Ok(Self {
- status: common_enums::AttemptStatus::from(item.response.status),
+ status: map_status(
+ item.response.transaction_status,
+ item.response.transaction_result,
+ item.response.transaction_type,
+ ),
response: Ok(PaymentsResponseData::TransactionResponse {
- resource_id: ResponseId::ConnectorTransactionId(item.response.id),
+ resource_id: ResponseId::ConnectorTransactionId(item.response.ipg_transaction_id),
redirection_data: None,
mandate_reference: None,
connector_metadata: None,
network_txn_id: None,
- connector_response_reference_id: None,
+ connector_response_reference_id: item.response.order_id,
incremental_authorization_allowed: None,
charge_id: None,
}),
@@ -142,87 +381,154 @@ impl<F, T> TryFrom<ResponseRouterData<F, FiservemeaPaymentsResponse, T, Payments
}
}
-//TODO: Fill the struct with respective fields
-// REFUND :
-// Type definition for RefundRequest
-#[derive(Default, Debug, Serialize)]
-pub struct FiservemeaRefundRequest {
- pub amount: StringMinorUnit,
+#[derive(Debug, Serialize)]
+#[serde(rename_all = "camelCase")]
+pub struct FiservemeaCaptureRequest {
+ request_type: FiservemeaRequestType,
+ transaction_amount: FiservemeaTransactionAmount,
}
-impl<F> TryFrom<&FiservemeaRouterData<&RefundsRouterData<F>>> for FiservemeaRefundRequest {
+impl TryFrom<&FiservemeaRouterData<&PaymentsCaptureRouterData>> for FiservemeaCaptureRequest {
type Error = error_stack::Report<errors::ConnectorError>;
- fn try_from(item: &FiservemeaRouterData<&RefundsRouterData<F>>) -> Result<Self, Self::Error> {
+ fn try_from(
+ item: &FiservemeaRouterData<&PaymentsCaptureRouterData>,
+ ) -> Result<Self, Self::Error> {
Ok(Self {
- amount: item.amount.to_owned(),
+ request_type: FiservemeaRequestType::PostAuthTransaction,
+ transaction_amount: FiservemeaTransactionAmount {
+ total: item.amount.clone(),
+ currency: item.router_data.request.currency,
+ },
})
}
}
-// Type definition for Refund Response
+#[derive(Debug, Serialize)]
+#[serde(rename_all = "camelCase")]
+pub struct FiservemeaVoidRequest {
+ request_type: FiservemeaRequestType,
+}
-#[allow(dead_code)]
-#[derive(Debug, Serialize, Default, Deserialize, Clone)]
-pub enum RefundStatus {
- Succeeded,
- Failed,
- #[default]
- Processing,
+impl TryFrom<&PaymentsCancelRouterData> for FiservemeaVoidRequest {
+ type Error = error_stack::Report<errors::ConnectorError>;
+ fn try_from(_item: &PaymentsCancelRouterData) -> Result<Self, Self::Error> {
+ Ok(Self {
+ request_type: FiservemeaRequestType::VoidPreAuthTransactions,
+ })
+ }
}
-impl From<RefundStatus> for enums::RefundStatus {
- fn from(item: RefundStatus) -> Self {
- match item {
- RefundStatus::Succeeded => Self::Success,
- RefundStatus::Failed => Self::Failure,
- RefundStatus::Processing => Self::Pending,
- //TODO: Review mapping
- }
+// REFUND :
+#[derive(Debug, Serialize)]
+#[serde(rename_all = "camelCase")]
+pub struct FiservemeaRefundRequest {
+ request_type: FiservemeaRequestType,
+ transaction_amount: FiservemeaTransactionAmount,
+}
+
+impl<F> TryFrom<&FiservemeaRouterData<&RefundsRouterData<F>>> for FiservemeaRefundRequest {
+ type Error = error_stack::Report<errors::ConnectorError>;
+ fn try_from(item: &FiservemeaRouterData<&RefundsRouterData<F>>) -> Result<Self, Self::Error> {
+ Ok(Self {
+ request_type: FiservemeaRequestType::ReturnTransaction,
+ transaction_amount: FiservemeaTransactionAmount {
+ total: item.amount.clone(),
+ currency: item.router_data.request.currency,
+ },
+ })
}
}
-//TODO: Fill the struct with respective fields
-#[derive(Default, Debug, Clone, Serialize, Deserialize)]
-pub struct RefundResponse {
- id: String,
- status: RefundStatus,
+fn map_refund_status(
+ fiservemea_status: Option<FiservemeaPaymentStatus>,
+ fiservemea_result: Option<FiservemeaPaymentResult>,
+) -> Result<enums::RefundStatus, errors::ConnectorError> {
+ match fiservemea_status {
+ Some(status) => match status {
+ FiservemeaPaymentStatus::Approved => Ok(enums::RefundStatus::Success),
+ FiservemeaPaymentStatus::Partial | FiservemeaPaymentStatus::Waiting => {
+ Ok(enums::RefundStatus::Pending)
+ }
+ FiservemeaPaymentStatus::ValidationFailed
+ | FiservemeaPaymentStatus::ProcessingFailed
+ | FiservemeaPaymentStatus::Declined => Ok(enums::RefundStatus::Failure),
+ },
+ None => match fiservemea_result {
+ Some(result) => match result {
+ FiservemeaPaymentResult::Approved => Ok(enums::RefundStatus::Success),
+ FiservemeaPaymentResult::Partial | FiservemeaPaymentResult::Waiting => {
+ Ok(enums::RefundStatus::Pending)
+ }
+ FiservemeaPaymentResult::Declined
+ | FiservemeaPaymentResult::Failed
+ | FiservemeaPaymentResult::Fraud => Ok(enums::RefundStatus::Failure),
+ },
+ None => Err(errors::ConnectorError::MissingRequiredField {
+ field_name: "transactionResult",
+ }),
+ },
+ }
}
-impl TryFrom<RefundsResponseRouterData<Execute, RefundResponse>> for RefundsRouterData<Execute> {
+impl TryFrom<RefundsResponseRouterData<Execute, FiservemeaPaymentsResponse>>
+ for RefundsRouterData<Execute>
+{
type Error = error_stack::Report<errors::ConnectorError>;
fn try_from(
- item: RefundsResponseRouterData<Execute, RefundResponse>,
+ item: RefundsResponseRouterData<Execute, FiservemeaPaymentsResponse>,
) -> Result<Self, Self::Error> {
Ok(Self {
response: Ok(RefundsResponseData {
- connector_refund_id: item.response.id.to_string(),
- refund_status: enums::RefundStatus::from(item.response.status),
+ connector_refund_id: item.response.ipg_transaction_id,
+ refund_status: map_refund_status(
+ item.response.transaction_status,
+ item.response.transaction_result,
+ )?,
}),
..item.data
})
}
}
-impl TryFrom<RefundsResponseRouterData<RSync, RefundResponse>> for RefundsRouterData<RSync> {
+impl TryFrom<RefundsResponseRouterData<RSync, FiservemeaPaymentsResponse>>
+ for RefundsRouterData<RSync>
+{
type Error = error_stack::Report<errors::ConnectorError>;
fn try_from(
- item: RefundsResponseRouterData<RSync, RefundResponse>,
+ item: RefundsResponseRouterData<RSync, FiservemeaPaymentsResponse>,
) -> Result<Self, Self::Error> {
Ok(Self {
response: Ok(RefundsResponseData {
- connector_refund_id: item.response.id.to_string(),
- refund_status: enums::RefundStatus::from(item.response.status),
+ connector_refund_id: item.response.ipg_transaction_id,
+ refund_status: map_refund_status(
+ item.response.transaction_status,
+ item.response.transaction_result,
+ )?,
}),
..item.data
})
}
}
-//TODO: Fill the struct with respective fields
-#[derive(Default, Debug, Serialize, Deserialize, PartialEq)]
+#[derive(Debug, Serialize, Deserialize)]
+pub struct ErrorDetails {
+ pub field: Option<String>,
+ pub message: Option<String>,
+}
+
+#[derive(Debug, Serialize, Deserialize)]
+pub struct FiservemeaError {
+ pub code: Option<String>,
+ pub message: Option<String>,
+ pub details: Option<Vec<ErrorDetails>>,
+}
+
+#[derive(Debug, Serialize, Deserialize)]
pub struct FiservemeaErrorResponse {
- pub status_code: u16,
- pub code: String,
- pub message: String,
- pub reason: Option<String>,
+ #[serde(rename = "type")]
+ fiservemea_type: Option<FiservemeaResponseType>,
+ client_request_id: Option<String>,
+ api_trace_id: Option<String>,
+ pub response_type: Option<String>,
+ pub error: Option<FiservemeaError>,
}
diff --git a/crates/hyperswitch_connectors/src/constants.rs b/crates/hyperswitch_connectors/src/constants.rs
index a8d08424190..1fd61689307 100644
--- a/crates/hyperswitch_connectors/src/constants.rs
+++ b/crates/hyperswitch_connectors/src/constants.rs
@@ -5,6 +5,7 @@ pub(crate) mod headers {
pub(crate) const AUTHORIZATION: &str = "Authorization";
pub(crate) const CONTENT_TYPE: &str = "Content-Type";
pub(crate) const IDEMPOTENCY_KEY: &str = "Idempotency-Key";
+ pub(crate) const MESSAGE_SIGNATURE: &str = "Message-Signature";
pub(crate) const TIMESTAMP: &str = "Timestamp";
pub(crate) const X_ACCEPT_VERSION: &str = "X-Accept-Version";
}
diff --git a/crates/router/src/core/admin.rs b/crates/router/src/core/admin.rs
index cb95feee9e9..59ed7ae605c 100644
--- a/crates/router/src/core/admin.rs
+++ b/crates/router/src/core/admin.rs
@@ -1351,6 +1351,10 @@ impl<'a> ConnectorAuthTypeAndMetadataValidation<'a> {
fiserv::transformers::FiservSessionObject::try_from(self.connector_meta_data)?;
Ok(())
}
+ api_enums::Connector::Fiservemea => {
+ fiservemea::transformers::FiservemeaAuthType::try_from(self.auth_type)?;
+ Ok(())
+ }
api_enums::Connector::Forte => {
forte::transformers::ForteAuthType::try_from(self.auth_type)?;
Ok(())
diff --git a/crates/router/src/types/api.rs b/crates/router/src/types/api.rs
index 681cd6fd110..352e5c45030 100644
--- a/crates/router/src/types/api.rs
+++ b/crates/router/src/types/api.rs
@@ -390,9 +390,9 @@ impl ConnectorData {
Ok(ConnectorEnum::Old(Box::new(connector::Ebanx::new())))
}
enums::Connector::Fiserv => Ok(ConnectorEnum::Old(Box::new(&connector::Fiserv))),
- // enums::Connector::Fiservemea => {
- // Ok(ConnectorEnum::Old(Box::new(connector::Fiservemea)))
- // }
+ enums::Connector::Fiservemea => {
+ Ok(ConnectorEnum::Old(Box::new(connector::Fiservemea::new())))
+ }
enums::Connector::Forte => {
Ok(ConnectorEnum::Old(Box::new(connector::Forte::new())))
}
diff --git a/crates/router/src/types/transformers.rs b/crates/router/src/types/transformers.rs
index 5d5e72efd15..15eb8ba541c 100644
--- a/crates/router/src/types/transformers.rs
+++ b/crates/router/src/types/transformers.rs
@@ -278,7 +278,7 @@ impl ForeignTryFrom<api_enums::Connector> for common_enums::RoutableConnectors {
api_enums::Connector::Dlocal => Self::Dlocal,
api_enums::Connector::Ebanx => Self::Ebanx,
api_enums::Connector::Fiserv => Self::Fiserv,
- // api_enums::Connector::Fiservemea => Self::Fiservemea,
+ api_enums::Connector::Fiservemea => Self::Fiservemea,
api_enums::Connector::Forte => Self::Forte,
api_enums::Connector::Globalpay => Self::Globalpay,
api_enums::Connector::Globepay => Self::Globepay,
diff --git a/loadtest/config/development.toml b/loadtest/config/development.toml
index efdef8fc88d..ddcafa87ed0 100644
--- a/loadtest/config/development.toml
+++ b/loadtest/config/development.toml
@@ -100,7 +100,7 @@ dlocal.base_url = "https://sandbox.dlocal.com/"
dummyconnector.base_url = "http://localhost:8080/dummy-connector"
ebanx.base_url = "https://sandbox.ebanxpay.com/"
fiserv.base_url = "https://cert.api.fiservapps.com/"
-fiservemea.base_url = "https://prod.emea.api.fiservapps.com/sandbox/ipp/payments-gateway/v2"
+fiservemea.base_url = "https://prod.emea.api.fiservapps.com/sandbox"
forte.base_url = "https://sandbox.forte.net/api/v3"
globalpay.base_url = "https://apis.sandbox.globalpay.com/ucp/"
globepay.base_url = "https://pay.globepay.co/"
|
2024-08-22T12:30:20Z
|
## Type of Change
<!-- Put an `x` in the boxes that apply -->
- [ ] Bugfix
- [x] New feature
- [ ] Enhancement
- [ ] Refactoring
- [ ] Dependency updates
- [ ] Documentation
- [ ] CI/CD
## Description
<!-- Describe your changes in detail -->
Integrate card payments for new connector Fiserv-EMEA
https://docs.fiserv.dev/
### Additional Changes
- [ ] This PR modifies the API contract
- [ ] This PR modifies the database schema
- [ ] This PR modifies application configuration/environment variables
<!--
Provide links to the files with corresponding changes.
Following are the paths where you can find config files:
1. `config`
2. `crates/router/src/configs`
3. `loadtest/config`
-->
## Motivation and Context
<!--
Why is this change required? What problem does it solve?
If it fixes an open issue, please link to the issue here.
If you don't have an issue, we'd recommend starting with one first so the PR
can focus on the implementation (unless it is an obvious bug or documentation fix
that will have little conversation).
-->
https://github.com/juspay/hyperswitch/issues/5671
## How did you test it?
<!--
Did you write an integration/unit/API test to verify the code changes?
Or did you test this change manually (provide relevant screenshots)?
-->
Following flows need to be tested for card payments for new connector FiservEMEA:
1. Authorize:
Request:
```
curl --location 'http://localhost:8080/payments' \
--header 'Content-Type: application/json' \
--header 'Accept: application/json' \
--header 'api-key: dev_patS2PyLZVJvSG2Ik9brOOFlHKdIWJdkDaRBnfgNe5qNKNMAlTaYugK5gEIbxlks' \
--data-raw '{
"amount": 1212,
"currency": "EUR",
"confirm": true,
"profile_id": "pro_NP3j3oHUpby6juMfh84Q",
"capture_method": "automatic",
"customer": {
"id": "custom1234",
"name": "John Doe",
"email": "customer@gmail.com"
},
"routing": {
"type": "single",
"data": "fiservemea"
},
"payment_method": "card",
"payment_method_type": "credit",
"payment_method_data": {
"card": {
"card_number": "5204740000001002",
"card_exp_month": "10",
"card_exp_year": "24",
"card_holder_name": "joseph Doe",
"card_cvc": "002"
}
}
}'
```
Response:
```
{
"payment_id": "pay_GIEAyY9nxrGPnOdnJiMV",
"merchant_id": "merchant_1724327816",
"status": "succeeded",
"amount": 1212,
"net_amount": 1212,
"amount_capturable": 0,
"amount_received": 1212,
"connector": "fiservemea",
"client_secret": "pay_GIEAyY9nxrGPnOdnJiMV_secret_PHfwCA6AfIxfhQjweIYA",
"created": "2024-08-26T12:17:59.861Z",
"currency": "EUR",
"customer_id": "custom1234",
"customer": {
"id": "custom1234",
"name": "John Doe",
"email": "customer@gmail.com",
"phone": null,
"phone_country_code": null
},
"description": null,
"refunds": null,
"disputes": null,
"mandate_id": null,
"mandate_data": null,
"setup_future_usage": null,
"off_session": null,
"capture_on": null,
"capture_method": "automatic",
"payment_method": "card",
"payment_method_data": {
"card": {
"last4": "1002",
"card_type": null,
"card_network": null,
"card_issuer": null,
"card_issuing_country": null,
"card_isin": "520474",
"card_extended_bin": null,
"card_exp_month": "10",
"card_exp_year": "24",
"card_holder_name": null,
"payment_checks": null,
"authentication_data": null
},
"billing": null
},
"payment_token": null,
"shipping": null,
"billing": null,
"order_details": null,
"email": "customer@gmail.com",
"name": "John Doe",
"phone": null,
"return_url": null,
"authentication_type": "no_three_ds",
"statement_descriptor_name": null,
"statement_descriptor_suffix": null,
"next_action": null,
"cancellation_reason": null,
"error_code": null,
"error_message": null,
"unified_code": null,
"unified_message": null,
"payment_experience": null,
"payment_method_type": "credit",
"connector_label": null,
"business_country": null,
"business_label": "default",
"business_sub_label": null,
"allowed_payment_method_types": null,
"ephemeral_key": {
"customer_id": "custom1234",
"created_at": 1724674679,
"expires": 1724678279,
"secret": "epk_c3ab3c993c5847febcda59695a87b1e1"
},
"manual_retry_allowed": false,
"connector_transaction_id": "84665967780",
"frm_message": null,
"metadata": null,
"connector_metadata": null,
"feature_metadata": null,
"reference_id": "pay_GIEAyY9nxrGPnOdnJiMV_1",
"payment_link": null,
"profile_id": "pro_NP3j3oHUpby6juMfh84Q",
"surcharge_details": null,
"attempt_count": 1,
"merchant_decision": null,
"merchant_connector_id": "mca_c0KwedmN1LCB446Q3E14",
"incremental_authorization_allowed": null,
"authorization_count": null,
"incremental_authorizations": null,
"external_authentication_details": null,
"external_3ds_authentication_attempted": false,
"expires_on": "2024-08-26T12:32:59.861Z",
"fingerprint": null,
"browser_info": null,
"payment_method_id": null,
"payment_method_status": null,
"updated": "2024-08-26T12:18:02.551Z",
"charges": null,
"frm_metadata": null,
"merchant_order_reference_id": null
}
```
2. Capture:
Request:
```
curl --location 'http://localhost:8080/payments/pay_3gqMd6a03V9O81pzFitu/capture' \
--header 'Content-Type: application/json' \
--header 'Accept: application/json' \
--header 'api-key: dev_patS2PyLZVJvSG2Ik9brOOFlHKdIWJdkDaRBnfgNe5qNKNMAlTaYugK5gEIbxlks' \
--data '{
"statement_descriptor_name": "Joseph",
"statement_descriptor_prefix" :"joseph",
"statement_descriptor_suffix": "JS"
}'
```
Response:
```
{
"payment_id": "pay_3gqMd6a03V9O81pzFitu",
"merchant_id": "merchant_1724327816",
"status": "succeeded",
"amount": 1212,
"net_amount": 1212,
"amount_capturable": 0,
"amount_received": 1212,
"connector": "fiservemea",
"client_secret": "pay_3gqMd6a03V9O81pzFitu_secret_fv0iv7EjtuZgOR1StM6e",
"created": "2024-08-26T12:23:18.684Z",
"currency": "EUR",
"customer_id": "custom1234",
"customer": {
"id": "custom1234",
"name": "John Doe",
"email": "customer@gmail.com",
"phone": null,
"phone_country_code": null
},
"description": null,
"refunds": null,
"disputes": null,
"mandate_id": null,
"mandate_data": null,
"setup_future_usage": null,
"off_session": null,
"capture_on": null,
"capture_method": "manual",
"payment_method": "card",
"payment_method_data": {
"card": {
"last4": "1002",
"card_type": null,
"card_network": null,
"card_issuer": null,
"card_issuing_country": null,
"card_isin": "520474",
"card_extended_bin": null,
"card_exp_month": "10",
"card_exp_year": "24",
"card_holder_name": null,
"payment_checks": null,
"authentication_data": null
},
"billing": null
},
"payment_token": null,
"shipping": null,
"billing": null,
"order_details": null,
"email": "customer@gmail.com",
"name": "John Doe",
"phone": null,
"return_url": null,
"authentication_type": "no_three_ds",
"statement_descriptor_name": null,
"statement_descriptor_suffix": null,
"next_action": null,
"cancellation_reason": null,
"error_code": null,
"error_message": null,
"unified_code": null,
"unified_message": null,
"payment_experience": null,
"payment_method_type": "credit",
"connector_label": null,
"business_country": null,
"business_label": "default",
"business_sub_label": null,
"allowed_payment_method_types": null,
"ephemeral_key": null,
"manual_retry_allowed": false,
"connector_transaction_id": "84665968022",
"frm_message": null,
"metadata": null,
"connector_metadata": null,
"feature_metadata": null,
"reference_id": "pay_3gqMd6a03V9O81pzFitu_1",
"payment_link": null,
"profile_id": "pro_NP3j3oHUpby6juMfh84Q",
"surcharge_details": null,
"attempt_count": 1,
"merchant_decision": null,
"merchant_connector_id": "mca_c0KwedmN1LCB446Q3E14",
"incremental_authorization_allowed": null,
"authorization_count": null,
"incremental_authorizations": null,
"external_authentication_details": null,
"external_3ds_authentication_attempted": false,
"expires_on": "2024-08-26T12:38:18.683Z",
"fingerprint": null,
"browser_info": null,
"payment_method_id": null,
"payment_method_status": null,
"updated": "2024-08-26T12:23:30.244Z",
"charges": null,
"frm_metadata": null,
"merchant_order_reference_id": null
}
```
3. Void:
Request:
```
curl --location 'http://localhost:8080/payments/pay_60FywCJo2ZpuMRPzFCQZ/cancel' \
--header 'Content-Type: application/json' \
--header 'Accept: application/json' \
--header 'api-key: dev_patS2PyLZVJvSG2Ik9brOOFlHKdIWJdkDaRBnfgNe5qNKNMAlTaYugK5gEIbxlks' \
--data '{
}'
```
Response:
```
{
"payment_id": "pay_60FywCJo2ZpuMRPzFCQZ",
"merchant_id": "merchant_1724327816",
"status": "cancelled",
"amount": 1212,
"net_amount": 1212,
"amount_capturable": 0,
"amount_received": null,
"connector": "fiservemea",
"client_secret": "pay_60FywCJo2ZpuMRPzFCQZ_secret_rnSGK2xGOtwbMF8YDLQR",
"created": "2024-08-26T12:23:45.007Z",
"currency": "EUR",
"customer_id": "custom1234",
"customer": {
"id": "custom1234",
"name": "John Doe",
"email": "customer@gmail.com",
"phone": null,
"phone_country_code": null
},
"description": null,
"refunds": null,
"disputes": null,
"mandate_id": null,
"mandate_data": null,
"setup_future_usage": null,
"off_session": null,
"capture_on": null,
"capture_method": "manual",
"payment_method": "card",
"payment_method_data": {
"card": {
"last4": "1002",
"card_type": null,
"card_network": null,
"card_issuer": null,
"card_issuing_country": null,
"card_isin": "520474",
"card_extended_bin": null,
"card_exp_month": "10",
"card_exp_year": "24",
"card_holder_name": null,
"payment_checks": null,
"authentication_data": null
},
"billing": null
},
"payment_token": null,
"shipping": null,
"billing": null,
"order_details": null,
"email": "customer@gmail.com",
"name": "John Doe",
"phone": null,
"return_url": null,
"authentication_type": "no_three_ds",
"statement_descriptor_name": null,
"statement_descriptor_suffix": null,
"next_action": null,
"cancellation_reason": null,
"error_code": null,
"error_message": null,
"unified_code": null,
"unified_message": null,
"payment_experience": null,
"payment_method_type": "credit",
"connector_label": null,
"business_country": null,
"business_label": "default",
"business_sub_label": null,
"allowed_payment_method_types": null,
"ephemeral_key": null,
"manual_retry_allowed": false,
"connector_transaction_id": "84665968043",
"frm_message": null,
"metadata": null,
"connector_metadata": null,
"feature_metadata": null,
"reference_id": "pay_60FywCJo2ZpuMRPzFCQZ_1",
"payment_link": null,
"profile_id": "pro_NP3j3oHUpby6juMfh84Q",
"surcharge_details": null,
"attempt_count": 1,
"merchant_decision": null,
"merchant_connector_id": "mca_c0KwedmN1LCB446Q3E14",
"incremental_authorization_allowed": null,
"authorization_count": null,
"incremental_authorizations": null,
"external_authentication_details": null,
"external_3ds_authentication_attempted": false,
"expires_on": "2024-08-26T12:38:45.007Z",
"fingerprint": null,
"browser_info": null,
"payment_method_id": null,
"payment_method_status": null,
"updated": "2024-08-26T12:23:52.932Z",
"charges": null,
"frm_metadata": null,
"merchant_order_reference_id": null
}
```
4. Refunds:
Request:
```
curl --location 'http://localhost:8080/refunds' \
--header 'Content-Type: application/json' \
--header 'Accept: application/json' \
--header 'api-key: dev_patS2PyLZVJvSG2Ik9brOOFlHKdIWJdkDaRBnfgNe5qNKNMAlTaYugK5gEIbxlks' \
--data '{
"payment_id": "pay_3gqMd6a03V9O81pzFitu",
"refund_type": "instant"
}'
```
Response:
```
{
"refund_id": "ref_EbXtA5W6YIYZOYvjf0k1",
"payment_id": "pay_3gqMd6a03V9O81pzFitu",
"amount": 1212,
"currency": "EUR",
"status": "succeeded",
"reason": null,
"metadata": null,
"error_message": null,
"error_code": null,
"created_at": "2024-08-26T12:24:20.690Z",
"updated_at": "2024-08-26T12:24:23.132Z",
"connector": "fiservemea",
"profile_id": "pro_NP3j3oHUpby6juMfh84Q",
"merchant_connector_id": "mca_c0KwedmN1LCB446Q3E14",
"charges": null
}
```
Cypress Test Cases also added for Non-3DS Cards:
<img width="972" alt="Screenshot 2024-08-26 at 7 13 41 PM" src="https://github.com/user-attachments/assets/17a47afe-b7d9-4765-9ab4-a585dea0d549">
## Checklist
<!-- Put an `x` in the boxes that apply -->
- [x] I formatted the code `cargo +nightly fmt --all`
- [x] I addressed lints thrown by `cargo clippy`
- [x] I reviewed the submitted code
- [ ] I added unit tests for my changes where possible
|
771f48cfe0ec6d8625ca3ff3095f5d9806915779
|
|
juspay/hyperswitch
|
juspay__hyperswitch-5675
|
Bug: Prod intent email
Email not getting delivered for prod intent, modify the email
|
diff --git a/crates/router/src/consts/user.rs b/crates/router/src/consts/user.rs
index 18fdf0dcbe6..1a2b2ef60a4 100644
--- a/crates/router/src/consts/user.rs
+++ b/crates/router/src/consts/user.rs
@@ -5,7 +5,7 @@ pub const MAX_NAME_LENGTH: usize = 70;
/// The max length of company name and merchant should be same
/// because we are deriving the merchant name from company name
pub const MAX_COMPANY_NAME_LENGTH: usize = MAX_ALLOWED_MERCHANT_NAME_LENGTH;
-pub const BUSINESS_EMAIL: &str = "biz@hyperswitch.io";
+pub const BUSINESS_EMAIL: &str = "neeraj.kumar@juspay.in";
pub const RECOVERY_CODES_COUNT: usize = 8;
pub const RECOVERY_CODE_LENGTH: usize = 8; // This is without counting the hyphen in between
|
2024-08-22T12:57:43Z
|
## Type of Change
<!-- Put an `x` in the boxes that apply -->
- [x] Bugfix
- [ ] New feature
- [ ] Enhancement
- [ ] Refactoring
- [ ] Dependency updates
- [ ] Documentation
- [ ] CI/CD
## Description
<!-- Describe your changes in detail -->
Changed the business email to which production intent requests go to
### Additional Changes
- [ ] This PR modifies the API contract
- [ ] This PR modifies the database schema
- [ ] This PR modifies application configuration/environment variables
<!--
Provide links to the files with corresponding changes.
Following are the paths where you can find config files:
1. `config`
2. `crates/router/src/configs`
3. `loadtest/config`
-->
## Motivation and Context
<!--
Why is this change required? What problem does it solve?
If it fixes an open issue, please link to the issue here.
If you don't have an issue, we'd recommend starting with one first so the PR
can focus on the implementation (unless it is an obvious bug or documentation fix
that will have little conversation).
-->
## How did you test it?
<!--
Did you write an integration/unit/API test to verify the code changes?
Or did you test this change manually (provide relevant screenshots)?
-->
## Checklist
<!-- Put an `x` in the boxes that apply -->
- [x] I formatted the code `cargo +nightly fmt --all`
- [x] I addressed lints thrown by `cargo clippy`
- [x] I reviewed the submitted code
- [ ] I added unit tests for my changes where possible
|
0eaadc42b77e0f27cc4bb26c7e04d7c4f762b6d9
|
|
juspay/hyperswitch
|
juspay__hyperswitch-5668
|
Bug: [FEATURE] allow testing payout links in test_mode
### Feature Description
Payout links is secure by nature, meaning it can be consumed only when below pre-requisites are met
- `allowed_domains` are configured in profile - these are later used for validating the render request, and blow embedding these links using CSP
- render request was originated from an `iframe` (checks `Sec-Fetch-Dest` request header)
Testing these requires a little configuration overhead, and is not easily accessible, introducing a `test_mode` flag which bypasses these checks in non `Production` env
### Possible Implementation
Allow setting `test_mode` against payout_link_config in profile or to be directly sent the payout create request (`test_mode` in create request takes precedence over `test_mode` in profile).
Based on the value, perform below operations
- validate client's Host / Origin headers
- validate `Sec-Fetch-Dest`
- set `Content-Security-Policy` in response headers
- perform top level checks on client (window.top.location !== window.location)
### Have you spent some time checking if this feature request has been raised before?
- [X] I checked and didn't find a similar issue
### Have you read the Contributing Guidelines?
- [X] I have read the [Contributing Guidelines](https://github.com/juspay/hyperswitch/blob/main/docs/CONTRIBUTING.md)
### Are you willing to submit a PR?
Yes, I am willing to submit a PR!
|
diff --git a/api-reference-v2/openapi_spec.json b/api-reference-v2/openapi_spec.json
index af1186ac9ed..cc1b2f3137e 100644
--- a/api-reference-v2/openapi_spec.json
+++ b/api-reference-v2/openapi_spec.json
@@ -2953,7 +2953,15 @@
"$ref": "#/components/schemas/BusinessGenericLinkConfig"
},
{
- "type": "object"
+ "type": "object",
+ "properties": {
+ "payout_test_mode": {
+ "type": "boolean",
+ "description": "Allows for removing any validations / pre-requisites which are necessary in a production environment",
+ "default": false,
+ "nullable": true
+ }
+ }
}
]
},
@@ -13927,6 +13935,12 @@
"description": "List of payout methods shown on collect UI",
"example": "[{\"payment_method\": \"bank_transfer\", \"payment_method_types\": [\"ach\", \"bacs\"]}]",
"nullable": true
+ },
+ "test_mode": {
+ "type": "boolean",
+ "description": "`test_mode` allows for opening payout links without any restrictions. This removes\n- domain name validations\n- check for making sure link is accessed within an iframe",
+ "example": false,
+ "nullable": true
}
}
}
diff --git a/crates/api_models/src/admin.rs b/crates/api_models/src/admin.rs
index 18ad5dbf844..41378def83a 100644
--- a/crates/api_models/src/admin.rs
+++ b/crates/api_models/src/admin.rs
@@ -2516,6 +2516,10 @@ pub struct BusinessCollectLinkConfig {
pub struct BusinessPayoutLinkConfig {
#[serde(flatten)]
pub config: BusinessGenericLinkConfig,
+
+ /// Allows for removing any validations / pre-requisites which are necessary in a production environment
+ #[schema(value_type = Option<bool>, default = false)]
+ pub payout_test_mode: Option<bool>,
}
#[derive(Clone, Debug, serde::Deserialize, serde::Serialize, ToSchema)]
diff --git a/crates/api_models/src/payouts.rs b/crates/api_models/src/payouts.rs
index 0010c2988e1..fc3bd5fcda7 100644
--- a/crates/api_models/src/payouts.rs
+++ b/crates/api_models/src/payouts.rs
@@ -202,6 +202,12 @@ pub struct PayoutCreatePayoutLinkConfig {
/// List of payout methods shown on collect UI
#[schema(value_type = Option<Vec<EnabledPaymentMethod>>, example = r#"[{"payment_method": "bank_transfer", "payment_method_types": ["ach", "bacs"]}]"#)]
pub enabled_payment_methods: Option<Vec<link_utils::EnabledPaymentMethod>>,
+
+ /// `test_mode` allows for opening payout links without any restrictions. This removes
+ /// - domain name validations
+ /// - check for making sure link is accessed within an iframe
+ #[schema(value_type = Option<bool>, example = false)]
+ pub test_mode: Option<bool>,
}
/// The payout method information required for carrying out a payout
@@ -772,6 +778,7 @@ pub struct PayoutLinkDetails {
pub amount: common_utils::types::StringMajorUnit,
pub currency: common_enums::Currency,
pub locale: String,
+ pub test_mode: bool,
}
#[derive(Clone, Debug, serde::Serialize)]
@@ -787,4 +794,5 @@ pub struct PayoutLinkStatusDetails {
pub error_message: Option<String>,
#[serde(flatten)]
pub ui_config: link_utils::GenericLinkUiConfigFormData,
+ pub test_mode: bool,
}
diff --git a/crates/common_utils/src/link_utils.rs b/crates/common_utils/src/link_utils.rs
index e95832eeba9..dc7153f2c5b 100644
--- a/crates/common_utils/src/link_utils.rs
+++ b/crates/common_utils/src/link_utils.rs
@@ -167,6 +167,8 @@ pub struct PayoutLinkData {
pub currency: enums::Currency,
/// A list of allowed domains (glob patterns) where this link can be embedded / opened from
pub allowed_domains: HashSet<String>,
+ /// `test_mode` can be used for testing payout links without any restrictions
+ pub test_mode: Option<bool>,
}
crate::impl_to_sql_from_sql_json!(PayoutLinkData);
diff --git a/crates/diesel_models/src/business_profile.rs b/crates/diesel_models/src/business_profile.rs
index cab1aec410f..6c9b839e764 100644
--- a/crates/diesel_models/src/business_profile.rs
+++ b/crates/diesel_models/src/business_profile.rs
@@ -552,6 +552,7 @@ common_utils::impl_to_sql_from_sql_json!(BusinessPaymentLinkConfig);
pub struct BusinessPayoutLinkConfig {
#[serde(flatten)]
pub config: BusinessGenericLinkConfig,
+ pub payout_test_mode: Option<bool>,
}
#[derive(Clone, Debug, serde::Deserialize, serde::Serialize)]
diff --git a/crates/router/src/core/generic_link/payout_link/initiate/script.js b/crates/router/src/core/generic_link/payout_link/initiate/script.js
index 2327bfba13c..276ef644948 100644
--- a/crates/router/src/core/generic_link/payout_link/initiate/script.js
+++ b/crates/router/src/core/generic_link/payout_link/initiate/script.js
@@ -1,6 +1,10 @@
// @ts-check
// Top level checks
+// @ts-ignore
+var payoutDetails = window.__PAYOUT_DETAILS;
+var isTestMode = payoutDetails.test_mode;
+
var isFramed = false;
try {
isFramed = window.parent.location !== window.location;
@@ -12,7 +16,7 @@ try {
}
// Remove the script from DOM incase it's not iframed
-if (!isFramed) {
+if (!isTestMode && !isFramed) {
function initializePayoutSDK() {
var errMsg = "{{i18n_not_allowed}}";
var contentElement = document.getElementById("payout-link");
diff --git a/crates/router/src/core/payout_link.rs b/crates/router/src/core/payout_link.rs
index d18afe02056..7ca564426e8 100644
--- a/crates/router/src/core/payout_link.rs
+++ b/crates/router/src/core/payout_link.rs
@@ -79,7 +79,10 @@ pub async fn initiate_payout_link(
message: "payout link not found".to_string(),
})?;
- validator::validate_payout_link_render_request(request_headers, &payout_link)?;
+ let allowed_domains = validator::validate_payout_link_render_request_and_get_allowed_domains(
+ request_headers,
+ &payout_link,
+ )?;
// Check status and return form data accordingly
let has_expired = common_utils::date_time::now() > payout_link.expiry;
@@ -120,7 +123,7 @@ pub async fn initiate_payout_link(
Ok(services::ApplicationResponse::GenericLinkForm(Box::new(
GenericLinks {
- allowed_domains: (link_data.allowed_domains),
+ allowed_domains,
data: GenericLinksData::ExpiredLink(expired_link_data),
locale,
},
@@ -204,6 +207,7 @@ pub async fn initiate_payout_link(
amount,
currency: payout.destination_currency,
locale: locale.clone(),
+ test_mode: link_data.test_mode.unwrap_or(false),
};
let serialized_css_content = String::new();
@@ -224,7 +228,7 @@ pub async fn initiate_payout_link(
};
Ok(services::ApplicationResponse::GenericLinkForm(Box::new(
GenericLinks {
- allowed_domains: (link_data.allowed_domains),
+ allowed_domains,
data: GenericLinksData::PayoutLink(generic_form_data),
locale,
},
@@ -249,6 +253,7 @@ pub async fn initiate_payout_link(
error_code: payout_attempt.error_code,
error_message: payout_attempt.error_message,
ui_config: ui_config_data,
+ test_mode: link_data.test_mode.unwrap_or(false),
};
let serialized_css_content = String::new();
@@ -267,7 +272,7 @@ pub async fn initiate_payout_link(
};
Ok(services::ApplicationResponse::GenericLinkForm(Box::new(
GenericLinks {
- allowed_domains: (link_data.allowed_domains),
+ allowed_domains,
data: GenericLinksData::PayoutLinkStatus(generic_status_data),
locale,
},
diff --git a/crates/router/src/core/payouts.rs b/crates/router/src/core/payouts.rs
index a54f00d6aa0..e0bd37aef0d 100644
--- a/crates/router/src/core/payouts.rs
+++ b/crates/router/src/core/payouts.rs
@@ -4,7 +4,7 @@ pub mod helpers;
pub mod retry;
pub mod transformers;
pub mod validator;
-use std::vec::IntoIter;
+use std::{collections::HashSet, vec::IntoIter};
use api_models::{self, enums as api_enums, payouts::PayoutLinkResponse};
#[cfg(feature = "payout_retry")]
@@ -28,7 +28,7 @@ use futures::future::join_all;
use masking::{PeekInterface, Secret};
#[cfg(feature = "payout_retry")]
use retry::GsmValidation;
-use router_env::{instrument, logger, tracing};
+use router_env::{instrument, logger, tracing, Env};
use scheduler::utils as pt_utils;
use serde_json;
use time::Duration;
@@ -2614,15 +2614,34 @@ pub async fn create_payout_link(
.and_then(|config| config.ui_config.clone())
.or(profile_ui_config);
- // Validate allowed_domains presence
- let allowed_domains = profile_config
+ let test_mode_in_config = payout_link_config_req
.as_ref()
- .map(|config| config.config.allowed_domains.to_owned())
- .get_required_value("allowed_domains")
- .change_context(errors::ApiErrorResponse::LinkConfigurationError {
- message: "Payout links cannot be used without setting allowed_domains in profile"
- .to_string(),
- })?;
+ .and_then(|config| config.test_mode)
+ .or_else(|| profile_config.as_ref().and_then(|c| c.payout_test_mode));
+ let is_test_mode_enabled = test_mode_in_config.unwrap_or(false);
+
+ let allowed_domains = match (router_env::which(), is_test_mode_enabled) {
+ // Throw error in case test_mode was enabled in production
+ (Env::Production, true) => Err(report!(errors::ApiErrorResponse::LinkConfigurationError {
+ message: "test_mode cannot be true for creating payout_links in production".to_string()
+ })),
+ // Send empty set of whitelisted domains
+ (_, true) => {
+ Ok(HashSet::new())
+ },
+ // Otherwise, fetch and use allowed domains from profile config
+ (_, false) => {
+ profile_config
+ .as_ref()
+ .map(|config| config.config.allowed_domains.to_owned())
+ .get_required_value("allowed_domains")
+ .change_context(errors::ApiErrorResponse::LinkConfigurationError {
+ message:
+ "Payout links cannot be used without setting allowed_domains in profile. If you're using a non-production environment, you can set test_mode to true while in payout_link_config"
+ .to_string(),
+ })
+ }
+ }?;
// Form data to be injected in the link
let (logo, merchant_name, theme) = match ui_config {
@@ -2685,6 +2704,7 @@ pub async fn create_payout_link(
amount: MinorUnit::from(*amount),
currency: *currency,
allowed_domains,
+ test_mode: test_mode_in_config,
};
create_payout_link_db_entry(state, merchant_id, &data, req.return_url.clone()).await
diff --git a/crates/router/src/core/payouts/validator.rs b/crates/router/src/core/payouts/validator.rs
index d425725645b..2d47a60f23d 100644
--- a/crates/router/src/core/payouts/validator.rs
+++ b/crates/router/src/core/payouts/validator.rs
@@ -1,3 +1,5 @@
+use std::collections::HashSet;
+
use actix_web::http::header;
#[cfg(feature = "olap")]
use common_utils::errors::CustomResult;
@@ -5,7 +7,7 @@ use common_utils::validation::validate_domain_against_allowed_domains;
use diesel_models::generic_link::PayoutLink;
use error_stack::{report, ResultExt};
pub use hyperswitch_domain_models::errors::StorageError;
-use router_env::{instrument, tracing};
+use router_env::{instrument, tracing, which as router_env_which, Env};
use url::Url;
use super::helpers;
@@ -225,88 +227,105 @@ pub(super) fn validate_payout_list_request_for_joins(
Ok(())
}
-pub fn validate_payout_link_render_request(
+pub fn validate_payout_link_render_request_and_get_allowed_domains(
request_headers: &header::HeaderMap,
payout_link: &PayoutLink,
-) -> RouterResult<()> {
+) -> RouterResult<HashSet<String>> {
let link_id = payout_link.link_id.to_owned();
let link_data = payout_link.link_data.to_owned();
- // Fetch destination is "iframe"
- match request_headers.get("sec-fetch-dest").and_then(|v| v.to_str().ok()) {
- Some("iframe") => Ok(()),
- Some(requestor) => Err(report!(errors::ApiErrorResponse::AccessForbidden {
- resource: "payout_link".to_string(),
- }))
- .attach_printable_lazy(|| {
- format!(
- "Access to payout_link [{}] is forbidden when requested through {}",
- link_id, requestor
- )
- }),
- None => Err(report!(errors::ApiErrorResponse::AccessForbidden {
- resource: "payout_link".to_string(),
- }))
- .attach_printable_lazy(|| {
- format!(
- "Access to payout_link [{}] is forbidden when sec-fetch-dest is not present in request headers",
- link_id
- )
- }),
- }?;
+ let is_test_mode_enabled = link_data.test_mode.unwrap_or(false);
- // Validate origin / referer
- let domain_in_req = {
- let origin_or_referer = request_headers
- .get("origin")
- .or_else(|| request_headers.get("referer"))
- .and_then(|v| v.to_str().ok())
- .ok_or_else(|| {
- report!(errors::ApiErrorResponse::AccessForbidden {
+ match (router_env_which(), is_test_mode_enabled) {
+ // Throw error in case test_mode was enabled in production
+ (Env::Production, true) => Err(report!(errors::ApiErrorResponse::LinkConfigurationError {
+ message: "test_mode cannot be true for rendering payout_links in production"
+ .to_string()
+ })),
+ // Skip all validations when test mode is enabled in non prod env
+ (_, true) => Ok(HashSet::new()),
+ // Otherwise, perform validations
+ (_, false) => {
+ // Fetch destination is "iframe"
+ match request_headers.get("sec-fetch-dest").and_then(|v| v.to_str().ok()) {
+ Some("iframe") => Ok(()),
+ Some(requestor) => Err(report!(errors::ApiErrorResponse::AccessForbidden {
resource: "payout_link".to_string(),
- })
- })
- .attach_printable_lazy(|| {
- format!(
- "Access to payout_link [{}] is forbidden when origin or referer is not present in request headers",
- link_id
- )
- })?;
-
- let url = Url::parse(origin_or_referer)
- .map_err(|_| {
- report!(errors::ApiErrorResponse::AccessForbidden {
+ }))
+ .attach_printable_lazy(|| {
+ format!(
+ "Access to payout_link [{}] is forbidden when requested through {}",
+ link_id, requestor
+ )
+ }),
+ None => Err(report!(errors::ApiErrorResponse::AccessForbidden {
resource: "payout_link".to_string(),
- })
- })
- .attach_printable_lazy(|| {
- format!("Invalid URL found in request headers {}", origin_or_referer)
- })?;
+ }))
+ .attach_printable_lazy(|| {
+ format!(
+ "Access to payout_link [{}] is forbidden when sec-fetch-dest is not present in request headers",
+ link_id
+ )
+ }),
+ }?;
+
+ // Validate origin / referer
+ let domain_in_req = {
+ let origin_or_referer = request_headers
+ .get("origin")
+ .or_else(|| request_headers.get("referer"))
+ .and_then(|v| v.to_str().ok())
+ .ok_or_else(|| {
+ report!(errors::ApiErrorResponse::AccessForbidden {
+ resource: "payout_link".to_string(),
+ })
+ })
+ .attach_printable_lazy(|| {
+ format!(
+ "Access to payout_link [{}] is forbidden when origin or referer is not present in request headers",
+ link_id
+ )
+ })?;
- url.host_str()
- .and_then(|host| url.port().map(|port| format!("{}:{}", host, port)))
- .or_else(|| url.host_str().map(String::from))
- .ok_or_else(|| {
- report!(errors::ApiErrorResponse::AccessForbidden {
+ let url = Url::parse(origin_or_referer)
+ .map_err(|_| {
+ report!(errors::ApiErrorResponse::AccessForbidden {
+ resource: "payout_link".to_string(),
+ })
+ })
+ .attach_printable_lazy(|| {
+ format!("Invalid URL found in request headers {}", origin_or_referer)
+ })?;
+
+ url.host_str()
+ .and_then(|host| url.port().map(|port| format!("{}:{}", host, port)))
+ .or_else(|| url.host_str().map(String::from))
+ .ok_or_else(|| {
+ report!(errors::ApiErrorResponse::AccessForbidden {
+ resource: "payout_link".to_string(),
+ })
+ })
+ .attach_printable_lazy(|| {
+ format!("host or port not found in request headers {:?}", url)
+ })?
+ };
+
+ if validate_domain_against_allowed_domains(
+ &domain_in_req,
+ link_data.allowed_domains.clone(),
+ ) {
+ Ok(link_data.allowed_domains)
+ } else {
+ Err(report!(errors::ApiErrorResponse::AccessForbidden {
resource: "payout_link".to_string(),
+ }))
+ .attach_printable_lazy(|| {
+ format!(
+ "Access to payout_link [{}] is forbidden from requestor - {}",
+ link_id, domain_in_req
+ )
})
- })
- .attach_printable_lazy(|| {
- format!("host or port not found in request headers {:?}", url)
- })?
- };
-
- if validate_domain_against_allowed_domains(&domain_in_req, link_data.allowed_domains) {
- Ok(())
- } else {
- Err(report!(errors::ApiErrorResponse::AccessForbidden {
- resource: "payout_link".to_string(),
- }))
- .attach_printable_lazy(|| {
- format!(
- "Access to payout_link [{}] is forbidden from requestor - {}",
- link_id, domain_in_req
- )
- })
+ }
+ }
}
}
diff --git a/crates/router/src/types/transformers.rs b/crates/router/src/types/transformers.rs
index 2cc95281f03..b385cc64ad3 100644
--- a/crates/router/src/types/transformers.rs
+++ b/crates/router/src/types/transformers.rs
@@ -1788,6 +1788,7 @@ impl ForeignFrom<api_models::admin::BusinessPayoutLinkConfig>
fn foreign_from(item: api_models::admin::BusinessPayoutLinkConfig) -> Self {
Self {
config: item.config.foreign_into(),
+ payout_test_mode: item.payout_test_mode,
}
}
}
@@ -1798,6 +1799,7 @@ impl ForeignFrom<diesel_models::business_profile::BusinessPayoutLinkConfig>
fn foreign_from(item: diesel_models::business_profile::BusinessPayoutLinkConfig) -> Self {
Self {
config: item.config.foreign_into(),
+ payout_test_mode: item.payout_test_mode,
}
}
}
|
2024-08-22T11:01:33Z
|
## Type of Change
<!-- Put an `x` in the boxes that apply -->
- [ ] Bugfix
- [x] New feature
- [ ] Enhancement
- [ ] Refactoring
- [ ] Dependency updates
- [ ] Documentation
- [ ] CI/CD
## Description
Described in #5668
### Additional Changes
- [x] This PR modifies the API contract
- [ ] This PR modifies the database schema
- [ ] This PR modifies application configuration/environment variables
<!--
Provide links to the files with corresponding changes.
Following are the paths where you can find config files:
1. `config`
2. `crates/router/src/configs`
3. `loadtest/config`
-->
## Motivation and Context
Allows for easily testing payout links in non prod env.
## How did you test it?
<details>
<summary>1. Create payout link without setting allowed_domains - *SHOULD FAIL*</summary>
curl --location 'http://localhost:8080/payouts/create' \
--header 'Accept-Language: fr' \
--header 'Content-Type: application/json' \
--header 'api-key: dev_1axlWLG2ZUMWX1B8TMZ7m1Y7EMIzJl5BW1iLEB6etVvLbEQ1XCKSj6rXHYegkkd3' \
--data '{
"amount": 1,
"currency": "EUR",
"customer_id": "cus_8GU0bxEIp0EyvQiGSoXw",
"description": "Its my first payout request",
"billing": {
"address": {
"city": "Hoogeveen",
"country": "NL",
"line1": "Raadhuisplein",
"line2": "92",
"zip": "7901 BW",
"state": "FL",
"first_name": "John",
"last_name": "Doe"
},
"phone": {
"number": "0650242319",
"country_code": "+31"
}
},
"return_url": "https://www.google.co.in",
"entity_type": "Individual",
"confirm": false,
"auto_fulfill": true,
"session_expiry": 1000000,
"priority": "instant",
"profile_id": "pro_24e5hK7LExVPjGqadW55",
"payout_link": true,
"connector": [
"adyen"
],
"payout_link_config": {
"theme": "#0066ff",
"logo": "https://hyperswitch.io/favicon.ico",
"merchant_name": "HyperSwitch Inc.",
"enabled_payment_methods": [
{
"payment_method": "card",
"payment_method_types": [
"debit",
"credit"
]
},
{
"payment_method": "bank_transfer",
"payment_method_types": [
"ach",
"bacs",
"sepa"
]
},
{
"payment_method": "wallet",
"payment_method_types": [
"pix",
"paypal",
"venmo"
]
}
]
}
}'

</details>
<details>
<summary>2. Create payout link without setting allowed_domains in test_mode - *PASS*</summary>
curl --location 'http://localhost:8080/payouts/create' \
--header 'Accept-Language: fr' \
--header 'Content-Type: application/json' \
--header 'api-key: dev_1axlWLG2ZUMWX1B8TMZ7m1Y7EMIzJl5BW1iLEB6etVvLbEQ1XCKSj6rXHYegkkd3' \
--data '{
"amount": 1,
"currency": "EUR",
"customer_id": "cus_8GU0bxEIp0EyvQiGSoXw",
"description": "Its my first payout request",
"billing": {
"address": {
"city": "Hoogeveen",
"country": "NL",
"line1": "Raadhuisplein",
"line2": "92",
"zip": "7901 BW",
"state": "FL",
"first_name": "John",
"last_name": "Doe"
},
"phone": {
"number": "0650242319",
"country_code": "+31"
}
},
"return_url": "https://www.google.co.in",
"entity_type": "Individual",
"confirm": false,
"auto_fulfill": true,
"session_expiry": 1000000,
"priority": "instant",
"profile_id": "pro_24e5hK7LExVPjGqadW55",
"payout_link": true,
"connector": [
"adyen"
],
"payout_link_config": {
"theme": "#0066ff",
"logo": "https://hyperswitch.io/favicon.ico",
"merchant_name": "HyperSwitch Inc.",
"test_mode": true,
"enabled_payment_methods": [
{
"payment_method": "card",
"payment_method_types": [
"debit",
"credit"
]
},
{
"payment_method": "bank_transfer",
"payment_method_types": [
"ach",
"bacs",
"sepa"
]
},
{
"payment_method": "wallet",
"payment_method_types": [
"pix",
"paypal",
"venmo"
]
}
]
}
}'


</details>
<details>
<summary>3. Create payout link using allowed_domains without test_mode - *SHOULD OPEN ONLY IN AN IFRAME*</summary>
curl --location 'http://localhost:8080/payouts/create' \
--header 'Accept-Language: fr' \
--header 'Content-Type: application/json' \
--header 'api-key: dev_1axlWLG2ZUMWX1B8TMZ7m1Y7EMIzJl5BW1iLEB6etVvLbEQ1XCKSj6rXHYegkkd3' \
--data '{
"amount": 1,
"currency": "EUR",
"customer_id": "cus_8GU0bxEIp0EyvQiGSoXw",
"description": "Its my first payout request",
"billing": {
"address": {
"city": "Hoogeveen",
"country": "NL",
"line1": "Raadhuisplein",
"line2": "92",
"zip": "7901 BW",
"state": "FL",
"first_name": "John",
"last_name": "Doe"
},
"phone": {
"number": "0650242319",
"country_code": "+31"
}
},
"return_url": "https://www.google.co.in",
"entity_type": "Individual",
"confirm": false,
"auto_fulfill": true,
"session_expiry": 1000000,
"priority": "instant",
"profile_id": "pro_24e5hK7LExVPjGqadW55",
"payout_link": true,
"connector": [
"adyen"
],
"payout_link_config": {
"theme": "#0066ff",
"logo": "https://hyperswitch.io/favicon.ico",
"merchant_name": "HyperSwitch Inc.",
"enabled_payment_methods": [
{
"payment_method": "card",
"payment_method_types": [
"debit",
"credit"
]
},
{
"payment_method": "bank_transfer",
"payment_method_types": [
"ach",
"bacs",
"sepa"
]
},
{
"payment_method": "wallet",
"payment_method_types": [
"pix",
"paypal",
"venmo"
]
}
]
}
}'



</details>
## Checklist
<!-- Put an `x` in the boxes that apply -->
- [x] I formatted the code `cargo +nightly fmt --all`
- [x] I addressed lints thrown by `cargo clippy`
- [x] I reviewed the submitted code
- [ ] I added unit tests for my changes where possible
|
963a2547e87fc7a4e8ed55627d3e7b9da2022f21
|
|
juspay/hyperswitch
|
juspay__hyperswitch-5634
|
Bug: [FIX]: add open banking in payment methods in wasm
add open banking in payment methods in wasm
|
diff --git a/crates/connector_configs/src/response_modifier.rs b/crates/connector_configs/src/response_modifier.rs
index 06f9d25b65d..b6b2e8555e3 100644
--- a/crates/connector_configs/src/response_modifier.rs
+++ b/crates/connector_configs/src/response_modifier.rs
@@ -225,6 +225,13 @@ impl ConnectorApiIntegrationPayload {
}
}
+ let open_banking = DashboardPaymentMethodPayload {
+ payment_method: api_models::enums::PaymentMethod::OpenBanking,
+ payment_method_type: api_models::enums::PaymentMethod::OpenBanking.to_string(),
+ provider: Some(open_banking_details),
+ card_provider: None,
+ };
+
let upi = DashboardPaymentMethodPayload {
payment_method: api_models::enums::PaymentMethod::Upi,
payment_method_type: api_models::enums::PaymentMethod::Upi.to_string(),
@@ -322,6 +329,7 @@ impl ConnectorApiIntegrationPayload {
DashboardRequestPayload {
connector: response.connector_name,
payment_methods_enabled: Some(vec![
+ open_banking,
upi,
voucher,
reward,
|
2024-08-14T12:08:54Z
|
## Type of Change
<!-- Put an `x` in the boxes that apply -->
- [x] Bugfix
- [ ] New feature
- [ ] Enhancement
- [ ] Refactoring
- [ ] Dependency updates
- [ ] Documentation
- [ ] CI/CD
## Description
plaid payment processor configuring was breaking

<!-- Describe your changes in detail -->
### Additional Changes
- [ ] This PR modifies the API contract
- [ ] This PR modifies the database schema
- [ ] This PR modifies application configuration/environment variables
<!--
Provide links to the files with corresponding changes.
Following are the paths where you can find config files:
1. `config`
2. `crates/router/src/configs`
3. `loadtest/config`
-->
## Motivation and Context
plaid connector configuring was breaking
<!--
Why is this change required? What problem does it solve?
If it fixes an open issue, please link to the issue here.
If you don't have an issue, we'd recommend starting with one first so the PR
can focus on the implementation (unless it is an obvious bug or documentation fix
that will have little conversation).
-->
## How did you test it?
updated the wasm, and tested with frontend changes locally it is working fine
<!--
Did you write an integration/unit/API test to verify the code changes?
Or did you test this change manually (provide relevant screenshots)?
-->
## Checklist
<!-- Put an `x` in the boxes that apply -->
- [x] I formatted the code `cargo +nightly fmt --all`
- [x] I addressed lints thrown by `cargo clippy`
- [x] I reviewed the submitted code
- [ ] I added unit tests for my changes where possible
|
2249010ceb9fc03249d8feb428f2209b2d2ee9f4
|
|
juspay/hyperswitch
|
juspay__hyperswitch-5650
|
Bug: feat(user_roles): Update both V1 and V2 user roles
Since we are introducing V2 user_roles. Before we start inserting V2 data, we should complete the other operations (update, delete and read).
This issue tracks the progress of changes for update.
|
diff --git a/crates/diesel_models/src/query/user_role.rs b/crates/diesel_models/src/query/user_role.rs
index b84ea63de1d..b7f79a4438f 100644
--- a/crates/diesel_models/src/query/user_role.rs
+++ b/crates/diesel_models/src/query/user_role.rs
@@ -41,47 +41,6 @@ impl UserRole {
.await
}
- pub async fn update_by_user_id_merchant_id(
- conn: &PgPooledConn,
- user_id: String,
- merchant_id: id_type::MerchantId,
- update: UserRoleUpdate,
- version: UserRoleVersion,
- ) -> StorageResult<Self> {
- generics::generic_update_with_unique_predicate_get_result::<
- <Self as HasTable>::Table,
- _,
- _,
- _,
- >(
- conn,
- dsl::user_id
- .eq(user_id)
- .and(dsl::merchant_id.eq(merchant_id))
- .and(dsl::version.eq(version)),
- UserRoleUpdateInternal::from(update),
- )
- .await
- }
-
- pub async fn update_by_user_id_org_id(
- conn: &PgPooledConn,
- user_id: String,
- org_id: id_type::OrganizationId,
- update: UserRoleUpdate,
- version: UserRoleVersion,
- ) -> StorageResult<Vec<Self>> {
- generics::generic_update_with_results::<<Self as HasTable>::Table, _, _, _>(
- conn,
- dsl::user_id
- .eq(user_id)
- .and(dsl::org_id.eq(org_id))
- .and(dsl::version.eq(version)),
- UserRoleUpdateInternal::from(update),
- )
- .await
- }
-
pub async fn list_by_user_id(
conn: &PgPooledConn,
user_id: String,
@@ -147,6 +106,46 @@ impl UserRole {
generics::generic_find_one::<<Self as HasTable>::Table, _, _>(conn, predicate).await
}
+ pub async fn update_by_user_id_org_id_merchant_id_profile_id(
+ conn: &PgPooledConn,
+ user_id: String,
+ org_id: id_type::OrganizationId,
+ merchant_id: id_type::MerchantId,
+ profile_id: Option<String>,
+ update: UserRoleUpdate,
+ version: UserRoleVersion,
+ ) -> StorageResult<Self> {
+ // Checking in user roles, for a user in token hierarchy, only one of the relation will be true, either org level, merchant level or profile level
+ // (org_id = ? && merchant_id = null && profile_id = null) || (org_id = ? && merchant_id = ? && profile_id = null) || (org_id = ? && merchant_id = ? && profile_id = ?)
+ let check_lineage = dsl::org_id
+ .eq(org_id.clone())
+ .and(dsl::merchant_id.is_null().and(dsl::profile_id.is_null()))
+ .or(dsl::org_id.eq(org_id.clone()).and(
+ dsl::merchant_id
+ .eq(merchant_id.clone())
+ .and(dsl::profile_id.is_null()),
+ ))
+ .or(dsl::org_id.eq(org_id).and(
+ dsl::merchant_id
+ .eq(merchant_id)
+ //TODO: In case of None, profile_id = NULL its unexpected behaviour, after V1 profile id will not be option
+ .and(dsl::profile_id.eq(profile_id)),
+ ));
+
+ let predicate = dsl::user_id
+ .eq(user_id)
+ .and(check_lineage)
+ .and(dsl::version.eq(version));
+
+ generics::generic_update_with_unique_predicate_get_result::<
+ <Self as HasTable>::Table,
+ UserRoleUpdateInternal,
+ _,
+ _,
+ >(conn, predicate, update.into())
+ .await
+ }
+
pub async fn delete_by_user_id_org_id_merchant_id_profile_id(
conn: &PgPooledConn,
user_id: String,
diff --git a/crates/diesel_models/src/user_role.rs b/crates/diesel_models/src/user_role.rs
index 87e6f332328..1a006f2a4ad 100644
--- a/crates/diesel_models/src/user_role.rs
+++ b/crates/diesel_models/src/user_role.rs
@@ -51,6 +51,7 @@ pub struct UserRoleUpdateInternal {
last_modified: PrimitiveDateTime,
}
+#[derive(Clone)]
pub enum UserRoleUpdate {
UpdateStatus {
status: enums::UserStatus,
diff --git a/crates/router/src/core/user.rs b/crates/router/src/core/user.rs
index 042e2c19e7c..671d3ee1535 100644
--- a/crates/router/src/core/user.rs
+++ b/crates/router/src/core/user.rs
@@ -594,19 +594,58 @@ pub async fn reset_password(
.change_context(UserErrors::InternalServerError)?;
if let Some(inviter_merchant_id) = email_token.get_merchant_id() {
- let update_status_result = state
+ let key_manager_state = &(&state).into();
+
+ let key_store = state
.store
- .update_user_role_by_user_id_merchant_id(
+ .get_merchant_key_store_by_merchant_id(
+ key_manager_state,
+ inviter_merchant_id,
+ &state.store.get_master_key().to_vec().into(),
+ )
+ .await
+ .change_context(UserErrors::InternalServerError)
+ .attach_printable("merchant_key_store not found")?;
+
+ let merchant_account = state
+ .store
+ .find_merchant_account_by_merchant_id(
+ key_manager_state,
+ inviter_merchant_id,
+ &key_store,
+ )
+ .await
+ .change_context(UserErrors::InternalServerError)
+ .attach_printable("merchant_account not found")?;
+
+ let (update_v1_result, update_v2_result) =
+ utils::user_role::update_v1_and_v2_user_roles_in_db(
+ &state,
user.user_id.clone().as_str(),
+ &merchant_account.organization_id,
inviter_merchant_id,
+ None,
UserRoleUpdate::UpdateStatus {
status: UserStatus::Active,
modified_by: user.user_id.clone(),
},
- UserRoleVersion::V1,
)
.await;
- logger::info!(?update_status_result);
+
+ if update_v1_result
+ .as_ref()
+ .is_err_and(|err| !err.current_context().is_db_not_found())
+ || update_v2_result
+ .as_ref()
+ .is_err_and(|err| !err.current_context().is_db_not_found())
+ {
+ return Err(report!(UserErrors::InternalServerError));
+ }
+
+ if update_v1_result.is_err() && update_v2_result.is_err() {
+ return Err(report!(UserErrors::InvalidRoleOperation))
+ .attach_printable("User not found in the organization")?;
+ }
}
let _ = auth::blacklist::insert_email_token_in_blacklist(&state, &token)
@@ -1014,19 +1053,53 @@ pub async fn accept_invite_from_email(
.get_merchant_id()
.ok_or(UserErrors::InternalServerError)?;
- let update_status_result = state
+ let key_manager_state = &(&state).into();
+
+ let key_store = state
.store
- .update_user_role_by_user_id_merchant_id(
- user.get_user_id(),
+ .get_merchant_key_store_by_merchant_id(
+ key_manager_state,
merchant_id,
- UserRoleUpdate::UpdateStatus {
- status: UserStatus::Active,
- modified_by: user.get_user_id().to_string(),
- },
- UserRoleVersion::V1,
+ &state.store.get_master_key().to_vec().into(),
)
.await
- .change_context(UserErrors::InternalServerError)?;
+ .change_context(UserErrors::InternalServerError)
+ .attach_printable("merchant_key_store not found")?;
+
+ let merchant_account = state
+ .store
+ .find_merchant_account_by_merchant_id(key_manager_state, merchant_id, &key_store)
+ .await
+ .change_context(UserErrors::InternalServerError)
+ .attach_printable("merchant_account not found")?;
+
+ let (update_v1_result, update_v2_result) = utils::user_role::update_v1_and_v2_user_roles_in_db(
+ &state,
+ user.get_user_id(),
+ &merchant_account.organization_id,
+ merchant_id,
+ None,
+ UserRoleUpdate::UpdateStatus {
+ status: UserStatus::Active,
+ modified_by: user.get_user_id().to_string(),
+ },
+ )
+ .await;
+
+ if update_v1_result
+ .as_ref()
+ .is_err_and(|err| !err.current_context().is_db_not_found())
+ || update_v2_result
+ .as_ref()
+ .is_err_and(|err| !err.current_context().is_db_not_found())
+ {
+ return Err(report!(UserErrors::InternalServerError));
+ }
+
+ if update_v1_result.is_err() && update_v2_result.is_err() {
+ return Err(report!(UserErrors::InvalidRoleOperation))
+ .attach_printable("User not found in the organization")?;
+ }
let _ = auth::blacklist::insert_email_token_in_blacklist(&state, &token)
.await
@@ -1039,21 +1112,18 @@ pub async fn accept_invite_from_email(
.change_context(UserErrors::InternalServerError)?
.into();
- let token = utils::user::generate_jwt_auth_token_without_profile(
- &state,
- &user_from_db,
- &update_status_result,
- )
- .await?;
- utils::user_role::set_role_permissions_in_cache_by_user_role(&state, &update_status_result)
- .await;
+ let user_role = user_from_db
+ .get_preferred_or_active_user_role_from_db(&state)
+ .await
+ .change_context(UserErrors::InternalServerError)?;
- let response = utils::user::get_dashboard_entry_response(
- &state,
- user_from_db,
- update_status_result,
- token.clone(),
- )?;
+ let token =
+ utils::user::generate_jwt_auth_token_without_profile(&state, &user_from_db, &user_role)
+ .await?;
+ utils::user_role::set_role_permissions_in_cache_by_user_role(&state, &user_role).await;
+
+ let response =
+ utils::user::get_dashboard_entry_response(&state, user_from_db, user_role, token.clone())?;
auth::cookies::set_cookie_response(response, token)
}
@@ -1091,19 +1161,53 @@ pub async fn accept_invite_from_email_token_only_flow(
.get_merchant_id()
.ok_or(UserErrors::LinkInvalid)?;
- let user_role = state
+ let key_manager_state = &(&state).into();
+
+ let key_store = state
.store
- .update_user_role_by_user_id_merchant_id(
- user_from_db.get_user_id(),
+ .get_merchant_key_store_by_merchant_id(
+ key_manager_state,
merchant_id,
- UserRoleUpdate::UpdateStatus {
- status: UserStatus::Active,
- modified_by: user_from_db.get_user_id().to_string(),
- },
- UserRoleVersion::V1,
+ &state.store.get_master_key().to_vec().into(),
)
.await
- .change_context(UserErrors::InternalServerError)?;
+ .change_context(UserErrors::InternalServerError)
+ .attach_printable("merchant_key_store not found")?;
+
+ let merchant_account = state
+ .store
+ .find_merchant_account_by_merchant_id(key_manager_state, merchant_id, &key_store)
+ .await
+ .change_context(UserErrors::InternalServerError)
+ .attach_printable("merchant_account not found")?;
+
+ let (update_v1_result, update_v2_result) = utils::user_role::update_v1_and_v2_user_roles_in_db(
+ &state,
+ user_from_db.get_user_id(),
+ &merchant_account.organization_id,
+ merchant_id,
+ None,
+ UserRoleUpdate::UpdateStatus {
+ status: UserStatus::Active,
+ modified_by: user_from_db.get_user_id().to_owned(),
+ },
+ )
+ .await;
+
+ if update_v1_result
+ .as_ref()
+ .is_err_and(|err| !err.current_context().is_db_not_found())
+ || update_v2_result
+ .as_ref()
+ .is_err_and(|err| !err.current_context().is_db_not_found())
+ {
+ return Err(report!(UserErrors::InternalServerError));
+ }
+
+ if update_v1_result.is_err() && update_v2_result.is_err() {
+ return Err(report!(UserErrors::InvalidRoleOperation))
+ .attach_printable("User not found in the organization")?;
+ }
if !user_from_db.is_verified() {
let _ = state
@@ -1126,6 +1230,11 @@ pub async fn accept_invite_from_email_token_only_flow(
)?;
let next_flow = current_flow.next(user_from_db.clone(), &state).await?;
+ let user_role = user_from_db
+ .get_preferred_or_active_user_role_from_db(&state)
+ .await
+ .change_context(UserErrors::InternalServerError)?;
+
let token = next_flow
.get_token_with_user_role(&state, &user_role)
.await?;
diff --git a/crates/router/src/core/user_role.rs b/crates/router/src/core/user_role.rs
index d9ee8f21805..b599a26fdfc 100644
--- a/crates/router/src/core/user_role.rs
+++ b/crates/router/src/core/user_role.rs
@@ -7,10 +7,8 @@ use diesel_models::{
};
use error_stack::{report, ResultExt};
use once_cell::sync::Lazy;
-use router_env::logger;
use crate::{
- consts,
core::errors::{StorageErrorExt, UserErrors, UserResponse},
routes::{app::ReqState, SessionState},
services::{
@@ -115,103 +113,155 @@ pub async fn update_user_role(
.attach_printable("User Changing their own role");
}
- let user_role_to_be_updated = user_to_be_updated
- .get_role_from_db_by_merchant_id(&state, &user_from_token.merchant_id)
- .await
- .to_not_found_response(UserErrors::InvalidRoleOperation)?;
-
- let role_to_be_updated = roles::RoleInfo::from_role_id(
+ let updator_role = roles::RoleInfo::from_role_id(
&state,
- &user_role_to_be_updated.role_id,
+ &user_from_token.role_id,
&user_from_token.merchant_id,
&user_from_token.org_id,
)
.await
.change_context(UserErrors::InternalServerError)?;
- if !role_to_be_updated.is_updatable() {
- return Err(report!(UserErrors::InvalidRoleOperation)).attach_printable(format!(
- "User role cannot be updated from {}",
- role_to_be_updated.get_role_id()
- ));
- }
+ let mut is_updated = false;
- state
+ let v2_user_role_to_be_updated = match state
.store
- .update_user_role_by_user_id_merchant_id(
+ .find_user_role_by_user_id_and_lineage(
user_to_be_updated.get_user_id(),
- &user_role_to_be_updated
- .merchant_id
- .ok_or(UserErrors::InternalServerError)
- .attach_printable("merchant_id not found in user_role")?,
- UserRoleUpdate::UpdateRole {
- role_id: req.role_id.clone(),
- modified_by: user_from_token.user_id,
- },
- UserRoleVersion::V1,
+ &user_from_token.org_id,
+ &user_from_token.merchant_id,
+ None,
+ UserRoleVersion::V2,
)
.await
- .to_not_found_response(UserErrors::InvalidRoleOperation)
- .attach_printable("User with given email is not found in the organization")?;
+ {
+ Ok(user_role) => Some(user_role),
+ Err(e) => {
+ if e.current_context().is_db_not_found() {
+ None
+ } else {
+ return Err(UserErrors::InternalServerError.into());
+ }
+ }
+ };
- auth::blacklist::insert_user_in_blacklist(&state, user_to_be_updated.get_user_id()).await?;
+ if let Some(user_role) = v2_user_role_to_be_updated {
+ let role_to_be_updated = roles::RoleInfo::from_role_id(
+ &state,
+ &user_role.role_id,
+ &user_from_token.merchant_id,
+ &user_from_token.org_id,
+ )
+ .await
+ .change_context(UserErrors::InternalServerError)?;
- Ok(ApplicationResponse::StatusOk)
-}
+ if !role_to_be_updated.is_updatable() {
+ return Err(report!(UserErrors::InvalidRoleOperation)).attach_printable(format!(
+ "User role cannot be updated from {}",
+ role_to_be_updated.get_role_id()
+ ));
+ }
-pub async fn transfer_org_ownership(
- state: SessionState,
- user_from_token: auth::UserFromToken,
- req: user_role_api::TransferOrgOwnershipRequest,
- _req_state: ReqState,
-) -> UserResponse<user_api::DashboardEntryResponse> {
- if user_from_token.role_id != consts::user_role::ROLE_ID_ORGANIZATION_ADMIN {
- return Err(report!(UserErrors::InvalidRoleOperation)).attach_printable(format!(
- "role_id = {} is not org_admin",
- user_from_token.role_id
- ));
- }
+ if updator_role.get_entity_type() < role_to_be_updated.get_entity_type() {
+ return Err(report!(UserErrors::InvalidRoleOperation)).attach_printable(format!(
+ "Invalid operation, update requestor = {} cannot update target = {}",
+ updator_role.get_entity_type(),
+ role_to_be_updated.get_entity_type()
+ ));
+ }
- let user_to_be_updated =
- utils::user::get_user_from_db_by_email(&state, domain::UserEmail::try_from(req.email)?)
+ state
+ .store
+ .update_user_role_by_user_id_and_lineage(
+ user_to_be_updated.get_user_id(),
+ &user_from_token.org_id,
+ &user_from_token.merchant_id,
+ None,
+ UserRoleUpdate::UpdateRole {
+ role_id: req.role_id.clone(),
+ modified_by: user_from_token.user_id.clone(),
+ },
+ UserRoleVersion::V2,
+ )
.await
- .to_not_found_response(UserErrors::InvalidRoleOperation)
- .attach_printable("User not found in our records".to_string())?;
+ .change_context(UserErrors::InternalServerError)?;
- if user_from_token.user_id == user_to_be_updated.get_user_id() {
- return Err(report!(UserErrors::InvalidRoleOperation))
- .attach_printable("User transferring ownership to themselves".to_string());
+ is_updated = true;
}
- state
+ let v1_user_role_to_be_updated = match state
.store
- .transfer_org_ownership_between_users(
- &user_from_token.user_id,
+ .find_user_role_by_user_id_and_lineage(
user_to_be_updated.get_user_id(),
&user_from_token.org_id,
+ &user_from_token.merchant_id,
+ None,
UserRoleVersion::V1,
)
.await
+ {
+ Ok(user_role) => Some(user_role),
+ Err(e) => {
+ if e.current_context().is_db_not_found() {
+ None
+ } else {
+ return Err(UserErrors::InternalServerError.into());
+ }
+ }
+ };
+
+ if let Some(user_role) = v1_user_role_to_be_updated {
+ let role_to_be_updated = roles::RoleInfo::from_role_id(
+ &state,
+ &user_role.role_id,
+ &user_from_token.merchant_id,
+ &user_from_token.org_id,
+ )
+ .await
.change_context(UserErrors::InternalServerError)?;
- auth::blacklist::insert_user_in_blacklist(&state, user_to_be_updated.get_user_id()).await?;
- auth::blacklist::insert_user_in_blacklist(&state, &user_from_token.user_id).await?;
+ if !role_to_be_updated.is_updatable() {
+ return Err(report!(UserErrors::InvalidRoleOperation)).attach_printable(format!(
+ "User role cannot be updated from {}",
+ role_to_be_updated.get_role_id()
+ ));
+ }
- let user_from_db = user_from_token.get_user_from_db(&state).await?;
- let user_role = user_from_db
- .get_role_from_db_by_merchant_id(&state, &user_from_token.merchant_id)
- .await
- .to_not_found_response(UserErrors::InvalidRoleOperation)?;
+ if updator_role.get_entity_type() < role_to_be_updated.get_entity_type() {
+ return Err(report!(UserErrors::InvalidRoleOperation)).attach_printable(format!(
+ "Invalid operation, update requestor = {} cannot update target = {}",
+ updator_role.get_entity_type(),
+ role_to_be_updated.get_entity_type()
+ ));
+ }
- utils::user_role::set_role_permissions_in_cache_by_user_role(&state, &user_role).await;
+ state
+ .store
+ .update_user_role_by_user_id_and_lineage(
+ user_to_be_updated.get_user_id(),
+ &user_from_token.org_id,
+ &user_from_token.merchant_id,
+ None,
+ UserRoleUpdate::UpdateRole {
+ role_id: req.role_id.clone(),
+ modified_by: user_from_token.user_id,
+ },
+ UserRoleVersion::V1,
+ )
+ .await
+ .change_context(UserErrors::InternalServerError)?;
- let token =
- utils::user::generate_jwt_auth_token_without_profile(&state, &user_from_db, &user_role)
- .await?;
- let response =
- utils::user::get_dashboard_entry_response(&state, user_from_db, user_role, token.clone())?;
+ is_updated = true;
+ }
- auth::cookies::set_cookie_response(response, token)
+ if !is_updated {
+ return Err(report!(UserErrors::InvalidRoleOperation))
+ .attach_printable("User with given email is not found in the organization")?;
+ }
+
+ auth::blacklist::insert_user_in_blacklist(&state, user_to_be_updated.get_user_id()).await?;
+
+ Ok(ApplicationResponse::StatusOk)
}
pub async fn accept_invitation(
@@ -219,30 +269,43 @@ pub async fn accept_invitation(
user_token: auth::UserFromToken,
req: user_role_api::AcceptInvitationRequest,
) -> UserResponse<()> {
- futures::future::join_all(req.merchant_ids.iter().map(|merchant_id| async {
- state
- .store
- .update_user_role_by_user_id_merchant_id(
- user_token.user_id.as_str(),
- merchant_id,
- UserRoleUpdate::UpdateStatus {
- status: UserStatus::Active,
- modified_by: user_token.user_id.clone(),
- },
- UserRoleVersion::V1,
- )
- .await
- .map_err(|e| {
- logger::error!("Error while accepting invitation {e:?}");
- })
- .ok()
- }))
- .await
- .into_iter()
- .reduce(Option::or)
- .flatten()
- .ok_or(UserErrors::MerchantIdNotFound.into())
- .map(|_| ApplicationResponse::StatusOk)
+ let merchant_accounts = state
+ .store
+ .list_multiple_merchant_accounts(&(&state).into(), req.merchant_ids)
+ .await
+ .change_context(UserErrors::InternalServerError)?;
+
+ let update_result =
+ futures::future::join_all(merchant_accounts.iter().map(|merchant_account| async {
+ let (update_v1_result, update_v2_result) =
+ utils::user_role::update_v1_and_v2_user_roles_in_db(
+ &state,
+ user_token.user_id.as_str(),
+ &merchant_account.organization_id,
+ merchant_account.get_id(),
+ None,
+ UserRoleUpdate::UpdateStatus {
+ status: UserStatus::Active,
+ modified_by: user_token.user_id.clone(),
+ },
+ )
+ .await;
+
+ if update_v1_result.is_err_and(|err| !err.current_context().is_db_not_found())
+ || update_v2_result.is_err_and(|err| !err.current_context().is_db_not_found())
+ {
+ Err(report!(UserErrors::InternalServerError))
+ } else {
+ Ok(())
+ }
+ }))
+ .await;
+
+ if update_result.iter().all(Result::is_err) {
+ return Err(UserErrors::MerchantIdNotFound.into());
+ }
+
+ Ok(ApplicationResponse::StatusOk)
}
pub async fn merchant_select(
@@ -250,38 +313,55 @@ pub async fn merchant_select(
user_token: auth::UserFromSinglePurposeToken,
req: user_role_api::MerchantSelectRequest,
) -> UserResponse<user_api::TokenOrPayloadResponse<user_api::DashboardEntryResponse>> {
- let user_role = futures::future::join_all(req.merchant_ids.iter().map(|merchant_id| async {
- state
- .store
- .update_user_role_by_user_id_merchant_id(
- user_token.user_id.as_str(),
- merchant_id,
- UserRoleUpdate::UpdateStatus {
- status: UserStatus::Active,
- modified_by: user_token.user_id.clone(),
- },
- UserRoleVersion::V1,
- )
- .await
- .map_err(|e| {
- logger::error!("Error while accepting invitation {e:?}");
- })
- .ok()
- }))
- .await
- .into_iter()
- .reduce(Option::or)
- .flatten()
- .ok_or(UserErrors::MerchantIdNotFound)?;
+ let merchant_accounts = state
+ .store
+ .list_multiple_merchant_accounts(&(&state).into(), req.merchant_ids)
+ .await
+ .change_context(UserErrors::InternalServerError)?;
+
+ let update_result =
+ futures::future::join_all(merchant_accounts.iter().map(|merchant_account| async {
+ let (update_v1_result, update_v2_result) =
+ utils::user_role::update_v1_and_v2_user_roles_in_db(
+ &state,
+ user_token.user_id.as_str(),
+ &merchant_account.organization_id,
+ merchant_account.get_id(),
+ None,
+ UserRoleUpdate::UpdateStatus {
+ status: UserStatus::Active,
+ modified_by: user_token.user_id.clone(),
+ },
+ )
+ .await;
+
+ if update_v1_result.is_err_and(|err| !err.current_context().is_db_not_found())
+ || update_v2_result.is_err_and(|err| !err.current_context().is_db_not_found())
+ {
+ Err(report!(UserErrors::InternalServerError))
+ } else {
+ Ok(())
+ }
+ }))
+ .await;
+
+ if update_result.iter().all(Result::is_err) {
+ return Err(UserErrors::MerchantIdNotFound.into());
+ }
if let Some(true) = req.need_dashboard_entry_response {
- let user_from_db = state
+ let user_from_db: domain::UserFromStorage = state
.global_store
.find_user_by_id(user_token.user_id.as_str())
.await
.change_context(UserErrors::InternalServerError)?
.into();
+ let user_role = user_from_db
+ .get_preferred_or_active_user_role_from_db(&state)
+ .await
+ .change_context(UserErrors::InternalServerError)?;
+
utils::user_role::set_role_permissions_in_cache_by_user_role(&state, &user_role).await;
let token =
@@ -307,29 +387,41 @@ pub async fn merchant_select_token_only_flow(
user_token: auth::UserFromSinglePurposeToken,
req: user_role_api::MerchantSelectRequest,
) -> UserResponse<user_api::TokenOrPayloadResponse<user_api::DashboardEntryResponse>> {
- let user_role = futures::future::join_all(req.merchant_ids.iter().map(|merchant_id| async {
- state
- .store
- .update_user_role_by_user_id_merchant_id(
- user_token.user_id.as_str(),
- merchant_id,
- UserRoleUpdate::UpdateStatus {
- status: UserStatus::Active,
- modified_by: user_token.user_id.clone(),
- },
- UserRoleVersion::V1,
- )
- .await
- .map_err(|e| {
- logger::error!("Error while accepting invitation {e:?}");
- })
- .ok()
- }))
- .await
- .into_iter()
- .reduce(Option::or)
- .flatten()
- .ok_or(UserErrors::MerchantIdNotFound)?;
+ let merchant_accounts = state
+ .store
+ .list_multiple_merchant_accounts(&(&state).into(), req.merchant_ids)
+ .await
+ .change_context(UserErrors::InternalServerError)?;
+
+ let update_result =
+ futures::future::join_all(merchant_accounts.iter().map(|merchant_account| async {
+ let (update_v1_result, update_v2_result) =
+ utils::user_role::update_v1_and_v2_user_roles_in_db(
+ &state,
+ user_token.user_id.as_str(),
+ &merchant_account.organization_id,
+ merchant_account.get_id(),
+ None,
+ UserRoleUpdate::UpdateStatus {
+ status: UserStatus::Active,
+ modified_by: user_token.user_id.clone(),
+ },
+ )
+ .await;
+
+ if update_v1_result.is_err_and(|err| !err.current_context().is_db_not_found())
+ || update_v2_result.is_err_and(|err| !err.current_context().is_db_not_found())
+ {
+ Err(report!(UserErrors::InternalServerError))
+ } else {
+ Ok(())
+ }
+ }))
+ .await;
+
+ if update_result.iter().all(Result::is_err) {
+ return Err(UserErrors::MerchantIdNotFound.into());
+ }
let user_from_db: domain::UserFromStorage = state
.global_store
@@ -338,6 +430,11 @@ pub async fn merchant_select_token_only_flow(
.change_context(UserErrors::InternalServerError)?
.into();
+ let user_role = user_from_db
+ .get_preferred_or_active_user_role_from_db(&state)
+ .await
+ .change_context(UserErrors::InternalServerError)?;
+
let current_flow =
domain::CurrentFlow::new(user_token, domain::SPTFlow::MerchantSelect.into())?;
let next_flow = current_flow.next(user_from_db.clone(), &state).await?;
diff --git a/crates/router/src/db/kafka_store.rs b/crates/router/src/db/kafka_store.rs
index 2f5bf8b6791..6f3fdfd77dd 100644
--- a/crates/router/src/db/kafka_store.rs
+++ b/crates/router/src/db/kafka_store.rs
@@ -2737,30 +2737,6 @@ impl UserRoleInterface for KafkaStore {
.await
}
- async fn update_user_role_by_user_id_merchant_id(
- &self,
- user_id: &str,
- merchant_id: &id_type::MerchantId,
- update: user_storage::UserRoleUpdate,
- version: enums::UserRoleVersion,
- ) -> CustomResult<user_storage::UserRole, errors::StorageError> {
- self.diesel_store
- .update_user_role_by_user_id_merchant_id(user_id, merchant_id, update, version)
- .await
- }
-
- async fn update_user_roles_by_user_id_org_id(
- &self,
- user_id: &str,
- org_id: &id_type::OrganizationId,
- update: user_storage::UserRoleUpdate,
- version: enums::UserRoleVersion,
- ) -> CustomResult<Vec<user_storage::UserRole>, errors::StorageError> {
- self.diesel_store
- .update_user_roles_by_user_id_org_id(user_id, org_id, update, version)
- .await
- }
-
async fn list_user_roles_by_user_id(
&self,
user_id: &str,
@@ -2790,34 +2766,43 @@ impl UserRoleInterface for KafkaStore {
.await
}
- async fn delete_user_role_by_user_id_and_lineage(
+ async fn update_user_role_by_user_id_and_lineage(
&self,
user_id: &str,
org_id: &id_type::OrganizationId,
merchant_id: &id_type::MerchantId,
profile_id: Option<&String>,
+ update: user_storage::UserRoleUpdate,
version: enums::UserRoleVersion,
) -> CustomResult<storage::UserRole, errors::StorageError> {
self.diesel_store
- .delete_user_role_by_user_id_and_lineage(
+ .update_user_role_by_user_id_and_lineage(
user_id,
org_id,
merchant_id,
profile_id,
+ update,
version,
)
.await
}
- async fn transfer_org_ownership_between_users(
+ async fn delete_user_role_by_user_id_and_lineage(
&self,
- from_user_id: &str,
- to_user_id: &str,
+ user_id: &str,
org_id: &id_type::OrganizationId,
+ merchant_id: &id_type::MerchantId,
+ profile_id: Option<&String>,
version: enums::UserRoleVersion,
- ) -> CustomResult<(), errors::StorageError> {
+ ) -> CustomResult<storage::UserRole, errors::StorageError> {
self.diesel_store
- .transfer_org_ownership_between_users(from_user_id, to_user_id, org_id, version)
+ .delete_user_role_by_user_id_and_lineage(
+ user_id,
+ org_id,
+ merchant_id,
+ profile_id,
+ version,
+ )
.await
}
diff --git a/crates/router/src/db/user_role.rs b/crates/router/src/db/user_role.rs
index 05f37d0ee72..a93aeb1ce34 100644
--- a/crates/router/src/db/user_role.rs
+++ b/crates/router/src/db/user_role.rs
@@ -1,6 +1,3 @@
-use std::collections::HashSet;
-
-use async_bb8_diesel::AsyncConnection;
use common_utils::id_type;
use diesel_models::{enums, user_role as storage};
use error_stack::{report, ResultExt};
@@ -8,7 +5,7 @@ use router_env::{instrument, tracing};
use super::MockDb;
use crate::{
- connection, consts,
+ connection,
core::errors::{self, CustomResult},
services::Store,
};
@@ -33,22 +30,6 @@ pub trait UserRoleInterface {
version: enums::UserRoleVersion,
) -> CustomResult<storage::UserRole, errors::StorageError>;
- async fn update_user_role_by_user_id_merchant_id(
- &self,
- user_id: &str,
- merchant_id: &id_type::MerchantId,
- update: storage::UserRoleUpdate,
- version: enums::UserRoleVersion,
- ) -> CustomResult<storage::UserRole, errors::StorageError>;
-
- async fn update_user_roles_by_user_id_org_id(
- &self,
- user_id: &str,
- org_id: &id_type::OrganizationId,
- update: storage::UserRoleUpdate,
- version: enums::UserRoleVersion,
- ) -> CustomResult<Vec<storage::UserRole>, errors::StorageError>;
-
async fn list_user_roles_by_user_id(
&self,
user_id: &str,
@@ -70,22 +51,24 @@ pub trait UserRoleInterface {
version: enums::UserRoleVersion,
) -> CustomResult<storage::UserRole, errors::StorageError>;
- async fn delete_user_role_by_user_id_and_lineage(
+ async fn update_user_role_by_user_id_and_lineage(
&self,
user_id: &str,
org_id: &id_type::OrganizationId,
merchant_id: &id_type::MerchantId,
profile_id: Option<&String>,
+ update: storage::UserRoleUpdate,
version: enums::UserRoleVersion,
) -> CustomResult<storage::UserRole, errors::StorageError>;
- async fn transfer_org_ownership_between_users(
+ async fn delete_user_role_by_user_id_and_lineage(
&self,
- from_user_id: &str,
- to_user_id: &str,
+ user_id: &str,
org_id: &id_type::OrganizationId,
+ merchant_id: &id_type::MerchantId,
+ profile_id: Option<&String>,
version: enums::UserRoleVersion,
- ) -> CustomResult<(), errors::StorageError>;
+ ) -> CustomResult<storage::UserRole, errors::StorageError>;
}
#[async_trait::async_trait]
@@ -132,46 +115,6 @@ impl UserRoleInterface for Store {
.map_err(|error| report!(errors::StorageError::from(error)))
}
- #[instrument(skip_all)]
- async fn update_user_role_by_user_id_merchant_id(
- &self,
- user_id: &str,
- merchant_id: &id_type::MerchantId,
- update: storage::UserRoleUpdate,
- version: enums::UserRoleVersion,
- ) -> CustomResult<storage::UserRole, errors::StorageError> {
- let conn = connection::pg_connection_write(self).await?;
- storage::UserRole::update_by_user_id_merchant_id(
- &conn,
- user_id.to_owned(),
- merchant_id.to_owned(),
- update,
- version,
- )
- .await
- .map_err(|error| report!(errors::StorageError::from(error)))
- }
-
- #[instrument(skip_all)]
- async fn update_user_roles_by_user_id_org_id(
- &self,
- user_id: &str,
- org_id: &id_type::OrganizationId,
- update: storage::UserRoleUpdate,
- version: enums::UserRoleVersion,
- ) -> CustomResult<Vec<storage::UserRole>, errors::StorageError> {
- let conn = connection::pg_connection_write(self).await?;
- storage::UserRole::update_by_user_id_org_id(
- &conn,
- user_id.to_owned(),
- org_id.to_owned(),
- update,
- version,
- )
- .await
- .map_err(|error| report!(errors::StorageError::from(error)))
- }
-
#[instrument(skip_all)]
async fn list_user_roles_by_user_id(
&self,
@@ -219,21 +162,23 @@ impl UserRoleInterface for Store {
}
#[instrument(skip_all)]
- async fn delete_user_role_by_user_id_and_lineage(
+ async fn update_user_role_by_user_id_and_lineage(
&self,
user_id: &str,
org_id: &id_type::OrganizationId,
merchant_id: &id_type::MerchantId,
profile_id: Option<&String>,
+ update: storage::UserRoleUpdate,
version: enums::UserRoleVersion,
) -> CustomResult<storage::UserRole, errors::StorageError> {
let conn = connection::pg_connection_write(self).await?;
- storage::UserRole::delete_by_user_id_org_id_merchant_id_profile_id(
+ storage::UserRole::update_by_user_id_org_id_merchant_id_profile_id(
&conn,
user_id.to_owned(),
org_id.to_owned(),
merchant_id.to_owned(),
profile_id.cloned(),
+ update,
version,
)
.await
@@ -241,97 +186,25 @@ impl UserRoleInterface for Store {
}
#[instrument(skip_all)]
- async fn transfer_org_ownership_between_users(
+ async fn delete_user_role_by_user_id_and_lineage(
&self,
- from_user_id: &str,
- to_user_id: &str,
+ user_id: &str,
org_id: &id_type::OrganizationId,
+ merchant_id: &id_type::MerchantId,
+ profile_id: Option<&String>,
version: enums::UserRoleVersion,
- ) -> CustomResult<(), errors::StorageError> {
- let conn = connection::pg_connection_write(self)
- .await
- .change_context(errors::StorageError::DatabaseConnectionError)?;
-
- conn.transaction_async(|conn| async move {
- let old_org_admin_user_roles = storage::UserRole::update_by_user_id_org_id(
- &conn,
- from_user_id.to_owned(),
- org_id.to_owned(),
- storage::UserRoleUpdate::UpdateRole {
- role_id: consts::user_role::ROLE_ID_MERCHANT_ADMIN.to_string(),
- modified_by: from_user_id.to_owned(),
- },
- version,
- )
- .await
- .map_err(|e| *e.current_context())?;
-
- let new_org_admin_user_roles = storage::UserRole::update_by_user_id_org_id(
- &conn,
- to_user_id.to_owned(),
- org_id.to_owned(),
- storage::UserRoleUpdate::UpdateRole {
- role_id: consts::user_role::ROLE_ID_ORGANIZATION_ADMIN.to_string(),
- modified_by: from_user_id.to_owned(),
- },
- version,
- )
- .await
- .map_err(|e| *e.current_context())?;
-
- let new_org_admin_merchant_ids = new_org_admin_user_roles
- .iter()
- .map(|user_role| {
- user_role
- .merchant_id
- .to_owned()
- .ok_or(errors::DatabaseError::Others)
- })
- .collect::<Result<HashSet<_>, _>>()?;
-
- let now = common_utils::date_time::now();
-
- let mut missing_new_user_roles = Vec::new();
-
- for old_role in old_org_admin_user_roles {
- let Some(old_role_merchant_id) = &old_role.merchant_id else {
- return Err(errors::DatabaseError::Others);
- };
- if !new_org_admin_merchant_ids.contains(old_role_merchant_id) {
- missing_new_user_roles.push(storage::UserRoleNew {
- user_id: to_user_id.to_string(),
- merchant_id: Some(old_role_merchant_id.to_owned()),
- role_id: consts::user_role::ROLE_ID_ORGANIZATION_ADMIN.to_string(),
- org_id: Some(org_id.to_owned()),
- status: enums::UserStatus::Active,
- created_by: from_user_id.to_string(),
- last_modified_by: from_user_id.to_string(),
- created_at: now,
- last_modified: now,
- profile_id: None,
- entity_id: None,
- entity_type: None,
- version: enums::UserRoleVersion::V1,
- });
- }
- }
-
- futures::future::try_join_all(missing_new_user_roles.into_iter().map(
- |user_role| async {
- user_role
- .insert(&conn)
- .await
- .map_err(|e| *e.current_context())
- },
- ))
- .await?;
-
- Ok::<_, errors::DatabaseError>(())
- })
+ ) -> CustomResult<storage::UserRole, errors::StorageError> {
+ let conn = connection::pg_connection_write(self).await?;
+ storage::UserRole::delete_by_user_id_org_id_merchant_id_profile_id(
+ &conn,
+ user_id.to_owned(),
+ org_id.to_owned(),
+ merchant_id.to_owned(),
+ profile_id.cloned(),
+ version,
+ )
.await
- .map_err(|error| report!(errors::StorageError::from(report!(error))))?;
-
- Ok(())
+ .map_err(|error| report!(errors::StorageError::from(error)))
}
}
@@ -422,185 +295,6 @@ impl UserRoleInterface for MockDb {
.into())
}
- async fn update_user_role_by_user_id_merchant_id(
- &self,
- user_id: &str,
- merchant_id: &id_type::MerchantId,
- update: storage::UserRoleUpdate,
- version: enums::UserRoleVersion,
- ) -> CustomResult<storage::UserRole, errors::StorageError> {
- let mut user_roles = self.user_roles.lock().await;
-
- for user_role in user_roles.iter_mut() {
- let Some(user_role_merchant_id) = &user_role.merchant_id else {
- return Err(errors::StorageError::DatabaseError(
- report!(errors::DatabaseError::Others)
- .attach_printable("merchant_id not found for user_role"),
- )
- .into());
- };
- if user_role.user_id == user_id
- && user_role_merchant_id == merchant_id
- && user_role.version == version
- {
- match &update {
- storage::UserRoleUpdate::UpdateRole {
- role_id,
- modified_by,
- } => {
- user_role.role_id = role_id.to_string();
- user_role.last_modified_by = modified_by.to_string();
- }
- storage::UserRoleUpdate::UpdateStatus {
- status,
- modified_by,
- } => {
- user_role.status = *status;
- user_role.last_modified_by = modified_by.to_string();
- }
- };
- return Ok(user_role.clone());
- }
- }
-
- Err(errors::StorageError::ValueNotFound(format!(
- "No user role available for user_id = {user_id} and merchant_id = {merchant_id:?}"
- ))
- .into())
- }
-
- async fn update_user_roles_by_user_id_org_id(
- &self,
- user_id: &str,
- org_id: &id_type::OrganizationId,
- update: storage::UserRoleUpdate,
- version: enums::UserRoleVersion,
- ) -> CustomResult<Vec<storage::UserRole>, errors::StorageError> {
- let mut user_roles = self.user_roles.lock().await;
- let mut updated_user_roles = Vec::new();
- for user_role in user_roles.iter_mut() {
- let Some(user_role_org_id) = &user_role.org_id else {
- return Err(errors::StorageError::DatabaseError(
- report!(errors::DatabaseError::Others)
- .attach_printable("org_id not found for user_role"),
- )
- .into());
- };
- if user_role.user_id == user_id
- && user_role_org_id == org_id
- && user_role.version == version
- {
- match &update {
- storage::UserRoleUpdate::UpdateRole {
- role_id,
- modified_by,
- } => {
- user_role.role_id = role_id.to_string();
- user_role.last_modified_by = modified_by.to_string();
- }
- storage::UserRoleUpdate::UpdateStatus {
- status,
- modified_by,
- } => {
- status.clone_into(&mut user_role.status);
- modified_by.clone_into(&mut user_role.last_modified_by);
- }
- }
- updated_user_roles.push(user_role.to_owned());
- }
- }
- if updated_user_roles.is_empty() {
- Err(errors::StorageError::ValueNotFound(format!(
- "No user role available for user_id = {user_id} and org_id = {org_id:?}"
- ))
- .into())
- } else {
- Ok(updated_user_roles)
- }
- }
-
- async fn transfer_org_ownership_between_users(
- &self,
- from_user_id: &str,
- to_user_id: &str,
- org_id: &id_type::OrganizationId,
- version: enums::UserRoleVersion,
- ) -> CustomResult<(), errors::StorageError> {
- let old_org_admin_user_roles = self
- .update_user_roles_by_user_id_org_id(
- from_user_id,
- org_id,
- storage::UserRoleUpdate::UpdateRole {
- role_id: consts::user_role::ROLE_ID_MERCHANT_ADMIN.to_string(),
- modified_by: from_user_id.to_string(),
- },
- version,
- )
- .await?;
-
- let new_org_admin_user_roles = self
- .update_user_roles_by_user_id_org_id(
- to_user_id,
- org_id,
- storage::UserRoleUpdate::UpdateRole {
- role_id: consts::user_role::ROLE_ID_ORGANIZATION_ADMIN.to_string(),
- modified_by: from_user_id.to_string(),
- },
- version,
- )
- .await?;
-
- let new_org_admin_merchant_ids = new_org_admin_user_roles
- .iter()
- .map(|user_role| {
- user_role.merchant_id.to_owned().ok_or(report!(
- errors::StorageError::DatabaseError(
- report!(errors::DatabaseError::Others)
- .attach_printable("merchant_id not found for user_role"),
- )
- ))
- })
- .collect::<Result<HashSet<_>, _>>()?;
-
- let now = common_utils::date_time::now();
- let mut missing_new_user_roles = Vec::new();
-
- for old_roles in old_org_admin_user_roles {
- let Some(merchant_id) = &old_roles.merchant_id else {
- return Err(errors::StorageError::DatabaseError(
- report!(errors::DatabaseError::Others)
- .attach_printable("merchant id not found for user role"),
- )
- .into());
- };
- if !new_org_admin_merchant_ids.contains(merchant_id) {
- let new_user_role = storage::UserRoleNew {
- user_id: to_user_id.to_string(),
- merchant_id: Some(merchant_id.to_owned()),
- role_id: consts::user_role::ROLE_ID_ORGANIZATION_ADMIN.to_string(),
- org_id: Some(org_id.to_owned()),
- status: enums::UserStatus::Active,
- created_by: from_user_id.to_string(),
- last_modified_by: from_user_id.to_string(),
- created_at: now,
- last_modified: now,
- profile_id: None,
- entity_id: None,
- entity_type: None,
- version: enums::UserRoleVersion::V1,
- };
-
- missing_new_user_roles.push(new_user_role);
- }
- }
-
- for user_role in missing_new_user_roles {
- self.insert_user_role(user_role).await?;
- }
-
- Ok(())
- }
-
async fn list_user_roles_by_user_id(
&self,
user_id: &str,
@@ -684,6 +378,60 @@ impl UserRoleInterface for MockDb {
.into())
}
+ async fn update_user_role_by_user_id_and_lineage(
+ &self,
+ user_id: &str,
+ org_id: &id_type::OrganizationId,
+ merchant_id: &id_type::MerchantId,
+ profile_id: Option<&String>,
+ update: storage::UserRoleUpdate,
+ version: enums::UserRoleVersion,
+ ) -> CustomResult<storage::UserRole, errors::StorageError> {
+ let mut user_roles = self.user_roles.lock().await;
+
+ for user_role in user_roles.iter_mut() {
+ let org_level_check = user_role.org_id.as_ref() == Some(org_id)
+ && user_role.merchant_id.is_none()
+ && user_role.profile_id.is_none();
+
+ let merchant_level_check = user_role.org_id.as_ref() == Some(org_id)
+ && user_role.merchant_id.as_ref() == Some(merchant_id)
+ && user_role.profile_id.is_none();
+
+ let profile_level_check = user_role.org_id.as_ref() == Some(org_id)
+ && user_role.merchant_id.as_ref() == Some(merchant_id)
+ && user_role.profile_id.as_ref() == profile_id;
+
+ // Check if the user role matches the conditions and the version matches
+ if user_role.user_id == user_id
+ && (org_level_check || merchant_level_check || profile_level_check)
+ && user_role.version == version
+ {
+ match &update {
+ storage::UserRoleUpdate::UpdateRole {
+ role_id,
+ modified_by,
+ } => {
+ user_role.role_id = role_id.to_string();
+ user_role.last_modified_by = modified_by.to_string();
+ }
+ storage::UserRoleUpdate::UpdateStatus {
+ status,
+ modified_by,
+ } => {
+ user_role.status = *status;
+ user_role.last_modified_by = modified_by.to_string();
+ }
+ }
+ return Ok(user_role.clone());
+ }
+ }
+ Err(
+ errors::StorageError::ValueNotFound("Cannot find user role to update".to_string())
+ .into(),
+ )
+ }
+
async fn delete_user_role_by_user_id_and_lineage(
&self,
user_id: &str,
diff --git a/crates/router/src/routes/app.rs b/crates/router/src/routes/app.rs
index 3d6fcb103c4..fe0781ab517 100644
--- a/crates/router/src/routes/app.rs
+++ b/crates/router/src/routes/app.rs
@@ -1712,10 +1712,6 @@ impl User {
.route(web::put().to(accept_invitation)),
)
.service(web::resource("/update_role").route(web::post().to(update_user_role)))
- .service(
- web::resource("/transfer_ownership")
- .route(web::post().to(transfer_org_ownership)),
- )
.service(web::resource("/delete").route(web::delete().to(delete_user_role))),
);
diff --git a/crates/router/src/routes/user_role.rs b/crates/router/src/routes/user_role.rs
index bce0e6da147..526722af98c 100644
--- a/crates/router/src/routes/user_role.rs
+++ b/crates/router/src/routes/user_role.rs
@@ -186,25 +186,6 @@ pub async fn update_user_role(
.await
}
-pub async fn transfer_org_ownership(
- state: web::Data<AppState>,
- req: HttpRequest,
- json_payload: web::Json<user_role_api::TransferOrgOwnershipRequest>,
-) -> HttpResponse {
- let flow = Flow::TransferOrgOwnership;
- let payload = json_payload.into_inner();
- Box::pin(api::server_wrap(
- flow,
- state.clone(),
- &req,
- payload,
- user_role_core::transfer_org_ownership,
- &auth::JWTAuth(Permission::UsersWrite),
- api_locking::LockAction::NotApplicable,
- ))
- .await
-}
-
pub async fn accept_invitation(
state: web::Data<AppState>,
req: HttpRequest,
diff --git a/crates/router/src/utils/user_role.rs b/crates/router/src/utils/user_role.rs
index 4fcc03b1904..7aebbe1bbcf 100644
--- a/crates/router/src/utils/user_role.rs
+++ b/crates/router/src/utils/user_role.rs
@@ -3,9 +3,13 @@ use std::collections::HashSet;
use api_models::user_role as user_role_api;
use common_enums::PermissionGroup;
use common_utils::id_type;
-use diesel_models::user_role::UserRole;
-use error_stack::{report, ResultExt};
+use diesel_models::{
+ enums::UserRoleVersion,
+ user_role::{UserRole, UserRoleUpdate},
+};
+use error_stack::{report, Report, ResultExt};
use router_env::logger;
+use storage_impl::errors::StorageError;
use crate::{
consts,
@@ -168,7 +172,53 @@ pub async fn get_multiple_role_info_for_user_roles(
.await
.to_not_found_response(UserErrors::InternalServerError)
.attach_printable("Role for user role doesn't exist")?;
- Ok::<_, error_stack::Report<UserErrors>>(role)
+ Ok::<_, Report<UserErrors>>(role)
}))
.await
}
+
+pub async fn update_v1_and_v2_user_roles_in_db(
+ state: &SessionState,
+ user_id: &str,
+ org_id: &id_type::OrganizationId,
+ merchant_id: &id_type::MerchantId,
+ profile_id: Option<&String>,
+ update: UserRoleUpdate,
+) -> (
+ Result<UserRole, Report<StorageError>>,
+ Result<UserRole, Report<StorageError>>,
+) {
+ let updated_v1_role = state
+ .store
+ .update_user_role_by_user_id_and_lineage(
+ user_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
+ .store
+ .update_user_role_by_user_id_and_lineage(
+ user_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)
+}
|
2024-08-20T14:55:26Z
|
## Type of Change
<!-- Put an `x` in the boxes that apply -->
- [ ] Bugfix
- [x] New feature
- [ ] Enhancement
- [ ] Refactoring
- [ ] Dependency updates
- [ ] Documentation
- [ ] CI/CD
## Description
<!-- Describe your changes in detail -->
- This PR adds a new db function which can update a user_role by it's lineage.
### Additional Changes
- [ ] This PR modifies the API contract
- [ ] This PR modifies the database schema
- [ ] This PR modifies application configuration/environment variables
<!--
Provide links to the files with corresponding changes.
Following are the paths where you can find config files:
1. `config`
2. `crates/router/src/configs`
3. `loadtest/config`
-->
## Motivation and Context
<!--
Why is this change required? What problem does it solve?
If it fixes an open issue, please link to the issue here.
If you don't have an issue, we'd recommend starting with one first so the PR
can focus on the implementation (unless it is an obvious bug or documentation fix
that will have little conversation).
-->
Closes [#5650](https://github.com/juspay/hyperswitch/issues/5650).
## How did you test it?
<!--
Did you write an integration/unit/API test to verify the code changes?
Or did you test this change manually (provide relevant screenshots)?
-->
All the following APIs should not break and work as before.
```
curl --location 'https://integ-api.hyperswitch.io/user/accept_invite_from_email' \
--header 'Content-Type: application/json' \
--data '{
"token": "email token"
}'
```
```
curl --location 'https://integ-api.hyperswitch.io/user/accept_invite_from_email?token_only=true' \
--header 'Content-Type: application/json' \
--data '{
"token": "email token"
}'
```
```
curl --location 'https://integ-api.hyperswitch.io/user/user/update_role' \
--header 'Content-Type: application/json' \
--header 'Authorization: ••••••' \
--data '{
"email": "user email",
"role_id": "merchant_iam_admin"
}'
```
The below one should be checked with invitation email token.
```
curl --location 'https://integ-api.hyperswitch.io/user/reset_password' \
--header 'Content-Type: application/json' \
--data '{
"token": "email token",
"password": "password"
}'
```
```
curl --location 'https://integ-api.hyperswitch.io/user/user/invite/accept' \
--header 'Content-Type: application/json' \
--header 'Authorization: ••••••' \
--data '{
"merchant_ids": [
"merchant_1705414503",
"merchant_1705414514"
]
}'
```
```
curl --location --request PUT 'https://integ-api.hyperswitch.io/user/user/invite/accept' \
--header 'Content-Type: application/json' \
--header 'Authorization: ••••••' \
--data '{
"merchant_ids": [
"merchant_1705414503",
"merchant_1705414514"
],
"need_dashboard_entry_response": true
}'
```
```
curl --location --request PUT 'https://integ-api.hyperswitch.io/user/user/invite/accept?token_only=true' \
--header 'Content-Type: application/json' \
--header 'Authorization: ••••••' \
--data '{
"merchant_ids": [
"merchant_1705414503",
"merchant_1705414514"
],
"need_dashboard_entry_response": true
}'
```
## Checklist
<!-- Put an `x` in the boxes that apply -->
- [x] I formatted the code `cargo +nightly fmt --all`
- [x] I addressed lints thrown by `cargo clippy`
- [x] I reviewed the submitted code
- [ ] I added unit tests for my changes where possible
|
cc5b06e72553c33c9d9ed5f9a944ceb5bb36f2c7
|
|
juspay/hyperswitch
|
juspay__hyperswitch-5632
|
Bug: use the saved billing details in the recurring payments
Currently when a payment method is the billing details will also get saved in the payment method table.
But when a recurring payment is performed with the saved payment method, it is expected that the billing details to be passed in the current payment as well instead of using already saved billing details.
This pr contains the changes to use the saved payment method billing details during the recurring payment.
|
diff --git a/crates/hyperswitch_domain_models/src/payment_address.rs b/crates/hyperswitch_domain_models/src/payment_address.rs
index d4f2cf9f350..548dd0c5416 100644
--- a/crates/hyperswitch_domain_models/src/payment_address.rs
+++ b/crates/hyperswitch_domain_models/src/payment_address.rs
@@ -53,6 +53,7 @@ impl PaymentAddress {
}
/// Unify the billing details from `payment_method_data.[payment_method_data].billing details`.
+ /// Here the fields passed in payment_method_data_billing takes precedence
pub fn unify_with_payment_method_data_billing(
self,
payment_method_data_billing: Option<Address>,
@@ -72,6 +73,29 @@ impl PaymentAddress {
}
}
+ /// Unify the billing details from `payment_method_data.[payment_method_data].billing details`.
+ /// Here the `self` takes precedence
+ pub fn unify_with_payment_data_billing(
+ self,
+ other_payment_method_billing: Option<Address>,
+ ) -> Self {
+ let unified_payment_method_billing = self
+ .get_payment_method_billing()
+ .map(|payment_method_billing| {
+ payment_method_billing
+ .clone()
+ .unify_address(other_payment_method_billing.as_ref())
+ })
+ .or(other_payment_method_billing);
+
+ Self {
+ shipping: self.shipping,
+ billing: self.billing,
+ unified_payment_method_billing,
+ payment_method_billing: self.payment_method_billing,
+ }
+ }
+
pub fn get_request_payment_method_billing(&self) -> Option<&Address> {
self.payment_method_billing.as_ref()
}
diff --git a/crates/router/src/core/payments/transformers.rs b/crates/router/src/core/payments/transformers.rs
index 9182bf93606..24f5ffdca9a 100644
--- a/crates/router/src/core/payments/transformers.rs
+++ b/crates/router/src/core/payments/transformers.rs
@@ -42,7 +42,7 @@ pub async fn construct_payment_router_data<'a, F, T>(
payment_data: PaymentData<F>,
connector_id: &str,
merchant_account: &domain::MerchantAccount,
- _key_store: &domain::MerchantKeyStore,
+ key_store: &domain::MerchantKeyStore,
customer: &'a Option<domain::Customer>,
merchant_connector_account: &helpers::MerchantConnectorAccountType,
merchant_recipient_data: Option<types::MerchantRecipientData>,
@@ -135,6 +135,26 @@ where
Some(merchant_connector_account),
);
+ let unified_address =
+ if let Some(payment_method_info) = payment_data.payment_method_info.clone() {
+ let payment_method_billing =
+ crate::core::payment_methods::cards::decrypt_generic_data::<Address>(
+ state,
+ payment_method_info.payment_method_billing_address,
+ key_store,
+ )
+ .await
+ .attach_printable("unable to decrypt payment method billing address details")?;
+ payment_data
+ .address
+ .clone()
+ .unify_with_payment_data_billing(payment_method_billing)
+ } else {
+ payment_data.address
+ };
+
+ crate::logger::debug!("unified address details {:?}", unified_address);
+
router_data = types::RouterData {
flow: PhantomData,
merchant_id: merchant_account.get_id().clone(),
@@ -147,7 +167,7 @@ where
connector_auth_type: auth_type,
description: payment_data.payment_intent.description.clone(),
return_url: payment_data.payment_intent.return_url.clone(),
- address: payment_data.address.clone(),
+ address: unified_address,
auth_type: payment_data
.payment_attempt
.authentication_type
|
2024-08-14T11:18:42Z
|
## Type of Change
<!-- Put an `x` in the boxes that apply -->
- [ ] Bugfix
- [ ] New feature
- [ ] Enhancement
- [x] Refactoring
- [ ] Dependency updates
- [ ] Documentation
- [ ] CI/CD
## Description
<!-- Describe your changes in detail -->
Currently when a payment method is the billing details will also get saved in the payment method table.
But when a recurring payment is performed with the saved payment method, it is expected that the billing details to be passed in the current payment as well instead of using already saved billing details.
This pr contains the changes to use the saved payment method billing details during the recurring payment.
### Additional Changes
- [ ] This PR modifies the API contract
- [ ] This PR modifies the database schema
- [ ] This PR modifies application configuration/environment variables
<!--
Provide links to the files with corresponding changes.
Following are the paths where you can find config files:
1. `config`
2. `crates/router/src/configs`
3. `loadtest/config`
-->
## Motivation and Context
<!--
Why is this change required? What problem does it solve?
If it fixes an open issue, please link to the issue here.
If you don't have an issue, we'd recommend starting with one first so the PR
can focus on the implementation (unless it is an obvious bug or documentation fix
that will have little conversation).
-->
## How did you test it?
<!--
Did you write an integration/unit/API test to verify the code changes?
Or did you test this change manually (provide relevant screenshots)?
-->
-> Create mca for cybersource
-> Create a payment to save a card
```
{
"amount": 100,
"amount_to_capture": 100,
"currency": "USD",
"confirm": true,
"capture_method": "automatic",
"capture_on": "2022-09-10T10:11:12Z",
"customer_id": "cu_{{$timestamp}}",
"email": "guest@example.com",
"name": "John Doe",
"phone": "999999999",
"phone_country_code": "+1",
"description": "Its my first payment request",
"authentication_type": "no_three_ds",
"setup_future_usage": "on_session",
"return_url": "http://127.0.0.1:4040",
"customer_acceptance": {
"acceptance_type": "offline",
"accepted_at": "1963-05-03T04:07:52.723Z",
"online": {
"ip_address": "in sit",
"user_agent": "amet irure esse"
}
},
"payment_method": "card",
"payment_method_data": {
"card": {
"card_number": "4000000000000119",
"card_exp_month": "03",
"card_exp_year": "2030",
"card_holder_name": "joseph Doe",
"card_cvc": "838"
}
},
"billing": {
"address": {
"line1": "1467",
"line2": "Harrison Street",
"line3": "Harrison Street",
"city": "San Fransico",
"state": "California",
"zip": "94122",
"country": "US",
"first_name": "PiX",
"last_name": "ss"
}
},
"shipping": {
"address": {
"line1": "1467",
"line2": "Harrison Street",
"line3": "Harrison Street",
"city": "San Fransico",
"state": "California",
"zip": "94122",
"country": "US",
"first_name": "PiX"
}
},
"browser_info": {
"user_agent": "Mozilla\/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit\/537.36 (KHTML, like Gecko) Chrome\/70.0.3538.110 Safari\/537.36",
"accept_header": "text\/html,application\/xhtml+xml,application\/xml;q=0.9,image\/webp,image\/apng,*\/*;q=0.8",
"language": "nl-NL",
"color_depth": 24,
"screen_height": 723,
"screen_width": 1536,
"time_zone": 0,
"java_enabled": true,
"java_script_enabled": true,
"ip_address": "125.0.0.1"
},
"statement_descriptor_name": "joseph",
"statement_descriptor_suffix": "JS",
"metadata": {
"udf1": "value1",
"new_customer": "true",
"login_date": "2019-09-10T10:11:12Z"
}
}
```
```
{
"payment_id": "pay_UEWLBw1G1wBgvsfuA7WB",
"merchant_id": "merchant_1723633906",
"status": "succeeded",
"amount": 100,
"net_amount": 100,
"amount_capturable": 0,
"amount_received": 100,
"connector": "cybersource",
"client_secret": "pay_UEWLBw1G1wBgvsfuA7WB_secret_yZ2lHGDhVFBq7u77qjCJ",
"created": "2024-08-14T11:11:51.983Z",
"currency": "USD",
"customer_id": "cu_1723633912",
"customer": {
"id": "cu_1723633912",
"name": "John Doe",
"email": "guest@example.com",
"phone": "999999999",
"phone_country_code": "+1"
},
"description": "Its my first payment request",
"refunds": null,
"disputes": null,
"mandate_id": null,
"mandate_data": null,
"setup_future_usage": "on_session",
"off_session": null,
"capture_on": null,
"capture_method": "automatic",
"payment_method": "card",
"payment_method_data": {
"card": {
"last4": "0119",
"card_type": null,
"card_network": null,
"card_issuer": null,
"card_issuing_country": null,
"card_isin": "400000",
"card_extended_bin": null,
"card_exp_month": "03",
"card_exp_year": "2030",
"card_holder_name": null,
"payment_checks": {
"avs_response": {
"code": "Y",
"codeRaw": "Y"
},
"card_verification": null
},
"authentication_data": null
},
"billing": null
},
"payment_token": "token_8CYTus4XuN7WktyT3X7i",
"shipping": {
"address": {
"city": "San Fransico",
"country": "US",
"line1": "1467",
"line2": "Harrison Street",
"line3": "Harrison Street",
"zip": "94122",
"state": "California",
"first_name": "PiX",
"last_name": null
},
"phone": null,
"email": null
},
"billing": {
"address": {
"city": "San Fransico",
"country": "US",
"line1": "1467",
"line2": "Harrison Street",
"line3": "Harrison Street",
"zip": "94122",
"state": "California",
"first_name": "PiX",
"last_name": "ss"
},
"phone": null,
"email": null
},
"order_details": null,
"email": "guest@example.com",
"name": "John Doe",
"phone": "999999999",
"return_url": "http://127.0.0.1:4040/",
"authentication_type": "no_three_ds",
"statement_descriptor_name": "joseph",
"statement_descriptor_suffix": "JS",
"next_action": null,
"cancellation_reason": null,
"error_code": null,
"error_message": null,
"unified_code": null,
"unified_message": null,
"payment_experience": null,
"payment_method_type": null,
"connector_label": null,
"business_country": null,
"business_label": "default",
"business_sub_label": null,
"allowed_payment_method_types": null,
"ephemeral_key": {
"customer_id": "cu_1723633912",
"created_at": 1723633911,
"expires": 1723637511,
"secret": "epk_5ba7fd4213f54f659bf419e626089c5c"
},
"manual_retry_allowed": false,
"connector_transaction_id": "7236339122516836903955",
"frm_message": null,
"metadata": {
"udf1": "value1",
"login_date": "2019-09-10T10:11:12Z",
"new_customer": "true"
},
"connector_metadata": null,
"feature_metadata": null,
"reference_id": "pay_UEWLBw1G1wBgvsfuA7WB_1",
"payment_link": null,
"profile_id": "pro_DYzvILr3A14CyJsK6xkr",
"surcharge_details": null,
"attempt_count": 1,
"merchant_decision": null,
"merchant_connector_id": "mca_FARwzfcWZdCdzslixC5L",
"incremental_authorization_allowed": false,
"authorization_count": null,
"incremental_authorizations": null,
"external_authentication_details": null,
"external_3ds_authentication_attempted": false,
"expires_on": "2024-08-14T11:26:51.983Z",
"fingerprint": null,
"browser_info": {
"language": "nl-NL",
"time_zone": 0,
"ip_address": "125.0.0.1",
"user_agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/70.0.3538.110 Safari/537.36",
"color_depth": 24,
"java_enabled": true,
"screen_width": 1536,
"accept_header": "text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,image/apng,*/*;q=0.8",
"screen_height": 723,
"java_script_enabled": true
},
"payment_method_id": null,
"payment_method_status": null,
"updated": "2024-08-14T11:11:53.399Z",
"charges": null,
"frm_metadata": null,
"merchant_order_reference_id": null
}
```
-> List payment methods for a customer
```
{
"amount": 100000,
"currency": "USD",
"capture_method": "automatic",
"authentication_type": "no_three_ds",
"confirm": false,
"customer_id": "cu_1723633912"
}
```
```
{
"payment_id": "pay_7vbNGGq2n3W1S0OCN66m",
"merchant_id": "merchant_1723633906",
"status": "requires_payment_method",
"amount": 100000,
"net_amount": 100000,
"amount_capturable": 0,
"amount_received": null,
"connector": null,
"client_secret": "pay_7vbNGGq2n3W1S0OCN66m_secret_Nm8uMOZFEkoRT87UKugm",
"created": "2024-08-14T11:12:49.616Z",
"currency": "USD",
"customer_id": "cu_1723633912",
"customer": {
"id": "cu_1723633912",
"name": "John Doe",
"email": "guest@example.com",
"phone": "999999999",
"phone_country_code": "+1"
},
"description": null,
"refunds": null,
"disputes": null,
"mandate_id": null,
"mandate_data": null,
"setup_future_usage": null,
"off_session": null,
"capture_on": null,
"capture_method": "automatic",
"payment_method": null,
"payment_method_data": null,
"payment_token": null,
"shipping": null,
"billing": null,
"order_details": null,
"email": "guest@example.com",
"name": "John Doe",
"phone": "999999999",
"return_url": null,
"authentication_type": "no_three_ds",
"statement_descriptor_name": null,
"statement_descriptor_suffix": null,
"next_action": null,
"cancellation_reason": null,
"error_code": null,
"error_message": null,
"unified_code": null,
"unified_message": null,
"payment_experience": null,
"payment_method_type": null,
"connector_label": null,
"business_country": null,
"business_label": "default",
"business_sub_label": null,
"allowed_payment_method_types": null,
"ephemeral_key": {
"customer_id": "cu_1723633912",
"created_at": 1723633969,
"expires": 1723637569,
"secret": "epk_35d19936f46b44229892ff22e1976740"
},
"manual_retry_allowed": null,
"connector_transaction_id": null,
"frm_message": null,
"metadata": null,
"connector_metadata": null,
"feature_metadata": null,
"reference_id": null,
"payment_link": null,
"profile_id": "pro_DYzvILr3A14CyJsK6xkr",
"surcharge_details": null,
"attempt_count": 1,
"merchant_decision": null,
"merchant_connector_id": null,
"incremental_authorization_allowed": null,
"authorization_count": null,
"incremental_authorizations": null,
"external_authentication_details": null,
"external_3ds_authentication_attempted": false,
"expires_on": "2024-08-14T11:27:49.616Z",
"fingerprint": null,
"browser_info": null,
"payment_method_id": null,
"payment_method_status": null,
"updated": "2024-08-14T11:12:49.626Z",
"charges": null,
"frm_metadata": null,
"merchant_order_reference_id": null
}
```
```
curl --location 'http://localhost:8080/customers/payment_methods?client_secret=pay_7vbNGGq2n3W1S0OCN66m_secret_Nm8uMOZFEkoRT87UKugm' \
--header 'Accept: application/json' \
--header 'api-key: pk_dev_b099e8ed348440b79d39fdfbb3f393dd'
```
```
{
"customer_payment_methods": [
{
"payment_token": "token_Abm2R8KFhP2N02lWMxWg",
"payment_method_id": "pm_O4GweV6awC1FW9KvgHCu",
"customer_id": "cu_1723633912",
"payment_method": "card",
"payment_method_type": null,
"payment_method_issuer": null,
"payment_method_issuer_code": null,
"recurring_enabled": false,
"installment_payment_enabled": false,
"payment_experience": [
"redirect_to_url"
],
"card": {
"scheme": null,
"issuer_country": null,
"last4_digits": "0119",
"expiry_month": "03",
"expiry_year": "2030",
"card_token": null,
"card_holder_name": "joseph Doe",
"card_fingerprint": null,
"nick_name": null,
"card_network": null,
"card_isin": "400000",
"card_issuer": null,
"card_type": null,
"saved_to_locker": true
},
"metadata": null,
"created": "2024-08-14T11:11:53.436Z",
"bank": null,
"surcharge_details": null,
"requires_cvv": true,
"last_used_at": "2024-08-14T11:12:35.615Z",
"default_payment_method_set": true,
"billing": {
"address": {
"city": "San Fransico",
"country": "US",
"line1": "1467",
"line2": "Harrison Street",
"line3": "Harrison Street",
"zip": "94122",
"state": "California",
"first_name": "joseph",
"last_name": "Doe"
},
"phone": null,
"email": null
}
}
],
"is_guest_customer": false
}
```
-> Confirm the payment with the token by without passing the billing details
```
curl --location 'http://localhost:8080/payments/pay_8Zx3ByOLe2LKJk80ovSO/confirm' \
--header 'api-key: pk_dev_c4ad2f0ffc704baf8c845f9463096d9d' \
--header 'Content-Type: application/json' \
--data '{
"payment_token": "token_JieHCOogYw7eZxhAkooU",
"client_secret": "pay_8Zx3ByOLe2LKJk80ovSO_secret_lF641suBegY0vA9BQ3wx",
"payment_method": "card"
}'
```
```
{
"payment_id": "pay_8Zx3ByOLe2LKJk80ovSO",
"merchant_id": "merchant_1723638884",
"status": "succeeded",
"amount": 100000,
"net_amount": 100000,
"amount_capturable": 0,
"amount_received": 100000,
"connector": "cybersource",
"client_secret": "pay_8Zx3ByOLe2LKJk80ovSO_secret_lF641suBegY0vA9BQ3wx",
"created": "2024-08-14T12:35:02.511Z",
"currency": "USD",
"customer_id": "cu_1723638892",
"customer": {
"id": "cu_1723638892",
"name": "John Doe",
"email": "guest@example.com",
"phone": "999999999",
"phone_country_code": "+1"
},
"description": null,
"refunds": null,
"disputes": null,
"mandate_id": null,
"mandate_data": null,
"setup_future_usage": null,
"off_session": null,
"capture_on": null,
"capture_method": "automatic",
"payment_method": null,
"payment_method_data": null,
"payment_token": "token_JieHCOogYw7eZxhAkooU",
"shipping": null,
"billing": null,
"order_details": null,
"email": "guest@example.com",
"name": "John Doe",
"phone": "999999999",
"return_url": null,
"authentication_type": "no_three_ds",
"statement_descriptor_name": null,
"statement_descriptor_suffix": null,
"next_action": null,
"cancellation_reason": null,
"error_code": null,
"error_message": null,
"unified_code": null,
"unified_message": null,
"payment_experience": null,
"payment_method_type": null,
"connector_label": null,
"business_country": null,
"business_label": "default",
"business_sub_label": null,
"allowed_payment_method_types": null,
"ephemeral_key": null,
"manual_retry_allowed": false,
"connector_transaction_id": "7236389224576123203954",
"frm_message": null,
"metadata": null,
"connector_metadata": null,
"feature_metadata": null,
"reference_id": "pay_8Zx3ByOLe2LKJk80ovSO_1",
"payment_link": null,
"profile_id": "pro_JzHXSgyHYbzaxsycvvjC",
"surcharge_details": null,
"attempt_count": 1,
"merchant_decision": null,
"merchant_connector_id": "mca_33pcEQPsIl5PumUlPxEb",
"incremental_authorization_allowed": false,
"authorization_count": null,
"incremental_authorizations": null,
"external_authentication_details": null,
"external_3ds_authentication_attempted": false,
"expires_on": "2024-08-14T12:50:02.511Z",
"fingerprint": null,
"browser_info": {
"language": null,
"time_zone": null,
"ip_address": "::1",
"user_agent": null,
"color_depth": null,
"java_enabled": null,
"screen_width": null,
"accept_header": null,
"screen_height": null,
"java_script_enabled": null
},
"payment_method_id": "pm_rY1D25c9x9LyyT20xX8x",
"payment_method_status": "active",
"updated": "2024-08-14T12:35:23.640Z",
"charges": null,
"frm_metadata": null,
"merchant_order_reference_id": null
}
```
## Checklist
<!-- Put an `x` in the boxes that apply -->
- [x] I formatted the code `cargo +nightly fmt --all`
- [x] I addressed lints thrown by `cargo clippy`
- [x] I reviewed the submitted code
- [ ] I added unit tests for my changes where possible
|
8fa51b7b1cdf4347dc5778859597aa9ed1691790
|
|
juspay/hyperswitch
|
juspay__hyperswitch-5627
|
Bug: feat(payments): show aggregate count of payment status
Show count of aggregate payments status in the given time range:

This can be part of filter Api.
|
diff --git a/crates/api_models/src/events/payment.rs b/crates/api_models/src/events/payment.rs
index 589dcd8d10b..941cbb33309 100644
--- a/crates/api_models/src/events/payment.rs
+++ b/crates/api_models/src/events/payment.rs
@@ -18,12 +18,13 @@ use crate::{
payments::{
ExtendedCardInfoResponse, PaymentIdType, PaymentListConstraints,
PaymentListFilterConstraints, PaymentListFilters, PaymentListFiltersV2,
- PaymentListResponse, PaymentListResponseV2, PaymentsApproveRequest, PaymentsCancelRequest,
- PaymentsCaptureRequest, PaymentsCompleteAuthorizeRequest,
- PaymentsExternalAuthenticationRequest, PaymentsExternalAuthenticationResponse,
- PaymentsIncrementalAuthorizationRequest, PaymentsManualUpdateRequest,
- PaymentsRejectRequest, PaymentsRequest, PaymentsResponse, PaymentsRetrieveRequest,
- PaymentsSessionResponse, PaymentsStartRequest, RedirectionResponse,
+ PaymentListResponse, PaymentListResponseV2, PaymentsAggregateResponse,
+ PaymentsApproveRequest, PaymentsCancelRequest, PaymentsCaptureRequest,
+ PaymentsCompleteAuthorizeRequest, PaymentsExternalAuthenticationRequest,
+ PaymentsExternalAuthenticationResponse, PaymentsIncrementalAuthorizationRequest,
+ PaymentsManualUpdateRequest, PaymentsRejectRequest, PaymentsRequest, PaymentsResponse,
+ PaymentsRetrieveRequest, PaymentsSessionResponse, PaymentsStartRequest,
+ RedirectionResponse,
},
};
impl ApiEventMetric for PaymentsRetrieveRequest {
@@ -225,6 +226,11 @@ impl ApiEventMetric for PaymentListResponseV2 {
Some(ApiEventsType::ResourceListAPI)
}
}
+impl ApiEventMetric for PaymentsAggregateResponse {
+ fn get_api_event_type(&self) -> Option<ApiEventsType> {
+ Some(ApiEventsType::ResourceListAPI)
+ }
+}
impl ApiEventMetric for RedirectionResponse {}
diff --git a/crates/api_models/src/payments.rs b/crates/api_models/src/payments.rs
index 88c915f0e73..f9041b27373 100644
--- a/crates/api_models/src/payments.rs
+++ b/crates/api_models/src/payments.rs
@@ -4099,6 +4099,12 @@ pub struct PaymentListFiltersV2 {
pub authentication_type: Vec<enums::AuthenticationType>,
}
+#[derive(Clone, Debug, serde::Serialize)]
+pub struct PaymentsAggregateResponse {
+ /// The list of intent status with their count
+ pub status_with_count: HashMap<enums::IntentStatus, i64>,
+}
+
#[derive(Clone, Debug, Eq, PartialEq, serde::Deserialize, serde::Serialize, ToSchema)]
pub struct AmountFilter {
/// The start amount to filter list of transactions which are greater than or equal to the start amount
diff --git a/crates/hyperswitch_domain_models/src/payments/payment_intent.rs b/crates/hyperswitch_domain_models/src/payments/payment_intent.rs
index 90e3619f02e..c129e83d556 100644
--- a/crates/hyperswitch_domain_models/src/payments/payment_intent.rs
+++ b/crates/hyperswitch_domain_models/src/payments/payment_intent.rs
@@ -67,6 +67,13 @@ pub trait PaymentIntentInterface {
storage_scheme: storage_enums::MerchantStorageScheme,
) -> error_stack::Result<Vec<PaymentIntent>, errors::StorageError>;
+ #[cfg(feature = "olap")]
+ async fn get_intent_status_with_count(
+ &self,
+ merchant_id: &id_type::MerchantId,
+ constraints: &api_models::payments::TimeRange,
+ ) -> error_stack::Result<Vec<(common_enums::IntentStatus, i64)>, errors::StorageError>;
+
#[cfg(feature = "olap")]
async fn get_filtered_payment_intents_attempt(
&self,
diff --git a/crates/router/src/core/payments.rs b/crates/router/src/core/payments.rs
index a8ec32cb55b..d49b621b6d1 100644
--- a/crates/router/src/core/payments.rs
+++ b/crates/router/src/core/payments.rs
@@ -3157,6 +3157,31 @@ pub async fn get_payment_filters(
))
}
+#[cfg(feature = "olap")]
+pub async fn get_aggregates_for_payments(
+ state: SessionState,
+ merchant: domain::MerchantAccount,
+ time_range: api::TimeRange,
+) -> RouterResponse<api::PaymentsAggregateResponse> {
+ let db = state.store.as_ref();
+ let intent_status_with_count = db
+ .get_intent_status_with_count(merchant.get_id(), &time_range)
+ .await
+ .to_not_found_response(errors::ApiErrorResponse::PaymentNotFound)?;
+
+ let mut status_map: HashMap<enums::IntentStatus, i64> =
+ intent_status_with_count.into_iter().collect();
+ for status in enums::IntentStatus::iter() {
+ status_map.entry(status).or_default();
+ }
+
+ Ok(services::ApplicationResponse::Json(
+ api::PaymentsAggregateResponse {
+ status_with_count: status_map,
+ },
+ ))
+}
+
pub async fn add_process_sync_task(
db: &dyn StorageInterface,
payment_attempt: &storage::PaymentAttempt,
diff --git a/crates/router/src/db/kafka_store.rs b/crates/router/src/db/kafka_store.rs
index 2f5bf8b6791..b8f1e320f47 100644
--- a/crates/router/src/db/kafka_store.rs
+++ b/crates/router/src/db/kafka_store.rs
@@ -1616,6 +1616,17 @@ impl PaymentIntentInterface for KafkaStore {
.await
}
+ #[cfg(feature = "olap")]
+ async fn get_intent_status_with_count(
+ &self,
+ merchant_id: &id_type::MerchantId,
+ time_range: &api_models::payments::TimeRange,
+ ) -> error_stack::Result<Vec<(common_enums::IntentStatus, i64)>, errors::DataStorageError> {
+ self.diesel_store
+ .get_intent_status_with_count(merchant_id, time_range)
+ .await
+ }
+
#[cfg(feature = "olap")]
async fn get_filtered_payment_intents_attempt(
&self,
diff --git a/crates/router/src/routes/app.rs b/crates/router/src/routes/app.rs
index 5fe71a6a8da..f7c7583ad33 100644
--- a/crates/router/src/routes/app.rs
+++ b/crates/router/src/routes/app.rs
@@ -539,6 +539,7 @@ impl Payments {
)
.service(web::resource("/filter").route(web::post().to(get_filters_for_payments)))
.service(web::resource("/v2/filter").route(web::get().to(get_payment_filters)))
+ .service(web::resource("/aggregate").route(web::get().to(get_payments_aggregates)))
.service(
web::resource("/{payment_id}/manual-update")
.route(web::put().to(payments_manual_update)),
diff --git a/crates/router/src/routes/lock_utils.rs b/crates/router/src/routes/lock_utils.rs
index 9f073853d88..9f2f99368e2 100644
--- a/crates/router/src/routes/lock_utils.rs
+++ b/crates/router/src/routes/lock_utils.rs
@@ -126,6 +126,7 @@ impl From<Flow> for ApiIdentifier {
| Flow::PaymentsStart
| Flow::PaymentsList
| Flow::PaymentsFilters
+ | Flow::PaymentsAggregate
| Flow::PaymentsRedirect
| Flow::PaymentsIncrementalAuthorization
| Flow::PaymentsExternalAuthentication
diff --git a/crates/router/src/routes/payments.rs b/crates/router/src/routes/payments.rs
index d2f0cfeb775..c79d2d316bc 100644
--- a/crates/router/src/routes/payments.rs
+++ b/crates/router/src/routes/payments.rs
@@ -1069,6 +1069,29 @@ pub async fn get_payment_filters(
.await
}
+#[instrument(skip_all, fields(flow = ?Flow::PaymentsAggregate))]
+#[cfg(feature = "olap")]
+pub async fn get_payments_aggregates(
+ state: web::Data<app::AppState>,
+ req: actix_web::HttpRequest,
+ payload: web::Query<payment_types::TimeRange>,
+) -> impl Responder {
+ let flow = Flow::PaymentsAggregate;
+ let payload = payload.into_inner();
+ Box::pin(api::server_wrap(
+ flow,
+ state,
+ &req,
+ payload,
+ |state, auth: auth::AuthenticationData, req, _| {
+ payments::get_aggregates_for_payments(state, auth.merchant_account, req)
+ },
+ &auth::JWTAuth(Permission::PaymentRead),
+ api_locking::LockAction::NotApplicable,
+ ))
+ .await
+}
+
#[cfg(feature = "oltp")]
#[instrument(skip_all, fields(flow = ?Flow::PaymentsApprove, payment_id))]
// #[post("/{payment_id}/approve")]
diff --git a/crates/router/src/types/api/payments.rs b/crates/router/src/types/api/payments.rs
index 6b156098d5e..ab25332a5c5 100644
--- a/crates/router/src/types/api/payments.rs
+++ b/crates/router/src/types/api/payments.rs
@@ -5,14 +5,14 @@ pub use api_models::payments::{
OnlineMandate, OpenBankingSessionToken, PayLaterData, PaymentIdType, PaymentListConstraints,
PaymentListFilterConstraints, PaymentListFilters, PaymentListFiltersV2, PaymentListResponse,
PaymentListResponseV2, PaymentMethodData, PaymentMethodDataRequest, PaymentMethodDataResponse,
- PaymentOp, PaymentRetrieveBody, PaymentRetrieveBodyWithCredentials, PaymentsApproveRequest,
- PaymentsCancelRequest, PaymentsCaptureRequest, PaymentsCompleteAuthorizeRequest,
- PaymentsExternalAuthenticationRequest, PaymentsIncrementalAuthorizationRequest,
- PaymentsManualUpdateRequest, PaymentsRedirectRequest, PaymentsRedirectionResponse,
- PaymentsRejectRequest, PaymentsRequest, PaymentsResponse, PaymentsResponseForm,
- PaymentsRetrieveRequest, PaymentsSessionRequest, PaymentsSessionResponse, PaymentsStartRequest,
- PgRedirectResponse, PhoneDetails, RedirectionResponse, SessionToken, TimeRange, UrlDetails,
- VerifyRequest, VerifyResponse, WalletData,
+ PaymentOp, PaymentRetrieveBody, PaymentRetrieveBodyWithCredentials, PaymentsAggregateResponse,
+ PaymentsApproveRequest, PaymentsCancelRequest, PaymentsCaptureRequest,
+ PaymentsCompleteAuthorizeRequest, PaymentsExternalAuthenticationRequest,
+ PaymentsIncrementalAuthorizationRequest, PaymentsManualUpdateRequest, PaymentsRedirectRequest,
+ PaymentsRedirectionResponse, PaymentsRejectRequest, PaymentsRequest, PaymentsResponse,
+ PaymentsResponseForm, PaymentsRetrieveRequest, PaymentsSessionRequest, PaymentsSessionResponse,
+ PaymentsStartRequest, PgRedirectResponse, PhoneDetails, RedirectionResponse, SessionToken,
+ TimeRange, UrlDetails, VerifyRequest, VerifyResponse, WalletData,
};
use error_stack::ResultExt;
pub use hyperswitch_domain_models::router_flow_types::payments::{
diff --git a/crates/router_env/src/logger/types.rs b/crates/router_env/src/logger/types.rs
index f1d2e5d8dcc..ccc2842bf5d 100644
--- a/crates/router_env/src/logger/types.rs
+++ b/crates/router_env/src/logger/types.rs
@@ -167,6 +167,8 @@ pub enum Flow {
PaymentsList,
/// Payments filters flow
PaymentsFilters,
+ /// Payments aggregates flow
+ PaymentsAggregate,
#[cfg(feature = "payouts")]
/// Payouts create flow
PayoutsCreate,
diff --git a/crates/storage_impl/src/mock_db/payment_intent.rs b/crates/storage_impl/src/mock_db/payment_intent.rs
index 59951045a1b..4fb06bc169c 100644
--- a/crates/storage_impl/src/mock_db/payment_intent.rs
+++ b/crates/storage_impl/src/mock_db/payment_intent.rs
@@ -41,6 +41,15 @@ impl PaymentIntentInterface for MockDb {
Err(StorageError::MockDbError)?
}
#[cfg(feature = "olap")]
+ async fn get_intent_status_with_count(
+ &self,
+ _merchant_id: &common_utils::id_type::MerchantId,
+ _time_range: &api_models::payments::TimeRange,
+ ) -> CustomResult<Vec<(common_enums::IntentStatus, i64)>, StorageError> {
+ // [#172]: Implement function for `MockDb`
+ Err(StorageError::MockDbError)?
+ }
+ #[cfg(feature = "olap")]
async fn get_filtered_active_attempt_ids_for_total_count(
&self,
_merchant_id: &common_utils::id_type::MerchantId,
diff --git a/crates/storage_impl/src/payments/payment_intent.rs b/crates/storage_impl/src/payments/payment_intent.rs
index c8dc011b814..f7127761afb 100644
--- a/crates/storage_impl/src/payments/payment_intent.rs
+++ b/crates/storage_impl/src/payments/payment_intent.rs
@@ -346,6 +346,16 @@ impl<T: DatabaseStore> PaymentIntentInterface for KVRouterStore<T> {
)
.await
}
+ #[cfg(feature = "olap")]
+ async fn get_intent_status_with_count(
+ &self,
+ merchant_id: &common_utils::id_type::MerchantId,
+ time_range: &api_models::payments::TimeRange,
+ ) -> error_stack::Result<Vec<(common_enums::IntentStatus, i64)>, StorageError> {
+ self.router_store
+ .get_intent_status_with_count(merchant_id, time_range)
+ .await
+ }
#[cfg(feature = "olap")]
async fn get_filtered_payment_intents_attempt(
@@ -655,6 +665,45 @@ impl<T: DatabaseStore> PaymentIntentInterface for crate::RouterStore<T> {
.await
}
+ #[cfg(feature = "olap")]
+ #[instrument(skip_all)]
+ async fn get_intent_status_with_count(
+ &self,
+ merchant_id: &common_utils::id_type::MerchantId,
+ time_range: &api_models::payments::TimeRange,
+ ) -> error_stack::Result<Vec<(common_enums::IntentStatus, i64)>, StorageError> {
+ let conn = connection::pg_connection_read(self).await.switch()?;
+ let conn = async_bb8_diesel::Connection::as_async_conn(&conn);
+
+ let mut query = <DieselPaymentIntent as HasTable>::table()
+ .group_by(pi_dsl::status)
+ .select((pi_dsl::status, diesel::dsl::count_star()))
+ .filter(pi_dsl::merchant_id.eq(merchant_id.to_owned()))
+ .into_boxed();
+
+ query = query.filter(pi_dsl::created_at.ge(time_range.start_time));
+
+ query = match time_range.end_time {
+ Some(ending_at) => query.filter(pi_dsl::created_at.le(ending_at)),
+ None => query,
+ };
+
+ logger::debug!(filter = %diesel::debug_query::<diesel::pg::Pg,_>(&query).to_string());
+
+ db_metrics::track_database_call::<<DieselPaymentIntent as HasTable>::Table, _, _>(
+ query.get_results_async::<(common_enums::IntentStatus, i64)>(conn),
+ db_metrics::DatabaseOperation::Filter,
+ )
+ .await
+ .map_err(|er| {
+ StorageError::DatabaseError(
+ error_stack::report!(diesel_models::errors::DatabaseError::from(er))
+ .attach_printable("Error filtering payment records"),
+ )
+ .into()
+ })
+ }
+
#[cfg(feature = "olap")]
#[instrument(skip_all)]
async fn get_filtered_payment_intents_attempt(
|
2024-08-21T09:00:45Z
|
## Type of Change
<!-- Put an `x` in the boxes that apply -->
- [ ] Bugfix
- [x] New feature
- [ ] Enhancement
- [ ] Refactoring
- [ ] Dependency updates
- [ ] Documentation
- [ ] CI/CD
## Description

- The endpoint `/aggregate` to support views

- Add support for aggregates in payments.
- For now it will have list of intent status along with the their count for a given time range.
( Profile level support will be covered in separate PR, with new route but same core function having profile_id as option)
### Additional Changes
- [x] This PR modifies the API contract
- [] This PR modifies the database schema
- [ ] This PR modifies application configuration/environment variables
<!--
Provide links to the files with corresponding changes.
Following are the paths where you can find config files:
1. `config`
2. `crates/router/src/configs`
3. `loadtest/config`
-->
## Motivation and Context
Closes [#5627](https://github.com/juspay/hyperswitch/issues/5627)
## How did you test it?
Request:
```
curl --location 'http://localhost:8080/payments/aggregate?start_time=2022-08-20T11%3A33%3A39.000Z' \
--header 'Content-Type: application/json' \
--header 'Authorization: Bearer JWT'
```
Response:
```
{
"status_with_count": {
"requires_capture": 0,
"requires_customer_action": 0,
"requires_payment_method": 0,
"processing": 0,
"cancelled": 0,
"requires_confirmation": 0,
"succeeded": 90,
"partially_captured": 0,
"partially_captured_and_capturable": 0,
"requires_merchant_action": 0,
"failed": 10
}
}
```
## Checklist
<!-- Put an `x` in the boxes that apply -->
- [x] I formatted the code `cargo +nightly fmt --all`
- [x] I addressed lints thrown by `cargo clippy`
- [x] I reviewed the submitted code
- [ ] I added unit tests for my changes where possible
|
cc5b06e72553c33c9d9ed5f9a944ceb5bb36f2c7
|
|
juspay/hyperswitch
|
juspay__hyperswitch-5625
|
Bug: [BUG] Fix Deserialization error in Pm auth core
### Feature Description
Currently, if we try to link accounts twice in pm auth flow, the `/exchange` call fails due to a deserialization error.
This happens because of extra entries created in DB during mandate save pm flow.
### Possible Implementation
Need to check on pm data first before deserialization.
### Have you spent some time checking if this feature request has been raised before?
- [X] I checked and didn't find a similar issue
### Have you read the Contributing Guidelines?
- [X] I have read the [Contributing Guidelines](https://github.com/juspay/hyperswitch/blob/main/docs/CONTRIBUTING.md)
### Are you willing to submit a PR?
Yes, I am willing to submit a PR!
|
diff --git a/crates/router/src/core/pm_auth.rs b/crates/router/src/core/pm_auth.rs
index 64c1918c5e5..47f843030ee 100644
--- a/crates/router/src/core/pm_auth.rs
+++ b/crates/router/src/core/pm_auth.rs
@@ -346,7 +346,9 @@ async fn store_bank_details_in_payment_methods(
> = HashMap::new();
for pm in payment_methods {
- if pm.payment_method == Some(enums::PaymentMethod::BankDebit) {
+ if pm.payment_method == Some(enums::PaymentMethod::BankDebit)
+ && pm.payment_method_data.is_some()
+ {
let bank_details_pm_data = crypto_operation::<serde_json::Value, masking::WithType>(
&(&state).into(),
type_name!(storage::PaymentMethod),
|
2024-08-13T11:30:58Z
|
## Type of Change
<!-- Put an `x` in the boxes that apply -->
- [x] Bugfix
- [ ] New feature
- [ ] Enhancement
- [ ] Refactoring
- [ ] Dependency updates
- [ ] Documentation
- [ ] CI/CD
## Description
<!-- Describe your changes in detail -->
Earlier, the mandate request was inserting another entry in payment_methods table which interfered with pm_auth when running it again. The `/auth/exchange` call was failing due to this.
Have fixed the logic in pm_auth to be more specific.
### Additional Changes
- [ ] This PR modifies the API contract
- [ ] This PR modifies the database schema
- [ ] This PR modifies application configuration/environment variables
<!--
Provide links to the files with corresponding changes.
Following are the paths where you can find config files:
1. `config`
2. `crates/router/src/configs`
3. `loadtest/config`
-->
## Motivation and Context
<!--
Why is this change required? What problem does it solve?
If it fixes an open issue, please link to the issue here.
If you don't have an issue, we'd recommend starting with one first so the PR
can focus on the implementation (unless it is an obvious bug or documentation fix
that will have little conversation).
-->
## How did you test it?
<!--
Did you write an integration/unit/API test to verify the code changes?
Or did you test this change manually (provide relevant screenshots)?
-->
Can be tested via SDK
1. Test Pm auth flow (with ` "setup_future_usage": "off_session"` passed in `payment_create` and `customer_acceptance` passed in `payment_confirm`)
2. Retest the Pm auth flow
## Checklist
<!-- Put an `x` in the boxes that apply -->
- [x] I formatted the code `cargo +nightly fmt --all`
- [x] I addressed lints thrown by `cargo clippy`
- [ ] I reviewed the submitted code
- [ ] I added unit tests for my changes where possible
|
67d580c0ebcfc070ad6ff5cab4079ca447541ee4
|
|
juspay/hyperswitch
|
juspay__hyperswitch-5622
|
Bug: fix(opensearch): Sort the global search results in descending order
When searching using global search, the results are not sorted. It would be better if they are sorted in newest to oldest order.
|
diff --git a/crates/analytics/src/opensearch.rs b/crates/analytics/src/opensearch.rs
index e74622a054a..f3dd5eea441 100644
--- a/crates/analytics/src/opensearch.rs
+++ b/crates/analytics/src/opensearch.rs
@@ -518,7 +518,19 @@ impl OpenSearchQueryBuilder {
let mut final_query = Map::new();
final_query.insert("bool".to_string(), json!({ "filter": updated_query }));
- let payload = json!({ "query": Value::Object(final_query) });
+ let mut sort_obj = Map::new();
+ sort_obj.insert(
+ "@timestamp".to_string(),
+ json!({
+ "order": "desc"
+ }),
+ );
+ let payload = json!({
+ "query": Value::Object(final_query),
+ "sort": [
+ Value::Object(sort_obj)
+ ]
+ });
payload
})
.collect::<Vec<Value>>())
|
2024-08-14T07:37:17Z
|
## Type of Change
<!-- Put an `x` in the boxes that apply -->
- [x] Bugfix
- [ ] New feature
- [x] Enhancement
- [ ] Refactoring
- [ ] Dependency updates
- [ ] Documentation
- [ ] CI/CD
## Description
<!-- Describe your changes in detail -->
When searching using global search, the results are not sorted. Sorted the results now in newest to oldest order.
### Additional Changes
- [ ] This PR modifies the API contract
- [ ] This PR modifies the database schema
- [ ] This PR modifies application configuration/environment variables
<!--
Provide links to the files with corresponding changes.
Following are the paths where you can find config files:
1. `config`
2. `crates/router/src/configs`
3. `loadtest/config`
-->
## Motivation and Context
<!--
Why is this change required? What problem does it solve?
If it fixes an open issue, please link to the issue here.
If you don't have an issue, we'd recommend starting with one first so the PR
can focus on the implementation (unless it is an obvious bug or documentation fix
that will have little conversation).
-->
Enhance search experience by listing the results in newest to oldest order.
Raised by this issue: [https://github.com/juspay/hyperswitch-control-center/issues/1131](https://github.com/juspay/hyperswitch-control-center/issues/1131)
## How did you test it?
<!--
Did you write an integration/unit/API test to verify the code changes?
Or did you test this change manually (provide relevant screenshots)?
-->
- Hit the `/search` API
```bash
curl --location 'http://localhost:8080/analytics/v1/search' \
--header 'Accept: */*' \
--header 'Accept-Language: en-US,en;q=0.9' \
--header 'Connection: keep-alive' \
--header 'Content-Type: application/json' \
--header 'Origin: http://localhost:9000' \
--header 'Referer: http://localhost:9000/' \
--header 'Sec-Fetch-Dest: empty' \
--header 'Sec-Fetch-Mode: cors' \
--header 'Sec-Fetch-Site: same-site' \
--header 'User-Agent: Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/126.0.0.0 Safari/537.36' \
--header 'api-key: hyperswitch' \
--header 'authorization: Bearer eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJ1c2VyX2lkIjoiYjc2ZDVmZjMtNGI1ZS00OTMyLTk1ZDItNmE3MTEyZWZiNTNlIiwibWVyY2hhbnRfaWQiOiJtZXJjaGFudF8xNzIxODE1MjkwIiwicm9sZV9pZCI6Im9yZ19hZG1pbiIsImV4cCI6MTcyMzc4ODI2OSwib3JnX2lkIjoib3JnX3VFNk1LbExxalU5MWlGUEVGck1rIiwicHJvZmlsZV9pZCI6bnVsbH0.AFuIb8uXW92J7V_0-nbPCHLDnl-l4CxSjBYIZNoW5KE' \
--header 'sec-ch-ua: "Not/A)Brand";v="8", "Chromium";v="126", "Google Chrome";v="126"' \
--header 'sec-ch-ua-mobile: ?0' \
--header 'sec-ch-ua-platform: "macOS"' \
--data-raw '{
"query": "usd",
"filters": {
"customer_email" : [
"test@test14.com"
]
},
"timeRange": {
"startTime": "2024-08-14T00:30:00Z",
"endTime": "2024-08-14T18:45:00Z"
}
}'
```
Results should now appear sorted in descending order
```bash
{
"@timestamp": "2024-08-14T07:25:02Z",
"active_attempt_id": "pay_nvWZxyMCOeA5UmlfRqKX_1",
"amount": 6540,
"amount_captured": 6540,
"attempt_count": 1,
"billing_details": null,
"business_country": null,
"business_label": "default",
"clickhouse_database": "default",
"client_secret": "pay_nvWZxyMCOeA5UmlfRqKX_secret_GgDrUrwfTVSHJjTbRUDi",
"connector_id": null,
"created_at": 1723620302,
"currency": "USD",
"customer_email": "f6cd0753a831880835a0e0d23136ef66318d8303605bd37fa80b4ecf248bd303",
"customer_id": "StripeCustomer",
"description": "Its my first payment request",
"feature_metadata": {
"redirect_response": null,
"search_tags": [
"9c202f2fabd12f758a12b449944f5cdaeadf39132680667543033158023bc805",
"ffd1c37eb18f3459e3da6f21f739866bce89a334061c248656cb71d83d2375f4"
]
},
"headers": {},
"last_synced": 1723620302,
"merchant_id": "merchant_1721815290",
"merchant_order_reference_id": null,
"metadata": "{\"data2\":\"camel\",\"login_date\":\"2019-09-10T10:11:12Z\",\"new_customer\":\"true\"}",
"modified_at": 1723620304,
"off_session": null,
"payment_confirm_source": null,
"payment_id": "pay_nvWZxyMCOeA5UmlfRqKX",
"profile_id": "pro_ZTGBrEwlRmTyzKFpnV9Z",
"return_url": "https://google.com/",
"setup_future_usage": null,
"shipping_details": null,
"sign_flag": 1,
"source_type": "kafka",
"statement_descriptor_name": "joseph",
"statement_descriptor_suffix": "JS",
"status": "succeeded",
"tenant_id": "public",
"timestamp": "2024-08-14T07:25:02Z"
},
{
"@timestamp": "2024-08-14T06:46:30Z",
"active_attempt_id": "pay_LzTCv5OHAApqOU43CxIm_1",
"amount": 6540,
"amount_captured": 6540,
"attempt_count": 1,
"billing_details": null,
"business_country": null,
"business_label": "default",
"clickhouse_database": "default",
"client_secret": "pay_LzTCv5OHAApqOU43CxIm_secret_AwCmBtbalAU85SWJGs0W",
"connector_id": null,
"created_at": 1723617990,
"currency": "USD",
"customer_email": "f6cd0753a831880835a0e0d23136ef66318d8303605bd37fa80b4ecf248bd303",
"customer_id": "StripeCustomer",
"description": "Its my first payment request",
"feature_metadata": {
"redirect_response": null,
"search_tags": [
"9c202f2fabd12f758a12b449944f5cdaeadf39132680667543033158023bc805",
"ffd1c37eb18f3459e3da6f21f739866bce89a334061c248656cb71d83d2375f4"
]
},
"headers": {},
"last_synced": 1723617990,
"merchant_id": "merchant_1721815290",
"merchant_order_reference_id": null,
"metadata": "{\"data2\":\"camel\",\"login_date\":\"2019-09-10T10:11:12Z\",\"new_customer\":\"true\"}",
"modified_at": 1723617991,
"off_session": null,
"payment_confirm_source": null,
"payment_id": "pay_LzTCv5OHAApqOU43CxIm",
"profile_id": "pro_ZTGBrEwlRmTyzKFpnV9Z",
"return_url": "https://google.com/",
"setup_future_usage": null,
"shipping_details": null,
"sign_flag": 1,
"source_type": "kafka",
"statement_descriptor_name": "joseph",
"statement_descriptor_suffix": "JS",
"status": "succeeded",
"tenant_id": "public",
"timestamp": "2024-08-14T06:46:30Z"
},
{
"@timestamp": "2024-08-14T06:45:39Z",
"active_attempt_id": "pay_djRThD60oIoz3jucMvQd_1",
"amount": 6540,
"amount_captured": 6540,
"attempt_count": 1,
"billing_details": null,
"business_country": null,
"business_label": "default",
"clickhouse_database": "default",
"client_secret": "pay_djRThD60oIoz3jucMvQd_secret_16zPOM5hVp7uY1Tjt6zW",
"connector_id": null,
"created_at": 1723617939,
"currency": "USD",
"customer_email": "f6cd0753a831880835a0e0d23136ef66318d8303605bd37fa80b4ecf248bd303",
"customer_id": "StripeCustomer",
"description": "Its my first payment request",
"feature_metadata": {
"redirect_response": null,
"search_tags": [
"9c202f2fabd12f758a12b449944f5cdaeadf39132680667543033158023bc805",
"ffd1c37eb18f3459e3da6f21f739866bce89a334061c248656cb71d83d2375f4"
]
},
"headers": {},
"last_synced": 1723617939,
"merchant_id": "merchant_1721815290",
"merchant_order_reference_id": null,
"metadata": "{\"data2\":\"camel\",\"login_date\":\"2019-09-10T10:11:12Z\",\"new_customer\":\"true\"}",
"modified_at": 1723617941,
"off_session": null,
"payment_confirm_source": null,
"payment_id": "pay_djRThD60oIoz3jucMvQd",
"profile_id": "pro_ZTGBrEwlRmTyzKFpnV9Z",
"return_url": "https://google.com/",
"setup_future_usage": null,
"shipping_details": null,
"sign_flag": 1,
"source_type": "kafka",
"statement_descriptor_name": "joseph",
"statement_descriptor_suffix": "JS",
"status": "succeeded",
"tenant_id": "public",
"timestamp": "2024-08-14T06:45:39Z"
},
```
<img width="769" alt="Screenshot 2024-08-14 at 1 03 32 PM" src="https://github.com/user-attachments/assets/6c275ea3-4fee-44d6-ad38-a96300e6151a">
## Checklist
<!-- Put an `x` in the boxes that apply -->
- [x] I formatted the code `cargo +nightly fmt --all`
- [x] I addressed lints thrown by `cargo clippy`
- [x] I reviewed the submitted code
- [ ] I added unit tests for my changes where possible
|
b213db213e623a1eea3f6dbd66703df4a897d93f
|
|
juspay/hyperswitch
|
juspay__hyperswitch-5649
|
Bug: [REFACTOR] Refactor Update and Retrieve Default Fallback behaviour in payments routing
### Feature Description
Refactor Update and Retrieve Default Fallback usages in payments core for routing
### Possible Implementation
Refactor Update and Retrieve Default Fallback usages in payments core for routing, and pass business_profile in the parameters instead of profile_id
### Have you spent some time checking if this feature request has been raised before?
- [X] I checked and didn't find a similar issue
### Have you read the Contributing Guidelines?
- [X] I have read the [Contributing Guidelines](https://github.com/juspay/hyperswitch/blob/main/docs/CONTRIBUTING.md)
### Are you willing to submit a PR?
Yes, I am willing to submit a PR!
|
diff --git a/Cargo.lock b/Cargo.lock
index cf7718d8875..0a0448cae47 100644
--- a/Cargo.lock
+++ b/Cargo.lock
@@ -454,6 +454,7 @@ dependencies = [
"nutype",
"reqwest",
"router_derive",
+ "rustc-hash",
"serde",
"serde_json",
"strum 0.26.2",
diff --git a/crates/api_models/Cargo.toml b/crates/api_models/Cargo.toml
index e342fb3db91..0134c6c6fc9 100644
--- a/crates/api_models/Cargo.toml
+++ b/crates/api_models/Cargo.toml
@@ -39,6 +39,7 @@ strum = { version = "0.26", features = ["derive"] }
time = { version = "0.3.35", features = ["serde", "serde-well-known", "std"] }
url = { version = "2.5.0", features = ["serde"] }
utoipa = { version = "4.2.0", features = ["preserve_order", "preserve_path_order"] }
+rustc-hash = "1.1.0"
nutype = { version = "0.4.2", features = ["serde"] }
# First party crates
diff --git a/crates/api_models/src/customers.rs b/crates/api_models/src/customers.rs
index c4261d624f1..1f890b1bf89 100644
--- a/crates/api_models/src/customers.rs
+++ b/crates/api_models/src/customers.rs
@@ -5,8 +5,8 @@ use common_utils::{
pii::{self, EmailStrategy},
types::{keymanager::ToEncryptable, Description},
};
-use euclid::dssa::graph::euclid_graph_prelude::FxHashMap;
use masking::{ExposeInterface, Secret, SwitchStrategy};
+use rustc_hash::FxHashMap;
use serde::{Deserialize, Serialize};
use utoipa::ToSchema;
diff --git a/crates/api_models/src/payments.rs b/crates/api_models/src/payments.rs
index 88c915f0e73..b18481b03da 100644
--- a/crates/api_models/src/payments.rs
+++ b/crates/api_models/src/payments.rs
@@ -15,9 +15,9 @@ use common_utils::{
types::{keymanager::ToEncryptable, MinorUnit, StringMajorUnit},
};
use error_stack::ResultExt;
-use euclid::dssa::graph::euclid_graph_prelude::FxHashMap;
use masking::{ExposeInterface, PeekInterface, Secret, SwitchStrategy, WithType};
use router_derive::Setter;
+use rustc_hash::FxHashMap;
use serde::{
de::{self, Unexpected, Visitor},
ser::Serializer,
diff --git a/crates/router/src/core/admin.rs b/crates/router/src/core/admin.rs
index 1f5fb068408..f49fce8e7f6 100644
--- a/crates/router/src/core/admin.rs
+++ b/crates/router/src/core/admin.rs
@@ -7,7 +7,7 @@ use api_models::{
use base64::Engine;
use common_utils::{
date_time,
- ext_traits::{AsyncExt, Encode, ValueExt},
+ ext_traits::{AsyncExt, Encode, OptionExt, ValueExt},
id_type, pii, type_name,
types::keymanager::{self as km_types, KeyManagerState},
};
@@ -21,12 +21,6 @@ use regex::Regex;
use router_env::metrics::add_attributes;
use uuid::Uuid;
-#[cfg(all(
- feature = "v2",
- feature = "routing_v2",
- feature = "business_profile_v2"
-))]
-use crate::core::routing;
#[cfg(any(feature = "v1", feature = "v2"))]
use crate::types::transformers::ForeignFrom;
use crate::{
@@ -37,8 +31,7 @@ use crate::{
payment_methods::{cards, transformers},
payments::helpers,
pm_auth::helpers::PaymentAuthConnectorDataExt,
- routing::helpers as routing_helpers,
- utils as core_utils,
+ routing, utils as core_utils,
},
db::StorageInterface,
routes::{metrics, SessionState},
@@ -55,6 +48,7 @@ use crate::{
},
utils,
};
+
const IBAN_MAX_LENGTH: usize = 34;
const BACS_SORT_CODE_LENGTH: usize = 6;
const BACS_MAX_ACCOUNT_NUMBER_LENGTH: usize = 8;
@@ -1871,23 +1865,40 @@ impl<'a> ConnectorTypeAndConnectorName<'a> {
Ok(routable_connector)
}
}
-
+#[cfg(all(
+ any(feature = "v1", feature = "v2"),
+ not(any(feature = "routing_v2", feature = "business_profile_v2",))
+))]
struct MerchantDefaultConfigUpdate<'a> {
routable_connector: &'a Option<api_enums::RoutableConnectors>,
merchant_connector_id: &'a String,
store: &'a dyn StorageInterface,
merchant_id: &'a id_type::MerchantId,
- default_routing_config: &'a Vec<api_models::routing::RoutableConnectorChoice>,
- default_routing_config_for_profile: &'a Vec<api_models::routing::RoutableConnectorChoice>,
profile_id: &'a String,
transaction_type: &'a api_enums::TransactionType,
}
-
+#[cfg(all(
+ any(feature = "v1", feature = "v2"),
+ not(any(feature = "routing_v2", feature = "business_profile_v2",))
+))]
impl<'a> MerchantDefaultConfigUpdate<'a> {
- async fn update_merchant_default_config(&self) -> RouterResult<()> {
- let mut default_routing_config = self.default_routing_config.to_owned();
- let mut default_routing_config_for_profile =
- self.default_routing_config_for_profile.to_owned();
+ async fn retrieve_and_update_default_fallback_routing_algorithm_if_routable_connector_exists(
+ &self,
+ ) -> RouterResult<()> {
+ let mut default_routing_config = routing::helpers::get_merchant_default_config(
+ self.store,
+ self.merchant_id.get_string_repr(),
+ self.transaction_type,
+ )
+ .await?;
+
+ let mut default_routing_config_for_profile = routing::helpers::get_merchant_default_config(
+ self.store,
+ self.profile_id,
+ self.transaction_type,
+ )
+ .await?;
+
if let Some(routable_connector_val) = self.routable_connector {
let choice = routing_types::RoutableConnectorChoice {
choice_kind: routing_types::RoutableChoiceKind::FullStruct,
@@ -1896,7 +1907,7 @@ impl<'a> MerchantDefaultConfigUpdate<'a> {
};
if !default_routing_config.contains(&choice) {
default_routing_config.push(choice.clone());
- routing_helpers::update_merchant_default_config(
+ routing::helpers::update_merchant_default_config(
self.store,
self.merchant_id.get_string_repr(),
default_routing_config.clone(),
@@ -1906,7 +1917,7 @@ impl<'a> MerchantDefaultConfigUpdate<'a> {
}
if !default_routing_config_for_profile.contains(&choice.clone()) {
default_routing_config_for_profile.push(choice);
- routing_helpers::update_merchant_default_config(
+ routing::helpers::update_merchant_default_config(
self.store,
self.profile_id,
default_routing_config_for_profile.clone(),
@@ -1918,7 +1929,53 @@ impl<'a> MerchantDefaultConfigUpdate<'a> {
Ok(())
}
}
+#[cfg(all(
+ feature = "v2",
+ feature = "routing_v2",
+ feature = "business_profile_v2",
+))]
+struct DefaultFallbackRoutingConfigUpdate<'a> {
+ routable_connector: &'a Option<api_enums::RoutableConnectors>,
+ merchant_connector_id: &'a String,
+ store: &'a dyn StorageInterface,
+ business_profile: domain::BusinessProfile,
+ key_store: hyperswitch_domain_models::merchant_key_store::MerchantKeyStore,
+ key_manager_state: &'a KeyManagerState,
+}
+#[cfg(all(
+ feature = "v2",
+ feature = "routing_v2",
+ feature = "business_profile_v2"
+))]
+impl<'a> DefaultFallbackRoutingConfigUpdate<'a> {
+ async fn retrieve_and_update_default_fallback_routing_algorithm_if_routable_connector_exists(
+ &self,
+ ) -> RouterResult<()> {
+ let profile_wrapper = BusinessProfileWrapper::new(self.business_profile.clone());
+ let default_routing_config_for_profile =
+ &mut profile_wrapper.get_default_fallback_list_of_connector_under_profile()?;
+ if let Some(routable_connector_val) = self.routable_connector {
+ let choice = routing_types::RoutableConnectorChoice {
+ choice_kind: routing_types::RoutableChoiceKind::FullStruct,
+ connector: *routable_connector_val,
+ merchant_connector_id: Some(self.merchant_connector_id.clone()),
+ };
+ if !default_routing_config_for_profile.contains(&choice.clone()) {
+ default_routing_config_for_profile.push(choice);
+ profile_wrapper
+ .update_default_fallback_routing_of_connectors_under_profile(
+ self.store,
+ &default_routing_config_for_profile,
+ self.key_manager_state,
+ &self.key_store,
+ )
+ .await?
+ }
+ }
+ Ok(())
+ }
+}
#[cfg(any(feature = "v1", feature = "v2", feature = "olap"))]
#[async_trait::async_trait]
trait MerchantConnectorAccountUpdateBridge {
@@ -2219,14 +2276,13 @@ trait MerchantConnectorAccountCreateBridge {
key_manager_state: &KeyManagerState,
) -> RouterResult<domain::MerchantConnectorAccount>;
- async fn validate_and_get_profile_id(
+ async fn validate_and_get_business_profile(
self,
merchant_account: &domain::MerchantAccount,
db: &dyn StorageInterface,
key_manager_state: &KeyManagerState,
key_store: &domain::MerchantKeyStore,
- should_validate: bool,
- ) -> RouterResult<String>;
+ ) -> RouterResult<domain::BusinessProfile>;
}
#[cfg(all(
@@ -2360,27 +2416,28 @@ impl MerchantConnectorAccountCreateBridge for api::MerchantConnectorCreate {
})
}
- async fn validate_and_get_profile_id(
+ async fn validate_and_get_business_profile(
self,
merchant_account: &domain::MerchantAccount,
db: &dyn StorageInterface,
key_manager_state: &KeyManagerState,
key_store: &domain::MerchantKeyStore,
- should_validate: bool,
- ) -> RouterResult<String> {
+ ) -> RouterResult<domain::BusinessProfile> {
let profile_id = self.profile_id;
// Check whether this business profile belongs to the merchant
- if should_validate {
- let _ = core_utils::validate_and_get_business_profile(
- db,
- key_manager_state,
- key_store,
- Some(&profile_id),
- merchant_account.get_id(),
- )
- .await?;
- }
- Ok(profile_id.clone())
+
+ let business_profile = core_utils::validate_and_get_business_profile(
+ db,
+ key_manager_state,
+ key_store,
+ Some(&profile_id),
+ merchant_account.get_id(),
+ )
+ .await?
+ .get_required_value("BusinessProfile")
+ .change_context(errors::ApiErrorResponse::BusinessProfileNotFound { id: profile_id })?;
+
+ Ok(business_profile)
}
}
@@ -2533,28 +2590,31 @@ impl MerchantConnectorAccountCreateBridge for api::MerchantConnectorCreate {
/// If profile_id is not passed, use default profile if available, or
/// If business_details (business_country and business_label) are passed, get the business_profile
/// or return a `MissingRequiredField` error
- async fn validate_and_get_profile_id(
+ async fn validate_and_get_business_profile(
self,
merchant_account: &domain::MerchantAccount,
db: &dyn StorageInterface,
key_manager_state: &KeyManagerState,
key_store: &domain::MerchantKeyStore,
- should_validate: bool,
- ) -> RouterResult<String> {
+ ) -> RouterResult<domain::BusinessProfile> {
match self.profile_id.or(merchant_account.default_profile.clone()) {
Some(profile_id) => {
// Check whether this business profile belongs to the merchant
- if should_validate {
- let _ = core_utils::validate_and_get_business_profile(
- db,
- key_manager_state,
- key_store,
- Some(&profile_id),
- merchant_account.get_id(),
- )
- .await?;
- }
- Ok(profile_id.clone())
+
+ let business_profile = core_utils::validate_and_get_business_profile(
+ db,
+ key_manager_state,
+ key_store,
+ Some(&profile_id),
+ merchant_account.get_id(),
+ )
+ .await?
+ .get_required_value("BusinessProfile")
+ .change_context(
+ errors::ApiErrorResponse::BusinessProfileNotFound { id: profile_id },
+ )?;
+
+ Ok(business_profile)
}
None => match self.business_country.zip(self.business_label) {
Some((business_country, business_label)) => {
@@ -2571,7 +2631,7 @@ impl MerchantConnectorAccountCreateBridge for api::MerchantConnectorCreate {
errors::ApiErrorResponse::BusinessProfileNotFound { id: profile_name },
)?;
- Ok(business_profile.profile_id)
+ Ok(business_profile)
}
_ => Err(report!(errors::ApiErrorResponse::MissingRequiredField {
field_name: "profile_id or business_country, business_label"
@@ -2627,15 +2687,9 @@ pub async fn create_connector(
&merchant_account,
)?;
- let profile_id = req
+ let business_profile = req
.clone()
- .validate_and_get_profile_id(
- &merchant_account,
- store,
- key_manager_state,
- &key_store,
- true,
- )
+ .validate_and_get_business_profile(&merchant_account, store, key_manager_state, &key_store)
.await?;
let pm_auth_config_validation = PMAuthConfigValidation {
@@ -2643,20 +2697,12 @@ pub async fn create_connector(
pm_auth_config: &req.pm_auth_config,
db: store,
merchant_id,
- profile_id: &profile_id.clone(),
+ profile_id: &business_profile.profile_id,
key_store: &key_store,
key_manager_state,
};
pm_auth_config_validation.validate_pm_auth_config().await?;
- let business_profile = state
- .store
- .find_business_profile_by_profile_id(key_manager_state, &key_store, &profile_id)
- .await
- .to_not_found_response(errors::ApiErrorResponse::BusinessProfileNotFound {
- id: profile_id.to_owned(),
- })?;
-
let connector_type_and_connector_enum = ConnectorTypeAndConnectorName {
connector_type: &req.connector_type,
connector_name: &req.connector_name,
@@ -2687,22 +2733,6 @@ pub async fn create_connector(
)
.await?;
- let transaction_type = req.get_transaction_type();
-
- let mut default_routing_config = routing_helpers::get_merchant_default_config(
- &*state.store,
- merchant_id.get_string_repr(),
- &transaction_type,
- )
- .await?;
-
- let mut default_routing_config_for_profile = routing_helpers::get_merchant_default_config(
- &*state.clone().store,
- &profile_id,
- &transaction_type,
- )
- .await?;
-
let mca = state
.store
.insert_merchant_connector_account(
@@ -2713,27 +2743,44 @@ pub async fn create_connector(
.await
.to_duplicate_response(
errors::ApiErrorResponse::DuplicateMerchantConnectorAccount {
- profile_id: profile_id.clone(),
+ profile_id: business_profile.profile_id.clone(),
connector_label: merchant_connector_account
.connector_label
.unwrap_or_default(),
},
)?;
+ #[cfg(all(
+ any(feature = "v1", feature = "v2"),
+ not(any(feature = "routing_v2", feature = "business_profile_v2",))
+ ))]
//update merchant default config
let merchant_default_config_update = MerchantDefaultConfigUpdate {
routable_connector: &routable_connector,
merchant_connector_id: &mca.get_id(),
store,
merchant_id,
- default_routing_config: &mut default_routing_config,
- default_routing_config_for_profile: &mut default_routing_config_for_profile,
- profile_id: &profile_id,
- transaction_type: &transaction_type,
+ profile_id: &business_profile.profile_id,
+ transaction_type: &req.get_transaction_type(),
+ };
+
+ #[cfg(all(
+ feature = "v2",
+ feature = "routing_v2",
+ feature = "business_profile_v2",
+ ))]
+ //update merchant default config
+ let merchant_default_config_update = DefaultFallbackRoutingConfigUpdate {
+ routable_connector: &routable_connector,
+ merchant_connector_id: &mca.get_id(),
+ store,
+ business_profile,
+ key_store,
+ key_manager_state,
};
merchant_default_config_update
- .update_merchant_default_config()
+ .retrieve_and_update_default_fallback_routing_algorithm_if_routable_connector_exists()
.await?;
metrics::MCA_CREATE.add(
@@ -3928,31 +3975,23 @@ impl BusinessProfileWrapper {
Ok(())
}
- pub fn get_profile_id_and_routing_algorithm_id<F>(
- &self,
- transaction_data: &routing::TransactionData<'_, F>,
- ) -> (Option<String>, Option<String>)
+ pub fn get_routing_algorithm_id<'a, F>(
+ &'a self,
+ transaction_data: &'a routing::TransactionData<'_, F>,
+ ) -> Option<String>
where
F: Send + Clone,
{
match transaction_data {
- routing::TransactionData::Payment(payment_data) => (
- payment_data.payment_intent.profile_id.clone(),
- self.profile.routing_algorithm_id.clone(),
- ),
+ routing::TransactionData::Payment(_) => self.profile.routing_algorithm_id.clone(),
#[cfg(feature = "payouts")]
- routing::TransactionData::Payout(payout_data) => (
- Some(payout_data.payout_attempt.profile_id.clone()),
- self.profile.payout_routing_algorithm_id.clone(),
- ),
+ routing::TransactionData::Payout(_) => self.profile.payout_routing_algorithm_id.clone(),
}
}
pub fn get_default_fallback_list_of_connector_under_profile(
&self,
) -> RouterResult<Vec<routing_types::RoutableConnectorChoice>> {
- use common_utils::ext_traits::OptionExt;
use masking::ExposeOptionInterface;
-
self.profile
.default_fallback_routing
.clone()
@@ -3975,7 +4014,7 @@ impl BusinessProfileWrapper {
})
}
- pub async fn update_default_routing_for_profile(
+ pub async fn update_default_fallback_routing_of_connectors_under_profile(
self,
db: &dyn StorageInterface,
updated_config: &Vec<routing_types::RoutableConnectorChoice>,
diff --git a/crates/router/src/core/payment_methods/cards.rs b/crates/router/src/core/payment_methods/cards.rs
index 3ce9c9ab5af..402e5b4b0a1 100644
--- a/crates/router/src/core/payment_methods/cards.rs
+++ b/crates/router/src/core/payment_methods/cards.rs
@@ -2435,10 +2435,17 @@ pub async fn list_payment_methods(
)
.await?;
+ let profile_id = profile_id
+ .clone()
+ .get_required_value("profile_id")
+ .change_context(errors::ApiErrorResponse::GenericNotFoundError {
+ message: "Profile id not found".to_string(),
+ })?;
+
// filter out payment connectors based on profile_id
let filtered_mcas = helpers::filter_mca_based_on_profile_and_connector_type(
all_mcas.clone(),
- profile_id.as_ref(),
+ &profile_id,
ConnectorType::PaymentProcessor,
);
@@ -2447,12 +2454,6 @@ pub async fn list_payment_methods(
let mut response: Vec<ResponsePaymentMethodIntermediate> = vec![];
// Key creation for storing PM_FILTER_CGRAPH
let key = {
- let profile_id = profile_id
- .clone()
- .get_required_value("profile_id")
- .change_context(errors::ApiErrorResponse::GenericNotFoundError {
- message: "Profile id not found".to_string(),
- })?;
format!(
"pm_filters_cgraph_{}_{}",
merchant_account.get_id().get_string_repr(),
diff --git a/crates/router/src/core/payments.rs b/crates/router/src/core/payments.rs
index a8ec32cb55b..31838c34a85 100644
--- a/crates/router/src/core/payments.rs
+++ b/crates/router/src/core/payments.rs
@@ -3494,6 +3494,7 @@ where
.merchant_connector_id
.clone()
.as_ref(),
+ business_profile.clone(),
)
.await?;
@@ -3526,15 +3527,13 @@ where
.attach_printable("Failed execution of straight through routing")?;
if check_eligibility {
- let profile_id = payment_data.payment_intent.profile_id.clone();
-
connectors = routing::perform_eligibility_analysis_with_fallback(
&state.clone(),
key_store,
connectors,
&TransactionData::Payment(payment_data),
eligible_connectors,
- profile_id,
+ business_profile,
)
.await
.change_context(errors::ApiErrorResponse::InternalServerError)
@@ -3575,15 +3574,13 @@ where
.attach_printable("Failed execution of straight through routing")?;
if check_eligibility {
- let profile_id = payment_data.payment_intent.profile_id.clone();
-
connectors = routing::perform_eligibility_analysis_with_fallback(
&state,
key_store,
connectors,
&TransactionData::Payment(payment_data),
eligible_connectors,
- profile_id,
+ business_profile,
)
.await
.change_context(errors::ApiErrorResponse::InternalServerError)
@@ -3949,6 +3946,7 @@ where
feature = "routing_v2",
feature = "business_profile_v2"
))]
+#[allow(clippy::too_many_arguments)]
pub async fn route_connector_v1<F>(
state: &SessionState,
merchant_account: &domain::MerchantAccount,
@@ -3962,14 +3960,14 @@ pub async fn route_connector_v1<F>(
where
F: Send + Clone,
{
- let (profile_id, routing_algorithm_id) =
- super::admin::BusinessProfileWrapper::new(business_profile.clone())
- .get_profile_id_and_routing_algorithm_id(&transaction_data);
+ let profile_wrapper = super::admin::BusinessProfileWrapper::new(business_profile.clone());
+ let routing_algorithm_id = profile_wrapper.get_routing_algorithm_id(&transaction_data);
let connectors = routing::perform_static_routing_v1(
state,
merchant_account.get_id(),
routing_algorithm_id,
+ business_profile,
&transaction_data,
)
.await
@@ -3981,7 +3979,7 @@ where
connectors,
&transaction_data,
eligible_connectors,
- profile_id,
+ business_profile,
)
.await
.change_context(errors::ApiErrorResponse::InternalServerError)
@@ -4050,17 +4048,12 @@ pub async fn route_connector_v1<F>(
where
F: Send + Clone,
{
- let (profile_id, routing_algorithm_id) = {
- let (profile_id, routing_algorithm) = match &transaction_data {
- TransactionData::Payment(payment_data) => (
- payment_data.payment_intent.profile_id.clone(),
- business_profile.routing_algorithm.clone(),
- ),
+ let routing_algorithm_id = {
+ let routing_algorithm = match &transaction_data {
+ TransactionData::Payment(_) => business_profile.routing_algorithm.clone(),
+
#[cfg(feature = "payouts")]
- TransactionData::Payout(payout_data) => (
- Some(payout_data.payout_attempt.profile_id.clone()),
- business_profile.payout_routing_algorithm.clone(),
- ),
+ TransactionData::Payout(_) => business_profile.payout_routing_algorithm.clone(),
};
let algorithm_ref = routing_algorithm
@@ -4069,13 +4062,14 @@ where
.change_context(errors::ApiErrorResponse::InternalServerError)
.attach_printable("Could not decode merchant routing algorithm ref")?
.unwrap_or_default();
- (profile_id, algorithm_ref.algorithm_id)
+ algorithm_ref.algorithm_id
};
let connectors = routing::perform_static_routing_v1(
state,
merchant_account.get_id(),
routing_algorithm_id,
+ business_profile,
&transaction_data,
)
.await
@@ -4086,7 +4080,7 @@ where
connectors,
&transaction_data,
eligible_connectors,
- profile_id,
+ business_profile,
)
.await
.change_context(errors::ApiErrorResponse::InternalServerError)
diff --git a/crates/router/src/core/payments/helpers.rs b/crates/router/src/core/payments/helpers.rs
index b2ecae090c2..c1b8aedb651 100644
--- a/crates/router/src/core/payments/helpers.rs
+++ b/crates/router/src/core/payments/helpers.rs
@@ -45,6 +45,12 @@ use super::{
operations::{BoxedOperation, Operation, PaymentResponse},
CustomerDetails, PaymentData,
};
+#[cfg(all(
+ feature = "v2",
+ feature = "routing_v2",
+ feature = "business_profile_v2"
+))]
+use crate::core::admin as core_admin;
use crate::{
configs::settings::{ConnectorRequestReferenceIdConfig, TempLockerEnableConfig},
connector,
@@ -124,15 +130,12 @@ pub fn create_certificate(
pub fn filter_mca_based_on_profile_and_connector_type(
merchant_connector_accounts: Vec<domain::MerchantConnectorAccount>,
- profile_id: Option<&String>,
+ profile_id: &String,
connector_type: ConnectorType,
) -> Vec<domain::MerchantConnectorAccount> {
merchant_connector_accounts
.into_iter()
- .filter(|mca| {
- profile_id.map_or(true, |id| &mca.profile_id == id)
- && mca.connector_type == connector_type
- })
+ .filter(|mca| &mca.profile_id == profile_id && mca.connector_type == connector_type)
.collect()
}
@@ -4269,18 +4272,12 @@ pub async fn get_apple_pay_retryable_connectors<F>(
key_store: &domain::MerchantKeyStore,
pre_routing_connector_data_list: &[api::ConnectorData],
merchant_connector_id: Option<&String>,
+ business_profile: domain::BusinessProfile,
) -> CustomResult<Option<Vec<api::ConnectorData>>, errors::ApiErrorResponse>
where
F: Send + Clone,
{
- let profile_id = &payment_data
- .payment_intent
- .profile_id
- .clone()
- .get_required_value("profile_id")
- .change_context(errors::ApiErrorResponse::MissingRequiredField {
- field_name: "profile_id",
- })?;
+ let profile_id = &business_profile.profile_id;
let pre_decided_connector_data_first = pre_routing_connector_data_list
.first()
@@ -4318,7 +4315,7 @@ where
let profile_specific_merchant_connector_account_list =
filter_mca_based_on_profile_and_connector_type(
merchant_connector_account_list,
- Some(profile_id),
+ profile_id,
ConnectorType::PaymentProcessor,
);
@@ -4349,7 +4346,10 @@ where
}
}
}
-
+ #[cfg(all(
+ any(feature = "v1", feature = "v2"),
+ not(any(feature = "routing_v2", feature = "business_profile_v2"))
+ ))]
let fallback_connetors_list = crate::core::routing::helpers::get_merchant_default_config(
&*state.clone().store,
profile_id,
@@ -4359,6 +4359,16 @@ where
.change_context(errors::ApiErrorResponse::InternalServerError)
.attach_printable("Failed to get merchant default fallback connectors config")?;
+ #[cfg(all(
+ feature = "v2",
+ feature = "routing_v2",
+ feature = "business_profile_v2"
+ ))]
+ let fallback_connetors_list = core_admin::BusinessProfileWrapper::new(business_profile)
+ .get_default_fallback_list_of_connector_under_profile()
+ .change_context(errors::ApiErrorResponse::InternalServerError)
+ .attach_printable("Failed to get merchant default fallback connectors config")?;
+
let mut routing_connector_data_list = Vec::new();
pre_routing_connector_data_list.iter().for_each(|pre_val| {
diff --git a/crates/router/src/core/payments/operations/payment_session.rs b/crates/router/src/core/payments/operations/payment_session.rs
index 371b028154e..af5f234e2ce 100644
--- a/crates/router/src/core/payments/operations/payment_session.rs
+++ b/crates/router/src/core/payments/operations/payment_session.rs
@@ -378,7 +378,7 @@ where
let filtered_connector_accounts = helpers::filter_mca_based_on_profile_and_connector_type(
all_connector_accounts,
- Some(&profile_id),
+ &profile_id,
common_enums::ConnectorType::PaymentProcessor,
);
diff --git a/crates/router/src/core/payments/routing.rs b/crates/router/src/core/payments/routing.rs
index c029e2d289c..30c1edb6e04 100644
--- a/crates/router/src/core/payments/routing.rs
+++ b/crates/router/src/core/payments/routing.rs
@@ -34,12 +34,18 @@ use rand::{
use rustc_hash::FxHashMap;
use storage_impl::redis::cache::{CacheKey, CGRAPH_CACHE, ROUTING_CACHE};
+#[cfg(all(
+ feature = "v2",
+ feature = "routing_v2",
+ feature = "business_profile_v2"
+))]
+use crate::core::admin;
#[cfg(feature = "payouts")]
use crate::core::payouts;
use crate::{
core::{
errors, errors as oss_errors, payments as payments_oss,
- routing::{self, helpers as routing_helpers},
+ routing::{self},
},
logger,
types::{
@@ -75,7 +81,7 @@ pub struct SessionRoutingPmTypeInput<'a> {
routing_algorithm: &'a MerchantAccountRoutingAlgorithm,
backend_input: dsl_inputs::BackendInput,
allowed_connectors: FxHashMap<String, api::GetToken>,
- profile_id: Option<String>,
+ profile_id: String,
}
type RoutingResult<O> = oss_errors::CustomResult<O, errors::RoutingError>;
@@ -273,28 +279,31 @@ pub async fn perform_static_routing_v1<F: Clone>(
state: &SessionState,
merchant_id: &common_utils::id_type::MerchantId,
algorithm_id: Option<String>,
+ business_profile: &domain::BusinessProfile,
transaction_data: &routing::TransactionData<'_, F>,
) -> RoutingResult<Vec<routing_types::RoutableConnectorChoice>> {
- let profile_id = match transaction_data {
- routing::TransactionData::Payment(payment_data) => payment_data
- .payment_intent
- .profile_id
- .as_ref()
- .get_required_value("profile_id")
- .change_context(errors::RoutingError::ProfileIdMissing)?,
- #[cfg(feature = "payouts")]
- routing::TransactionData::Payout(payout_data) => &payout_data.payout_attempt.profile_id,
- };
let algorithm_id = if let Some(id) = algorithm_id {
id
} else {
- let fallback_config = routing_helpers::get_merchant_default_config(
+ #[cfg(all(
+ any(feature = "v1", feature = "v2"),
+ not(any(feature = "routing_v2", feature = "business_profile_v2"))
+ ))]
+ let fallback_config = routing::helpers::get_merchant_default_config(
&*state.clone().store,
- profile_id,
+ &business_profile.profile_id,
&api_enums::TransactionType::from(transaction_data),
)
.await
.change_context(errors::RoutingError::FallbackConfigFetchFailed)?;
+ #[cfg(all(
+ feature = "v2",
+ feature = "routing_v2",
+ feature = "business_profile_v2"
+ ))]
+ let fallback_config = admin::BusinessProfileWrapper::new(business_profile.clone())
+ .get_default_fallback_list_of_connector_under_profile()
+ .change_context(errors::RoutingError::FallbackConfigFetchFailed)?;
return Ok(fallback_config);
};
@@ -302,7 +311,7 @@ pub async fn perform_static_routing_v1<F: Clone>(
state,
merchant_id,
&algorithm_id,
- Some(profile_id).cloned(),
+ business_profile.profile_id.clone(),
&api_enums::TransactionType::from(transaction_data),
)
.await?;
@@ -333,15 +342,10 @@ async fn ensure_algorithm_cached_v1(
state: &SessionState,
merchant_id: &common_utils::id_type::MerchantId,
algorithm_id: &str,
- profile_id: Option<String>,
+ profile_id: String,
transaction_type: &api_enums::TransactionType,
) -> RoutingResult<Arc<CachedAlgorithm>> {
let key = {
- let profile_id = profile_id
- .clone()
- .get_required_value("profile_id")
- .change_context(errors::RoutingError::ProfileIdMissing)?;
-
match transaction_type {
common_enums::TransactionType::Payment => {
format!(
@@ -421,15 +425,12 @@ pub async fn refresh_routing_cache_v1(
state: &SessionState,
key: String,
algorithm_id: &str,
- profile_id: Option<String>,
+ profile_id: String,
) -> RoutingResult<Arc<CachedAlgorithm>> {
let algorithm = {
let algorithm = state
.store
- .find_routing_algorithm_by_profile_id_algorithm_id(
- &profile_id.unwrap_or_default(),
- algorithm_id,
- )
+ .find_routing_algorithm_by_profile_id_algorithm_id(&profile_id, algorithm_id)
.await
.change_context(errors::RoutingError::DslMissingInDb)?;
let algorithm: routing_types::RoutingAlgorithm = algorithm
@@ -506,16 +507,12 @@ pub fn perform_volume_split(
pub async fn get_merchant_cgraph<'a>(
state: &SessionState,
key_store: &domain::MerchantKeyStore,
- profile_id: Option<String>,
+ profile_id: String,
transaction_type: &api_enums::TransactionType,
) -> RoutingResult<Arc<hyperswitch_constraint_graph::ConstraintGraph<euclid_dir::DirValue>>> {
let merchant_id = &key_store.merchant_id;
let key = {
- let profile_id = profile_id
- .clone()
- .get_required_value("profile_id")
- .change_context(errors::RoutingError::ProfileIdMissing)?;
match transaction_type {
api_enums::TransactionType::Payment => {
format!("cgraph_{}_{}", merchant_id.get_string_repr(), profile_id)
@@ -549,7 +546,7 @@ pub async fn refresh_cgraph_cache<'a>(
state: &SessionState,
key_store: &domain::MerchantKeyStore,
key: String,
- profile_id: Option<String>,
+ profile_id: String,
transaction_type: &api_enums::TransactionType,
) -> RoutingResult<Arc<hyperswitch_constraint_graph::ConstraintGraph<euclid_dir::DirValue>>> {
let mut merchant_connector_accounts = state
@@ -588,7 +585,7 @@ pub async fn refresh_cgraph_cache<'a>(
let merchant_connector_accounts =
payments_oss::helpers::filter_mca_based_on_profile_and_connector_type(
merchant_connector_accounts,
- profile_id.as_ref(),
+ &profile_id,
connector_type,
);
@@ -648,7 +645,7 @@ async fn perform_cgraph_filtering(
chosen: Vec<routing_types::RoutableConnectorChoice>,
backend_input: dsl_inputs::BackendInput,
eligible_connectors: Option<&Vec<api_enums::RoutableConnectors>>,
- profile_id: Option<String>,
+ profile_id: String,
transaction_type: &api_enums::TransactionType,
) -> RoutingResult<Vec<routing_types::RoutableConnectorChoice>> {
let context = euclid_graph::AnalysisContext::from_dir_values(
@@ -692,7 +689,7 @@ pub async fn perform_eligibility_analysis<F: Clone>(
chosen: Vec<routing_types::RoutableConnectorChoice>,
transaction_data: &routing::TransactionData<'_, F>,
eligible_connectors: Option<&Vec<api_enums::RoutableConnectors>>,
- profile_id: Option<String>,
+ profile_id: String,
) -> RoutingResult<Vec<routing_types::RoutableConnectorChoice>> {
let backend_input = match transaction_data {
routing::TransactionData::Payment(payment_data) => make_dsl_input(payment_data)?,
@@ -717,9 +714,13 @@ pub async fn perform_fallback_routing<F: Clone>(
key_store: &domain::MerchantKeyStore,
transaction_data: &routing::TransactionData<'_, F>,
eligible_connectors: Option<&Vec<api_enums::RoutableConnectors>>,
- profile_id: Option<String>,
+ business_profile: &domain::BusinessProfile,
) -> RoutingResult<Vec<routing_types::RoutableConnectorChoice>> {
- let fallback_config = routing_helpers::get_merchant_default_config(
+ #[cfg(all(
+ any(feature = "v1", feature = "v2"),
+ not(any(feature = "routing_v2", feature = "business_profile_v2"))
+ ))]
+ let fallback_config = routing::helpers::get_merchant_default_config(
&*state.store,
match transaction_data {
routing::TransactionData::Payment(payment_data) => payment_data
@@ -735,7 +736,14 @@ pub async fn perform_fallback_routing<F: Clone>(
)
.await
.change_context(errors::RoutingError::FallbackConfigFetchFailed)?;
-
+ #[cfg(all(
+ feature = "v2",
+ feature = "routing_v2",
+ feature = "business_profile_v2"
+ ))]
+ let fallback_config = admin::BusinessProfileWrapper::new(business_profile.clone())
+ .get_default_fallback_list_of_connector_under_profile()
+ .change_context(errors::RoutingError::FallbackConfigFetchFailed)?;
let backend_input = match transaction_data {
routing::TransactionData::Payment(payment_data) => make_dsl_input(payment_data)?,
#[cfg(feature = "payouts")]
@@ -748,7 +756,7 @@ pub async fn perform_fallback_routing<F: Clone>(
fallback_config,
backend_input,
eligible_connectors,
- profile_id,
+ business_profile.profile_id.clone(),
&api_enums::TransactionType::from(transaction_data),
)
.await
@@ -760,7 +768,7 @@ pub async fn perform_eligibility_analysis_with_fallback<F: Clone>(
chosen: Vec<routing_types::RoutableConnectorChoice>,
transaction_data: &routing::TransactionData<'_, F>,
eligible_connectors: Option<Vec<api_enums::RoutableConnectors>>,
- profile_id: Option<String>,
+ business_profile: &domain::BusinessProfile,
) -> RoutingResult<Vec<routing_types::RoutableConnectorChoice>> {
let mut final_selection = perform_eligibility_analysis(
state,
@@ -768,7 +776,7 @@ pub async fn perform_eligibility_analysis_with_fallback<F: Clone>(
chosen,
transaction_data,
eligible_connectors.as_ref(),
- profile_id.clone(),
+ business_profile.profile_id.clone(),
)
.await?;
@@ -777,7 +785,7 @@ pub async fn perform_eligibility_analysis_with_fallback<F: Clone>(
key_store,
transaction_data,
eligible_connectors.as_ref(),
- profile_id,
+ business_profile,
)
.await;
@@ -831,7 +839,7 @@ pub async fn perform_session_flow_routing(
feature = "business_profile_v2"
))]
let routing_algorithm =
- MerchantAccountRoutingAlgorithm::V1(business_profile.routing_algorithm_id);
+ MerchantAccountRoutingAlgorithm::V1(business_profile.routing_algorithm_id.clone());
#[cfg(all(
any(feature = "v1", feature = "v2"),
@@ -929,11 +937,14 @@ pub async fn perform_session_flow_routing(
routing_algorithm: &routing_algorithm,
backend_input: backend_input.clone(),
allowed_connectors,
-
- profile_id: session_input.payment_intent.profile_id.clone(),
+ profile_id: profile_id.clone(),
};
- let routable_connector_choice_option =
- perform_session_routing_for_pm_type(&session_pm_input, transaction_type).await?;
+ let routable_connector_choice_option = perform_session_routing_for_pm_type(
+ &session_pm_input,
+ transaction_type,
+ &business_profile,
+ )
+ .await?;
if let Some(routable_connector_choice) = routable_connector_choice_option {
let mut session_routing_choice: Vec<routing_types::SessionRoutingChoice> = Vec::new();
@@ -964,26 +975,20 @@ pub async fn perform_session_flow_routing(
Ok(result)
}
+#[cfg(all(
+ any(feature = "v1", feature = "v2"),
+ not(any(feature = "routing_v2", feature = "business_profile_v2"))
+))]
async fn perform_session_routing_for_pm_type(
session_pm_input: &SessionRoutingPmTypeInput<'_>,
transaction_type: &api_enums::TransactionType,
+ _business_profile: &domain::BusinessProfile,
) -> RoutingResult<Option<Vec<api_models::routing::RoutableConnectorChoice>>> {
let merchant_id = &session_pm_input.key_store.merchant_id;
- #[cfg(all(
- any(feature = "v1", feature = "v2"),
- not(any(feature = "routing_v2", feature = "business_profile_v2"))
- ))]
+
let algorithm_id = match session_pm_input.routing_algorithm {
MerchantAccountRoutingAlgorithm::V1(algorithm_ref) => &algorithm_ref.algorithm_id,
};
- #[cfg(all(
- feature = "v2",
- feature = "routing_v2",
- feature = "business_profile_v2"
- ))]
- let algorithm_id = match session_pm_input.routing_algorithm {
- MerchantAccountRoutingAlgorithm::V1(algorithm_id) => algorithm_id,
- };
let chosen_connectors = if let Some(ref algorithm_id) = algorithm_id {
let cached_algorithm = ensure_algorithm_cached_v1(
@@ -1008,13 +1013,9 @@ async fn perform_session_routing_for_pm_type(
)?,
}
} else {
- routing_helpers::get_merchant_default_config(
+ routing::helpers::get_merchant_default_config(
&*session_pm_input.state.clone().store,
- session_pm_input
- .profile_id
- .as_ref()
- .get_required_value("profile_id")
- .change_context(errors::RoutingError::ProfileIdMissing)?,
+ &session_pm_input.profile_id,
transaction_type,
)
.await
@@ -1033,13 +1034,9 @@ async fn perform_session_routing_for_pm_type(
.await?;
if final_selection.is_empty() {
- let fallback = routing_helpers::get_merchant_default_config(
+ let fallback = routing::helpers::get_merchant_default_config(
&*session_pm_input.state.clone().store,
- session_pm_input
- .profile_id
- .as_ref()
- .get_required_value("profile_id")
- .change_context(errors::RoutingError::ProfileIdMissing)?,
+ &session_pm_input.profile_id,
transaction_type,
)
.await
@@ -1064,6 +1061,83 @@ async fn perform_session_routing_for_pm_type(
}
}
+#[cfg(all(
+ feature = "v2",
+ feature = "routing_v2",
+ feature = "business_profile_v2"
+))]
+async fn perform_session_routing_for_pm_type(
+ session_pm_input: &SessionRoutingPmTypeInput<'_>,
+ transaction_type: &api_enums::TransactionType,
+ business_profile: &domain::BusinessProfile,
+) -> RoutingResult<Option<Vec<api_models::routing::RoutableConnectorChoice>>> {
+ let merchant_id = &session_pm_input.key_store.merchant_id;
+
+ let MerchantAccountRoutingAlgorithm::V1(algorithm_id) = session_pm_input.routing_algorithm;
+
+ let profile_wrapper = admin::BusinessProfileWrapper::new(business_profile.clone());
+ let chosen_connectors = if let Some(ref algorithm_id) = algorithm_id {
+ let cached_algorithm = ensure_algorithm_cached_v1(
+ &session_pm_input.state.clone(),
+ merchant_id,
+ algorithm_id,
+ session_pm_input.profile_id.clone(),
+ transaction_type,
+ )
+ .await?;
+
+ match cached_algorithm.as_ref() {
+ CachedAlgorithm::Single(conn) => vec![(**conn).clone()],
+ CachedAlgorithm::Priority(plist) => plist.clone(),
+ CachedAlgorithm::VolumeSplit(splits) => {
+ perform_volume_split(splits.to_vec(), Some(session_pm_input.attempt_id))
+ .change_context(errors::RoutingError::ConnectorSelectionFailed)?
+ }
+ CachedAlgorithm::Advanced(interpreter) => execute_dsl_and_get_connector_v1(
+ session_pm_input.backend_input.clone(),
+ interpreter,
+ )?,
+ }
+ } else {
+ profile_wrapper
+ .get_default_fallback_list_of_connector_under_profile()
+ .change_context(errors::RoutingError::FallbackConfigFetchFailed)?
+ };
+
+ let mut final_selection = perform_cgraph_filtering(
+ &session_pm_input.state.clone(),
+ session_pm_input.key_store,
+ chosen_connectors,
+ session_pm_input.backend_input.clone(),
+ None,
+ session_pm_input.profile_id.clone(),
+ transaction_type,
+ )
+ .await?;
+
+ if final_selection.is_empty() {
+ let fallback = profile_wrapper
+ .get_default_fallback_list_of_connector_under_profile()
+ .change_context(errors::RoutingError::FallbackConfigFetchFailed)?;
+
+ final_selection = perform_cgraph_filtering(
+ &session_pm_input.state.clone(),
+ session_pm_input.key_store,
+ fallback,
+ session_pm_input.backend_input.clone(),
+ None,
+ session_pm_input.profile_id.clone(),
+ transaction_type,
+ )
+ .await?;
+ }
+
+ if final_selection.is_empty() {
+ Ok(None)
+ } else {
+ Ok(Some(final_selection))
+ }
+}
pub fn make_dsl_input_for_surcharge(
payment_attempt: &oss_storage::PaymentAttempt,
payment_intent: &oss_storage::PaymentIntent,
diff --git a/crates/router/src/core/payout_link.rs b/crates/router/src/core/payout_link.rs
index 0e480605112..d18afe02056 100644
--- a/crates/router/src/core/payout_link.rs
+++ b/crates/router/src/core/payout_link.rs
@@ -300,7 +300,7 @@ pub async fn filter_payout_methods(
// Filter MCAs based on profile_id and connector_type
let filtered_mcas = helpers::filter_mca_based_on_profile_and_connector_type(
all_mcas,
- Some(&payout.profile_id),
+ &payout.profile_id,
common_enums::ConnectorType::PayoutProcessor,
);
let address = payout
diff --git a/crates/router/src/core/payouts/helpers.rs b/crates/router/src/core/payouts/helpers.rs
index 67e35e7dff6..4f9e3f9529e 100644
--- a/crates/router/src/core/payouts/helpers.rs
+++ b/crates/router/src/core/payouts/helpers.rs
@@ -33,6 +33,7 @@ use crate::{
route_connector_v1, routing, CustomerDetails,
},
routing::TransactionData,
+ utils as core_utils,
},
db::StorageInterface,
routes::{metrics, SessionState},
@@ -745,6 +746,17 @@ pub async fn decide_payout_connector(
return Ok(api::ConnectorCallType::PreDetermined(connector_data));
}
+ // Validate and get the business_profile from payout_attempt
+ let business_profile = core_utils::validate_and_get_business_profile(
+ state.store.as_ref(),
+ &(state).into(),
+ key_store,
+ Some(&payout_attempt.profile_id),
+ merchant_account.get_id(),
+ )
+ .await?
+ .get_required_value("BusinessProfile")?;
+
// 2. Check routing algorithm passed in the request
if let Some(routing_algorithm) = request_straight_through {
let (mut connectors, check_eligibility) =
@@ -759,7 +771,7 @@ pub async fn decide_payout_connector(
connectors,
&TransactionData::<()>::Payout(payout_data),
eligible_connectors,
- Some(payout_attempt.profile_id.clone()),
+ &business_profile,
)
.await
.change_context(errors::ApiErrorResponse::InternalServerError)
@@ -807,7 +819,7 @@ pub async fn decide_payout_connector(
connectors,
&TransactionData::<()>::Payout(payout_data),
eligible_connectors,
- Some(payout_attempt.profile_id.clone()),
+ &business_profile,
)
.await
.change_context(errors::ApiErrorResponse::InternalServerError)
diff --git a/crates/router/src/core/routing.rs b/crates/router/src/core/routing.rs
index 0c50a01e36d..2b7f2d18306 100644
--- a/crates/router/src/core/routing.rs
+++ b/crates/router/src/core/routing.rs
@@ -706,7 +706,7 @@ pub async fn update_default_fallback_routing(
},
)?;
profile_wrapper
- .update_default_routing_for_profile(
+ .update_default_fallback_routing_of_connectors_under_profile(
db,
&updated_list_of_connectors,
key_manager_state,
@@ -949,7 +949,7 @@ pub async fn retrieve_linked_routing_config(
routing_types::LinkedRoutingConfigRetrieveResponse::ProfileBased(active_algorithms),
))
}
-
+// List all the default fallback algorithms under all the profile under a merchant
pub async fn retrieve_default_routing_config_for_profiles(
state: SessionState,
merchant_account: domain::MerchantAccount,
diff --git a/crates/storage_impl/src/payouts/payouts.rs b/crates/storage_impl/src/payouts/payouts.rs
index 94405a0249b..680d535a652 100644
--- a/crates/storage_impl/src/payouts/payouts.rs
+++ b/crates/storage_impl/src/payouts/payouts.rs
@@ -6,17 +6,21 @@ use async_bb8_diesel::{AsyncConnection, AsyncRunQueryDsl};
use common_utils::errors::ReportSwitchExt;
use common_utils::ext_traits::Encode;
#[cfg(feature = "olap")]
-use diesel::{associations::HasTable, ExpressionMethods, QueryDsl};
+use diesel::{
+ associations::HasTable, ExpressionMethods, JoinOnDsl, NullableExpressionMethods, QueryDsl,
+};
#[cfg(all(
feature = "olap",
any(feature = "v1", feature = "v2"),
not(feature = "customer_v2")
))]
-use diesel::{JoinOnDsl, NullableExpressionMethods};
+use diesel_models::payout_attempt::PayoutAttempt as DieselPayoutAttempt;
#[cfg(feature = "olap")]
use diesel_models::{
- customers::Customer as DieselCustomer, enums as storage_enums, query::generics::db_metrics,
- schema::payouts::dsl as po_dsl,
+ customers::Customer as DieselCustomer,
+ enums as storage_enums,
+ query::generics::db_metrics,
+ schema::{customers::dsl as cust_dsl, payout_attempt::dsl as poa_dsl, payouts::dsl as po_dsl},
};
use diesel_models::{
enums::MerchantStorageScheme,
@@ -26,15 +30,6 @@ use diesel_models::{
PayoutsUpdate as DieselPayoutsUpdate,
},
};
-#[cfg(all(
- feature = "olap",
- any(feature = "v1", feature = "v2"),
- not(feature = "customer_v2")
-))]
-use diesel_models::{
- payout_attempt::PayoutAttempt as DieselPayoutAttempt,
- schema::{customers::dsl as cust_dsl, payout_attempt::dsl as poa_dsl},
-};
use error_stack::ResultExt;
#[cfg(feature = "olap")]
use hyperswitch_domain_models::payouts::PayoutFetchConstraints;
|
2024-08-19T18:35:53Z
|
## Type of Change
<!-- Put an `x` in the boxes that apply -->
- [ ] Bugfix
- [ ] New feature
- [ ] Enhancement
- [ ] Refactoring
- [ ] Dependency updates
- [ ] Documentation
- [ ] CI/CD
## Description
This PR refactors the fallback routing behaviour in payments routing for v2. Update the function to accept business_profile as a parameter instead of profile_id.
### Additional Changes
- [ ] This PR modifies the API contract
- [ ] This PR modifies the database schema
- [ ] This PR modifies application configuration/environment variables
<!--
Provide links to the files with corresponding changes.
Following are the paths where you can find config files:
1. `config`
2. `crates/router/src/configs`
3. `loadtest/config`
-->
## Motivation and Context
<!--
Why is this change required? What problem does it solve?
If it fixes an open issue, please link to the issue here.
If you don't have an issue, we'd recommend starting with one first so the PR
can focus on the implementation (unless it is an obvious bug or documentation fix
that will have little conversation).
-->
## How did you test it?
For v2:
- create a MA and add 2 MCAs, it will be added for default fallback in the order they were cretaed
- make a payment , it should go through the mca that was added first based on default fallback
## Checklist
<!-- Put an `x` in the boxes that apply -->
- [ ] I formatted the code `cargo +nightly fmt --all`
- [ ] I addressed lints thrown by `cargo clippy`
- [ ] I reviewed the submitted code
- [ ] I added unit tests for my changes where possible
|
6e7b38a622d1399260f9a144e07a58bc6a7a6655
|
|
juspay/hyperswitch
|
juspay__hyperswitch-5621
|
Bug: [BUG] payout operations are using payment connectors
### Bug Description
In case payment connectors were added prior to adding the same payout connector (Eg - onboarding `Adyen` as `payment_processor` and then onboarding `Adyen` as `payout_processor`), the payout transactions are routed via payment transactions (the first onboarding of the connector with the same name)
### Expected Behavior
Payout operations should make sure the payout txns are routed only through payout processors.
### Actual Behavior
Payout operations are routed through the first same processor that was onboarded (payments in this case)
### Steps for reproducing
1. Create a new merchant account
2. Create a payment processor (preferrably Adyen)
3. Create a payout processor for the same connector name (Adyen)
4. Make a payout transaction
5. Payout transaction should be routed through the payment connector
### Have you spent some time checking if this bug has been raised before?
- [X] I checked and didn't find a similar issue
### Have you read the Contributing Guidelines?
- [X] I have read the [Contributing Guidelines](https://github.com/juspay/hyperswitch/blob/main/docs/CONTRIBUTING.md)
### Are you willing to submit a PR?
Yes, I am willing to submit a PR!
|
diff --git a/crates/router/src/core/payouts.rs b/crates/router/src/core/payouts.rs
index 07b50d3a154..44a3983a96a 100644
--- a/crates/router/src/core/payouts.rs
+++ b/crates/router/src/core/payouts.rs
@@ -1106,7 +1106,7 @@ pub async fn create_recipient(
// 1. Form router data
let router_data = core_utils::construct_payout_router_data(
state,
- &connector_data.connector_name,
+ connector_data,
merchant_account,
key_store,
payout_data,
@@ -1273,7 +1273,7 @@ pub async fn check_payout_eligibility(
// 1. Form Router data
let router_data = core_utils::construct_payout_router_data(
state,
- &connector_data.connector_name,
+ connector_data,
merchant_account,
key_store,
payout_data,
@@ -1453,7 +1453,7 @@ pub async fn create_payout(
// 1. Form Router data
let mut router_data = core_utils::construct_payout_router_data(
state,
- &connector_data.connector_name,
+ connector_data,
merchant_account,
key_store,
payout_data,
@@ -1645,7 +1645,7 @@ pub async fn create_payout_retrieve(
// 1. Form Router data
let mut router_data = core_utils::construct_payout_router_data(
state,
- &connector_data.connector_name,
+ connector_data,
merchant_account,
key_store,
payout_data,
@@ -1787,7 +1787,7 @@ pub async fn create_recipient_disburse_account(
// 1. Form Router data
let router_data = core_utils::construct_payout_router_data(
state,
- &connector_data.connector_name,
+ connector_data,
merchant_account,
key_store,
payout_data,
@@ -1872,7 +1872,7 @@ pub async fn cancel_payout(
// 1. Form Router data
let router_data = core_utils::construct_payout_router_data(
state,
- &connector_data.connector_name,
+ connector_data,
merchant_account,
key_store,
payout_data,
@@ -1977,7 +1977,7 @@ pub async fn fulfill_payout(
// 1. Form Router data
let mut router_data = core_utils::construct_payout_router_data(
state,
- &connector_data.connector_name,
+ connector_data,
merchant_account,
key_store,
payout_data,
diff --git a/crates/router/src/core/utils.rs b/crates/router/src/core/utils.rs
index 7bc4505b973..d5af1f20afb 100644
--- a/crates/router/src/core/utils.rs
+++ b/crates/router/src/core/utils.rs
@@ -30,7 +30,7 @@ use crate::{
db::StorageInterface,
routes::SessionState,
types::{
- self, domain,
+ self, api, domain,
storage::{self, enums},
PollConfig,
},
@@ -49,7 +49,7 @@ const IRRELEVANT_ATTEMPT_ID_IN_DISPUTE_FLOW: &str = "irrelevant_attempt_id_in_di
#[instrument(skip_all)]
pub async fn get_mca_for_payout<'a>(
state: &'a SessionState,
- connector_id: &str,
+ connector_data: &api::ConnectorData,
merchant_account: &domain::MerchantAccount,
key_store: &domain::MerchantKeyStore,
payout_data: &PayoutData,
@@ -63,8 +63,8 @@ pub async fn get_mca_for_payout<'a>(
None,
key_store,
&payout_data.profile_id,
- connector_id,
- payout_data.payout_attempt.merchant_connector_id.as_ref(),
+ &connector_data.connector_name.to_string(),
+ connector_data.merchant_connector_id.as_ref(),
)
.await?;
Ok(merchant_connector_account)
@@ -76,19 +76,20 @@ pub async fn get_mca_for_payout<'a>(
#[instrument(skip_all)]
pub async fn construct_payout_router_data<'a, F>(
state: &'a SessionState,
- connector_name: &api_models::enums::Connector,
+ connector_data: &api::ConnectorData,
merchant_account: &domain::MerchantAccount,
key_store: &domain::MerchantKeyStore,
payout_data: &mut PayoutData,
) -> RouterResult<types::PayoutsRouterData<F>> {
let merchant_connector_account = get_mca_for_payout(
state,
- &connector_name.to_string(),
+ connector_data,
merchant_account,
key_store,
payout_data,
)
.await?;
+ let connector_name = connector_data.connector_name;
payout_data.merchant_connector_account = Some(merchant_connector_account.clone());
let connector_auth_type: types::ConnectorAuthType = merchant_connector_account
.get_connector_account_details()
@@ -770,7 +771,7 @@ pub async fn construct_upload_file_router_data<'a>(
payment_attempt: &storage::PaymentAttempt,
merchant_account: &domain::MerchantAccount,
key_store: &domain::MerchantKeyStore,
- create_file_request: &types::api::CreateFileRequest,
+ create_file_request: &api::CreateFileRequest,
connector_id: &str,
file_key: String,
) -> RouterResult<types::UploadFileRouterData> {
|
2024-08-14T06:57:00Z
|
## Type of Change
<!-- Put an `x` in the boxes that apply -->
- [x] Bugfix
- [ ] New feature
- [ ] Enhancement
- [ ] Refactoring
- [ ] Dependency updates
- [ ] Documentation
- [ ] CI/CD
## Description
Described in #5621
### Additional Changes
- [ ] This PR modifies the API contract
- [ ] This PR modifies the database schema
- [ ] This PR modifies application configuration/environment variables
<!--
Provide links to the files with corresponding changes.
Following are the paths where you can find config files:
1. `config`
2. `crates/router/src/configs`
3. `loadtest/config`
-->
## How did you test it?
<details>
<summary>1. Create a merchant account</summary>
curl --location 'https://sandbox.hyperswitch.io/accounts' \
--header 'Content-Type: application/json' \
--header 'Accept: application/json' \
--header 'api-key: test_admin' \
--data-raw '{
"merchant_id": "merchant_1723634705",
"locker_id": "m0010",
"merchant_name": "NewAge Retailer",
"merchant_details": {
"primary_contact_person": "John Test",
"primary_email": "JohnTest@test.com",
"primary_phone": "sunt laborum",
"secondary_contact_person": "John Test2",
"secondary_email": "JohnTest2@test.com",
"secondary_phone": "cillum do dolor id",
"website": "https://www.example.com",
"about_business": "Online Retail with a wide selection of organic products for North America",
"address": {
"line1": "1467",
"line2": "Harrison Street",
"line3": "Harrison Street",
"city": "San Fransico",
"state": "California",
"zip": "94122",
"country": "US"
}
},
"return_url": "https://google.com/success",
"webhook_details": {
"webhook_version": "1.0.1",
"webhook_username": "ekart_retail",
"webhook_password": "password_ekart@123",
"payment_created_enabled": true,
"payment_succeeded_enabled": true,
"payment_failed_enabled": true
},
"sub_merchants_enabled": false,
"metadata": {
"city": "NY",
"unit": "245"
},
"primary_business_details": [
{
"country": "US",
"business": "food"
}
]
}'
</details>
<details>
<summary>2. Create a payment connector</summary>
curl --location 'https://sandbox.hyperswitch.io/account/merchant_1723447743/connectors' \
--header 'Content-Type: application/json' \
--header 'Accept: application/json' \
--header 'x-feature: integ-custom' \
--header 'api-key: test_admin' \
--data '{
"connector_type": "payment_processor",
"connector_name": "adyen",
"connector_label": "adyen_payments",
"connector_account_details": {
"auth_type": "SignatureKey",
"api_key": "adyen_api_key",
"key1": "adyen_key1",
"api_secret": "adyen_api_secret"
},
"test_mode": true,
"disabled": false,
"metadata": {
"city": "NY",
"unit": "245",
"endpoint_prefix": ""
},
"payment_methods_enabled": [
{
"payment_method": "card",
"payment_method_types": [
{
"payment_method_type": "credit",
"minimum_amount": 1,
"maximum_amount": 68607706,
"recurring_enabled": true,
"installment_payment_enabled": true
},
{
"payment_method_type": "debit",
"minimum_amount": 1,
"maximum_amount": 68607706,
"recurring_enabled": true,
"installment_payment_enabled": true
}
]
},
{
"payment_method": "bank_transfer",
"payment_method_types": [
{
"payment_method_type": "sepa",
"minimum_amount": 1,
"maximum_amount": 68607706,
"recurring_enabled": true,
"installment_payment_enabled": true
}
]
}
]
}'
</details>
<details>
<summary>3. Create a payout connector</summary>
curl --location 'https://sandbox.hyperswitch.io/account/merchant_1723447743/connectors' \
--header 'Content-Type: application/json' \
--header 'Accept: application/json' \
--header 'x-feature: integ-custom' \
--header 'api-key: test_admin' \
--data '{
"connector_type": "payout_processor",
"connector_name": "adyen",
"connector_label": "adyen_payouts",
"connector_account_details": {
"auth_type": "SignatureKey",
"api_key": "AQEphmfuXNWTK0Qc+iSEl3cshueYR55DGcESCNGoI7BTPLxjT7UBfl5QRzAQwV1bDb7kfNy1WIxIIkxgBw==-ziErjWyNKGE3hIz5kq+BUr2d82K2zdzE7Ums4FmpQxs=-#8zJ+$%]+;6:%q&X",
"key1": "TestAccount280ECOM",
"api_secret": "AQE6g3HYdt+JC0QL7H+krT1r87XJHatuAp5aWWtPiEyujXJqncR5Bch1VG8x3TFphs7fQO2UDw7kAnLvtRDBXVsNvuR83LVYjEgiTGAH-37o4c1326UtLekCWoFi9y/Do/RdojTYJHWjrz9PRZIM=-uxYPa9ju]2F3YVn)"
},
"test_mode": true,
"disabled": false,
"metadata": {
"city": "NY",
"unit": "245",
"endpoint_prefix": ""
},
"payment_methods_enabled": [
{
"payment_method": "card",
"payment_method_types": [
{
"payment_method_type": "credit",
"minimum_amount": 1,
"maximum_amount": 68607706,
"recurring_enabled": true,
"installment_payment_enabled": true
},
{
"payment_method_type": "debit",
"minimum_amount": 1,
"maximum_amount": 68607706,
"recurring_enabled": true,
"installment_payment_enabled": true
}
]
},
{
"payment_method": "bank_transfer",
"payment_method_types": [
{
"payment_method_type": "sepa",
"minimum_amount": 1,
"maximum_amount": 68607706,
"recurring_enabled": true,
"installment_payment_enabled": true
}
]
}
]
}'
</details>
<details>
<summary>4. Create a payment txn</summary>
curl --location 'https://sandbox.hyperswitch.io/payments' \
--header 'Content-Type: application/json' \
--header 'Accept: application/json' \
--header 'api-key: snd_QwyXwKBhuv9cLgvQHoBSg7393kQIIb9UyhZZoDIZdG9LlOUDBgxGl8fQNApUw4i9' \
--data '{
"amount": 6540,
"currency": "USD",
"confirm": true,
"capture_method": "automatic",
"capture_on": "2022-09-10T10:11:12Z",
"amount_to_capture": 6540,
"description": "Its my first payment request",
"authentication_type": "no_three_ds",
"return_url": "https://google.com",
"payment_method": "card",
"payment_method_type": "credit",
"payment_method_data": {
"card": {
"card_number": "4242424242424242",
"card_exp_month": "10",
"card_exp_year": "25",
"card_holder_name": "joseph Doe",
"card_cvc": "123"
}
},
"billing": {
"address": {
"line1": "1467",
"line2": "Harrison Street",
"line3": "Harrison Street",
"city": "San Fransico",
"state": "California",
"zip": "94122",
"country": "US",
"first_name": "joseph",
"last_name": "Doe"
}
},
"browser_info": {
"color_depth": 2,
"java_enabled": false,
"java_script_enabled": true,
"language": "en",
"screen_height": 100,
"screen_width": 200,
"time_zone": 530,
"ip_address": "127.0.0.1",
"accept_header": "-",
"user_agent": "Mozilla"
},
"statement_descriptor_name": "joseph",
"statement_descriptor_suffix": "JS",
"metadata": {
"udf1": "value1",
"new_customer": "true",
"login_date": "2019-09-10T10:11:12Z"
},
"business_label": "food",
"business_country": "US"
}'
</details>
<details>
<summary>5. Create a payout txn</summary>
curl --location 'https://sandbox.hyperswitch.io/payouts/create' \
--header 'Content-Type: application/json' \
--header 'api-key: snd_QwyXwKBhuv9cLgvQHoBSg7393kQIIb9UyhZZoDIZdG9LlOUDBgxGl8fQNApUw4i9' \
--data-raw '{
"amount": 100,
"currency": "EUR",
"profile_id": "pro_zPFmAstI3w3Ekf903ReS",
"customer": {
"id": "new_id",
"email": "new_cust@example.com",
"name": "John Doe",
"phone": "999999999",
"phone_country_code": "+65"
},
"connector": [
"adyen"
],
"description": "Its my first payout request",
"payout_type": "card",
"payout_method_data": {
"card": {
"card_number": "4111111111111111",
"expiry_month": "3",
"expiry_year": "2030",
"card_holder_name": "John Doe"
}
},
"billing": {
"address": {
"line1": "1467",
"line2": "Harrison Street",
"line3": "Harrison Street",
"city": "San Fransico",
"state": "CA",
"zip": "94122",
"country": "US",
"first_name": "John",
"last_name": "Doe"
},
"phone": {
"number": "8056594427",
"country_code": "+91"
}
},
"entity_type": "Individual",
"recurring": true,
"metadata": {
"ref": "123"
},
"confirm": true,
"auto_fulfill": true
}'
</details>
## Checklist
<!-- Put an `x` in the boxes that apply -->
- [x] I formatted the code `cargo +nightly fmt --all`
- [x] I addressed lints thrown by `cargo clippy`
- [x] I reviewed the submitted code
- [ ] I added unit tests for my changes where possible
|
b213db213e623a1eea3f6dbd66703df4a897d93f
|
|
juspay/hyperswitch
|
juspay__hyperswitch-5611
|
Bug: Add redis commands required for success rate based routing
|
diff --git a/crates/redis_interface/src/commands.rs b/crates/redis_interface/src/commands.rs
index ccfeb3e5b12..9b76d8d9c81 100644
--- a/crates/redis_interface/src/commands.rs
+++ b/crates/redis_interface/src/commands.rs
@@ -15,7 +15,7 @@ use common_utils::{
};
use error_stack::{report, ResultExt};
use fred::{
- interfaces::{HashesInterface, KeysInterface, SetsInterface, StreamsInterface},
+ interfaces::{HashesInterface, KeysInterface, ListInterface, SetsInterface, StreamsInterface},
prelude::RedisErrorKind,
types::{
Expiration, FromRedis, MultipleIDs, MultipleKeys, MultipleOrderedPairs, MultipleStrings,
@@ -371,6 +371,19 @@ impl super::RedisConnectionPool {
Ok(hsetnx)
}
+ #[instrument(level = "DEBUG", skip(self))]
+ pub async fn increment_field_in_hash(
+ &self,
+ key: &str,
+ field: &str,
+ increment: i64,
+ ) -> CustomResult<usize, errors::RedisError> {
+ self.pool
+ .hincrby(self.add_prefix(key), field, increment)
+ .await
+ .change_context(errors::RedisError::IncrementHashFieldFailed)
+ }
+
#[instrument(level = "DEBUG", skip(self))]
pub async fn hscan(
&self,
@@ -630,6 +643,55 @@ impl super::RedisConnectionPool {
})
}
+ #[instrument(level = "DEBUG", skip(self))]
+ pub async fn append_elements_to_list<V>(
+ &self,
+ key: &str,
+ elements: V,
+ ) -> CustomResult<(), errors::RedisError>
+ where
+ V: TryInto<MultipleValues> + Debug + Send,
+ V::Error: Into<fred::error::RedisError> + Send,
+ {
+ self.pool
+ .rpush(self.add_prefix(key), elements)
+ .await
+ .change_context(errors::RedisError::AppendElementsToListFailed)
+ }
+
+ #[instrument(level = "DEBUG", skip(self))]
+ pub async fn get_list_elements(
+ &self,
+ key: &str,
+ start: i64,
+ stop: i64,
+ ) -> CustomResult<Vec<String>, errors::RedisError> {
+ self.pool
+ .lrange(self.add_prefix(key), start, stop)
+ .await
+ .change_context(errors::RedisError::GetListElementsFailed)
+ }
+
+ #[instrument(level = "DEBUG", skip(self))]
+ pub async fn get_list_length(&self, key: &str) -> CustomResult<usize, errors::RedisError> {
+ self.pool
+ .llen(self.add_prefix(key))
+ .await
+ .change_context(errors::RedisError::GetListLengthFailed)
+ }
+
+ #[instrument(level = "DEBUG", skip(self))]
+ pub async fn lpop_list_elements(
+ &self,
+ key: &str,
+ count: Option<usize>,
+ ) -> CustomResult<Vec<String>, errors::RedisError> {
+ self.pool
+ .lpop(self.add_prefix(key), count)
+ .await
+ .change_context(errors::RedisError::PopListElementsFailed)
+ }
+
// Consumer Group API
#[instrument(level = "DEBUG", skip(self))]
diff --git a/crates/redis_interface/src/errors.rs b/crates/redis_interface/src/errors.rs
index cc7f8bdd21f..0e2a4b8d63b 100644
--- a/crates/redis_interface/src/errors.rs
+++ b/crates/redis_interface/src/errors.rs
@@ -68,4 +68,14 @@ pub enum RedisError {
OnMessageError,
#[error("Got an unknown result from redis")]
UnknownResult,
+ #[error("Failed to append elements to list in Redis")]
+ AppendElementsToListFailed,
+ #[error("Failed to get list elements in Redis")]
+ GetListElementsFailed,
+ #[error("Failed to get length of list")]
+ GetListLengthFailed,
+ #[error("Failed to pop list elements in Redis")]
+ PopListElementsFailed,
+ #[error("Failed to increment hash field in Redis")]
+ IncrementHashFieldFailed,
}
|
2024-08-13T10:03:46Z
|
## Type of Change
<!-- Put an `x` in the boxes that apply -->
- [ ] Bugfix
- [ ] New feature
- [ ] Enhancement
- [ ] Refactoring
- [ ] Dependency updates
- [ ] Documentation
- [ ] CI/CD
## Description
<!-- Describe your changes in detail -->
This PR adds the required redis commands for success rate based routing. Below are the added redis commands -
* RPUSH (Push current block to aggregates list): Pushing an item to LIST
* LRANGE (Get a list of buckets in aggregates): Access an item from LIST in a given range
* LLEN (Check length of aggregates list): Get the length of LIST
* LPOP (Remove first bucket in aggregates list): Remove first n elements from LIST
* HINCRBY (Increment current_block's fields): Increment key of map
### Additional Changes
- [ ] This PR modifies the API contract
- [ ] This PR modifies the database schema
- [ ] This PR modifies application configuration/environment variables
<!--
Provide links to the files with corresponding changes.
Following are the paths where you can find config files:
1. `config`
2. `crates/router/src/configs`
3. `loadtest/config`
-->
## Motivation and Context
<!--
Why is this change required? What problem does it solve?
If it fixes an open issue, please link to the issue here.
If you don't have an issue, we'd recommend starting with one first so the PR
can focus on the implementation (unless it is an obvious bug or documentation fix
that will have little conversation).
-->
## How did you test it?
<!--
Did you write an integration/unit/API test to verify the code changes?
Or did you test this change manually (provide relevant screenshots)?
-->
As this PR only adds the new redis commands and doesn't involve any existing code changes, basic sanity tests should suffice
## Checklist
<!-- Put an `x` in the boxes that apply -->
- [x] I formatted the code `cargo +nightly fmt --all`
- [x] I addressed lints thrown by `cargo clippy`
- [x] I reviewed the submitted code
- [ ] I added unit tests for my changes where possible
|
e757605fdc287685c573d0c1c461cea556e5a5ce
|
|
juspay/hyperswitch
|
juspay__hyperswitch-5626
|
Bug: feat(disputes): support filters in disputes list
Support filters in disputes list
- Get list of filters to be applied on disputes list
- It can be multi-select for options like status and connector
- `get` api to be used to pass filters which to be applied on list API
- Implement parsing logic for get api, (to be used by other get filter APIs as well)
Filters:
- Date (Timerange)
- Status
- Payment id or Dispute id search
- Amount
- Currency
- Connector
|
diff --git a/crates/api_models/src/disputes.rs b/crates/api_models/src/disputes.rs
index a1340b5aa5a..4ddb50af0f2 100644
--- a/crates/api_models/src/disputes.rs
+++ b/crates/api_models/src/disputes.rs
@@ -1,11 +1,13 @@
use std::collections::HashMap;
+use common_utils::types::TimeRange;
use masking::{Deserialize, Serialize};
+use serde::de::Error;
use time::PrimitiveDateTime;
use utoipa::ToSchema;
use super::enums::{DisputeStage, DisputeStatus};
-use crate::files;
+use crate::{admin::MerchantConnectorInfo, enums, files};
#[derive(Clone, Debug, Serialize, ToSchema, Eq, PartialEq)]
pub struct DisputeResponse {
@@ -108,41 +110,51 @@ pub struct DisputeEvidenceBlock {
pub file_metadata_response: files::FileMetadataResponse,
}
-#[derive(Clone, Debug, Deserialize, ToSchema, Serialize)]
+#[derive(Clone, Debug, Deserialize, Serialize, ToSchema)]
#[serde(deny_unknown_fields)]
-pub struct DisputeListConstraints {
- /// limit on the number of objects to return
- pub limit: Option<i64>,
+pub struct DisputeListGetConstraints {
+ /// The identifier for dispute
+ pub dispute_id: Option<String>,
+ /// The payment_id against which dispute is raised
+ pub payment_id: Option<common_utils::id_type::PaymentId>,
+ /// Limit on the number of objects to return
+ pub limit: Option<u32>,
+ /// The starting point within a list of object
+ pub offset: Option<u32>,
/// The identifier for business profile
#[schema(value_type = Option<String>)]
pub profile_id: Option<common_utils::id_type::ProfileId>,
- /// status of the dispute
- pub dispute_status: Option<DisputeStatus>,
- /// stage of the dispute
- pub dispute_stage: Option<DisputeStage>,
- /// reason for the dispute
+ /// The comma separated list of status of the disputes
+ #[serde(default, deserialize_with = "parse_comma_separated")]
+ pub dispute_status: Option<Vec<DisputeStatus>>,
+ /// The comma separated list of stages of the disputes
+ #[serde(default, deserialize_with = "parse_comma_separated")]
+ pub dispute_stage: Option<Vec<DisputeStage>>,
+ /// Reason for the dispute
pub reason: Option<String>,
- /// connector linked to dispute
- pub connector: Option<String>,
- /// The time at which dispute is received
- #[schema(example = "2022-09-10T10:11:12Z")]
- pub received_time: Option<PrimitiveDateTime>,
- /// Time less than the dispute received time
- #[schema(example = "2022-09-10T10:11:12Z")]
- #[serde(rename = "received_time.lt")]
- pub received_time_lt: Option<PrimitiveDateTime>,
- /// Time greater than the dispute received time
- #[schema(example = "2022-09-10T10:11:12Z")]
- #[serde(rename = "received_time.gt")]
- pub received_time_gt: Option<PrimitiveDateTime>,
- /// Time less than or equals to the dispute received time
- #[schema(example = "2022-09-10T10:11:12Z")]
- #[serde(rename = "received_time.lte")]
- pub received_time_lte: Option<PrimitiveDateTime>,
- /// Time greater than or equals to the dispute received time
- #[schema(example = "2022-09-10T10:11:12Z")]
- #[serde(rename = "received_time.gte")]
- pub received_time_gte: Option<PrimitiveDateTime>,
+ /// The comma separated list of connectors linked to disputes
+ #[serde(default, deserialize_with = "parse_comma_separated")]
+ pub connector: Option<Vec<String>>,
+ /// The comma separated list of currencies of the disputes
+ #[serde(default, deserialize_with = "parse_comma_separated")]
+ pub currency: Option<Vec<common_enums::Currency>>,
+ /// The merchant connector id to filter the disputes list
+ pub merchant_connector_id: Option<common_utils::id_type::MerchantConnectorAccountId>,
+ /// The time range for which objects are needed. TimeRange has two fields start_time and end_time from which objects can be filtered as per required scenarios (created_at, time less than, greater than etc).
+ #[serde(flatten)]
+ pub time_range: Option<TimeRange>,
+}
+
+#[derive(Clone, Debug, serde::Serialize, ToSchema)]
+pub struct DisputeListFilters {
+ /// The map of available connector filters, where the key is the connector name and the value is a list of MerchantConnectorInfo instances
+ pub connector: HashMap<String, Vec<MerchantConnectorInfo>>,
+ /// The list of available currency filters
+ pub currency: Vec<enums::Currency>,
+ /// The list of available dispute status filters
+ pub dispute_status: Vec<DisputeStatus>,
+ /// The list of available dispute stage filters
+ pub dispute_stage: Vec<DisputeStage>,
}
#[derive(Default, Clone, Debug, Serialize, Deserialize, ToSchema)]
@@ -216,3 +228,19 @@ pub struct DisputesAggregateResponse {
/// Different status of disputes with their count
pub status_with_count: HashMap<DisputeStatus, i64>,
}
+
+fn parse_comma_separated<'de, D, T>(v: D) -> Result<Option<Vec<T>>, D::Error>
+where
+ D: serde::Deserializer<'de>,
+ T: std::str::FromStr,
+ <T as std::str::FromStr>::Err: std::fmt::Debug + std::fmt::Display + std::error::Error,
+{
+ let output = Option::<&str>::deserialize(v)?;
+ output
+ .map(|s| {
+ s.split(",")
+ .map(|x| x.parse::<T>().map_err(D::Error::custom))
+ .collect::<Result<_, _>>()
+ })
+ .transpose()
+}
diff --git a/crates/api_models/src/events.rs b/crates/api_models/src/events.rs
index b10f8e32dba..fefc596fe73 100644
--- a/crates/api_models/src/events.rs
+++ b/crates/api_models/src/events.rs
@@ -73,7 +73,7 @@ impl_api_event_type!(
RetrievePaymentLinkRequest,
PaymentLinkListConstraints,
MandateId,
- DisputeListConstraints,
+ DisputeListGetConstraints,
RetrieveApiKeyResponse,
ProfileResponse,
ProfileUpdate,
@@ -168,3 +168,9 @@ impl ApiEventMetric for PaymentMethodIntentCreate {
Some(ApiEventsType::PaymentMethodCreate)
}
}
+
+impl ApiEventMetric for DisputeListFilters {
+ fn get_api_event_type(&self) -> Option<ApiEventsType> {
+ Some(ApiEventsType::ResourceListAPI)
+ }
+}
diff --git a/crates/common_enums/src/enums.rs b/crates/common_enums/src/enums.rs
index 31cb43669b2..312a5bf092d 100644
--- a/crates/common_enums/src/enums.rs
+++ b/crates/common_enums/src/enums.rs
@@ -1817,6 +1817,7 @@ pub enum CardNetwork {
serde::Deserialize,
serde::Serialize,
strum::Display,
+ strum::EnumIter,
strum::EnumString,
ToSchema,
)]
diff --git a/crates/hyperswitch_domain_models/src/disputes.rs b/crates/hyperswitch_domain_models/src/disputes.rs
new file mode 100644
index 00000000000..87ae6204ac7
--- /dev/null
+++ b/crates/hyperswitch_domain_models/src/disputes.rs
@@ -0,0 +1,89 @@
+use crate::errors;
+
+pub struct DisputeListConstraints {
+ pub dispute_id: Option<String>,
+ pub payment_id: Option<common_utils::id_type::PaymentId>,
+ pub limit: Option<u32>,
+ pub offset: Option<u32>,
+ pub profile_id: Option<Vec<common_utils::id_type::ProfileId>>,
+ pub dispute_status: Option<Vec<common_enums::DisputeStatus>>,
+ pub dispute_stage: Option<Vec<common_enums::DisputeStage>>,
+ pub reason: Option<String>,
+ pub connector: Option<Vec<String>>,
+ pub merchant_connector_id: Option<common_utils::id_type::MerchantConnectorAccountId>,
+ pub currency: Option<Vec<common_enums::Currency>>,
+ pub time_range: Option<common_utils::types::TimeRange>,
+}
+
+impl
+ TryFrom<(
+ api_models::disputes::DisputeListGetConstraints,
+ Option<Vec<common_utils::id_type::ProfileId>>,
+ )> for DisputeListConstraints
+{
+ type Error = error_stack::Report<errors::api_error_response::ApiErrorResponse>;
+ fn try_from(
+ (value, auth_profile_id_list): (
+ api_models::disputes::DisputeListGetConstraints,
+ Option<Vec<common_utils::id_type::ProfileId>>,
+ ),
+ ) -> Result<Self, Self::Error> {
+ let api_models::disputes::DisputeListGetConstraints {
+ dispute_id,
+ payment_id,
+ limit,
+ offset,
+ profile_id,
+ dispute_status,
+ dispute_stage,
+ reason,
+ connector,
+ merchant_connector_id,
+ currency,
+ time_range,
+ } = value;
+ let profile_id_from_request_body = profile_id;
+ // Match both the profile ID from the request body and the list of authenticated profile IDs coming from auth layer
+ let profile_id_list = match (profile_id_from_request_body, auth_profile_id_list) {
+ (None, None) => None,
+ // Case when the request body profile ID is None, but authenticated profile IDs are available, return the auth list
+ (None, Some(auth_profile_id_list)) => Some(auth_profile_id_list),
+ // Case when the request body profile ID is provided, but the auth list is None, create a vector with the request body profile ID
+ (Some(profile_id_from_request_body), None) => Some(vec![profile_id_from_request_body]),
+ (Some(profile_id_from_request_body), Some(auth_profile_id_list)) => {
+ // Check if the profile ID from the request body is present in the authenticated profile ID list
+ let profile_id_from_request_body_is_available_in_auth_profile_id_list =
+ auth_profile_id_list.contains(&profile_id_from_request_body);
+
+ if profile_id_from_request_body_is_available_in_auth_profile_id_list {
+ Some(vec![profile_id_from_request_body])
+ } else {
+ // If the profile ID is not valid, return an error indicating access is not available
+ return Err(error_stack::Report::new(
+ errors::api_error_response::ApiErrorResponse::PreconditionFailed {
+ message: format!(
+ "Access not available for the given profile_id {:?}",
+ profile_id_from_request_body
+ ),
+ },
+ ));
+ }
+ }
+ };
+
+ Ok(Self {
+ dispute_id,
+ payment_id,
+ limit,
+ offset,
+ profile_id: profile_id_list,
+ dispute_status,
+ dispute_stage,
+ reason,
+ connector,
+ merchant_connector_id,
+ currency,
+ time_range,
+ })
+ }
+}
diff --git a/crates/hyperswitch_domain_models/src/lib.rs b/crates/hyperswitch_domain_models/src/lib.rs
index b0a660ad5d3..c99fbd89cd5 100644
--- a/crates/hyperswitch_domain_models/src/lib.rs
+++ b/crates/hyperswitch_domain_models/src/lib.rs
@@ -3,6 +3,7 @@ pub mod behaviour;
pub mod business_profile;
pub mod consts;
pub mod customer;
+pub mod disputes;
pub mod errors;
pub mod mandates;
pub mod merchant_account;
diff --git a/crates/router/src/core/disputes.rs b/crates/router/src/core/disputes.rs
index 30b73eb4c6a..8f083c3103a 100644
--- a/crates/router/src/core/disputes.rs
+++ b/crates/router/src/core/disputes.rs
@@ -1,11 +1,13 @@
-use api_models::{disputes as dispute_models, files as files_api_models};
+use std::collections::HashMap;
+
+use api_models::{
+ admin::MerchantConnectorInfo, disputes as dispute_models, files as files_api_models,
+};
use common_utils::ext_traits::{Encode, ValueExt};
use error_stack::ResultExt;
use router_env::{instrument, tracing};
-pub mod transformers;
-use std::collections::HashMap;
-
use strum::IntoEnumIterator;
+pub mod transformers;
use super::{
errors::{self, ConnectorErrorExt, RouterResponse, StorageErrorExt},
@@ -48,12 +50,13 @@ pub async fn retrieve_dispute(
pub async fn retrieve_disputes_list(
state: SessionState,
merchant_account: domain::MerchantAccount,
- _profile_id_list: Option<Vec<common_utils::id_type::ProfileId>>,
- constraints: api_models::disputes::DisputeListConstraints,
+ profile_id_list: Option<Vec<common_utils::id_type::ProfileId>>,
+ constraints: api_models::disputes::DisputeListGetConstraints,
) -> RouterResponse<Vec<api_models::disputes::DisputeResponse>> {
+ let dispute_list_constraints = &(constraints.clone(), profile_id_list.clone()).try_into()?;
let disputes = state
.store
- .find_disputes_by_merchant_id(merchant_account.get_id(), constraints)
+ .find_disputes_by_constraints(merchant_account.get_id(), dispute_list_constraints)
.await
.to_not_found_response(errors::ApiErrorResponse::InternalServerError)
.attach_printable("Unable to retrieve disputes")?;
@@ -76,6 +79,59 @@ pub async fn accept_dispute(
todo!()
}
+#[instrument(skip(state))]
+pub async fn get_filters_for_disputes(
+ state: SessionState,
+ merchant_account: domain::MerchantAccount,
+ profile_id_list: Option<Vec<common_utils::id_type::ProfileId>>,
+) -> RouterResponse<api_models::disputes::DisputeListFilters> {
+ let merchant_connector_accounts = if let services::ApplicationResponse::Json(data) =
+ super::admin::list_payment_connectors(
+ state,
+ merchant_account.get_id().to_owned(),
+ profile_id_list,
+ )
+ .await?
+ {
+ data
+ } else {
+ return Err(error_stack::report!(
+ errors::ApiErrorResponse::InternalServerError
+ ))
+ .attach_printable(
+ "Failed to retrieve merchant connector accounts while fetching dispute list filters.",
+ );
+ };
+
+ let connector_map = merchant_connector_accounts
+ .into_iter()
+ .filter_map(|merchant_connector_account| {
+ merchant_connector_account
+ .connector_label
+ .clone()
+ .map(|label| {
+ let info = merchant_connector_account.to_merchant_connector_info(&label);
+ (merchant_connector_account.connector_name, info)
+ })
+ })
+ .fold(
+ HashMap::new(),
+ |mut map: HashMap<String, Vec<MerchantConnectorInfo>>, (connector_name, info)| {
+ map.entry(connector_name).or_default().push(info);
+ map
+ },
+ );
+
+ Ok(services::ApplicationResponse::Json(
+ api_models::disputes::DisputeListFilters {
+ connector: connector_map,
+ currency: storage_enums::Currency::iter().collect(),
+ dispute_status: storage_enums::DisputeStatus::iter().collect(),
+ dispute_stage: storage_enums::DisputeStage::iter().collect(),
+ },
+ ))
+}
+
#[cfg(feature = "v1")]
#[instrument(skip(state))]
pub async fn accept_dispute(
diff --git a/crates/router/src/db/dispute.rs b/crates/router/src/db/dispute.rs
index a44528fde43..d7f4af63015 100644
--- a/crates/router/src/db/dispute.rs
+++ b/crates/router/src/db/dispute.rs
@@ -1,6 +1,7 @@
use std::collections::HashMap;
use error_stack::report;
+use hyperswitch_domain_models::disputes;
use router_env::{instrument, tracing};
use super::{MockDb, Store};
@@ -30,10 +31,10 @@ pub trait DisputeInterface {
dispute_id: &str,
) -> CustomResult<storage::Dispute, errors::StorageError>;
- async fn find_disputes_by_merchant_id(
+ async fn find_disputes_by_constraints(
&self,
merchant_id: &common_utils::id_type::MerchantId,
- dispute_constraints: api_models::disputes::DisputeListConstraints,
+ dispute_constraints: &disputes::DisputeListConstraints,
) -> CustomResult<Vec<storage::Dispute>, errors::StorageError>;
async fn find_disputes_by_merchant_id_payment_id(
@@ -101,10 +102,10 @@ impl DisputeInterface for Store {
}
#[instrument(skip_all)]
- async fn find_disputes_by_merchant_id(
+ async fn find_disputes_by_constraints(
&self,
merchant_id: &common_utils::id_type::MerchantId,
- dispute_constraints: api_models::disputes::DisputeListConstraints,
+ dispute_constraints: &disputes::DisputeListConstraints,
) -> CustomResult<Vec<storage::Dispute>, errors::StorageError> {
let conn = connection::pg_connection_read(self).await?;
storage::Dispute::filter_by_constraints(&conn, merchant_id, dispute_constraints)
@@ -238,75 +239,96 @@ impl DisputeInterface for MockDb {
.into())
}
- async fn find_disputes_by_merchant_id(
+ async fn find_disputes_by_constraints(
&self,
merchant_id: &common_utils::id_type::MerchantId,
- dispute_constraints: api_models::disputes::DisputeListConstraints,
+ dispute_constraints: &disputes::DisputeListConstraints,
) -> CustomResult<Vec<storage::Dispute>, errors::StorageError> {
let locked_disputes = self.disputes.lock().await;
-
- Ok(locked_disputes
+ let limit_usize = dispute_constraints
+ .limit
+ .unwrap_or(u32::MAX)
+ .try_into()
+ .unwrap_or(usize::MAX);
+ let offset_usize = dispute_constraints
+ .offset
+ .unwrap_or(0)
+ .try_into()
+ .unwrap_or(usize::MIN);
+ let filtered_disputes: Vec<storage::Dispute> = locked_disputes
.iter()
- .filter(|d| {
- d.merchant_id == *merchant_id
+ .filter(|dispute| {
+ dispute.merchant_id == *merchant_id
&& dispute_constraints
- .dispute_status
+ .dispute_id
.as_ref()
- .map(|status| status == &d.dispute_status)
- .unwrap_or(true)
+ .map_or(true, |id| &dispute.dispute_id == id)
&& dispute_constraints
- .dispute_stage
+ .payment_id
.as_ref()
- .map(|stage| stage == &d.dispute_stage)
- .unwrap_or(true)
+ .map_or(true, |id| &dispute.payment_id == id)
&& dispute_constraints
- .reason
+ .profile_id
.as_ref()
- .and_then(|reason| {
- d.connector_reason
+ .map_or(true, |profile_ids| {
+ dispute
+ .profile_id
.as_ref()
- .map(|connector_reason| connector_reason == reason)
+ .map_or(true, |id| profile_ids.contains(id))
})
- .unwrap_or(true)
&& dispute_constraints
- .connector
+ .dispute_status
.as_ref()
- .map(|connector| connector == &d.connector)
- .unwrap_or(true)
+ .map_or(true, |statuses| statuses.contains(&dispute.dispute_status))
&& dispute_constraints
- .received_time
+ .dispute_stage
.as_ref()
- .map(|received_time| received_time == &d.created_at)
- .unwrap_or(true)
+ .map_or(true, |stages| stages.contains(&dispute.dispute_stage))
+ && dispute_constraints.reason.as_ref().map_or(true, |reason| {
+ dispute
+ .connector_reason
+ .as_ref()
+ .map_or(true, |d_reason| d_reason == reason)
+ })
&& dispute_constraints
- .received_time_lt
+ .connector
.as_ref()
- .map(|received_time_lt| received_time_lt > &d.created_at)
- .unwrap_or(true)
+ .map_or(true, |connectors| {
+ connectors
+ .iter()
+ .any(|connector| dispute.connector.as_str() == *connector)
+ })
&& dispute_constraints
- .received_time_gt
+ .merchant_connector_id
.as_ref()
- .map(|received_time_gt| received_time_gt < &d.created_at)
- .unwrap_or(true)
+ .map_or(true, |id| {
+ dispute.merchant_connector_id.as_ref() == Some(id)
+ })
&& dispute_constraints
- .received_time_lte
+ .currency
.as_ref()
- .map(|received_time_lte| received_time_lte >= &d.created_at)
- .unwrap_or(true)
+ .map_or(true, |currencies| {
+ currencies
+ .iter()
+ .any(|currency| dispute.currency.as_str() == currency.to_string())
+ })
&& dispute_constraints
- .received_time_gte
+ .time_range
.as_ref()
- .map(|received_time_gte| received_time_gte <= &d.created_at)
- .unwrap_or(true)
+ .map_or(true, |range| {
+ let dispute_time = dispute.created_at;
+ dispute_time >= range.start_time
+ && range
+ .end_time
+ .map_or(true, |end_time| dispute_time <= end_time)
+ })
})
- .take(
- dispute_constraints
- .limit
- .and_then(|limit| usize::try_from(limit).ok())
- .unwrap_or(usize::MAX),
- )
+ .skip(offset_usize)
+ .take(limit_usize)
.cloned()
- .collect())
+ .collect();
+
+ Ok(filtered_disputes)
}
async fn find_disputes_by_merchant_id_payment_id(
@@ -437,11 +459,11 @@ mod tests {
mod mockdb_dispute_interface {
use std::borrow::Cow;
- use api_models::disputes::DisputeListConstraints;
use diesel_models::{
dispute::DisputeNew,
enums::{DisputeStage, DisputeStatus},
};
+ use hyperswitch_domain_models::disputes::DisputeListConstraints;
use masking::Secret;
use redis_interface::RedisSettings;
use serde_json::Value;
@@ -648,20 +670,21 @@ mod tests {
.unwrap();
let found_disputes = mockdb
- .find_disputes_by_merchant_id(
+ .find_disputes_by_constraints(
&merchant_id,
- DisputeListConstraints {
+ &DisputeListConstraints {
+ dispute_id: None,
+ payment_id: None,
+ profile_id: None,
+ connector: None,
+ merchant_connector_id: None,
+ currency: None,
limit: None,
+ offset: None,
dispute_status: None,
dispute_stage: None,
reason: None,
- connector: None,
- received_time: None,
- received_time_lt: None,
- received_time_gt: None,
- received_time_lte: None,
- received_time_gte: None,
- profile_id: None,
+ time_range: None,
},
)
.await
diff --git a/crates/router/src/db/kafka_store.rs b/crates/router/src/db/kafka_store.rs
index ff7e8145c33..36b66244e18 100644
--- a/crates/router/src/db/kafka_store.rs
+++ b/crates/router/src/db/kafka_store.rs
@@ -14,6 +14,7 @@ use hyperswitch_domain_models::payouts::{
payout_attempt::PayoutAttemptInterface, payouts::PayoutsInterface,
};
use hyperswitch_domain_models::{
+ disputes,
payments::{payment_attempt::PaymentAttemptInterface, payment_intent::PaymentIntentInterface},
refunds,
};
@@ -590,13 +591,13 @@ impl DisputeInterface for KafkaStore {
.await
}
- async fn find_disputes_by_merchant_id(
+ async fn find_disputes_by_constraints(
&self,
merchant_id: &id_type::MerchantId,
- dispute_constraints: api_models::disputes::DisputeListConstraints,
+ dispute_constraints: &disputes::DisputeListConstraints,
) -> CustomResult<Vec<storage::Dispute>, errors::StorageError> {
self.diesel_store
- .find_disputes_by_merchant_id(merchant_id, dispute_constraints)
+ .find_disputes_by_constraints(merchant_id, dispute_constraints)
.await
}
diff --git a/crates/router/src/routes/app.rs b/crates/router/src/routes/app.rs
index 01a48c56401..dafee54ae05 100644
--- a/crates/router/src/routes/app.rs
+++ b/crates/router/src/routes/app.rs
@@ -1496,6 +1496,11 @@ impl Disputes {
web::resource("/profile/list")
.route(web::get().to(disputes::retrieve_disputes_list_profile)),
)
+ .service(web::resource("/filter").route(web::get().to(disputes::get_disputes_filters)))
+ .service(
+ web::resource("/profile/filter")
+ .route(web::get().to(disputes::get_disputes_filters_profile)),
+ )
.service(
web::resource("/accept/{dispute_id}")
.route(web::post().to(disputes::accept_dispute)),
diff --git a/crates/router/src/routes/disputes.rs b/crates/router/src/routes/disputes.rs
index 50a26ceae89..1a8c4410a53 100644
--- a/crates/router/src/routes/disputes.rs
+++ b/crates/router/src/routes/disputes.rs
@@ -87,10 +87,10 @@ pub async fn retrieve_dispute(
pub async fn retrieve_disputes_list(
state: web::Data<AppState>,
req: HttpRequest,
- payload: web::Query<dispute_models::DisputeListConstraints>,
+ query: web::Query<dispute_models::DisputeListGetConstraints>,
) -> HttpResponse {
let flow = Flow::DisputesList;
- let payload = payload.into_inner();
+ let payload = query.into_inner();
Box::pin(api::server_wrap(
flow,
state,
@@ -140,7 +140,7 @@ pub async fn retrieve_disputes_list(
pub async fn retrieve_disputes_list_profile(
state: web::Data<AppState>,
req: HttpRequest,
- payload: web::Query<dispute_models::DisputeListConstraints>,
+ payload: web::Query<dispute_models::DisputeListGetConstraints>,
) -> HttpResponse {
let flow = Flow::DisputesList;
let payload = payload.into_inner();
@@ -170,6 +170,81 @@ pub async fn retrieve_disputes_list_profile(
.await
}
+/// 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, _, _| disputes::get_filters_for_disputes(state, auth.merchant_account, None),
+ auth::auth_type(
+ &auth::HeaderAuth(auth::ApiKeyAuth),
+ &auth::JWTAuth {
+ permission: Permission::DisputeRead,
+ minimum_entity_level: EntityType::Merchant,
+ },
+ req.headers(),
+ ),
+ api_locking::LockAction::NotApplicable,
+ ))
+ .await
+}
+
+/// 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, _, _| {
+ disputes::get_filters_for_disputes(
+ state,
+ auth.merchant_account,
+ auth.profile_id.map(|profile_id| vec![profile_id]),
+ )
+ },
+ auth::auth_type(
+ &auth::HeaderAuth(auth::ApiKeyAuth),
+ &auth::JWTAuth {
+ permission: Permission::DisputeRead,
+ minimum_entity_level: EntityType::Profile,
+ },
+ req.headers(),
+ ),
+ api_locking::LockAction::NotApplicable,
+ ))
+ .await
+}
+
/// Disputes - Accept Dispute
#[utoipa::path(
get,
diff --git a/crates/router/src/routes/lock_utils.rs b/crates/router/src/routes/lock_utils.rs
index d6d3ec8a952..482bc40c49f 100644
--- a/crates/router/src/routes/lock_utils.rs
+++ b/crates/router/src/routes/lock_utils.rs
@@ -172,6 +172,7 @@ impl From<Flow> for ApiIdentifier {
Flow::DisputesRetrieve
| Flow::DisputesList
+ | Flow::DisputesFilters
| Flow::DisputesEvidenceSubmit
| Flow::AttachDisputeEvidence
| Flow::RetrieveDisputeEvidence
diff --git a/crates/router/src/routes/refunds.rs b/crates/router/src/routes/refunds.rs
index 40184c5fcfa..b287b5e9790 100644
--- a/crates/router/src/routes/refunds.rs
+++ b/crates/router/src/routes/refunds.rs
@@ -381,7 +381,7 @@ pub async fn get_refunds_filters(state: web::Data<AppState>, req: HttpRequest) -
/// To list the refunds filters associated with list of connectors, currencies and payment statuses
#[utoipa::path(
get,
- path = "/refunds/v2/filter/profile",
+ path = "/refunds/v2/profile/filter",
responses(
(status = 200, description = "List of static filters", body = RefundListFilters),
),
diff --git a/crates/router/src/types/storage/dispute.rs b/crates/router/src/types/storage/dispute.rs
index 45f2073708b..28a9573b333 100644
--- a/crates/router/src/types/storage/dispute.rs
+++ b/crates/router/src/types/storage/dispute.rs
@@ -4,6 +4,7 @@ use diesel::{associations::HasTable, ExpressionMethods, QueryDsl};
pub use diesel_models::dispute::{Dispute, DisputeNew, DisputeUpdate};
use diesel_models::{errors, query::generics::db_metrics, schema::dispute::dsl};
use error_stack::ResultExt;
+use hyperswitch_domain_models::disputes;
use crate::{connection::PgPooledConn, logger};
@@ -12,7 +13,7 @@ pub trait DisputeDbExt: Sized {
async fn filter_by_constraints(
conn: &PgPooledConn,
merchant_id: &common_utils::id_type::MerchantId,
- dispute_list_constraints: api_models::disputes::DisputeListConstraints,
+ dispute_list_constraints: &disputes::DisputeListConstraints,
) -> CustomResult<Vec<Self>, errors::DatabaseError>;
async fn get_dispute_status_with_count(
@@ -28,45 +29,77 @@ impl DisputeDbExt for Dispute {
async fn filter_by_constraints(
conn: &PgPooledConn,
merchant_id: &common_utils::id_type::MerchantId,
- dispute_list_constraints: api_models::disputes::DisputeListConstraints,
+ dispute_list_constraints: &disputes::DisputeListConstraints,
) -> CustomResult<Vec<Self>, errors::DatabaseError> {
let mut filter = <Self as HasTable>::table()
.filter(dsl::merchant_id.eq(merchant_id.to_owned()))
.order(dsl::modified_at.desc())
.into_boxed();
- if let Some(profile_id) = dispute_list_constraints.profile_id {
- filter = filter.filter(dsl::profile_id.eq(profile_id));
+ let mut search_by_payment_or_dispute_id = false;
+
+ if let (Some(payment_id), Some(dispute_id)) = (
+ &dispute_list_constraints.payment_id,
+ &dispute_list_constraints.dispute_id,
+ ) {
+ search_by_payment_or_dispute_id = true;
+ filter = filter
+ .filter(dsl::payment_id.eq(payment_id.to_owned()))
+ .or_filter(dsl::dispute_id.eq(dispute_id.to_owned()));
+ };
+
+ if !search_by_payment_or_dispute_id {
+ if let Some(payment_id) = &dispute_list_constraints.payment_id {
+ filter = filter.filter(dsl::payment_id.eq(payment_id.to_owned()));
+ };
}
- if let Some(received_time) = dispute_list_constraints.received_time {
- filter = filter.filter(dsl::created_at.eq(received_time));
+ if !search_by_payment_or_dispute_id {
+ if let Some(dispute_id) = &dispute_list_constraints.dispute_id {
+ filter = filter.filter(dsl::dispute_id.eq(dispute_id.clone()));
+ };
}
- if let Some(received_time_lt) = dispute_list_constraints.received_time_lt {
- filter = filter.filter(dsl::created_at.lt(received_time_lt));
+
+ if let Some(time_range) = dispute_list_constraints.time_range {
+ filter = filter.filter(dsl::created_at.ge(time_range.start_time));
+
+ if let Some(end_time) = time_range.end_time {
+ filter = filter.filter(dsl::created_at.le(end_time));
+ }
}
- if let Some(received_time_gt) = dispute_list_constraints.received_time_gt {
- filter = filter.filter(dsl::created_at.gt(received_time_gt));
+
+ if let Some(profile_id) = &dispute_list_constraints.profile_id {
+ filter = filter.filter(dsl::profile_id.eq_any(profile_id.clone()));
}
- if let Some(received_time_lte) = dispute_list_constraints.received_time_lte {
- filter = filter.filter(dsl::created_at.le(received_time_lte));
+ if let Some(connector_list) = &dispute_list_constraints.connector {
+ filter = filter.filter(dsl::connector.eq_any(connector_list.clone()));
}
- if let Some(received_time_gte) = dispute_list_constraints.received_time_gte {
- filter = filter.filter(dsl::created_at.ge(received_time_gte));
+
+ if let Some(reason) = &dispute_list_constraints.reason {
+ filter = filter.filter(dsl::connector_reason.eq(reason.clone()));
}
- if let Some(connector) = dispute_list_constraints.connector {
- filter = filter.filter(dsl::connector.eq(connector));
+ if let Some(dispute_stage) = &dispute_list_constraints.dispute_stage {
+ filter = filter.filter(dsl::dispute_stage.eq_any(dispute_stage.clone()));
}
- if let Some(reason) = dispute_list_constraints.reason {
- filter = filter.filter(dsl::connector_reason.eq(reason));
+ if let Some(dispute_status) = &dispute_list_constraints.dispute_status {
+ filter = filter.filter(dsl::dispute_status.eq_any(dispute_status.clone()));
}
- if let Some(dispute_stage) = dispute_list_constraints.dispute_stage {
- filter = filter.filter(dsl::dispute_stage.eq(dispute_stage));
+
+ if let Some(currency_list) = &dispute_list_constraints.currency {
+ let currency: Vec<String> = currency_list
+ .iter()
+ .map(|currency| currency.to_string())
+ .collect();
+
+ filter = filter.filter(dsl::currency.eq_any(currency));
}
- if let Some(dispute_status) = dispute_list_constraints.dispute_status {
- filter = filter.filter(dsl::dispute_status.eq(dispute_status));
+ if let Some(merchant_connector_id) = &dispute_list_constraints.merchant_connector_id {
+ filter = filter.filter(dsl::merchant_connector_id.eq(merchant_connector_id.clone()))
}
if let Some(limit) = dispute_list_constraints.limit {
- filter = filter.limit(limit);
+ filter = filter.limit(limit.into());
+ }
+ if let Some(offset) = dispute_list_constraints.offset {
+ filter = filter.offset(offset.into());
}
logger::debug!(query = %diesel::debug_query::<diesel::pg::Pg, _>(&filter).to_string());
diff --git a/crates/router_env/src/logger/types.rs b/crates/router_env/src/logger/types.rs
index 12e30f54549..603c5cc91c1 100644
--- a/crates/router_env/src/logger/types.rs
+++ b/crates/router_env/src/logger/types.rs
@@ -274,6 +274,8 @@ pub enum Flow {
DisputesRetrieve,
/// Dispute List flow
DisputesList,
+ /// Dispute Filters flow
+ DisputesFilters,
/// Cards Info flow
CardsInfo,
/// Create File flow
|
2024-08-15T17:30:42Z
|
## Type of Change
<!-- Put an `x` in the boxes that apply -->
- [ ] Bugfix
- [x] New feature
- [ ] Enhancement
- [ ] Refactoring
- [ ] Dependency updates
- [ ] Documentation
- [ ] CI/CD
## Description
Add filters for disputes list
### Additional Changes
- [ ] This PR modifies the API contract
- [ ] This PR modifies the database schema
- [ ] This PR modifies application configuration/environment variables
<!--
Provide links to the files with corresponding changes.
Following are the paths where you can find config files:
1. `config`
2. `crates/router/src/configs`
3. `loadtest/config`
-->
## Motivation and Context
Closes #5626
## How did you test it?
The following endpoints will give profile or merchant level filters:
The start_time and end_time are in primitive data time format:
`start_time`=`2024-07-03T18:00:00.000Z`
`end_time`=`2024-10-03T18:00:00.000Z`
```
curl --location --request GET 'http://localhost:8080/disputes/filter' \
--header 'Content-Type: application/json' \
--header 'Accept: application/json' \
--header 'Authorization: Bearer JWT' \
--data
```
```
curl --location --request GET 'http://localhost:8080/disputes/profile/filter' \
--header 'Content-Type: application/json' \
--header 'Accept: application/json' \
--header 'Authorization: Bearer JWT' \
--data
```
Response: Set of dropdown filters:
```
{
"connector": { List of configured connectors},
"currency": [
"AED",
"ALL",
"AMD",
... and other list of available currencies
],
"dispute_status": [
"dispute_opened",
"dispute_expired",
"dispute_accepted",
"dispute_cancelled",
"dispute_challenged",
"dispute_won",
"dispute_lost"
],
"dispute_stage": [
"pre_dispute",
"dispute",
"pre_arbitration"
]
}
```
The list api will accept set of filters in query param and gives desired response
```
curl --location 'http://localhost:8080/disputes/list?connector=c1,c2,c3¤cy=cur1,cur2,cur3&dispute_stage=d1,d2&dispute_status=ds1,ds2' \
--header 'Content-Type: application/json' \
--header 'Accept: application/json' \
--header 'Authorization: Bearer JWT' \
--data ''
```
```
curl --location 'http://localhost:8080/disputes/list?start_time=2024-07-03T18:00:00.000Z&end_time=2024-10-03T18:00:00.000Z' \
--header 'Content-Type: application/json' \
--header 'Accept: application/json' \
--header 'Authorization: Bearer JWT' \
--data ''
```
Response will be list after applying the filters passed in query param.
```
[
{
"dispute_id": "dp_c5dsfPtddlzuGN6kEusg",
"payment_id": "test_F2wxddVYyES3ZmxdYE07",
"attempt_id": "test_F2wxddVYyES3ZmxdYE07_1",
"amount": "1040",
"currency": "GBP",
"dispute_stage": "dispute",
"dispute_status": "dispute_expired",
"connector": "checkout",
"connector_status": "DisputeExpired",
"connector_dispute_id": "dsp_c0db6a8d577h763b1c00",
"connector_reason": "",
"connector_reason_code": "10.4",
"challenge_required_by": "2024-07-03T18:00:00.000Z",
"connector_created_at": "2024-06-13T14:39:16.710Z",
"connector_updated_at": "2024-07-03T18:00:36.610Z",
"created_at": "2024-06-13T14:39:17.037Z",
"profile_id": "pro_cz810B3XlrAPQu69pCi6",
"merchant_connector_id": "mca_6rzLRT6znmFkdTpSLu0x"
}
]
```
## Checklist
<!-- Put an `x` in the boxes that apply -->
- [ ] I formatted the code `cargo +nightly fmt --all`
- [ ] I addressed lints thrown by `cargo clippy`
- [ ] I reviewed the submitted code
- [ ] I added unit tests for my changes where possible
|
a94cf25bb6eb40fafc5327aceffac8292b47b001
|
|
juspay/hyperswitch
|
juspay__hyperswitch-5603
|
Bug: fix(opensearch): Add date-suffixed indexes for opensearch locally
Currently the events get pushed to indexes of the form `{{ .topic }}`
In addition we can push the events to date-suffixed indexes of the form
- `vector-{{ .topic }}-%Y-%m-%d` for events pushed through vector
- `fluentd-{{ .topic }}-%Y-%m-%d` for events pushed through fluentd
|
diff --git a/config/vector.yaml b/config/vector.yaml
index 17049677fe5..54ff25cab5a 100644
--- a/config/vector.yaml
+++ b/config/vector.yaml
@@ -71,7 +71,7 @@ transforms:
window_secs: 60
sinks:
- opensearch_events:
+ opensearch_events_1:
type: elasticsearch
inputs:
- events
@@ -93,9 +93,32 @@ sinks:
- partition
- topic
bulk:
- # Add a date prefixed index for better grouping
- # index: "vector-{{ .topic }}-%Y-%m-%d"
- index: "{{ .topic }}"
+ index: "vector-{{ .topic }}"
+
+ opensearch_events_2:
+ type: elasticsearch
+ inputs:
+ - events
+ endpoints:
+ - "https://opensearch:9200"
+ id_key: message_key
+ api_version: v7
+ tls:
+ verify_certificate: false
+ verify_hostname: false
+ auth:
+ strategy: basic
+ user: admin
+ password: 0penS3arc#
+ encoding:
+ except_fields:
+ - message_key
+ - offset
+ - partition
+ - topic
+ bulk:
+ # Add a date suffixed index for better grouping
+ index: "vector-{{ .topic }}-%Y-%m-%d"
opensearch_logs:
type: elasticsearch
@@ -112,7 +135,7 @@ sinks:
user: admin
password: 0penS3arc#
bulk:
- # Add a date prefixed index for better grouping
+ # Add a date suffixed index for better grouping
# index: "vector-{{ .topic }}-%Y-%m-%d"
index: "logs-{{ .container_name }}-%Y-%m-%d"
diff --git a/crates/analytics/docs/README.md b/crates/analytics/docs/README.md
index da9a3c79f1f..96218fc231c 100644
--- a/crates/analytics/docs/README.md
+++ b/crates/analytics/docs/README.md
@@ -108,11 +108,11 @@ global_search=true
To view the data on the OpenSearch dashboard perform the following steps:
-- Go to the OpenSearch Dashboard home and click on `Stack Management` under the Management tab
+- Go to the OpenSearch Dashboard home and click on `Dashboards Management` under the Management tab
- Select `Index Patterns`
- Click on `Create index pattern`
- Define an index pattern with the same name that matches your indices and click on `Next Step`
- Select a time field that will be used for time-based queries
- Save the index pattern
-Now, head on to the `Discover` tab, to select the newly created index pattern and query the data
\ No newline at end of file
+Now, head on to `Discover` under the `OpenSearch Dashboards` tab, to select the newly created index pattern and query the data
\ No newline at end of file
diff --git a/docker/fluentd/conf/fluent.conf b/docker/fluentd/conf/fluent.conf
index 785254a3b25..d0f7c861c32 100644
--- a/docker/fluentd/conf/fluent.conf
+++ b/docker/fluentd/conf/fluent.conf
@@ -47,7 +47,25 @@
index_name hyperswitch-payment-intent-events
id_key payment_id
user admin
- password admin
+ password '0penS3arc#'
+ ssl_verify false
+ prefer_oj_serializer true
+ reload_on_failure true
+ reload_connections false
+ request_timeout 120s
+ bulk_message_request_threshold 10MB
+ include_timestamp true
+ </store>
+
+ <store>
+ @type opensearch
+ host opensearch
+ port 9200
+ scheme https
+ index_name fluentd-hyperswitch-payment-intent-events-%Y-%m-%d
+ id_key payment_id
+ user admin
+ password '0penS3arc#'
ssl_verify false
prefer_oj_serializer true
reload_on_failure true
@@ -55,6 +73,10 @@
request_timeout 120s
bulk_message_request_threshold 10MB
include_timestamp true
+ <buffer tag, time>
+ timekey 10s
+ timekey_wait 10s
+ </buffer>
</store>
</match>
@@ -73,7 +95,25 @@
index_name hyperswitch-payment-attempt-events
id_key attempt_id
user admin
- password admin
+ password '0penS3arc#'
+ ssl_verify false
+ prefer_oj_serializer true
+ reload_on_failure true
+ reload_connections false
+ request_timeout 120s
+ bulk_message_request_threshold 10MB
+ include_timestamp true
+ </store>
+
+ <store>
+ @type opensearch
+ host opensearch
+ port 9200
+ scheme https
+ index_name fluentd-hyperswitch-payment-attempt-events-%Y-%m-%d
+ id_key attempt_id
+ user admin
+ password '0penS3arc#'
ssl_verify false
prefer_oj_serializer true
reload_on_failure true
@@ -81,6 +121,10 @@
request_timeout 120s
bulk_message_request_threshold 10MB
include_timestamp true
+ <buffer tag, time>
+ timekey 10s
+ timekey_wait 10s
+ </buffer>
</store>
</match>
@@ -99,7 +143,25 @@
index_name hyperswitch-refund-events
id_key refund_id
user admin
- password admin
+ password '0penS3arc#'
+ ssl_verify false
+ prefer_oj_serializer true
+ reload_on_failure true
+ reload_connections false
+ request_timeout 120s
+ bulk_message_request_threshold 10MB
+ include_timestamp true
+ </store>
+
+ <store>
+ @type opensearch
+ host opensearch
+ port 9200
+ scheme https
+ index_name fluentd-hyperswitch-refund-events-%Y-%m-%d
+ id_key refund_id
+ user admin
+ password '0penS3arc#'
ssl_verify false
prefer_oj_serializer true
reload_on_failure true
@@ -107,6 +169,10 @@
request_timeout 120s
bulk_message_request_threshold 10MB
include_timestamp true
+ <buffer tag, time>
+ timekey 10s
+ timekey_wait 10s
+ </buffer>
</store>
</match>
@@ -134,4 +200,26 @@
bulk_message_request_threshold 10MB
include_timestamp true
</store>
+
+ <store>
+ @type opensearch
+ host opensearch
+ port 9200
+ scheme https
+ index_name fluentd-hyperswitch-dispute-events-%Y-%m-%d
+ id_key dispute_id
+ user admin
+ password '0penS3arc#'
+ ssl_verify false
+ prefer_oj_serializer true
+ reload_on_failure true
+ reload_connections false
+ request_timeout 120s
+ bulk_message_request_threshold 10MB
+ include_timestamp true
+ <buffer tag, time>
+ timekey 10s
+ timekey_wait 10s
+ </buffer>
+ </store>
</match>
\ No newline at end of file
|
2024-08-14T13:57:50Z
|
## Type of Change
<!-- Put an `x` in the boxes that apply -->
- [x] Bugfix
- [ ] New feature
- [x] Enhancement
- [ ] Refactoring
- [ ] Dependency updates
- [ ] Documentation
- [ ] CI/CD
## Description
<!-- Describe your changes in detail -->
Currently the events get pushed to indexes of the form `{{ .topic }}` locally.
In addition we can now push the events to date-suffixed indexes of the form
- `vector-{{ .topic }}-%Y-%m-%d for events pushed through vector`
- `fluentd-{{ .topic }}-%Y-%m-%d for events pushed through fluentd`
We can also have the existing indexes for aggregating events for the respective indexes of the form
- `vector-{{ .topic }}` (pushed through vector)
- `{{ .topic }}` (pushed through fluentd)
### Additional Changes
- [ ] This PR modifies the API contract
- [ ] This PR modifies the database schema
- [ ] This PR modifies application configuration/environment variables
<!--
Provide links to the files with corresponding changes.
Following are the paths where you can find config files:
1. `config`
2. `crates/router/src/configs`
3. `loadtest/config`
-->
## Motivation and Context
<!--
Why is this change required? What problem does it solve?
If it fixes an open issue, please link to the issue here.
If you don't have an issue, we'd recommend starting with one first so the PR
can focus on the implementation (unless it is an obvious bug or documentation fix
that will have little conversation).
-->
Can have respective results pushed to date-specific indexes for better analytics
## How did you test it?
<!--
Did you write an integration/unit/API test to verify the code changes?
Or did you test this change manually (provide relevant screenshots)?
-->
Made payments, and ensured the creation of separate indexes on opensearch from both fluentd and vector
<img width="1303" alt="Screenshot 2024-08-14 at 7 23 14 PM" src="https://github.com/user-attachments/assets/9269f65c-c95c-4388-9196-7d8893dcb098">
<img width="1313" alt="Screenshot 2024-08-14 at 7 23 23 PM" src="https://github.com/user-attachments/assets/e4454177-3655-4c32-b96f-83b8c9a68a04">
<img width="1719" alt="Screenshot 2024-08-14 at 7 23 41 PM" src="https://github.com/user-attachments/assets/b9eefe7d-c372-4d90-9dc7-cdfc5fe63190">
<img width="1726" alt="Screenshot 2024-08-14 at 7 23 49 PM" src="https://github.com/user-attachments/assets/c74b2407-80eb-4b97-a3f7-9bde573cce5e">
<img width="1728" alt="Screenshot 2024-08-14 at 7 23 58 PM" src="https://github.com/user-attachments/assets/568dcb0f-b332-4908-97c2-4889230f2747">

## Checklist
<!-- Put an `x` in the boxes that apply -->
- [x] I formatted the code `cargo +nightly fmt --all`
- [x] I addressed lints thrown by `cargo clippy`
- [x] I reviewed the submitted code
- [ ] I added unit tests for my changes where possible
|
72b61310523403113b469e6e6a9a89806849bb1e
|
|
juspay/hyperswitch
|
juspay__hyperswitch-5605
|
Bug: [REFACTOR] Refactor update and retrieve of fallback api-v2
### Feature Description
Refactor update and retrieve of fallback api-v2
### Possible Implementation
Refactor update and retrieve of fallback api-v2
### Have you spent some time checking if this feature request has been raised before?
- [X] I checked and didn't find a similar issue
### Have you read the Contributing Guidelines?
- [X] I have read the [Contributing Guidelines](https://github.com/juspay/hyperswitch/blob/main/docs/CONTRIBUTING.md)
### Are you willing to submit a PR?
Yes, I am willing to submit a PR!
|
diff --git a/crates/diesel_models/src/business_profile.rs b/crates/diesel_models/src/business_profile.rs
index bb4aa21cda6..cf873d4b61f 100644
--- a/crates/diesel_models/src/business_profile.rs
+++ b/crates/diesel_models/src/business_profile.rs
@@ -251,7 +251,7 @@ pub struct BusinessProfile {
// pub order_fulfillment_time_origin: Option<OrderFulfillmentTimeOrigin>,
pub frm_routing_algorithm_id: Option<String>,
pub payout_routing_algorithm_id: Option<String>,
- // pub default_fallback_routing: Option<pii::SecretSerdeValue>,
+ pub default_fallback_routing: Option<pii::SecretSerdeValue>,
}
#[cfg(all(feature = "v2", feature = "business_profile_v2"))]
@@ -289,7 +289,7 @@ pub struct BusinessProfileNew {
// pub order_fulfillment_time_origin: Option<OrderFulfillmentTimeOrigin>,
pub frm_routing_algorithm_id: Option<String>,
pub payout_routing_algorithm_id: Option<String>,
- // pub default_fallback_routing: Option<pii::SecretSerdeValue>,
+ pub default_fallback_routing: Option<pii::SecretSerdeValue>,
}
#[cfg(all(feature = "v2", feature = "business_profile_v2"))]
@@ -324,7 +324,7 @@ pub struct BusinessProfileUpdateInternal {
// pub order_fulfillment_time_origin: Option<OrderFulfillmentTimeOrigin>,
pub frm_routing_algorithm_id: Option<String>,
pub payout_routing_algorithm_id: Option<String>,
- // pub default_fallback_routing: Option<pii::SecretSerdeValue>,
+ pub default_fallback_routing: Option<pii::SecretSerdeValue>,
}
#[cfg(all(feature = "v2", feature = "business_profile_v2"))]
@@ -358,7 +358,7 @@ impl BusinessProfileUpdateInternal {
// order_fulfillment_time_origin,
frm_routing_algorithm_id,
payout_routing_algorithm_id,
- // default_fallback_routing,
+ default_fallback_routing,
} = self;
BusinessProfile {
profile_id: source.profile_id,
@@ -407,7 +407,7 @@ impl BusinessProfileUpdateInternal {
frm_routing_algorithm_id: frm_routing_algorithm_id.or(source.frm_routing_algorithm_id),
payout_routing_algorithm_id: payout_routing_algorithm_id
.or(source.payout_routing_algorithm_id),
- // default_fallback_routing: default_fallback_routing.or(source.default_fallback_routing),
+ default_fallback_routing: default_fallback_routing.or(source.default_fallback_routing),
}
}
}
@@ -451,7 +451,7 @@ impl From<BusinessProfileNew> for BusinessProfile {
// order_fulfillment_time_origin: new.order_fulfillment_time_origin,
frm_routing_algorithm_id: new.frm_routing_algorithm_id,
payout_routing_algorithm_id: new.payout_routing_algorithm_id,
- // default_fallback_routing: new.default_fallback_routing,
+ default_fallback_routing: new.default_fallback_routing,
}
}
}
diff --git a/crates/diesel_models/src/schema_v2.rs b/crates/diesel_models/src/schema_v2.rs
index b5a4ff384ad..e4ae651f72d 100644
--- a/crates/diesel_models/src/schema_v2.rs
+++ b/crates/diesel_models/src/schema_v2.rs
@@ -208,6 +208,7 @@ diesel::table! {
frm_routing_algorithm_id -> Nullable<Varchar>,
#[max_length = 64]
payout_routing_algorithm_id -> Nullable<Varchar>,
+ default_fallback_routing -> Nullable<Jsonb>,
}
}
diff --git a/crates/hyperswitch_domain_models/src/business_profile.rs b/crates/hyperswitch_domain_models/src/business_profile.rs
index dcc6a88c824..fa9af562cf3 100644
--- a/crates/hyperswitch_domain_models/src/business_profile.rs
+++ b/crates/hyperswitch_domain_models/src/business_profile.rs
@@ -439,7 +439,7 @@ pub struct BusinessProfile {
// pub order_fulfillment_time_origin: Option<OrderFulfillmentTimeOrigin>,
pub frm_routing_algorithm_id: Option<String>,
pub payout_routing_algorithm_id: Option<String>,
- // pub default_fallback_routing: Option<pii::SecretSerdeValue>,
+ pub default_fallback_routing: Option<pii::SecretSerdeValue>,
}
#[cfg(all(feature = "v2", feature = "business_profile_v2"))]
@@ -470,7 +470,7 @@ pub struct BusinessProfileGeneralUpdate {
// pub order_fulfillment_time_origin: Option<OrderFulfillmentTimeOrigin>,
pub frm_routing_algorithm_id: Option<String>,
pub payout_routing_algorithm_id: Option<String>,
- // pub default_fallback_routing: Option<pii::SecretSerdeValue>,
+ pub default_fallback_routing: Option<pii::SecretSerdeValue>,
}
#[cfg(all(feature = "v2", feature = "business_profile_v2"))]
@@ -481,6 +481,9 @@ pub enum BusinessProfileUpdate {
routing_algorithm_id: Option<String>,
payout_routing_algorithm_id: Option<String>,
},
+ DefaultRoutingFallbackUpdate {
+ default_fallback_routing: Option<pii::SecretSerdeValue>,
+ },
ExtendedCardInfoUpdate {
is_extended_card_info_enabled: Option<bool>,
},
@@ -522,7 +525,7 @@ impl From<BusinessProfileUpdate> for BusinessProfileUpdateInternal {
// order_fulfillment_time_origin,
frm_routing_algorithm_id,
payout_routing_algorithm_id,
- // default_fallback_routing,
+ default_fallback_routing,
} = *update;
Self {
profile_name,
@@ -553,7 +556,7 @@ impl From<BusinessProfileUpdate> for BusinessProfileUpdateInternal {
// order_fulfillment_time_origin,
frm_routing_algorithm_id,
payout_routing_algorithm_id,
- // default_fallback_routing,
+ default_fallback_routing,
}
}
BusinessProfileUpdate::RoutingAlgorithmUpdate {
@@ -587,7 +590,7 @@ impl From<BusinessProfileUpdate> for BusinessProfileUpdateInternal {
// order_fulfillment_time_origin: None,
frm_routing_algorithm_id: None,
payout_routing_algorithm_id,
- // default_fallback_routing: None,
+ default_fallback_routing: None,
},
BusinessProfileUpdate::ExtendedCardInfoUpdate {
is_extended_card_info_enabled,
@@ -619,7 +622,7 @@ impl From<BusinessProfileUpdate> for BusinessProfileUpdateInternal {
// order_fulfillment_time: None,
// order_fulfillment_time_origin: None,
frm_routing_algorithm_id: None,
- // default_fallback_routing: None,
+ default_fallback_routing: None,
},
BusinessProfileUpdate::ConnectorAgnosticMitUpdate {
is_connector_agnostic_mit_enabled,
@@ -651,7 +654,39 @@ impl From<BusinessProfileUpdate> for BusinessProfileUpdateInternal {
// order_fulfillment_time: None,
// order_fulfillment_time_origin: None,
frm_routing_algorithm_id: None,
- // default_fallback_routing: None,
+ default_fallback_routing: None,
+ },
+ BusinessProfileUpdate::DefaultRoutingFallbackUpdate {
+ default_fallback_routing,
+ } => Self {
+ profile_name: None,
+ modified_at: now,
+ return_url: None,
+ enable_payment_response_hash: None,
+ payment_response_hash_key: None,
+ redirect_to_merchant_with_http_post: None,
+ webhook_details: None,
+ metadata: None,
+ is_recon_enabled: None,
+ applepay_verified_domains: None,
+ payment_link_config: None,
+ session_expiry: None,
+ authentication_connector_details: None,
+ payout_link_config: None,
+ is_extended_card_info_enabled: None,
+ extended_card_info_config: None,
+ is_connector_agnostic_mit_enabled: None,
+ use_billing_as_payment_method_billing: None,
+ collect_shipping_details_from_wallet_connector: None,
+ collect_billing_details_from_wallet_connector: None,
+ outgoing_webhook_custom_http_headers: None,
+ routing_algorithm_id: None,
+ payout_routing_algorithm_id: None,
+ intent_fulfillment_time: None,
+ // order_fulfillment_time: None,
+ // order_fulfillment_time_origin: None,
+ frm_routing_algorithm_id: None,
+ default_fallback_routing,
},
}
}
@@ -699,7 +734,7 @@ impl super::behaviour::Conversion for BusinessProfile {
// order_fulfillment_time: self.order_fulfillment_time,
// order_fulfillment_time_origin: self.order_fulfillment_time_origin,
frm_routing_algorithm_id: self.frm_routing_algorithm_id,
- // default_fallback_routing: self.default_fallback_routing,
+ default_fallback_routing: self.default_fallback_routing,
})
}
@@ -760,7 +795,7 @@ impl super::behaviour::Conversion for BusinessProfile {
// order_fulfillment_time_origin: item.order_fulfillment_time_origin,
frm_routing_algorithm_id: item.frm_routing_algorithm_id,
payout_routing_algorithm_id: item.payout_routing_algorithm_id,
- // default_fallback_routing: item.default_fallback_routing,
+ default_fallback_routing: item.default_fallback_routing,
})
}
.await
@@ -805,7 +840,7 @@ impl super::behaviour::Conversion for BusinessProfile {
// order_fulfillment_time_origin: self.order_fulfillment_time_origin,
frm_routing_algorithm_id: self.frm_routing_algorithm_id,
payout_routing_algorithm_id: self.payout_routing_algorithm_id,
- // default_fallback_routing: self.default_fallback_routing,
+ default_fallback_routing: self.default_fallback_routing,
})
}
}
diff --git a/crates/router/src/core/admin.rs b/crates/router/src/core/admin.rs
index 2b3360f35da..89cd956c995 100644
--- a/crates/router/src/core/admin.rs
+++ b/crates/router/src/core/admin.rs
@@ -3718,6 +3718,62 @@ impl BusinessProfileWrapper {
),
}
}
+ pub fn get_default_fallback_list_of_connector_under_profile(
+ &self,
+ ) -> RouterResult<Vec<routing_types::RoutableConnectorChoice>> {
+ use common_utils::ext_traits::OptionExt;
+ use masking::ExposeOptionInterface;
+
+ self.profile
+ .default_fallback_routing
+ .clone()
+ .expose_option()
+ .parse_value::<Vec<routing_types::RoutableConnectorChoice>>(
+ "Vec<RoutableConnectorChoice>",
+ )
+ .change_context(errors::ApiErrorResponse::InternalServerError)
+ .attach_printable("Merchant default config has invalid structure")
+ }
+ pub fn get_default_routing_configs_from_profile(
+ &self,
+ ) -> RouterResult<routing_types::ProfileDefaultRoutingConfig> {
+ let profile_id = self.profile.profile_id.clone();
+ let connectors = self.get_default_fallback_list_of_connector_under_profile()?;
+
+ Ok(routing_types::ProfileDefaultRoutingConfig {
+ profile_id,
+ connectors,
+ })
+ }
+
+ pub async fn update_default_routing_for_profile(
+ self,
+ db: &dyn StorageInterface,
+ updated_config: &Vec<routing_types::RoutableConnectorChoice>,
+ key_manager_state: &KeyManagerState,
+ merchant_key_store: &domain::MerchantKeyStore,
+ ) -> RouterResult<()> {
+ let default_fallback_routing = Secret::from(
+ updated_config
+ .encode_to_value()
+ .change_context(errors::ApiErrorResponse::InternalServerError)
+ .attach_printable("Failed to convert routing ref to value")?,
+ );
+ let business_profile_update = domain::BusinessProfileUpdate::DefaultRoutingFallbackUpdate {
+ default_fallback_routing: Some(default_fallback_routing),
+ };
+
+ db.update_business_profile_by_profile_id(
+ key_manager_state,
+ merchant_key_store,
+ self.profile,
+ business_profile_update,
+ )
+ .await
+ .change_context(errors::ApiErrorResponse::InternalServerError)
+ .attach_printable("Failed to update routing algorithm ref in business profile")?;
+ Ok(())
+ }
}
pub async fn extended_card_info_toggle(
diff --git a/crates/router/src/core/routing.rs b/crates/router/src/core/routing.rs
index 9d819f8df9f..0c50a01e36d 100644
--- a/crates/router/src/core/routing.rs
+++ b/crates/router/src/core/routing.rs
@@ -640,7 +640,90 @@ pub async fn unlink_routing_config(
}
}
-//feature update
+#[cfg(all(
+ feature = "v2",
+ feature = "routing_v2",
+ feature = "business_profile_v2"
+))]
+pub async fn update_default_fallback_routing(
+ state: SessionState,
+ merchant_account: domain::MerchantAccount,
+ key_store: domain::MerchantKeyStore,
+ profile_id: String,
+ updated_list_of_connectors: Vec<routing_types::RoutableConnectorChoice>,
+) -> RouterResponse<Vec<routing_types::RoutableConnectorChoice>> {
+ metrics::ROUTING_UPDATE_CONFIG.add(&metrics::CONTEXT, 1, &[]);
+ let db = state.store.as_ref();
+ let key_manager_state = &(&state).into();
+ let profile = core_utils::validate_and_get_business_profile(
+ db,
+ key_manager_state,
+ &key_store,
+ Some(&profile_id),
+ merchant_account.get_id(),
+ )
+ .await?
+ .get_required_value("BusinessProfile")?;
+ let profile_wrapper = admin::BusinessProfileWrapper::new(profile);
+ let default_list_of_connectors =
+ profile_wrapper.get_default_fallback_list_of_connector_under_profile()?;
+
+ utils::when(
+ default_list_of_connectors.len() != updated_list_of_connectors.len(),
+ || {
+ Err(errors::ApiErrorResponse::PreconditionFailed {
+ message: "current config and updated config have different lengths".to_string(),
+ })
+ },
+ )?;
+
+ let existing_set_of_default_connectors: FxHashSet<String> = FxHashSet::from_iter(
+ default_list_of_connectors
+ .iter()
+ .map(|conn_choice| conn_choice.to_string()),
+ );
+ let updated_set_of_default_connectors: FxHashSet<String> = FxHashSet::from_iter(
+ updated_list_of_connectors
+ .iter()
+ .map(|conn_choice| conn_choice.to_string()),
+ );
+
+ let symmetric_diff_between_existing_and_updated_connectors: Vec<String> =
+ existing_set_of_default_connectors
+ .symmetric_difference(&updated_set_of_default_connectors)
+ .cloned()
+ .collect();
+
+ utils::when(
+ !symmetric_diff_between_existing_and_updated_connectors.is_empty(),
+ || {
+ Err(errors::ApiErrorResponse::InvalidRequestData {
+ message: format!(
+ "connector mismatch between old and new configs ({})",
+ symmetric_diff_between_existing_and_updated_connectors.join(", ")
+ ),
+ })
+ },
+ )?;
+ profile_wrapper
+ .update_default_routing_for_profile(
+ db,
+ &updated_list_of_connectors,
+ key_manager_state,
+ &key_store,
+ )
+ .await?;
+
+ metrics::ROUTING_UPDATE_CONFIG_SUCCESS_RESPONSE.add(&metrics::CONTEXT, 1, &[]);
+ Ok(service_api::ApplicationResponse::Json(
+ updated_list_of_connectors,
+ ))
+}
+
+#[cfg(all(
+ any(feature = "v1", feature = "v2"),
+ not(any(feature = "routing_v2", feature = "business_profile_v2"))
+))]
pub async fn update_default_routing_config(
state: SessionState,
merchant_account: domain::MerchantAccount,
@@ -693,6 +776,42 @@ pub async fn update_default_routing_config(
Ok(service_api::ApplicationResponse::Json(updated_config))
}
+#[cfg(all(
+ feature = "v2",
+ feature = "routing_v2",
+ feature = "business_profile_v2"
+))]
+pub async fn retrieve_default_fallback_algorithm_for_profile(
+ state: SessionState,
+ merchant_account: domain::MerchantAccount,
+ key_store: domain::MerchantKeyStore,
+ profile_id: String,
+) -> RouterResponse<Vec<routing_types::RoutableConnectorChoice>> {
+ metrics::ROUTING_RETRIEVE_DEFAULT_CONFIG.add(&metrics::CONTEXT, 1, &[]);
+ let db = state.store.as_ref();
+ let key_manager_state = &(&state).into();
+ let profile = core_utils::validate_and_get_business_profile(
+ db,
+ key_manager_state,
+ &key_store,
+ Some(&profile_id),
+ merchant_account.get_id(),
+ )
+ .await?
+ .get_required_value("BusinessProfile")?;
+
+ let connectors_choice = admin::BusinessProfileWrapper::new(profile)
+ .get_default_fallback_list_of_connector_under_profile()?;
+
+ metrics::ROUTING_RETRIEVE_DEFAULT_CONFIG_SUCCESS_RESPONSE.add(&metrics::CONTEXT, 1, &[]);
+ Ok(service_api::ApplicationResponse::Json(connectors_choice))
+}
+
+#[cfg(all(
+ any(feature = "v1", feature = "v2"),
+ not(any(feature = "routing_v2", feature = "business_profile_v2"))
+))]
+
pub async fn retrieve_default_routing_config(
state: SessionState,
merchant_account: domain::MerchantAccount,
@@ -712,7 +831,6 @@ pub async fn retrieve_default_routing_config(
service_api::ApplicationResponse::Json(conn_choice)
})
}
-
#[cfg(all(
feature = "v2",
feature = "routing_v2",
diff --git a/crates/router/src/routes/app.rs b/crates/router/src/routes/app.rs
index a6ce8c568b1..614774ebb04 100644
--- a/crates/router/src/routes/app.rs
+++ b/crates/router/src/routes/app.rs
@@ -1469,21 +1469,8 @@ impl BusinessProfile {
web::scope("/{profile_id}")
.service(
web::resource("/fallback_routing")
- .route(web::get().to(|state, req| {
- routing::routing_retrieve_default_config(
- state,
- req,
- &TransactionType::Payment,
- )
- }))
- .route(web::post().to(|state, req, payload| {
- routing::routing_update_default_config(
- state,
- req,
- payload,
- &TransactionType::Payment,
- )
- })),
+ .route(web::get().to(routing::routing_retrieve_default_config))
+ .route(web::post().to(routing::routing_update_default_config)),
)
.service(
web::resource("/activate_routing_algorithm").route(web::patch().to(
diff --git a/crates/router/src/routes/routing.rs b/crates/router/src/routes/routing.rs
index 485a55baa50..e6266f148f1 100644
--- a/crates/router/src/routes/routing.rs
+++ b/crates/router/src/routes/routing.rs
@@ -280,7 +280,55 @@ pub async fn routing_unlink_config(
.await
}
-#[cfg(feature = "olap")]
+#[cfg(all(
+ feature = "olap",
+ feature = "v2",
+ feature = "routing_v2",
+ feature = "business_profile_v2"
+))]
+#[instrument(skip_all)]
+pub async fn routing_update_default_config(
+ state: web::Data<AppState>,
+ req: HttpRequest,
+ path: web::Path<String>,
+ 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.merchant_account,
+ auth.key_store,
+ wrapper.profile_id,
+ wrapper.updated_config,
+ )
+ },
+ #[cfg(not(feature = "release"))]
+ auth::auth_type(
+ &auth::HeaderAuth(auth::ApiKeyAuth),
+ &auth::JWTAuth(Permission::RoutingWrite),
+ req.headers(),
+ ),
+ #[cfg(feature = "release")]
+ &auth::JWTAuth(Permission::RoutingWrite),
+ api_locking::LockAction::NotApplicable,
+ ))
+ .await
+}
+
+#[cfg(all(
+ feature = "olap",
+ any(feature = "v1", feature = "v2"),
+ not(any(feature = "routing_v2", feature = "business_profile_v2"))
+))]
#[instrument(skip_all)]
pub async fn routing_update_default_config(
state: web::Data<AppState>,
@@ -314,7 +362,49 @@ pub async fn routing_update_default_config(
.await
}
-#[cfg(feature = "olap")]
+#[cfg(all(
+ feature = "olap",
+ feature = "v2",
+ feature = "routing_v2",
+ feature = "business_profile_v2"
+))]
+#[instrument(skip_all)]
+pub async fn routing_retrieve_default_config(
+ state: web::Data<AppState>,
+ req: HttpRequest,
+ path: web::Path<String>,
+) -> impl Responder {
+ Box::pin(oss_api::server_wrap(
+ Flow::RoutingRetrieveDefaultConfig,
+ state,
+ &req,
+ path.into_inner(),
+ |state, auth: auth::AuthenticationData, profile_id, _| {
+ routing::retrieve_default_fallback_algorithm_for_profile(
+ state,
+ auth.merchant_account,
+ auth.key_store,
+ profile_id,
+ )
+ },
+ #[cfg(not(feature = "release"))]
+ auth::auth_type(
+ &auth::HeaderAuth(auth::ApiKeyAuth),
+ &auth::JWTAuth(Permission::RoutingRead),
+ req.headers(),
+ ),
+ #[cfg(feature = "release")]
+ &auth::JWTAuth(Permission::RoutingRead),
+ api_locking::LockAction::NotApplicable,
+ ))
+ .await
+}
+
+#[cfg(all(
+ feature = "olap",
+ any(feature = "v1", feature = "v2"),
+ not(any(feature = "routing_v2", feature = "business_profile_v2"))
+))]
#[instrument(skip_all)]
pub async fn routing_retrieve_default_config(
state: web::Data<AppState>,
diff --git a/v2_migrations/2024-07-31-100300_business_profile_add_v2_columns_drop_v1_columns/down.sql b/v2_migrations/2024-07-31-100300_business_profile_add_v2_columns_drop_v1_columns/down.sql
index 3d35becdfab..94c02697c50 100644
--- a/v2_migrations/2024-07-31-100300_business_profile_add_v2_columns_drop_v1_columns/down.sql
+++ b/v2_migrations/2024-07-31-100300_business_profile_add_v2_columns_drop_v1_columns/down.sql
@@ -1,18 +1,22 @@
-- This adds back dropped columns in `up.sql`.
-- However, if the old columns were dropped, then we won't have data previously
-- stored in these columns.
-ALTER TABLE business_profile
- ADD COLUMN routing_algorithm JSON DEFAULT NULL,
+ALTER TABLE
+ business_profile
+ADD
+ COLUMN routing_algorithm JSON DEFAULT NULL,
-- ADD COLUMN intent_fulfillment_time BIGINT DEFAULT NULL,
- ADD COLUMN frm_routing_algorithm JSONB DEFAULT NULL,
- ADD COLUMN payout_routing_algorithm JSONB DEFAULT NULL;
+ADD
+ COLUMN frm_routing_algorithm JSONB DEFAULT NULL,
+ADD
+ COLUMN payout_routing_algorithm JSONB DEFAULT NULL;
-ALTER TABLE business_profile
- DROP COLUMN routing_algorithm_id,
+ALTER TABLE
+ business_profile DROP COLUMN routing_algorithm_id,
-- DROP COLUMN order_fulfillment_time,
-- DROP COLUMN order_fulfillment_time_origin,
DROP COLUMN frm_routing_algorithm_id,
- DROP COLUMN payout_routing_algorithm_id;
- -- DROP COLUMN default_fallback_routing;
+ DROP COLUMN payout_routing_algorithm_id,
+ DROP COLUMN default_fallback_routing;
--- DROP TYPE "OrderFulfillmentTimeOrigin";
+-- DROP TYPE "OrderFulfillmentTimeOrigin";
\ No newline at end of file
diff --git a/v2_migrations/2024-07-31-100300_business_profile_add_v2_columns_drop_v1_columns/up.sql b/v2_migrations/2024-07-31-100300_business_profile_add_v2_columns_drop_v1_columns/up.sql
index 2b98bef00d4..d2275ad2362 100644
--- a/v2_migrations/2024-07-31-100300_business_profile_add_v2_columns_drop_v1_columns/up.sql
+++ b/v2_migrations/2024-07-31-100300_business_profile_add_v2_columns_drop_v1_columns/up.sql
@@ -1,17 +1,21 @@
-- CREATE TYPE "OrderFulfillmentTimeOrigin" AS ENUM ('create', 'confirm');
-
-ALTER TABLE business_profile
- ADD COLUMN routing_algorithm_id VARCHAR(64) DEFAULT NULL,
- -- ADD COLUMN order_fulfillment_time BIGINT DEFAULT NULL,
- -- ADD COLUMN order_fulfillment_time_origin "OrderFulfillmentTimeOrigin" DEFAULT NULL,
- ADD COLUMN frm_routing_algorithm_id VARCHAR(64) DEFAULT NULL,
- ADD COLUMN payout_routing_algorithm_id VARCHAR(64) DEFAULT NULL;
- -- ADD COLUMN default_fallback_routing JSONB DEFAULT NULL;
+ALTER TABLE
+ business_profile
+ADD
+ COLUMN routing_algorithm_id VARCHAR(64) DEFAULT NULL,
+ -- ADD COLUMN order_fulfillment_time BIGINT DEFAULT NULL,
+ -- ADD COLUMN order_fulfillment_time_origin "OrderFulfillmentTimeOrigin" DEFAULT NULL,
+ADD
+ COLUMN frm_routing_algorithm_id VARCHAR(64) DEFAULT NULL,
+ADD
+ COLUMN payout_routing_algorithm_id VARCHAR(64) DEFAULT NULL,
+ADD
+ COLUMN default_fallback_routing JSONB DEFAULT NULL;
-- Note: This query should not be run on higher environments as this leads to data loss.
-- The application will work fine even without these queries being run.
-ALTER TABLE business_profile
- DROP COLUMN routing_algorithm,
- -- DROP COLUMN intent_fulfillment_time,
- DROP COLUMN frm_routing_algorithm,
- DROP COLUMN payout_routing_algorithm;
+ALTER TABLE
+ business_profile DROP COLUMN routing_algorithm,
+ -- DROP COLUMN intent_fulfillment_time,
+ DROP COLUMN frm_routing_algorithm,
+ DROP COLUMN payout_routing_algorithm;
\ No newline at end of file
|
2024-08-12T08:42:20Z
|
## Type of Change
<!-- Put an `x` in the boxes that apply -->
- [ ] Bugfix
- [ ] New feature
- [ ] Enhancement
- [x] Refactoring
- [ ] Dependency updates
- [ ] Documentation
- [ ] CI/CD
## Description
Refactor fallback routing apis for v2. Refactor the fallback apis for routing to retrieve and update the fallback routing algorithms.
### Additional Changes
- [ ] This PR modifies the API contract
- [ ] This PR modifies the database schema
- [ ] This PR modifies application configuration/environment variables
<!--
Provide links to the files with corresponding changes.
Following are the paths where you can find config files:
1. `config`
2. `crates/router/src/configs`
3. `loadtest/config`
-->
## Motivation and Context
<!--
Why is this change required? What problem does it solve?
If it fixes an open issue, please link to the issue here.
If you don't have an issue, we'd recommend starting with one first so the PR
can focus on the implementation (unless it is an obvious bug or documentation fix
that will have little conversation).
-->
## How did you test it?
- To retrieve the default fallback config
```
curl --location 'http://localhost:8080/v2/profile/pro_VirB3AxB3qItFTnLsuA2/fallback_routing' \
--header 'Authorization: Bearer eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJ1c2VyX2lkIjoiYWQyMTRiZjUtMjgyYS00OWRiLWIzMjEtZGM3ZTExODRlNTliIiwibWVyY2hhbnRfaWQiOiJzZW5kZXJfbmV0Iiwicm9sZV9pZCI6ImludGVybmFsX3ZpZXdfb25seSIsImV4cCI6MTcyMTMxMDI0NCwib3JnX2lkIjoib3JnX2JmQXZqZWZRMG5oTjVJVm95VTZGIn0.hCH_Pd0d2d08ESOUy1PMGfyuh5TzXQLfi0wBIev1O6U' \
--data ''
```
- To update the default fallback config
```
curl --location 'http://localhost:8080/v2/profile/pro_VirB3AxB3qItFTnLsuA2/fallback_routing' \
--header 'Content-Type: application/json' \
--header 'api-key: dev_jsssWAg0XyxGK0ycPunkFjlItYNs30X1IVOr1MIF7lwrDQgBBk7npwdkZB4t7EQd' \
--data '["checkout", "stripe" ,"adyen", "authorizedotnet"]'
```
## Checklist
<!-- Put an `x` in the boxes that apply -->
- [ ] I formatted the code `cargo +nightly fmt --all`
- [ ] I addressed lints thrown by `cargo clippy`
- [ ] I reviewed the submitted code
- [ ] I added unit tests for my changes where possible
|
ed13ecac04f82b5c69b11636c1e355e7e17c60fd
|
|
juspay/hyperswitch
|
juspay__hyperswitch-5595
|
Bug: return missing required filed error when a domain is missing during apple pay session call
Reference issue for the feature https://github.com/juspay/hyperswitch/issues/5354
As described in the above issue the apple pay domain needs to be fetched dynamically by the sdk and to be sent in the session request header. When sdk fails to send which is not expected to happen, we try to get the domain that merchant has configured in the merchant connector account. Now ff merchant has not configured a domain it will result in an `InternalServerError` instead it should be missing required filed.
|
diff --git a/crates/router/src/core/payments/flows/session_flow.rs b/crates/router/src/core/payments/flows/session_flow.rs
index cdd8452fdb3..4a1d57cda34 100644
--- a/crates/router/src/core/payments/flows/session_flow.rs
+++ b/crates/router/src/core/payments/flows/session_flow.rs
@@ -411,10 +411,8 @@ async fn create_applepay_session_token(
"Retry apple pay session call with the merchant configured domain {error:?}"
);
let merchant_configured_domain = merchant_configured_domain_optional
- .ok_or(errors::ApiErrorResponse::InternalServerError)
- .attach_printable(
- "Failed to get initiative_context for apple pay session call retry",
- )?;
+ .get_required_value("apple pay domain")
+ .attach_printable("Failed to get domain for apple pay session call")?;
let apple_pay_retry_session_request =
payment_types::ApplepaySessionRequest {
initiative_context: merchant_configured_domain,
@@ -496,15 +494,16 @@ fn get_session_request_for_manual_apple_pay(
session_token_data: payment_types::SessionTokenInfo,
merchant_domain: Option<String>,
) -> RouterResult<payment_types::ApplepaySessionRequest> {
- let initiative_context = session_token_data
- .initiative_context
- .ok_or(errors::ApiErrorResponse::InternalServerError)
- .attach_printable("Failed to get initiative_context for apple pay session call")?;
+ let initiative_context = merchant_domain
+ .or_else(|| session_token_data.initiative_context.clone())
+ .get_required_value("apple pay domain")
+ .attach_printable("Failed to get domain for apple pay session call")?;
+
Ok(payment_types::ApplepaySessionRequest {
merchant_identifier: session_token_data.merchant_identifier.clone(),
display_name: session_token_data.display_name.clone(),
initiative: session_token_data.initiative.to_string(),
- initiative_context: merchant_domain.unwrap_or(initiative_context),
+ initiative_context,
})
}
|
2024-08-12T13:42:44Z
|
## Type of Change
<!-- Put an `x` in the boxes that apply -->
- [x] Bugfix
- [ ] New feature
- [ ] Enhancement
- [ ] Refactoring
- [ ] Dependency updates
- [ ] Documentation
- [ ] CI/CD
## Description
<!-- Describe your changes in detail -->
Reference issue for the feature https://github.com/juspay/hyperswitch/issues/5354
As described in the above issue the apple pay domain needs to be fetched dynamically by the sdk and to be sent in the session request header. When sdk fails to send which is not expected to happen, we try to get the domain that merchant has configured in the merchant connector account. Now ff merchant has not configured a domain it will result in an `InternalServerError` instead it should be missing required filed.
### Additional Changes
- [ ] This PR modifies the API contract
- [ ] This PR modifies the database schema
- [ ] This PR modifies application configuration/environment variables
<!--
Provide links to the files with corresponding changes.
Following are the paths where you can find config files:
1. `config`
2. `crates/router/src/configs`
3. `loadtest/config`
-->
## Motivation and Context
<!--
Why is this change required? What problem does it solve?
If it fixes an open issue, please link to the issue here.
If you don't have an issue, we'd recommend starting with one first so the PR
can focus on the implementation (unless it is an obvious bug or documentation fix
that will have little conversation).
-->
## How did you test it?
<!--
Did you write an integration/unit/API test to verify the code changes?
Or did you test this change manually (provide relevant screenshots)?
-->
-> Create mca with apple pay enabled and metadata not containing apple pay domain
-> Create a payment with confirm false
-> Make a session call
- session call without passing domain in header
```
curl --location 'http://localhost:8080/payments/session_tokens' \
--header 'Content-Type: application/json' \
--header 'api-key: pk_dev_baf0b480b51a492cb3aa58c7fae2dcc4' \
--data '{
"payment_id": "pay_XjjNQMVggZqOVVE58zZ1",
"wallets": [],
"client_secret": "pay_XjjNQMVggZqOVVE58zZ1_secret_2qs22xiuLcUIyW6jHrTc"
}'
```
```
{
"payment_id": "pay_XjjNQMVggZqOVVE58zZ1",
"client_secret": "pay_XjjNQMVggZqOVVE58zZ1_secret_2qs22xiuLcUIyW6jHrTc",
"session_token": [
{
"wallet_name": "google_pay",
"merchant_info": {
"merchant_name": "Stripe"
},
"shipping_address_required": false,
"email_required": false,
"shipping_address_parameters": {
"phone_number_required": false
},
"allowed_payment_methods": [
{
"type": "CARD",
"parameters": {
"allowed_auth_methods": [
"PAN_ONLY",
"CRYPTOGRAM_3DS"
],
"allowed_card_networks": [
"AMEX",
"DISCOVER",
"INTERAC",
"JCB",
"MASTERCARD",
"VISA"
],
"billing_address_required": false
},
"tokenization_specification": {
"type": "PAYMENT_GATEWAY",
"parameters": {
"gateway": "stripe",
"stripe:version": "2018-10-31",
"stripe:publishableKey": "pk_test_51Msk2GAGHc77EJXX78h549SX2uaOnEkUYqBfjcoD05PIpAnDkYxMn8nQ4d19im85NQuX4Z6WDyHaUw2fFTPBWsIY00Wa7oNerO"
}
}
}
],
"transaction_info": {
"country_code": "US",
"currency_code": "USD",
"total_price_status": "Final",
"total_price": "1000.00"
},
"delayed_session_token": false,
"connector": "stripe",
"sdk_next_action": {
"next_action": "confirm"
},
"secrets": null
}
]
}
```
<img width="1648" alt="image" src="https://github.com/user-attachments/assets/7b154ce7-b1e2-4a4f-ad29-673ee853b376">
- session call when domain is passed in the header
```
curl --location 'http://localhost:8080/payments/session_tokens' \
--header 'Content-Type: application/json' \
--header 'x-merchant-domain: sdk-test-app.netlify.app' \
--header 'api-key: pk_dev_baf0b480b51a492cb3aa58c7fae2dcc4' \
--data '{
"payment_id": "pay_XjjNQMVggZqOVVE58zZ1",
"wallets": [],
"client_secret": "pay_XjjNQMVggZqOVVE58zZ1_secret_2qs22xiuLcUIyW6jHrTc"
}'
```
```
{
"payment_id": "pay_XjjNQMVggZqOVVE58zZ1",
"client_secret": "pay_XjjNQMVggZqOVVE58zZ1_secret_2qs22xiuLcUIyW6jHrTc",
"session_token": [
{
"wallet_name": "apple_pay",
"session_token_data": {
"epoch_timestamp": 1723470817764,
"expires_at": 1723474417764,
"merchant_session_identifier": "SSHED1FA8C99F8947C7A69F2729CF38BEAD_2101F68F6980DFE07DEFE987B1CAF2961766C119C8FDCBB33566B1A97F33C9C3",
"nonce": "704365e7",
"merchant_identifier": "76B79A8E91F4D365B0B636C8F75CB207D52532E82C2C085DE79D6D8135EF3813",
"domain_name": "sdk-test-app.netlify.app",
"display_name": "applepay",
"signature": "308006092a864886f70d010702a0803080020101310d300b0609608648016503040201308006092a864886f70d0107010000a080308203e330820388a003020102020816634c8b0e305717300a06082a8648ce3d040302307a312e302c06035504030c254170706c65204170706c69636174696f6e20496e746567726174696f6e204341202d20473331263024060355040b0c1d4170706c652043657274696669636174696f6e20417574686f7269747931133011060355040a0c0a4170706c6520496e632e310b3009060355040613025553301e170d3234303432393137343732375a170d3239303432383137343732365a305f3125302306035504030c1c6563632d736d702d62726f6b65722d7369676e5f5543342d50524f4431143012060355040b0c0b694f532053797374656d7331133011060355040a0c0a4170706c6520496e632e310b30090603550406130255533059301306072a8648ce3d020106082a8648ce3d03010703420004c21577edebd6c7b2218f68dd7090a1218dc7b0bd6f2c283d846095d94af4a5411b83420ed811f3407e83331f1c54c3f7eb3220d6bad5d4eff49289893e7c0f13a38202113082020d300c0603551d130101ff04023000301f0603551d2304183016801423f249c44f93e4ef27e6c4f6286c3fa2bbfd2e4b304506082b0601050507010104393037303506082b060105050730018629687474703a2f2f6f6373702e6170706c652e636f6d2f6f63737030342d6170706c65616963613330323082011d0603551d2004820114308201103082010c06092a864886f7636405013081fe3081c306082b060105050702023081b60c81b352656c69616e6365206f6e207468697320636572746966696361746520627920616e7920706172747920617373756d657320616363657074616e6365206f6620746865207468656e206170706c696361626c65207374616e64617264207465726d7320616e6420636f6e646974696f6e73206f66207573652c20636572746966696361746520706f6c69637920616e642063657274696669636174696f6e2070726163746963652073746174656d656e74732e303606082b06010505070201162a687474703a2f2f7777772e6170706c652e636f6d2f6365727469666963617465617574686f726974792f30340603551d1f042d302b3029a027a0258623687474703a2f2f63726c2e6170706c652e636f6d2f6170706c6561696361332e63726c301d0603551d0e041604149457db6fd57481868989762f7e578507e79b5824300e0603551d0f0101ff040403020780300f06092a864886f76364061d04020500300a06082a8648ce3d0403020349003046022100c6f023cb2614bb303888a162983e1a93f1056f50fa78cdb9ba4ca241cc14e25e022100be3cd0dfd16247f6494475380e9d44c228a10890a3a1dc724b8b4cb8889818bc308202ee30820275a0030201020208496d2fbf3a98da97300a06082a8648ce3d0403023067311b301906035504030c124170706c6520526f6f74204341202d20473331263024060355040b0c1d4170706c652043657274696669636174696f6e20410b06092a864886f70d010701301c06092a864886f70d010905310f170d3234303831323133353333375a302806092a864886f70d010934311b3019300b0609608648016503040201a10a06082a8648ce3d040302302f06092a864886f70d0109043122042061fcb394a5ae46559a4ebd948019bddadd3f0bd590f66a3fc0ba4e90e8bb2532300a06082a8648ce3d0403020447304502200565aaf04f5fbb7da8d58fba8fd66a8d1f19f1227160d256b75e5d2c3a0e162f022100b17d0fac6b40c05f1bff0dce8b2079eb2cfb0eacfef56d2d31bbf23ffcf2a58d000000000000",
"operational_analytics_identifier": "applepay:76B79A8E91F4D365B0B636C8F75CB207D52532E82C2C085DE79D6D8135EF3813",
"retries": 0,
"psp_id": "76B79A8E91F4D365B0B636C8F75CB207D52532E82C2C085DE79D6D8135EF3813"
},
"payment_request_data": {
"country_code": "US",
"currency_code": "USD",
"total": {
"label": "applepay",
"type": "final",
"amount": "1000.00"
},
"merchant_capabilities": [
"supports3DS"
],
"supported_networks": [
"visa",
"masterCard",
"amex",
"discover"
],
"merchant_identifier": "m.checkout"
},
"connector": "stripe",
"delayed_session_token": false,
"sdk_next_action": {
"next_action": "confirm"
},
"connector_reference_id": null,
"connector_sdk_public_key": null,
"connector_merchant_id": null
},
{
"wallet_name": "google_pay",
"merchant_info": {
"merchant_name": "Stripe"
},
"shipping_address_required": false,
"email_required": false,
"shipping_address_parameters": {
"phone_number_required": false
},
"allowed_payment_methods": [
{
"type": "CARD",
"parameters": {
"allowed_auth_methods": [
"PAN_ONLY",
"CRYPTOGRAM_3DS"
],
"allowed_card_networks": [
"AMEX",
"DISCOVER",
"INTERAC",
"JCB",
"MASTERCARD",
"VISA"
],
"billing_address_required": false
},
"tokenization_specification": {
"type": "PAYMENT_GATEWAY",
"parameters": {
"gateway": "stripe",
"stripe:version": "2018-10-31",
"stripe:publishableKey": "pk_test_51MskkYxMn8nQ4d19im85NQuX4Z6WDyHaUw2fFTPBWsIY00Wa7oNerO"
}
}
}
],
"transaction_info": {
"country_code": "US",
"currency_code": "USD",
"total_price_status": "Final",
"total_price": "1000.00"
},
"delayed_session_token": false,
"connector": "stripe",
"sdk_next_action": {
"next_action": "confirm"
},
"secrets": null
}
]
}
```
## Checklist
<!-- Put an `x` in the boxes that apply -->
- [x] I formatted the code `cargo +nightly fmt --all`
- [x] I addressed lints thrown by `cargo clippy`
- [x] I reviewed the submitted code
- [ ] I added unit tests for my changes where possible
|
c8943eb289664093f2a4d515bfacd804f86cd20a
|
|
juspay/hyperswitch
|
juspay__hyperswitch-5629
|
Bug: [FEATURE] [COINBASE] Move connector code to crate hyperswitch_connectors
### Feature Description
Connector code for `coinbase` needs to be moved from crate `router` to new crate `hyperswitch_connectors`
### Possible Implementation
Connector code for `coinbase` needs to be moved from crate `router` to new crate `hyperswitch_connectors`
### Have you spent some time checking if this feature request has been raised before?
- [X] I checked and didn't find a similar issue
### Have you read the Contributing Guidelines?
- [X] I have read the [Contributing Guidelines](https://github.com/juspay/hyperswitch/blob/main/docs/CONTRIBUTING.md)
### Are you willing to submit a PR?
Yes, I am willing to submit a PR!
|
diff --git a/crates/hyperswitch_connectors/src/connectors.rs b/crates/hyperswitch_connectors/src/connectors.rs
index 48c50936d60..f057b7d4a33 100644
--- a/crates/hyperswitch_connectors/src/connectors.rs
+++ b/crates/hyperswitch_connectors/src/connectors.rs
@@ -1,5 +1,8 @@
pub mod bambora;
pub mod bitpay;
+pub mod cashtocode;
+pub mod coinbase;
+pub mod cryptopay;
pub mod deutschebank;
pub mod fiserv;
pub mod fiservemea;
@@ -18,8 +21,9 @@ pub mod volt;
pub mod worldline;
pub use self::{
- bambora::Bambora, bitpay::Bitpay, deutschebank::Deutschebank, fiserv::Fiserv,
- fiservemea::Fiservemea, fiuu::Fiuu, globepay::Globepay, helcim::Helcim, mollie::Mollie,
- nexixpay::Nexixpay, novalnet::Novalnet, powertranz::Powertranz, stax::Stax, taxjar::Taxjar,
- thunes::Thunes, tsys::Tsys, volt::Volt, worldline::Worldline,
+ bambora::Bambora, bitpay::Bitpay, cashtocode::Cashtocode, coinbase::Coinbase,
+ cryptopay::Cryptopay, deutschebank::Deutschebank, fiserv::Fiserv, fiservemea::Fiservemea,
+ fiuu::Fiuu, globepay::Globepay, helcim::Helcim, mollie::Mollie, nexixpay::Nexixpay,
+ novalnet::Novalnet, powertranz::Powertranz, stax::Stax, taxjar::Taxjar, thunes::Thunes,
+ tsys::Tsys, volt::Volt, worldline::Worldline,
};
diff --git a/crates/router/src/connector/cashtocode.rs b/crates/hyperswitch_connectors/src/connectors/cashtocode.rs
similarity index 67%
rename from crates/router/src/connector/cashtocode.rs
rename to crates/hyperswitch_connectors/src/connectors/cashtocode.rs
index 2155b80dd81..c72b63aebc0 100644
--- a/crates/router/src/connector/cashtocode.rs
+++ b/crates/hyperswitch_connectors/src/connectors/cashtocode.rs
@@ -1,33 +1,41 @@
pub mod transformers;
-
use base64::Engine;
+use common_enums::enums;
use common_utils::{
- request::RequestContent,
+ errors::CustomResult,
+ ext_traits::ByteSliceExt,
+ request::{Method, Request, RequestBuilder, RequestContent},
types::{AmountConvertor, FloatMajorUnit, FloatMajorUnitForConnector},
};
-use diesel_models::enums;
use error_stack::ResultExt;
-use masking::{PeekInterface, Secret};
-use transformers as cashtocode;
-
-use super::utils as connector_utils;
-use crate::{
- configs::settings::{self},
- core::errors::{self, CustomResult},
- events::connector_api_logs::ConnectorEvent,
- headers,
- services::{
- self,
- request::{self, Mask},
- ConnectorIntegration, ConnectorValidation,
+use hyperswitch_domain_models::{
+ api::ApplicationResponse,
+ router_data::{AccessToken, ErrorResponse, RouterData},
+ router_flow_types::{
+ access_token_auth::AccessTokenAuth,
+ payments::{Authorize, Capture, PSync, PaymentMethodToken, Session, SetupMandate, Void},
+ refunds::{Execute, RSync},
},
- types::{
- self,
- api::{self, ConnectorCommon, ConnectorCommonExt},
- storage, ErrorResponse, Response,
+ router_request_types::{
+ AccessTokenRequestData, PaymentMethodTokenizationData, PaymentsAuthorizeData,
+ PaymentsCancelData, PaymentsCaptureData, PaymentsSessionData, PaymentsSyncData,
+ RefundsData, SetupMandateRequestData,
},
- utils::{ByteSliceExt, BytesExt},
+ router_response_types::{PaymentsResponseData, RefundsResponseData},
+ types::{PaymentsAuthorizeRouterData, PaymentsSyncRouterData},
};
+use hyperswitch_interfaces::{
+ api::{self, ConnectorCommon, ConnectorCommonExt, ConnectorIntegration, ConnectorValidation},
+ configs::Connectors,
+ errors,
+ events::connector_api_logs::ConnectorEvent,
+ types::{PaymentsAuthorizeType, Response},
+ webhooks,
+};
+use masking::{Mask, PeekInterface, Secret};
+use transformers as cashtocode;
+
+use crate::{constants::headers, types::ResponseRouterData, utils};
#[derive(Clone)]
pub struct Cashtocode {
@@ -56,13 +64,13 @@ impl api::RefundExecute for Cashtocode {}
impl api::RefundSync for Cashtocode {}
fn get_b64_auth_cashtocode(
- payment_method_type: &Option<storage::enums::PaymentMethodType>,
+ payment_method_type: &Option<enums::PaymentMethodType>,
auth_type: &transformers::CashtocodeAuth,
-) -> CustomResult<Vec<(String, request::Maskable<String>)>, errors::ConnectorError> {
+) -> CustomResult<Vec<(String, masking::Maskable<String>)>, errors::ConnectorError> {
fn construct_basic_auth(
username: Option<Secret<String>>,
password: Option<Secret<String>>,
- ) -> Result<request::Maskable<String>, errors::ConnectorError> {
+ ) -> Result<masking::Maskable<String>, errors::ConnectorError> {
let username = username.ok_or(errors::ConnectorError::FailedToObtainAuthType)?;
let password = password.ok_or(errors::ConnectorError::FailedToObtainAuthType)?;
Ok(format!(
@@ -77,11 +85,11 @@ fn get_b64_auth_cashtocode(
}
let auth_header = match payment_method_type {
- Some(storage::enums::PaymentMethodType::ClassicReward) => construct_basic_auth(
+ Some(enums::PaymentMethodType::ClassicReward) => construct_basic_auth(
auth_type.username_classic.to_owned(),
auth_type.password_classic.to_owned(),
),
- Some(storage::enums::PaymentMethodType::Evoucher) => construct_basic_auth(
+ Some(enums::PaymentMethodType::Evoucher) => construct_basic_auth(
auth_type.username_evoucher.to_owned(),
auth_type.password_evoucher.to_owned(),
),
@@ -91,12 +99,8 @@ fn get_b64_auth_cashtocode(
Ok(vec![(headers::AUTHORIZATION.to_string(), auth_header)])
}
-impl
- ConnectorIntegration<
- api::PaymentMethodToken,
- types::PaymentMethodTokenizationData,
- types::PaymentsResponseData,
- > for Cashtocode
+impl ConnectorIntegration<PaymentMethodToken, PaymentMethodTokenizationData, PaymentsResponseData>
+ for Cashtocode
{
// Not Implemented (R)
}
@@ -115,7 +119,7 @@ impl ConnectorCommon for Cashtocode {
"application/json"
}
- fn base_url<'a>(&self, connectors: &'a settings::Connectors) -> &'a str {
+ fn base_url<'a>(&self, connectors: &'a Connectors) -> &'a str {
connectors.cashtocode.base_url.as_ref()
}
@@ -153,39 +157,26 @@ impl ConnectorValidation for Cashtocode {
match capture_method {
enums::CaptureMethod::Automatic | enums::CaptureMethod::Manual => Ok(()),
enums::CaptureMethod::ManualMultiple | enums::CaptureMethod::Scheduled => Err(
- connector_utils::construct_not_supported_error_report(capture_method, self.id()),
+ utils::construct_not_supported_error_report(capture_method, self.id()),
),
}
}
}
-impl ConnectorIntegration<api::Session, types::PaymentsSessionData, types::PaymentsResponseData>
- for Cashtocode
-{
+impl ConnectorIntegration<Session, PaymentsSessionData, PaymentsResponseData> for Cashtocode {
//TODO: implement sessions flow
}
-impl ConnectorIntegration<api::AccessTokenAuth, types::AccessTokenRequestData, types::AccessToken>
- for Cashtocode
-{
-}
+impl ConnectorIntegration<AccessTokenAuth, AccessTokenRequestData, AccessToken> for Cashtocode {}
-impl
- ConnectorIntegration<
- api::SetupMandate,
- types::SetupMandateRequestData,
- types::PaymentsResponseData,
- > for Cashtocode
+impl ConnectorIntegration<SetupMandate, SetupMandateRequestData, PaymentsResponseData>
+ for Cashtocode
{
fn build_request(
&self,
- _req: &types::RouterData<
- api::SetupMandate,
- types::SetupMandateRequestData,
- types::PaymentsResponseData,
- >,
- _connectors: &settings::Connectors,
- ) -> CustomResult<Option<services::Request>, errors::ConnectorError> {
+ _req: &RouterData<SetupMandate, SetupMandateRequestData, PaymentsResponseData>,
+ _connectors: &Connectors,
+ ) -> CustomResult<Option<Request>, errors::ConnectorError> {
Err(
errors::ConnectorError::NotImplemented("Setup Mandate flow for Cashtocode".to_string())
.into(),
@@ -193,17 +184,15 @@ impl
}
}
-impl ConnectorIntegration<api::Authorize, types::PaymentsAuthorizeData, types::PaymentsResponseData>
- for Cashtocode
-{
+impl ConnectorIntegration<Authorize, PaymentsAuthorizeData, PaymentsResponseData> for Cashtocode {
fn get_headers(
&self,
- req: &types::PaymentsAuthorizeRouterData,
- _connectors: &settings::Connectors,
- ) -> CustomResult<Vec<(String, request::Maskable<String>)>, errors::ConnectorError> {
+ req: &PaymentsAuthorizeRouterData,
+ _connectors: &Connectors,
+ ) -> CustomResult<Vec<(String, masking::Maskable<String>)>, errors::ConnectorError> {
let mut header = vec![(
headers::CONTENT_TYPE.to_string(),
- types::PaymentsAuthorizeType::get_content_type(self)
+ PaymentsAuthorizeType::get_content_type(self)
.to_owned()
.into(),
)];
@@ -225,8 +214,8 @@ impl ConnectorIntegration<api::Authorize, types::PaymentsAuthorizeData, types::P
fn get_url(
&self,
- _req: &types::PaymentsAuthorizeRouterData,
- connectors: &settings::Connectors,
+ _req: &PaymentsAuthorizeRouterData,
+ connectors: &Connectors,
) -> CustomResult<String, errors::ConnectorError> {
Ok(format!(
"{}/merchant/paytokens",
@@ -236,10 +225,10 @@ impl ConnectorIntegration<api::Authorize, types::PaymentsAuthorizeData, types::P
fn get_request_body(
&self,
- req: &types::PaymentsAuthorizeRouterData,
- _connectors: &settings::Connectors,
+ req: &PaymentsAuthorizeRouterData,
+ _connectors: &Connectors,
) -> CustomResult<RequestContent, errors::ConnectorError> {
- let amount = connector_utils::convert_amount(
+ let amount = utils::convert_amount(
self.amount_converter,
req.request.minor_amount,
req.request.currency,
@@ -250,20 +239,16 @@ impl ConnectorIntegration<api::Authorize, types::PaymentsAuthorizeData, types::P
fn build_request(
&self,
- req: &types::PaymentsAuthorizeRouterData,
- connectors: &settings::Connectors,
- ) -> CustomResult<Option<services::Request>, errors::ConnectorError> {
+ req: &PaymentsAuthorizeRouterData,
+ connectors: &Connectors,
+ ) -> CustomResult<Option<Request>, errors::ConnectorError> {
Ok(Some(
- services::RequestBuilder::new()
- .method(services::Method::Post)
- .url(&types::PaymentsAuthorizeType::get_url(
- self, req, connectors,
- )?)
+ RequestBuilder::new()
+ .method(Method::Post)
+ .url(&PaymentsAuthorizeType::get_url(self, req, connectors)?)
.attach_default_headers()
- .headers(types::PaymentsAuthorizeType::get_headers(
- self, req, connectors,
- )?)
- .set_body(types::PaymentsAuthorizeType::get_request_body(
+ .headers(PaymentsAuthorizeType::get_headers(self, req, connectors)?)
+ .set_body(PaymentsAuthorizeType::get_request_body(
self, req, connectors,
)?)
.build(),
@@ -272,10 +257,10 @@ impl ConnectorIntegration<api::Authorize, types::PaymentsAuthorizeData, types::P
fn handle_response(
&self,
- data: &types::PaymentsAuthorizeRouterData,
+ data: &PaymentsAuthorizeRouterData,
event_builder: Option<&mut ConnectorEvent>,
res: Response,
- ) -> CustomResult<types::PaymentsAuthorizeRouterData, errors::ConnectorError> {
+ ) -> CustomResult<PaymentsAuthorizeRouterData, errors::ConnectorError> {
let response: cashtocode::CashtocodePaymentsResponse = res
.response
.parse_struct("Cashtocode PaymentsAuthorizeResponse")
@@ -283,7 +268,7 @@ impl ConnectorIntegration<api::Authorize, types::PaymentsAuthorizeData, types::P
event_builder.map(|i| i.set_response_body(&response));
router_env::logger::info!(connector_response=?response);
- types::RouterData::try_from(types::ResponseRouterData {
+ RouterData::try_from(ResponseRouterData {
response,
data: data.clone(),
http_code: res.status_code,
@@ -299,23 +284,21 @@ impl ConnectorIntegration<api::Authorize, types::PaymentsAuthorizeData, types::P
}
}
-impl ConnectorIntegration<api::PSync, types::PaymentsSyncData, types::PaymentsResponseData>
- for Cashtocode
-{
+impl ConnectorIntegration<PSync, PaymentsSyncData, PaymentsResponseData> for Cashtocode {
// default implementation of build_request method will be executed
fn handle_response(
&self,
- data: &types::PaymentsSyncRouterData,
+ data: &PaymentsSyncRouterData,
event_builder: Option<&mut ConnectorEvent>,
res: Response,
- ) -> CustomResult<types::PaymentsSyncRouterData, errors::ConnectorError> {
+ ) -> CustomResult<PaymentsSyncRouterData, errors::ConnectorError> {
let response: transformers::CashtocodePaymentsSyncResponse = res
.response
.parse_struct("CashtocodePaymentsSyncResponse")
.change_context(errors::ConnectorError::ResponseDeserializationFailed)?;
event_builder.map(|i| i.set_response_body(&response));
router_env::logger::info!(connector_response=?response);
- types::RouterData::try_from(types::ResponseRouterData {
+ RouterData::try_from(ResponseRouterData {
response,
data: data.clone(),
http_code: res.status_code,
@@ -331,18 +314,12 @@ impl ConnectorIntegration<api::PSync, types::PaymentsSyncData, types::PaymentsRe
}
}
-impl ConnectorIntegration<api::Capture, types::PaymentsCaptureData, types::PaymentsResponseData>
- for Cashtocode
-{
+impl ConnectorIntegration<Capture, PaymentsCaptureData, PaymentsResponseData> for Cashtocode {
fn build_request(
&self,
- _req: &types::RouterData<
- api::Capture,
- types::PaymentsCaptureData,
- types::PaymentsResponseData,
- >,
- _connectors: &settings::Connectors,
- ) -> CustomResult<Option<services::Request>, errors::ConnectorError> {
+ _req: &RouterData<Capture, PaymentsCaptureData, PaymentsResponseData>,
+ _connectors: &Connectors,
+ ) -> CustomResult<Option<Request>, errors::ConnectorError> {
Err(errors::ConnectorError::FlowNotSupported {
flow: "Capture".to_string(),
connector: "Cashtocode".to_string(),
@@ -351,14 +328,12 @@ impl ConnectorIntegration<api::Capture, types::PaymentsCaptureData, types::Payme
}
}
-impl ConnectorIntegration<api::Void, types::PaymentsCancelData, types::PaymentsResponseData>
- for Cashtocode
-{
+impl ConnectorIntegration<Void, PaymentsCancelData, PaymentsResponseData> for Cashtocode {
fn build_request(
&self,
- _req: &types::RouterData<api::Void, types::PaymentsCancelData, types::PaymentsResponseData>,
- _connectors: &settings::Connectors,
- ) -> CustomResult<Option<services::Request>, errors::ConnectorError> {
+ _req: &RouterData<Void, PaymentsCancelData, PaymentsResponseData>,
+ _connectors: &Connectors,
+ ) -> CustomResult<Option<Request>, errors::ConnectorError> {
Err(errors::ConnectorError::FlowNotSupported {
flow: "Payments Cancel".to_string(),
connector: "Cashtocode".to_string(),
@@ -368,21 +343,20 @@ impl ConnectorIntegration<api::Void, types::PaymentsCancelData, types::PaymentsR
}
#[async_trait::async_trait]
-impl api::IncomingWebhook for Cashtocode {
+impl webhooks::IncomingWebhook for Cashtocode {
fn get_webhook_source_verification_signature(
&self,
- request: &api::IncomingWebhookRequestDetails<'_>,
+ request: &webhooks::IncomingWebhookRequestDetails<'_>,
_connector_webhook_secrets: &api_models::webhooks::ConnectorWebhookSecrets,
) -> CustomResult<Vec<u8>, errors::ConnectorError> {
- let base64_signature =
- connector_utils::get_header_key_value("authorization", request.headers)?;
+ let base64_signature = utils::get_header_key_value("authorization", request.headers)?;
let signature = base64_signature.as_bytes().to_owned();
Ok(signature)
}
async fn verify_webhook_source(
&self,
- request: &api::IncomingWebhookRequestDetails<'_>,
+ request: &webhooks::IncomingWebhookRequestDetails<'_>,
merchant_id: &common_utils::id_type::MerchantId,
connector_webhook_details: Option<common_utils::pii::SecretSerdeValue>,
_connector_account_details: common_utils::crypto::Encryptable<Secret<serde_json::Value>>,
@@ -412,7 +386,7 @@ impl api::IncomingWebhook for Cashtocode {
fn get_webhook_object_reference_id(
&self,
- request: &api::IncomingWebhookRequestDetails<'_>,
+ request: &webhooks::IncomingWebhookRequestDetails<'_>,
) -> CustomResult<api_models::webhooks::ObjectReferenceId, errors::ConnectorError> {
let webhook: transformers::CashtocodePaymentsSyncResponse = request
.body
@@ -426,14 +400,14 @@ impl api::IncomingWebhook for Cashtocode {
fn get_webhook_event_type(
&self,
- _request: &api::IncomingWebhookRequestDetails<'_>,
- ) -> CustomResult<api::IncomingWebhookEvent, errors::ConnectorError> {
- Ok(api::IncomingWebhookEvent::PaymentIntentSuccess)
+ _request: &webhooks::IncomingWebhookRequestDetails<'_>,
+ ) -> CustomResult<api_models::webhooks::IncomingWebhookEvent, errors::ConnectorError> {
+ Ok(api_models::webhooks::IncomingWebhookEvent::PaymentIntentSuccess)
}
fn get_webhook_resource_object(
&self,
- request: &api::IncomingWebhookRequestDetails<'_>,
+ request: &webhooks::IncomingWebhookRequestDetails<'_>,
) -> CustomResult<Box<dyn masking::ErasedMaskSerialize>, errors::ConnectorError> {
let webhook: transformers::CashtocodeIncomingWebhook = request
.body
@@ -445,9 +419,8 @@ impl api::IncomingWebhook for Cashtocode {
fn get_webhook_api_response(
&self,
- request: &api::IncomingWebhookRequestDetails<'_>,
- ) -> CustomResult<services::api::ApplicationResponse<serde_json::Value>, errors::ConnectorError>
- {
+ request: &webhooks::IncomingWebhookRequestDetails<'_>,
+ ) -> CustomResult<ApplicationResponse<serde_json::Value>, errors::ConnectorError> {
let status = "EXECUTED".to_string();
let obj: transformers::CashtocodePaymentsSyncResponse = request
.body
@@ -455,22 +428,16 @@ impl api::IncomingWebhook for Cashtocode {
.change_context(errors::ConnectorError::WebhookReferenceIdNotFound)?;
let response: serde_json::Value =
serde_json::json!({ "status": status, "transactionId" : obj.transaction_id});
- Ok(services::api::ApplicationResponse::Json(response))
+ Ok(ApplicationResponse::Json(response))
}
}
-impl ConnectorIntegration<api::refunds::Execute, types::RefundsData, types::RefundsResponseData>
- for Cashtocode
-{
+impl ConnectorIntegration<Execute, RefundsData, RefundsResponseData> for Cashtocode {
fn build_request(
&self,
- _req: &types::RouterData<
- api::refunds::Execute,
- types::RefundsData,
- types::RefundsResponseData,
- >,
- _connectors: &settings::Connectors,
- ) -> CustomResult<Option<services::Request>, errors::ConnectorError> {
+ _req: &RouterData<Execute, RefundsData, RefundsResponseData>,
+ _connectors: &Connectors,
+ ) -> CustomResult<Option<Request>, errors::ConnectorError> {
Err(errors::ConnectorError::FlowNotSupported {
flow: "Refunds".to_string(),
connector: "Cashtocode".to_string(),
@@ -479,8 +446,6 @@ impl ConnectorIntegration<api::refunds::Execute, types::RefundsData, types::Refu
}
}
-impl ConnectorIntegration<api::refunds::RSync, types::RefundsData, types::RefundsResponseData>
- for Cashtocode
-{
+impl ConnectorIntegration<RSync, RefundsData, RefundsResponseData> for Cashtocode {
// default implementation of build_request method will be executed
}
diff --git a/crates/router/src/connector/cashtocode/transformers.rs b/crates/hyperswitch_connectors/src/connectors/cashtocode/transformers.rs
similarity index 81%
rename from crates/router/src/connector/cashtocode/transformers.rs
rename to crates/hyperswitch_connectors/src/connectors/cashtocode/transformers.rs
index e6f4b9e57cf..49493127621 100644
--- a/crates/router/src/connector/cashtocode/transformers.rs
+++ b/crates/hyperswitch_connectors/src/connectors/cashtocode/transformers.rs
@@ -1,18 +1,24 @@
use std::collections::HashMap;
+use common_enums::enums;
pub use common_utils::request::Method;
use common_utils::{
errors::CustomResult, ext_traits::ValueExt, id_type, pii::Email, types::FloatMajorUnit,
};
use error_stack::ResultExt;
+use hyperswitch_domain_models::{
+ router_data::{ConnectorAuthType, ErrorResponse, RouterData},
+ router_request_types::{PaymentsAuthorizeData, ResponseId},
+ router_response_types::{PaymentsResponseData, RedirectForm},
+ types::PaymentsAuthorizeRouterData,
+};
+use hyperswitch_interfaces::errors;
use masking::Secret;
use serde::{Deserialize, Serialize};
use crate::{
- connector::utils::{self, PaymentsAuthorizeRequestData, RouterData},
- core::errors,
- services,
- types::{self, storage::enums},
+ types::ResponseRouterData,
+ utils::{self, PaymentsAuthorizeRequestData, RouterData as OtherRouterData},
};
#[derive(Default, Debug, Serialize)]
@@ -32,7 +38,7 @@ pub struct CashtocodePaymentsRequest {
}
fn get_mid(
- connector_auth_type: &types::ConnectorAuthType,
+ connector_auth_type: &ConnectorAuthType,
payment_method_type: Option<enums::PaymentMethodType>,
currency: enums::Currency,
) -> Result<Secret<String>, errors::ConnectorError> {
@@ -50,10 +56,10 @@ fn get_mid(
}
}
-impl TryFrom<(&types::PaymentsAuthorizeRouterData, FloatMajorUnit)> for CashtocodePaymentsRequest {
+impl TryFrom<(&PaymentsAuthorizeRouterData, FloatMajorUnit)> for CashtocodePaymentsRequest {
type Error = error_stack::Report<errors::ConnectorError>;
fn try_from(
- (item, amount): (&types::PaymentsAuthorizeRouterData, FloatMajorUnit),
+ (item, amount): (&PaymentsAuthorizeRouterData, FloatMajorUnit),
) -> Result<Self, Self::Error> {
let customer_id = item.get_customer_id()?;
let url = item.request.get_router_return_url()?;
@@ -63,7 +69,7 @@ impl TryFrom<(&types::PaymentsAuthorizeRouterData, FloatMajorUnit)> for Cashtoco
item.request.currency,
)?;
match item.payment_method {
- diesel_models::enums::PaymentMethod::Reward => Ok(Self {
+ enums::PaymentMethod::Reward => Ok(Self {
amount,
transaction_id: item.attempt_id.clone(),
currency: item.request.currency,
@@ -96,12 +102,12 @@ pub struct CashtocodeAuth {
pub merchant_id_evoucher: Option<Secret<String>>,
}
-impl TryFrom<&types::ConnectorAuthType> for CashtocodeAuthType {
+impl TryFrom<&ConnectorAuthType> for CashtocodeAuthType {
type Error = error_stack::Report<errors::ConnectorError>; // Assuming ErrorStack is the appropriate error type
- fn try_from(auth_type: &types::ConnectorAuthType) -> Result<Self, Self::Error> {
+ fn try_from(auth_type: &ConnectorAuthType) -> Result<Self, Self::Error> {
match auth_type {
- types::ConnectorAuthType::CurrencyAuthKey { auth_key_map } => {
+ ConnectorAuthType::CurrencyAuthKey { auth_key_map } => {
let transformed_auths = auth_key_map
.iter()
.map(|(currency, identity_auth_key)| {
@@ -125,13 +131,13 @@ impl TryFrom<&types::ConnectorAuthType> for CashtocodeAuthType {
}
}
-impl TryFrom<(&types::ConnectorAuthType, &enums::Currency)> for CashtocodeAuth {
+impl TryFrom<(&ConnectorAuthType, &enums::Currency)> for CashtocodeAuth {
type Error = error_stack::Report<errors::ConnectorError>;
- fn try_from(value: (&types::ConnectorAuthType, &enums::Currency)) -> Result<Self, Self::Error> {
+ fn try_from(value: (&ConnectorAuthType, &enums::Currency)) -> Result<Self, Self::Error> {
let (auth_type, currency) = value;
- if let types::ConnectorAuthType::CurrencyAuthKey { auth_key_map } = auth_type {
+ if let ConnectorAuthType::CurrencyAuthKey { auth_key_map } = auth_type {
if let Some(identity_auth_key) = auth_key_map.get(currency) {
let cashtocode_auth: Self = identity_auth_key
.to_owned()
@@ -199,15 +205,15 @@ pub struct CashtocodePaymentsSyncResponse {
fn get_redirect_form_data(
payment_method_type: &enums::PaymentMethodType,
response_data: CashtocodePaymentsResponseData,
-) -> CustomResult<services::RedirectForm, errors::ConnectorError> {
+) -> CustomResult<RedirectForm, errors::ConnectorError> {
match payment_method_type {
- enums::PaymentMethodType::ClassicReward => Ok(services::RedirectForm::Form {
+ enums::PaymentMethodType::ClassicReward => Ok(RedirectForm::Form {
//redirect form is manually constructed because the connector for this pm type expects query params in the url
endpoint: response_data.pay_url.to_string(),
method: Method::Post,
form_fields: Default::default(),
}),
- enums::PaymentMethodType::Evoucher => Ok(services::RedirectForm::from((
+ enums::PaymentMethodType::Evoucher => Ok(RedirectForm::from((
//here the pay url gets parsed, and query params are sent as formfields as the connector expects
response_data.pay_url,
Method::Get,
@@ -220,27 +226,27 @@ fn get_redirect_form_data(
impl<F>
TryFrom<
- types::ResponseRouterData<
+ ResponseRouterData<
F,
CashtocodePaymentsResponse,
- types::PaymentsAuthorizeData,
- types::PaymentsResponseData,
+ PaymentsAuthorizeData,
+ PaymentsResponseData,
>,
- > for types::RouterData<F, types::PaymentsAuthorizeData, types::PaymentsResponseData>
+ > for RouterData<F, PaymentsAuthorizeData, PaymentsResponseData>
{
type Error = error_stack::Report<errors::ConnectorError>;
fn try_from(
- item: types::ResponseRouterData<
+ item: ResponseRouterData<
F,
CashtocodePaymentsResponse,
- types::PaymentsAuthorizeData,
- types::PaymentsResponseData,
+ PaymentsAuthorizeData,
+ PaymentsResponseData,
>,
) -> Result<Self, Self::Error> {
let (status, response) = match item.response {
CashtocodePaymentsResponse::CashtoCodeError(error_data) => (
enums::AttemptStatus::Failure,
- Err(types::ErrorResponse {
+ Err(ErrorResponse {
code: error_data.error.to_string(),
status_code: item.http_code,
message: error_data.error_description,
@@ -259,8 +265,8 @@ impl<F>
let redirection_data = get_redirect_form_data(payment_method_type, response_data)?;
(
enums::AttemptStatus::AuthenticationPending,
- Ok(types::PaymentsResponseData::TransactionResponse {
- resource_id: types::ResponseId::ConnectorTransactionId(
+ Ok(PaymentsResponseData::TransactionResponse {
+ resource_id: ResponseId::ConnectorTransactionId(
item.data.attempt_id.clone(),
),
redirection_data: Some(redirection_data),
@@ -283,29 +289,17 @@ impl<F>
}
}
-impl<F, T>
- TryFrom<
- types::ResponseRouterData<
- F,
- CashtocodePaymentsSyncResponse,
- T,
- types::PaymentsResponseData,
- >,
- > for types::RouterData<F, T, types::PaymentsResponseData>
+impl<F, T> TryFrom<ResponseRouterData<F, CashtocodePaymentsSyncResponse, T, PaymentsResponseData>>
+ for RouterData<F, T, PaymentsResponseData>
{
type Error = error_stack::Report<errors::ConnectorError>;
fn try_from(
- item: types::ResponseRouterData<
- F,
- CashtocodePaymentsSyncResponse,
- T,
- types::PaymentsResponseData,
- >,
+ item: ResponseRouterData<F, CashtocodePaymentsSyncResponse, T, PaymentsResponseData>,
) -> Result<Self, Self::Error> {
Ok(Self {
status: enums::AttemptStatus::Charged, // Charged status is hardcoded because cashtocode do not support Psync, and we only receive webhooks when payment is succeeded, this tryFrom is used for CallConnectorAction.
- response: Ok(types::PaymentsResponseData::TransactionResponse {
- resource_id: types::ResponseId::ConnectorTransactionId(
+ response: Ok(PaymentsResponseData::TransactionResponse {
+ resource_id: ResponseId::ConnectorTransactionId(
item.data.attempt_id.clone(), //in response they only send PayUrl, so we use attempt_id as connector_transaction_id
),
redirection_data: None,
diff --git a/crates/router/src/connector/coinbase.rs b/crates/hyperswitch_connectors/src/connectors/coinbase.rs
similarity index 64%
rename from crates/router/src/connector/coinbase.rs
rename to crates/hyperswitch_connectors/src/connectors/coinbase.rs
index 0c3c0be41db..7b149952ca8 100644
--- a/crates/router/src/connector/coinbase.rs
+++ b/crates/hyperswitch_connectors/src/connectors/coinbase.rs
@@ -2,31 +2,45 @@ pub mod transformers;
use std::fmt::Debug;
-use common_utils::{crypto, ext_traits::ByteSliceExt, request::RequestContent};
-use diesel_models::enums;
+use common_enums::enums;
+use common_utils::{
+ crypto,
+ errors::CustomResult,
+ ext_traits::ByteSliceExt,
+ request::{Method, Request, RequestBuilder, RequestContent},
+};
use error_stack::ResultExt;
-use transformers as coinbase;
-
-use self::coinbase::CoinbaseWebhookDetails;
-use super::utils;
-use crate::{
- configs::settings,
- connector::utils as connector_utils,
- core::errors::{self, CustomResult},
- events::connector_api_logs::ConnectorEvent,
- headers,
- services::{
- self,
- request::{self, Mask},
- ConnectorIntegration, ConnectorValidation,
+use hyperswitch_domain_models::{
+ router_data::{AccessToken, ConnectorAuthType, ErrorResponse, RouterData},
+ router_flow_types::{
+ access_token_auth::AccessTokenAuth,
+ payments::{Authorize, Capture, PSync, PaymentMethodToken, Session, SetupMandate, Void},
+ refunds::{Execute, RSync},
},
+ router_request_types::{
+ AccessTokenRequestData, PaymentMethodTokenizationData, PaymentsAuthorizeData,
+ PaymentsCancelData, PaymentsCaptureData, PaymentsSessionData, PaymentsSyncData,
+ RefundsData, SetupMandateRequestData,
+ },
+ router_response_types::{PaymentsResponseData, RefundsResponseData},
types::{
- self,
- api::{self, ConnectorCommon, ConnectorCommonExt},
- ErrorResponse, Response,
+ PaymentsAuthorizeRouterData, PaymentsCaptureRouterData, PaymentsSyncRouterData,
+ RefundsRouterData,
},
- utils::BytesExt,
};
+use hyperswitch_interfaces::{
+ api::{self, ConnectorCommon, ConnectorCommonExt, ConnectorIntegration, ConnectorValidation},
+ configs::Connectors,
+ errors,
+ events::connector_api_logs::ConnectorEvent,
+ types::{PaymentsAuthorizeType, PaymentsSyncType, Response},
+ webhooks,
+};
+use masking::Mask;
+use transformers as coinbase;
+
+use self::coinbase::CoinbaseWebhookDetails;
+use crate::{constants::headers, types::ResponseRouterData, utils};
#[derive(Debug, Clone)]
pub struct Coinbase;
@@ -50,9 +64,9 @@ where
{
fn build_headers(
&self,
- req: &types::RouterData<Flow, Request, Response>,
- _connectors: &settings::Connectors,
- ) -> CustomResult<Vec<(String, request::Maskable<String>)>, errors::ConnectorError> {
+ req: &RouterData<Flow, Request, Response>,
+ _connectors: &Connectors,
+ ) -> CustomResult<Vec<(String, masking::Maskable<String>)>, errors::ConnectorError> {
let mut header = vec![
(
headers::CONTENT_TYPE.to_string(),
@@ -78,14 +92,14 @@ impl ConnectorCommon for Coinbase {
"application/json"
}
- fn base_url<'a>(&self, connectors: &'a settings::Connectors) -> &'a str {
+ fn base_url<'a>(&self, connectors: &'a Connectors) -> &'a str {
connectors.coinbase.base_url.as_ref()
}
fn get_auth_header(
&self,
- auth_type: &types::ConnectorAuthType,
- ) -> CustomResult<Vec<(String, request::Maskable<String>)>, errors::ConnectorError> {
+ auth_type: &ConnectorAuthType,
+ ) -> CustomResult<Vec<(String, masking::Maskable<String>)>, errors::ConnectorError> {
let auth: coinbase::CoinbaseAuthType = coinbase::CoinbaseAuthType::try_from(auth_type)
.change_context(errors::ConnectorError::FailedToObtainAuthType)?;
Ok(vec![(
@@ -128,49 +142,32 @@ impl ConnectorValidation for Coinbase {
match capture_method {
enums::CaptureMethod::Automatic | enums::CaptureMethod::Manual => Ok(()),
enums::CaptureMethod::ManualMultiple | enums::CaptureMethod::Scheduled => Err(
- connector_utils::construct_not_supported_error_report(capture_method, self.id()),
+ utils::construct_not_supported_error_report(capture_method, self.id()),
),
}
}
}
-impl
- ConnectorIntegration<
- api::PaymentMethodToken,
- types::PaymentMethodTokenizationData,
- types::PaymentsResponseData,
- > for Coinbase
+impl ConnectorIntegration<PaymentMethodToken, PaymentMethodTokenizationData, PaymentsResponseData>
+ for Coinbase
{
// Not Implemented (R)
}
-impl ConnectorIntegration<api::Session, types::PaymentsSessionData, types::PaymentsResponseData>
- for Coinbase
-{
+impl ConnectorIntegration<Session, PaymentsSessionData, PaymentsResponseData> for Coinbase {
//TODO: implement sessions flow
}
-impl ConnectorIntegration<api::AccessTokenAuth, types::AccessTokenRequestData, types::AccessToken>
- for Coinbase
-{
-}
+impl ConnectorIntegration<AccessTokenAuth, AccessTokenRequestData, AccessToken> for Coinbase {}
-impl
- ConnectorIntegration<
- api::SetupMandate,
- types::SetupMandateRequestData,
- types::PaymentsResponseData,
- > for Coinbase
+impl ConnectorIntegration<SetupMandate, SetupMandateRequestData, PaymentsResponseData>
+ for Coinbase
{
fn build_request(
&self,
- _req: &types::RouterData<
- api::SetupMandate,
- types::SetupMandateRequestData,
- types::PaymentsResponseData,
- >,
- _connectors: &settings::Connectors,
- ) -> CustomResult<Option<services::Request>, errors::ConnectorError> {
+ _req: &RouterData<SetupMandate, SetupMandateRequestData, PaymentsResponseData>,
+ _connectors: &Connectors,
+ ) -> CustomResult<Option<Request>, errors::ConnectorError> {
Err(
errors::ConnectorError::NotImplemented("Setup Mandate flow for Coinbase".to_string())
.into(),
@@ -178,14 +175,12 @@ impl
}
}
-impl ConnectorIntegration<api::Authorize, types::PaymentsAuthorizeData, types::PaymentsResponseData>
- for Coinbase
-{
+impl ConnectorIntegration<Authorize, PaymentsAuthorizeData, PaymentsResponseData> for Coinbase {
fn get_headers(
&self,
- req: &types::PaymentsAuthorizeRouterData,
- connectors: &settings::Connectors,
- ) -> CustomResult<Vec<(String, request::Maskable<String>)>, errors::ConnectorError> {
+ req: &PaymentsAuthorizeRouterData,
+ connectors: &Connectors,
+ ) -> CustomResult<Vec<(String, masking::Maskable<String>)>, errors::ConnectorError> {
self.build_headers(req, connectors)
}
@@ -195,16 +190,16 @@ impl ConnectorIntegration<api::Authorize, types::PaymentsAuthorizeData, types::P
fn get_url(
&self,
- _req: &types::PaymentsAuthorizeRouterData,
- _connectors: &settings::Connectors,
+ _req: &PaymentsAuthorizeRouterData,
+ _connectors: &Connectors,
) -> CustomResult<String, errors::ConnectorError> {
Ok(format!("{}/charges", self.base_url(_connectors)))
}
fn get_request_body(
&self,
- req: &types::PaymentsAuthorizeRouterData,
- _connectors: &settings::Connectors,
+ req: &PaymentsAuthorizeRouterData,
+ _connectors: &Connectors,
) -> CustomResult<RequestContent, errors::ConnectorError> {
let connector_req = coinbase::CoinbasePaymentsRequest::try_from(req)?;
Ok(RequestContent::Json(Box::new(connector_req)))
@@ -212,19 +207,15 @@ impl ConnectorIntegration<api::Authorize, types::PaymentsAuthorizeData, types::P
fn build_request(
&self,
- req: &types::PaymentsAuthorizeRouterData,
- connectors: &settings::Connectors,
- ) -> CustomResult<Option<services::Request>, errors::ConnectorError> {
+ req: &PaymentsAuthorizeRouterData,
+ connectors: &Connectors,
+ ) -> CustomResult<Option<Request>, errors::ConnectorError> {
Ok(Some(
- services::RequestBuilder::new()
- .method(services::Method::Post)
- .url(&types::PaymentsAuthorizeType::get_url(
- self, req, connectors,
- )?)
- .headers(types::PaymentsAuthorizeType::get_headers(
- self, req, connectors,
- )?)
- .set_body(types::PaymentsAuthorizeType::get_request_body(
+ RequestBuilder::new()
+ .method(Method::Post)
+ .url(&PaymentsAuthorizeType::get_url(self, req, connectors)?)
+ .headers(PaymentsAuthorizeType::get_headers(self, req, connectors)?)
+ .set_body(PaymentsAuthorizeType::get_request_body(
self, req, connectors,
)?)
.build(),
@@ -233,17 +224,17 @@ impl ConnectorIntegration<api::Authorize, types::PaymentsAuthorizeData, types::P
fn handle_response(
&self,
- data: &types::PaymentsAuthorizeRouterData,
+ data: &PaymentsAuthorizeRouterData,
event_builder: Option<&mut ConnectorEvent>,
res: Response,
- ) -> CustomResult<types::PaymentsAuthorizeRouterData, errors::ConnectorError> {
+ ) -> CustomResult<PaymentsAuthorizeRouterData, errors::ConnectorError> {
let response: coinbase::CoinbasePaymentsResponse = res
.response
.parse_struct("Coinbase PaymentsAuthorizeResponse")
.change_context(errors::ConnectorError::ResponseDeserializationFailed)?;
event_builder.map(|i| i.set_response_body(&response));
router_env::logger::info!(connector_response=?response);
- types::RouterData::try_from(types::ResponseRouterData {
+ RouterData::try_from(ResponseRouterData {
response,
data: data.clone(),
http_code: res.status_code,
@@ -260,14 +251,12 @@ impl ConnectorIntegration<api::Authorize, types::PaymentsAuthorizeData, types::P
}
}
-impl ConnectorIntegration<api::PSync, types::PaymentsSyncData, types::PaymentsResponseData>
- for Coinbase
-{
+impl ConnectorIntegration<PSync, PaymentsSyncData, PaymentsResponseData> for Coinbase {
fn get_headers(
&self,
- req: &types::PaymentsSyncRouterData,
- connectors: &settings::Connectors,
- ) -> CustomResult<Vec<(String, request::Maskable<String>)>, errors::ConnectorError> {
+ req: &PaymentsSyncRouterData,
+ connectors: &Connectors,
+ ) -> CustomResult<Vec<(String, masking::Maskable<String>)>, errors::ConnectorError> {
self.build_headers(req, connectors)
}
@@ -277,8 +266,8 @@ impl ConnectorIntegration<api::PSync, types::PaymentsSyncData, types::PaymentsRe
fn get_url(
&self,
- _req: &types::PaymentsSyncRouterData,
- _connectors: &settings::Connectors,
+ _req: &PaymentsSyncRouterData,
+ _connectors: &Connectors,
) -> CustomResult<String, errors::ConnectorError> {
let connector_id = _req
.request
@@ -294,31 +283,31 @@ impl ConnectorIntegration<api::PSync, types::PaymentsSyncData, types::PaymentsRe
fn build_request(
&self,
- req: &types::PaymentsSyncRouterData,
- connectors: &settings::Connectors,
- ) -> CustomResult<Option<services::Request>, errors::ConnectorError> {
+ req: &PaymentsSyncRouterData,
+ connectors: &Connectors,
+ ) -> CustomResult<Option<Request>, errors::ConnectorError> {
Ok(Some(
- services::RequestBuilder::new()
- .method(services::Method::Get)
- .url(&types::PaymentsSyncType::get_url(self, req, connectors)?)
- .headers(types::PaymentsSyncType::get_headers(self, req, connectors)?)
+ RequestBuilder::new()
+ .method(Method::Get)
+ .url(&PaymentsSyncType::get_url(self, req, connectors)?)
+ .headers(PaymentsSyncType::get_headers(self, req, connectors)?)
.build(),
))
}
fn handle_response(
&self,
- data: &types::PaymentsSyncRouterData,
+ data: &PaymentsSyncRouterData,
event_builder: Option<&mut ConnectorEvent>,
res: Response,
- ) -> CustomResult<types::PaymentsSyncRouterData, errors::ConnectorError> {
+ ) -> CustomResult<PaymentsSyncRouterData, errors::ConnectorError> {
let response: coinbase::CoinbasePaymentsResponse = res
.response
.parse_struct("coinbase PaymentsSyncResponse")
.change_context(errors::ConnectorError::ResponseDeserializationFailed)?;
event_builder.map(|i| i.set_response_body(&response));
router_env::logger::info!(connector_response=?response);
- types::RouterData::try_from(types::ResponseRouterData {
+ RouterData::try_from(ResponseRouterData {
response,
data: data.clone(),
http_code: res.status_code,
@@ -335,14 +324,12 @@ impl ConnectorIntegration<api::PSync, types::PaymentsSyncData, types::PaymentsRe
}
}
-impl ConnectorIntegration<api::Capture, types::PaymentsCaptureData, types::PaymentsResponseData>
- for Coinbase
-{
+impl ConnectorIntegration<Capture, PaymentsCaptureData, PaymentsResponseData> for Coinbase {
fn build_request(
&self,
- _req: &types::PaymentsCaptureRouterData,
- _connectors: &settings::Connectors,
- ) -> CustomResult<Option<services::Request>, errors::ConnectorError> {
+ _req: &PaymentsCaptureRouterData,
+ _connectors: &Connectors,
+ ) -> CustomResult<Option<Request>, errors::ConnectorError> {
Err(errors::ConnectorError::FlowNotSupported {
flow: "Capture".to_string(),
connector: "Coinbase".to_string(),
@@ -351,19 +338,14 @@ impl ConnectorIntegration<api::Capture, types::PaymentsCaptureData, types::Payme
}
}
-impl ConnectorIntegration<api::Void, types::PaymentsCancelData, types::PaymentsResponseData>
- for Coinbase
-{
-}
+impl ConnectorIntegration<Void, PaymentsCancelData, PaymentsResponseData> for Coinbase {}
-impl ConnectorIntegration<api::Execute, types::RefundsData, types::RefundsResponseData>
- for Coinbase
-{
+impl ConnectorIntegration<Execute, RefundsData, RefundsResponseData> for Coinbase {
fn build_request(
&self,
- _req: &types::RefundsRouterData<api::Execute>,
- _connectors: &settings::Connectors,
- ) -> CustomResult<Option<services::Request>, errors::ConnectorError> {
+ _req: &RefundsRouterData<Execute>,
+ _connectors: &Connectors,
+ ) -> CustomResult<Option<Request>, errors::ConnectorError> {
Err(errors::ConnectorError::FlowNotSupported {
flow: "Refund".to_string(),
connector: "Coinbase".to_string(),
@@ -372,22 +354,22 @@ impl ConnectorIntegration<api::Execute, types::RefundsData, types::RefundsRespon
}
}
-impl ConnectorIntegration<api::RSync, types::RefundsData, types::RefundsResponseData> for Coinbase {
+impl ConnectorIntegration<RSync, RefundsData, RefundsResponseData> for Coinbase {
// default implementation of build_request method will be executed
}
#[async_trait::async_trait]
-impl api::IncomingWebhook for Coinbase {
+impl webhooks::IncomingWebhook for Coinbase {
fn get_webhook_source_verification_algorithm(
&self,
- _request: &api::IncomingWebhookRequestDetails<'_>,
+ _request: &webhooks::IncomingWebhookRequestDetails<'_>,
) -> CustomResult<Box<dyn crypto::VerifySignature + Send>, errors::ConnectorError> {
Ok(Box::new(crypto::HmacSha256))
}
fn get_webhook_source_verification_signature(
&self,
- request: &api::IncomingWebhookRequestDetails<'_>,
+ request: &webhooks::IncomingWebhookRequestDetails<'_>,
_connector_webhook_secrets: &api_models::webhooks::ConnectorWebhookSecrets,
) -> CustomResult<Vec<u8>, errors::ConnectorError> {
let base64_signature =
@@ -398,7 +380,7 @@ impl api::IncomingWebhook for Coinbase {
fn get_webhook_source_verification_message(
&self,
- request: &api::IncomingWebhookRequestDetails<'_>,
+ request: &webhooks::IncomingWebhookRequestDetails<'_>,
_merchant_id: &common_utils::id_type::MerchantId,
_connector_webhook_secrets: &api_models::webhooks::ConnectorWebhookSecrets,
) -> CustomResult<Vec<u8>, errors::ConnectorError> {
@@ -409,7 +391,7 @@ impl api::IncomingWebhook for Coinbase {
fn get_webhook_object_reference_id(
&self,
- request: &api::IncomingWebhookRequestDetails<'_>,
+ request: &webhooks::IncomingWebhookRequestDetails<'_>,
) -> CustomResult<api_models::webhooks::ObjectReferenceId, errors::ConnectorError> {
let notif: CoinbaseWebhookDetails = request
.body
@@ -422,31 +404,31 @@ impl api::IncomingWebhook for Coinbase {
fn get_webhook_event_type(
&self,
- request: &api::IncomingWebhookRequestDetails<'_>,
- ) -> CustomResult<api::IncomingWebhookEvent, errors::ConnectorError> {
+ request: &webhooks::IncomingWebhookRequestDetails<'_>,
+ ) -> CustomResult<api_models::webhooks::IncomingWebhookEvent, errors::ConnectorError> {
let notif: CoinbaseWebhookDetails = request
.body
.parse_struct("CoinbaseWebhookDetails")
.change_context(errors::ConnectorError::WebhookEventTypeNotFound)?;
match notif.event.event_type {
coinbase::WebhookEventType::Confirmed | coinbase::WebhookEventType::Resolved => {
- Ok(api::IncomingWebhookEvent::PaymentIntentSuccess)
+ Ok(api_models::webhooks::IncomingWebhookEvent::PaymentIntentSuccess)
}
coinbase::WebhookEventType::Failed => {
- Ok(api::IncomingWebhookEvent::PaymentActionRequired)
+ Ok(api_models::webhooks::IncomingWebhookEvent::PaymentActionRequired)
}
coinbase::WebhookEventType::Pending => {
- Ok(api::IncomingWebhookEvent::PaymentIntentProcessing)
+ Ok(api_models::webhooks::IncomingWebhookEvent::PaymentIntentProcessing)
}
coinbase::WebhookEventType::Unknown | coinbase::WebhookEventType::Created => {
- Ok(api::IncomingWebhookEvent::EventNotSupported)
+ Ok(api_models::webhooks::IncomingWebhookEvent::EventNotSupported)
}
}
}
fn get_webhook_resource_object(
&self,
- request: &api::IncomingWebhookRequestDetails<'_>,
+ request: &webhooks::IncomingWebhookRequestDetails<'_>,
) -> CustomResult<Box<dyn masking::ErasedMaskSerialize>, errors::ConnectorError> {
let notif: CoinbaseWebhookDetails = request
.body
diff --git a/crates/router/src/connector/coinbase/transformers.rs b/crates/hyperswitch_connectors/src/connectors/coinbase/transformers.rs
similarity index 87%
rename from crates/router/src/connector/coinbase/transformers.rs
rename to crates/hyperswitch_connectors/src/connectors/coinbase/transformers.rs
index 82a6add72ee..3633c366c4c 100644
--- a/crates/router/src/connector/coinbase/transformers.rs
+++ b/crates/hyperswitch_connectors/src/connectors/coinbase/transformers.rs
@@ -1,15 +1,24 @@
use std::collections::HashMap;
-use common_utils::pii;
+use common_enums::enums;
+use common_utils::{pii, request::Method};
use error_stack::ResultExt;
+use hyperswitch_domain_models::{
+ router_data::{ConnectorAuthType, RouterData},
+ router_flow_types::refunds::{Execute, RSync},
+ router_request_types::ResponseId,
+ router_response_types::{PaymentsResponseData, RedirectForm},
+ types,
+};
+use hyperswitch_interfaces::errors;
+use masking::Secret;
use serde::{Deserialize, Serialize};
use crate::{
- connector::utils::{self, AddressDetailsData, PaymentsAuthorizeRequestData, RouterData},
- core::errors,
- pii::Secret,
- services,
- types::{self, api, storage::enums},
+ types::{RefundsResponseRouterData, ResponseRouterData},
+ utils::{
+ self, AddressDetailsData, PaymentsAuthorizeRequestData, RouterData as OtherRouterData,
+ },
};
#[derive(Debug, Default, Eq, PartialEq, Serialize)]
@@ -46,10 +55,10 @@ pub struct CoinbaseAuthType {
pub(super) api_key: Secret<String>,
}
-impl TryFrom<&types::ConnectorAuthType> for CoinbaseAuthType {
+impl TryFrom<&ConnectorAuthType> for CoinbaseAuthType {
type Error = error_stack::Report<errors::ConnectorError>;
- fn try_from(_auth_type: &types::ConnectorAuthType) -> Result<Self, Self::Error> {
- if let types::ConnectorAuthType::HeaderKey { api_key } = _auth_type {
+ fn try_from(_auth_type: &ConnectorAuthType) -> Result<Self, Self::Error> {
+ if let ConnectorAuthType::HeaderKey { api_key } = _auth_type {
Ok(Self {
api_key: api_key.to_owned(),
})
@@ -112,23 +121,17 @@ pub struct CoinbasePaymentsResponse {
data: CoinbasePaymentResponseData,
}
-impl<F, T>
- TryFrom<types::ResponseRouterData<F, CoinbasePaymentsResponse, T, types::PaymentsResponseData>>
- for types::RouterData<F, T, types::PaymentsResponseData>
+impl<F, T> TryFrom<ResponseRouterData<F, CoinbasePaymentsResponse, T, PaymentsResponseData>>
+ for RouterData<F, T, PaymentsResponseData>
{
type Error = error_stack::Report<errors::ConnectorError>;
fn try_from(
- item: types::ResponseRouterData<
- F,
- CoinbasePaymentsResponse,
- T,
- types::PaymentsResponseData,
- >,
+ item: ResponseRouterData<F, CoinbasePaymentsResponse, T, PaymentsResponseData>,
) -> Result<Self, Self::Error> {
let form_fields = HashMap::new();
- let redirection_data = services::RedirectForm::Form {
+ let redirection_data = RedirectForm::Form {
endpoint: item.response.data.hosted_url.to_string(),
- method: services::Method::Get,
+ method: Method::Get,
form_fields,
};
let timeline = item
@@ -138,10 +141,10 @@ impl<F, T>
.last()
.ok_or(errors::ConnectorError::ResponseHandlingFailed)?
.clone();
- let connector_id = types::ResponseId::ConnectorTransactionId(item.response.data.id.clone());
+ let connector_id = ResponseId::ConnectorTransactionId(item.response.data.id.clone());
let attempt_status = timeline.status.clone();
let response_data = timeline.context.map_or(
- Ok(types::PaymentsResponseData::TransactionResponse {
+ Ok(PaymentsResponseData::TransactionResponse {
resource_id: connector_id.clone(),
redirection_data: Some(redirection_data),
mandate_reference: None,
@@ -152,9 +155,9 @@ impl<F, T>
charge_id: None,
}),
|context| {
- Ok(types::PaymentsResponseData::TransactionUnresolvedResponse{
+ Ok(PaymentsResponseData::TransactionUnresolvedResponse{
resource_id: connector_id,
- reason: Some(api::enums::UnresolvedResponseReason {
+ reason: Some(api_models::enums::UnresolvedResponseReason {
code: context.to_string(),
message: "Please check the transaction in coinbase dashboard and resolve manually"
.to_string(),
@@ -207,12 +210,12 @@ impl From<RefundStatus> for enums::RefundStatus {
#[derive(Default, Debug, Clone, Serialize, Deserialize)]
pub struct RefundResponse {}
-impl TryFrom<types::RefundsResponseRouterData<api::Execute, RefundResponse>>
- for types::RefundsRouterData<api::Execute>
+impl TryFrom<RefundsResponseRouterData<Execute, RefundResponse>>
+ for types::RefundsRouterData<Execute>
{
type Error = error_stack::Report<errors::ConnectorError>;
fn try_from(
- _item: types::RefundsResponseRouterData<api::Execute, RefundResponse>,
+ _item: RefundsResponseRouterData<Execute, RefundResponse>,
) -> Result<Self, Self::Error> {
Err(errors::ConnectorError::NotImplemented(
"try_from RefundsResponseRouterData".to_string(),
@@ -221,12 +224,10 @@ impl TryFrom<types::RefundsResponseRouterData<api::Execute, RefundResponse>>
}
}
-impl TryFrom<types::RefundsResponseRouterData<api::RSync, RefundResponse>>
- for types::RefundsRouterData<api::RSync>
-{
+impl TryFrom<RefundsResponseRouterData<RSync, RefundResponse>> for types::RefundsRouterData<RSync> {
type Error = error_stack::Report<errors::ConnectorError>;
fn try_from(
- _item: types::RefundsResponseRouterData<api::RSync, RefundResponse>,
+ _item: RefundsResponseRouterData<RSync, RefundResponse>,
) -> Result<Self, Self::Error> {
Err(errors::ConnectorError::NotImplemented(
"try_from RefundsResponseRouterData".to_string(),
diff --git a/crates/router/src/connector/cryptopay.rs b/crates/hyperswitch_connectors/src/connectors/cryptopay.rs
similarity index 69%
rename from crates/router/src/connector/cryptopay.rs
rename to crates/hyperswitch_connectors/src/connectors/cryptopay.rs
index 765a07646c6..dcd629f4336 100644
--- a/crates/router/src/connector/cryptopay.rs
+++ b/crates/hyperswitch_connectors/src/connectors/cryptopay.rs
@@ -4,35 +4,44 @@ use base64::Engine;
use common_utils::{
crypto::{self, GenerateDigest, SignMessage},
date_time,
+ errors::CustomResult,
ext_traits::ByteSliceExt,
- request::RequestContent,
+ request::{Method, Request, RequestBuilder, RequestContent},
types::{AmountConvertor, StringMajorUnit, StringMajorUnitForConnector},
};
use error_stack::ResultExt;
use hex::encode;
-use masking::PeekInterface;
+use hyperswitch_domain_models::{
+ router_data::{AccessToken, ConnectorAuthType, ErrorResponse, RouterData},
+ router_flow_types::{
+ access_token_auth::AccessTokenAuth,
+ payments::{Authorize, Capture, PSync, PaymentMethodToken, Session, SetupMandate, Void},
+ refunds::{Execute, RSync},
+ },
+ router_request_types::{
+ AccessTokenRequestData, PaymentMethodTokenizationData, PaymentsAuthorizeData,
+ PaymentsCancelData, PaymentsCaptureData, PaymentsSessionData, PaymentsSyncData,
+ RefundsData, SetupMandateRequestData,
+ },
+ router_response_types::{PaymentsResponseData, RefundsResponseData},
+ types::{PaymentsAuthorizeRouterData, PaymentsSyncRouterData},
+};
+use hyperswitch_interfaces::{
+ api::{self, ConnectorCommon, ConnectorCommonExt, ConnectorIntegration, ConnectorValidation},
+ configs::Connectors,
+ errors,
+ events::connector_api_logs::ConnectorEvent,
+ types::{PaymentsAuthorizeType, PaymentsSyncType, Response},
+ webhooks,
+};
+use masking::{Mask, PeekInterface};
use transformers as cryptopay;
use self::cryptopay::CryptopayWebhookDetails;
-use super::utils;
use crate::{
- configs::settings,
- consts,
- core::errors::{self, CustomResult},
- events::connector_api_logs::ConnectorEvent,
- headers,
- services::{
- self,
- request::{self, Mask},
- ConnectorIntegration, ConnectorValidation,
- },
- types::{
- self,
- api::{self, ConnectorCommon, ConnectorCommonExt},
- transformers::ForeignTryFrom,
- ErrorResponse, Response,
- },
- utils::BytesExt,
+ constants::headers,
+ types::ResponseRouterData,
+ utils::{self, ForeignTryFrom},
};
#[derive(Clone)]
@@ -61,12 +70,8 @@ impl api::RefundExecute for Cryptopay {}
impl api::RefundSync for Cryptopay {}
impl api::PaymentToken for Cryptopay {}
-impl
- ConnectorIntegration<
- api::PaymentMethodToken,
- types::PaymentMethodTokenizationData,
- types::PaymentsResponseData,
- > for Cryptopay
+impl ConnectorIntegration<PaymentMethodToken, PaymentMethodTokenizationData, PaymentsResponseData>
+ for Cryptopay
{
// Not Implemented (R)
}
@@ -77,16 +82,13 @@ where
{
fn build_headers(
&self,
- req: &types::RouterData<Flow, Request, Response>,
- connectors: &settings::Connectors,
- ) -> CustomResult<Vec<(String, request::Maskable<String>)>, errors::ConnectorError> {
+ req: &RouterData<Flow, Request, Response>,
+ connectors: &Connectors,
+ ) -> CustomResult<Vec<(String, masking::Maskable<String>)>, errors::ConnectorError> {
let method = self.get_http_method();
let payload = match method {
- common_utils::request::Method::Get => String::default(),
- common_utils::request::Method::Post
- | common_utils::request::Method::Put
- | common_utils::request::Method::Delete
- | common_utils::request::Method::Patch => {
+ Method::Get => String::default(),
+ Method::Post | Method::Put | Method::Delete | Method::Patch => {
let body = self
.get_request_body(req, connectors)?
.get_inner_value()
@@ -121,7 +123,7 @@ where
)
.change_context(errors::ConnectorError::RequestEncodingFailed)
.attach_printable("Failed to sign the message")?;
- let authz = consts::BASE64_ENGINE.encode(authz);
+ let authz = common_utils::consts::BASE64_ENGINE.encode(authz);
let auth_string: String = format!("HMAC {}:{}", auth.api_key.peek(), authz);
let headers = vec![
@@ -152,14 +154,14 @@ impl ConnectorCommon for Cryptopay {
"application/json"
}
- fn base_url<'a>(&self, connectors: &'a settings::Connectors) -> &'a str {
+ fn base_url<'a>(&self, connectors: &'a Connectors) -> &'a str {
connectors.cryptopay.base_url.as_ref()
}
fn get_auth_header(
&self,
- auth_type: &types::ConnectorAuthType,
- ) -> CustomResult<Vec<(String, request::Maskable<String>)>, errors::ConnectorError> {
+ auth_type: &ConnectorAuthType,
+ ) -> CustomResult<Vec<(String, masking::Maskable<String>)>, errors::ConnectorError> {
let auth = cryptopay::CryptopayAuthType::try_from(auth_type)
.change_context(errors::ConnectorError::FailedToObtainAuthType)?;
Ok(vec![(
@@ -192,32 +194,18 @@ impl ConnectorCommon for Cryptopay {
}
}
-impl ConnectorIntegration<api::Session, types::PaymentsSessionData, types::PaymentsResponseData>
- for Cryptopay
-{
-}
+impl ConnectorIntegration<Session, PaymentsSessionData, PaymentsResponseData> for Cryptopay {}
-impl ConnectorIntegration<api::AccessTokenAuth, types::AccessTokenRequestData, types::AccessToken>
- for Cryptopay
-{
-}
+impl ConnectorIntegration<AccessTokenAuth, AccessTokenRequestData, AccessToken> for Cryptopay {}
-impl
- ConnectorIntegration<
- api::SetupMandate,
- types::SetupMandateRequestData,
- types::PaymentsResponseData,
- > for Cryptopay
+impl ConnectorIntegration<SetupMandate, SetupMandateRequestData, PaymentsResponseData>
+ for Cryptopay
{
fn build_request(
&self,
- _req: &types::RouterData<
- api::SetupMandate,
- types::SetupMandateRequestData,
- types::PaymentsResponseData,
- >,
- _connectors: &settings::Connectors,
- ) -> CustomResult<Option<services::Request>, errors::ConnectorError> {
+ _req: &RouterData<SetupMandate, SetupMandateRequestData, PaymentsResponseData>,
+ _connectors: &Connectors,
+ ) -> CustomResult<Option<Request>, errors::ConnectorError> {
Err(
errors::ConnectorError::NotImplemented("Setup Mandate flow for Cryptopay".to_string())
.into(),
@@ -225,14 +213,12 @@ impl
}
}
-impl ConnectorIntegration<api::Authorize, types::PaymentsAuthorizeData, types::PaymentsResponseData>
- for Cryptopay
-{
+impl ConnectorIntegration<Authorize, PaymentsAuthorizeData, PaymentsResponseData> for Cryptopay {
fn get_headers(
&self,
- req: &types::PaymentsAuthorizeRouterData,
- connectors: &settings::Connectors,
- ) -> CustomResult<Vec<(String, request::Maskable<String>)>, errors::ConnectorError> {
+ req: &PaymentsAuthorizeRouterData,
+ connectors: &Connectors,
+ ) -> CustomResult<Vec<(String, masking::Maskable<String>)>, errors::ConnectorError> {
self.build_headers(req, connectors)
}
@@ -242,16 +228,16 @@ impl ConnectorIntegration<api::Authorize, types::PaymentsAuthorizeData, types::P
fn get_url(
&self,
- _req: &types::PaymentsAuthorizeRouterData,
- connectors: &settings::Connectors,
+ _req: &PaymentsAuthorizeRouterData,
+ connectors: &Connectors,
) -> CustomResult<String, errors::ConnectorError> {
Ok(format!("{}/api/invoices", self.base_url(connectors)))
}
fn get_request_body(
&self,
- req: &types::PaymentsAuthorizeRouterData,
- _connectors: &settings::Connectors,
+ req: &PaymentsAuthorizeRouterData,
+ _connectors: &Connectors,
) -> CustomResult<RequestContent, errors::ConnectorError> {
let amount = utils::convert_amount(
self.amount_converter,
@@ -265,20 +251,16 @@ impl ConnectorIntegration<api::Authorize, types::PaymentsAuthorizeData, types::P
fn build_request(
&self,
- req: &types::PaymentsAuthorizeRouterData,
- connectors: &settings::Connectors,
- ) -> CustomResult<Option<services::Request>, errors::ConnectorError> {
+ req: &PaymentsAuthorizeRouterData,
+ connectors: &Connectors,
+ ) -> CustomResult<Option<Request>, errors::ConnectorError> {
Ok(Some(
- services::RequestBuilder::new()
- .method(services::Method::Post)
- .url(&types::PaymentsAuthorizeType::get_url(
- self, req, connectors,
- )?)
+ RequestBuilder::new()
+ .method(Method::Post)
+ .url(&PaymentsAuthorizeType::get_url(self, req, connectors)?)
.attach_default_headers()
- .headers(types::PaymentsAuthorizeType::get_headers(
- self, req, connectors,
- )?)
- .set_body(types::PaymentsAuthorizeType::get_request_body(
+ .headers(PaymentsAuthorizeType::get_headers(self, req, connectors)?)
+ .set_body(PaymentsAuthorizeType::get_request_body(
self, req, connectors,
)?)
.build(),
@@ -287,10 +269,10 @@ impl ConnectorIntegration<api::Authorize, types::PaymentsAuthorizeData, types::P
fn handle_response(
&self,
- data: &types::PaymentsAuthorizeRouterData,
+ data: &PaymentsAuthorizeRouterData,
event_builder: Option<&mut ConnectorEvent>,
res: Response,
- ) -> CustomResult<types::PaymentsAuthorizeRouterData, errors::ConnectorError> {
+ ) -> CustomResult<PaymentsAuthorizeRouterData, errors::ConnectorError> {
let response: cryptopay::CryptopayPaymentsResponse = res
.response
.parse_struct("Cryptopay PaymentsAuthorizeResponse")
@@ -305,8 +287,8 @@ impl ConnectorIntegration<api::Authorize, types::PaymentsAuthorizeData, types::P
)?),
None => None,
};
- types::RouterData::foreign_try_from((
- types::ResponseRouterData {
+ RouterData::foreign_try_from((
+ ResponseRouterData {
response,
data: data.clone(),
http_code: res.status_code,
@@ -327,7 +309,7 @@ impl ConnectorIntegration<api::Authorize, types::PaymentsAuthorizeData, types::P
impl ConnectorValidation for Cryptopay {
fn validate_psync_reference_id(
&self,
- _data: &hyperswitch_domain_models::router_request_types::PaymentsSyncData,
+ _data: &PaymentsSyncData,
_is_three_ds: bool,
_status: common_enums::enums::AttemptStatus,
_connector_meta_data: Option<common_utils::pii::SecretSerdeValue>,
@@ -337,14 +319,12 @@ impl ConnectorValidation for Cryptopay {
}
}
-impl ConnectorIntegration<api::PSync, types::PaymentsSyncData, types::PaymentsResponseData>
- for Cryptopay
-{
+impl ConnectorIntegration<PSync, PaymentsSyncData, PaymentsResponseData> for Cryptopay {
fn get_headers(
&self,
- req: &types::PaymentsSyncRouterData,
- connectors: &settings::Connectors,
- ) -> CustomResult<Vec<(String, request::Maskable<String>)>, errors::ConnectorError> {
+ req: &PaymentsSyncRouterData,
+ connectors: &Connectors,
+ ) -> CustomResult<Vec<(String, masking::Maskable<String>)>, errors::ConnectorError> {
self.build_headers(req, connectors)
}
@@ -352,14 +332,14 @@ impl ConnectorIntegration<api::PSync, types::PaymentsSyncData, types::PaymentsRe
self.common_get_content_type()
}
- fn get_http_method(&self) -> services::Method {
- services::Method::Get
+ fn get_http_method(&self) -> Method {
+ Method::Get
}
fn get_url(
&self,
- req: &types::PaymentsSyncRouterData,
- connectors: &settings::Connectors,
+ req: &PaymentsSyncRouterData,
+ connectors: &Connectors,
) -> CustomResult<String, errors::ConnectorError> {
let custom_id = req.connector_request_reference_id.clone();
Ok(format!(
@@ -370,25 +350,25 @@ impl ConnectorIntegration<api::PSync, types::PaymentsSyncData, types::PaymentsRe
fn build_request(
&self,
- req: &types::PaymentsSyncRouterData,
- connectors: &settings::Connectors,
- ) -> CustomResult<Option<services::Request>, errors::ConnectorError> {
+ req: &PaymentsSyncRouterData,
+ connectors: &Connectors,
+ ) -> CustomResult<Option<Request>, errors::ConnectorError> {
Ok(Some(
- services::RequestBuilder::new()
- .method(services::Method::Get)
- .url(&types::PaymentsSyncType::get_url(self, req, connectors)?)
+ RequestBuilder::new()
+ .method(Method::Get)
+ .url(&PaymentsSyncType::get_url(self, req, connectors)?)
.attach_default_headers()
- .headers(types::PaymentsSyncType::get_headers(self, req, connectors)?)
+ .headers(PaymentsSyncType::get_headers(self, req, connectors)?)
.build(),
))
}
fn handle_response(
&self,
- data: &types::PaymentsSyncRouterData,
+ data: &PaymentsSyncRouterData,
event_builder: Option<&mut ConnectorEvent>,
res: Response,
- ) -> CustomResult<types::PaymentsSyncRouterData, errors::ConnectorError> {
+ ) -> CustomResult<PaymentsSyncRouterData, errors::ConnectorError> {
let response: cryptopay::CryptopayPaymentsResponse = res
.response
.parse_struct("cryptopay PaymentsSyncResponse")
@@ -403,8 +383,8 @@ impl ConnectorIntegration<api::PSync, types::PaymentsSyncData, types::PaymentsRe
)?),
None => None,
};
- types::RouterData::foreign_try_from((
- types::ResponseRouterData {
+ RouterData::foreign_try_from((
+ ResponseRouterData {
response,
data: data.clone(),
http_code: res.status_code,
@@ -422,38 +402,26 @@ impl ConnectorIntegration<api::PSync, types::PaymentsSyncData, types::PaymentsRe
}
}
-impl ConnectorIntegration<api::Capture, types::PaymentsCaptureData, types::PaymentsResponseData>
- for Cryptopay
-{
-}
+impl ConnectorIntegration<Capture, PaymentsCaptureData, PaymentsResponseData> for Cryptopay {}
-impl ConnectorIntegration<api::Void, types::PaymentsCancelData, types::PaymentsResponseData>
- for Cryptopay
-{
-}
+impl ConnectorIntegration<Void, PaymentsCancelData, PaymentsResponseData> for Cryptopay {}
-impl ConnectorIntegration<api::Execute, types::RefundsData, types::RefundsResponseData>
- for Cryptopay
-{
-}
+impl ConnectorIntegration<Execute, RefundsData, RefundsResponseData> for Cryptopay {}
-impl ConnectorIntegration<api::RSync, types::RefundsData, types::RefundsResponseData>
- for Cryptopay
-{
-}
+impl ConnectorIntegration<RSync, RefundsData, RefundsResponseData> for Cryptopay {}
#[async_trait::async_trait]
-impl api::IncomingWebhook for Cryptopay {
+impl webhooks::IncomingWebhook for Cryptopay {
fn get_webhook_source_verification_algorithm(
&self,
- _request: &api::IncomingWebhookRequestDetails<'_>,
+ _request: &webhooks::IncomingWebhookRequestDetails<'_>,
) -> CustomResult<Box<dyn crypto::VerifySignature + Send>, errors::ConnectorError> {
Ok(Box::new(crypto::HmacSha256))
}
fn get_webhook_source_verification_signature(
&self,
- request: &api::IncomingWebhookRequestDetails<'_>,
+ request: &webhooks::IncomingWebhookRequestDetails<'_>,
_connector_webhook_secrets: &api_models::webhooks::ConnectorWebhookSecrets,
) -> CustomResult<Vec<u8>, errors::ConnectorError> {
let base64_signature =
@@ -464,7 +432,7 @@ impl api::IncomingWebhook for Cryptopay {
fn get_webhook_source_verification_message(
&self,
- request: &api::IncomingWebhookRequestDetails<'_>,
+ request: &webhooks::IncomingWebhookRequestDetails<'_>,
_merchant_id: &common_utils::id_type::MerchantId,
_connector_webhook_secrets: &api_models::webhooks::ConnectorWebhookSecrets,
) -> CustomResult<Vec<u8>, errors::ConnectorError> {
@@ -475,7 +443,7 @@ impl api::IncomingWebhook for Cryptopay {
fn get_webhook_object_reference_id(
&self,
- request: &api::IncomingWebhookRequestDetails<'_>,
+ request: &webhooks::IncomingWebhookRequestDetails<'_>,
) -> CustomResult<api_models::webhooks::ObjectReferenceId, errors::ConnectorError> {
let notif: CryptopayWebhookDetails =
request
@@ -494,8 +462,8 @@ impl api::IncomingWebhook for Cryptopay {
fn get_webhook_event_type(
&self,
- request: &api::IncomingWebhookRequestDetails<'_>,
- ) -> CustomResult<api::IncomingWebhookEvent, errors::ConnectorError> {
+ request: &webhooks::IncomingWebhookRequestDetails<'_>,
+ ) -> CustomResult<api_models::webhooks::IncomingWebhookEvent, errors::ConnectorError> {
let notif: CryptopayWebhookDetails =
request
.body
@@ -503,21 +471,21 @@ impl api::IncomingWebhook for Cryptopay {
.change_context(errors::ConnectorError::WebhookEventTypeNotFound)?;
match notif.data.status {
cryptopay::CryptopayPaymentStatus::Completed => {
- Ok(api::IncomingWebhookEvent::PaymentIntentSuccess)
+ Ok(api_models::webhooks::IncomingWebhookEvent::PaymentIntentSuccess)
}
cryptopay::CryptopayPaymentStatus::Unresolved => {
- Ok(api::IncomingWebhookEvent::PaymentActionRequired)
+ Ok(api_models::webhooks::IncomingWebhookEvent::PaymentActionRequired)
}
cryptopay::CryptopayPaymentStatus::Cancelled => {
- Ok(api::IncomingWebhookEvent::PaymentIntentFailure)
+ Ok(api_models::webhooks::IncomingWebhookEvent::PaymentIntentFailure)
}
- _ => Ok(api::IncomingWebhookEvent::EventNotSupported),
+ _ => Ok(api_models::webhooks::IncomingWebhookEvent::EventNotSupported),
}
}
fn get_webhook_resource_object(
&self,
- request: &api::IncomingWebhookRequestDetails<'_>,
+ request: &webhooks::IncomingWebhookRequestDetails<'_>,
) -> CustomResult<Box<dyn masking::ErasedMaskSerialize>, errors::ConnectorError> {
let notif: CryptopayWebhookDetails =
request
diff --git a/crates/router/src/connector/cryptopay/transformers.rs b/crates/hyperswitch_connectors/src/connectors/cryptopay/transformers.rs
similarity index 76%
rename from crates/router/src/connector/cryptopay/transformers.rs
rename to crates/hyperswitch_connectors/src/connectors/cryptopay/transformers.rs
index cd22890ca52..03a585f76bd 100644
--- a/crates/router/src/connector/cryptopay/transformers.rs
+++ b/crates/hyperswitch_connectors/src/connectors/cryptopay/transformers.rs
@@ -1,17 +1,23 @@
+use common_enums::enums;
use common_utils::{
pii,
types::{MinorUnit, StringMajorUnit},
};
+use hyperswitch_domain_models::{
+ payment_method_data::PaymentMethodData,
+ router_data::{ConnectorAuthType, ErrorResponse, RouterData},
+ router_request_types::ResponseId,
+ router_response_types::{PaymentsResponseData, RedirectForm},
+ types,
+};
+use hyperswitch_interfaces::{consts, errors};
use masking::Secret;
use reqwest::Url;
use serde::{Deserialize, Serialize};
use crate::{
- connector::utils::{self, is_payment_failure, CryptoData, PaymentsAuthorizeRequestData},
- consts,
- core::errors,
- services,
- types::{self, domain, storage::enums, transformers::ForeignTryFrom},
+ types::ResponseRouterData,
+ utils::{self, CryptoData, ForeignTryFrom, PaymentsAuthorizeRequestData},
};
#[derive(Debug, Serialize)]
@@ -51,7 +57,7 @@ impl TryFrom<&CryptopayRouterData<&types::PaymentsAuthorizeRouterData>>
item: &CryptopayRouterData<&types::PaymentsAuthorizeRouterData>,
) -> Result<Self, Self::Error> {
let cryptopay_request = match item.router_data.request.payment_method_data {
- domain::PaymentMethodData::Crypto(ref cryptodata) => {
+ PaymentMethodData::Crypto(ref cryptodata) => {
let pay_currency = cryptodata.get_pay_currency()?;
Ok(Self {
price_amount: item.amount.clone(),
@@ -65,26 +71,24 @@ impl TryFrom<&CryptopayRouterData<&types::PaymentsAuthorizeRouterData>>
custom_id: item.router_data.connector_request_reference_id.clone(),
})
}
- domain::PaymentMethodData::Card(_)
- | domain::PaymentMethodData::CardRedirect(_)
- | domain::PaymentMethodData::Wallet(_)
- | domain::PaymentMethodData::PayLater(_)
- | domain::PaymentMethodData::BankRedirect(_)
- | domain::PaymentMethodData::BankDebit(_)
- | domain::PaymentMethodData::BankTransfer(_)
- | domain::PaymentMethodData::MandatePayment {}
- | domain::PaymentMethodData::Reward {}
- | domain::PaymentMethodData::RealTimePayment(_)
- | domain::PaymentMethodData::Upi(_)
- | domain::PaymentMethodData::Voucher(_)
- | domain::PaymentMethodData::GiftCard(_)
- | domain::PaymentMethodData::OpenBanking(_)
- | domain::PaymentMethodData::CardToken(_)
- | domain::PaymentMethodData::NetworkToken(_) => {
- Err(errors::ConnectorError::NotImplemented(
- utils::get_unimplemented_payment_method_error_message("CryptoPay"),
- ))
- }
+ PaymentMethodData::Card(_)
+ | PaymentMethodData::CardRedirect(_)
+ | PaymentMethodData::Wallet(_)
+ | PaymentMethodData::PayLater(_)
+ | PaymentMethodData::BankRedirect(_)
+ | PaymentMethodData::BankDebit(_)
+ | PaymentMethodData::BankTransfer(_)
+ | PaymentMethodData::MandatePayment {}
+ | PaymentMethodData::Reward {}
+ | PaymentMethodData::RealTimePayment(_)
+ | PaymentMethodData::Upi(_)
+ | PaymentMethodData::Voucher(_)
+ | PaymentMethodData::GiftCard(_)
+ | PaymentMethodData::OpenBanking(_)
+ | PaymentMethodData::CardToken(_)
+ | PaymentMethodData::NetworkToken(_) => Err(errors::ConnectorError::NotImplemented(
+ utils::get_unimplemented_payment_method_error_message("CryptoPay"),
+ )),
}?;
Ok(cryptopay_request)
}
@@ -96,10 +100,10 @@ pub struct CryptopayAuthType {
pub(super) api_secret: Secret<String>,
}
-impl TryFrom<&types::ConnectorAuthType> for CryptopayAuthType {
+impl TryFrom<&ConnectorAuthType> for CryptopayAuthType {
type Error = error_stack::Report<errors::ConnectorError>;
- fn try_from(auth_type: &types::ConnectorAuthType) -> Result<Self, Self::Error> {
- if let types::ConnectorAuthType::BodyKey { api_key, key1 } = auth_type {
+ fn try_from(auth_type: &ConnectorAuthType) -> Result<Self, Self::Error> {
+ if let ConnectorAuthType::BodyKey { api_key, key1 } = auth_type {
Ok(Self {
api_key: api_key.to_owned(),
api_secret: key1.to_owned(),
@@ -140,21 +144,21 @@ pub struct CryptopayPaymentsResponse {
impl<F, T>
ForeignTryFrom<(
- types::ResponseRouterData<F, CryptopayPaymentsResponse, T, types::PaymentsResponseData>,
+ ResponseRouterData<F, CryptopayPaymentsResponse, T, PaymentsResponseData>,
Option<MinorUnit>,
- )> for types::RouterData<F, T, types::PaymentsResponseData>
+ )> for RouterData<F, T, PaymentsResponseData>
{
type Error = error_stack::Report<errors::ConnectorError>;
fn foreign_try_from(
(item, amount_captured_in_minor_units): (
- types::ResponseRouterData<F, CryptopayPaymentsResponse, T, types::PaymentsResponseData>,
+ ResponseRouterData<F, CryptopayPaymentsResponse, T, PaymentsResponseData>,
Option<MinorUnit>,
),
) -> Result<Self, Self::Error> {
let status = enums::AttemptStatus::from(item.response.data.status.clone());
- let response = if is_payment_failure(status) {
+ let response = if utils::is_payment_failure(status) {
let payment_response = &item.response.data;
- Err(types::ErrorResponse {
+ Err(ErrorResponse {
code: payment_response
.name
.clone()
@@ -173,11 +177,9 @@ impl<F, T>
.response
.data
.hosted_page_url
- .map(|x| services::RedirectForm::from((x, services::Method::Get)));
- Ok(types::PaymentsResponseData::TransactionResponse {
- resource_id: types::ResponseId::ConnectorTransactionId(
- item.response.data.id.clone(),
- ),
+ .map(|x| RedirectForm::from((x, common_utils::request::Method::Get)));
+ Ok(PaymentsResponseData::TransactionResponse {
+ resource_id: ResponseId::ConnectorTransactionId(item.response.data.id.clone()),
redirection_data,
mandate_reference: None,
connector_metadata: None,
diff --git a/crates/hyperswitch_connectors/src/connectors/volt/transformers.rs b/crates/hyperswitch_connectors/src/connectors/volt/transformers.rs
index 1093ef4e6f0..953b6316ff8 100644
--- a/crates/hyperswitch_connectors/src/connectors/volt/transformers.rs
+++ b/crates/hyperswitch_connectors/src/connectors/volt/transformers.rs
@@ -14,7 +14,7 @@ use serde::{Deserialize, Serialize};
use crate::{
types::{RefreshTokenRouterData, RefundsResponseRouterData, ResponseRouterData},
- utils::{self, AddressDetailsData, RouterData as _},
+ utils::{self, is_payment_failure, AddressDetailsData, RouterData as _},
};
const PASSWORD: &str = "password";
@@ -605,32 +605,3 @@ pub struct VoltErrorList {
pub property: String,
pub message: String,
}
-
-fn is_payment_failure(status: enums::AttemptStatus) -> bool {
- match status {
- common_enums::AttemptStatus::AuthenticationFailed
- | common_enums::AttemptStatus::AuthorizationFailed
- | common_enums::AttemptStatus::CaptureFailed
- | common_enums::AttemptStatus::VoidFailed
- | common_enums::AttemptStatus::Failure => true,
- common_enums::AttemptStatus::Started
- | common_enums::AttemptStatus::RouterDeclined
- | common_enums::AttemptStatus::AuthenticationPending
- | common_enums::AttemptStatus::AuthenticationSuccessful
- | common_enums::AttemptStatus::Authorized
- | common_enums::AttemptStatus::Charged
- | common_enums::AttemptStatus::Authorizing
- | common_enums::AttemptStatus::CodInitiated
- | common_enums::AttemptStatus::Voided
- | common_enums::AttemptStatus::VoidInitiated
- | common_enums::AttemptStatus::CaptureInitiated
- | common_enums::AttemptStatus::AutoRefunded
- | common_enums::AttemptStatus::PartialCharged
- | common_enums::AttemptStatus::PartialChargedAndChargeable
- | common_enums::AttemptStatus::Unresolved
- | common_enums::AttemptStatus::Pending
- | common_enums::AttemptStatus::PaymentMethodAwaited
- | common_enums::AttemptStatus::ConfirmationAwaited
- | common_enums::AttemptStatus::DeviceDataCollectionPending => false,
- }
-}
diff --git a/crates/hyperswitch_connectors/src/constants.rs b/crates/hyperswitch_connectors/src/constants.rs
index c5ca6512a34..4c27e11fc45 100644
--- a/crates/hyperswitch_connectors/src/constants.rs
+++ b/crates/hyperswitch_connectors/src/constants.rs
@@ -10,6 +10,8 @@ pub(crate) mod headers {
pub(crate) const MERCHANT_ID: &str = "Merchant-ID";
pub(crate) const TIMESTAMP: &str = "Timestamp";
pub(crate) const X_ACCEPT_VERSION: &str = "X-Accept-Version";
+ pub(crate) const X_CC_API_KEY: &str = "X-CC-Api-Key";
+ pub(crate) const X_CC_VERSION: &str = "X-CC-Version";
pub(crate) const X_NN_ACCESS_KEY: &str = "X-NN-Access-Key";
pub(crate) const X_RANDOM_VALUE: &str = "X-RandomValue";
pub(crate) const X_REQUEST_DATE: &str = "X-RequestDate";
diff --git a/crates/hyperswitch_connectors/src/default_implementations.rs b/crates/hyperswitch_connectors/src/default_implementations.rs
index a667c5ddc3c..31052ab0df2 100644
--- a/crates/hyperswitch_connectors/src/default_implementations.rs
+++ b/crates/hyperswitch_connectors/src/default_implementations.rs
@@ -91,6 +91,9 @@ macro_rules! default_imp_for_authorize_session_token {
default_imp_for_authorize_session_token!(
connectors::Bambora,
connectors::Bitpay,
+ connectors::Cashtocode,
+ connectors::Coinbase,
+ connectors::Cryptopay,
connectors::Deutschebank,
connectors::Fiserv,
connectors::Fiservemea,
@@ -126,6 +129,9 @@ macro_rules! default_imp_for_calculate_tax {
default_imp_for_calculate_tax!(
connectors::Bambora,
connectors::Bitpay,
+ connectors::Cashtocode,
+ connectors::Coinbase,
+ connectors::Cryptopay,
connectors::Fiserv,
connectors::Fiservemea,
connectors::Helcim,
@@ -160,6 +166,9 @@ macro_rules! default_imp_for_session_update {
default_imp_for_session_update!(
connectors::Bambora,
connectors::Bitpay,
+ connectors::Cashtocode,
+ connectors::Coinbase,
+ connectors::Cryptopay,
connectors::Fiserv,
connectors::Fiservemea,
connectors::Helcim,
@@ -196,6 +205,9 @@ macro_rules! default_imp_for_complete_authorize {
default_imp_for_complete_authorize!(
connectors::Bitpay,
+ connectors::Cashtocode,
+ connectors::Coinbase,
+ connectors::Cryptopay,
connectors::Fiserv,
connectors::Fiservemea,
connectors::Fiuu,
@@ -229,6 +241,9 @@ macro_rules! default_imp_for_incremental_authorization {
default_imp_for_incremental_authorization!(
connectors::Bambora,
connectors::Bitpay,
+ connectors::Cashtocode,
+ connectors::Coinbase,
+ connectors::Cryptopay,
connectors::Deutschebank,
connectors::Fiserv,
connectors::Fiservemea,
@@ -265,6 +280,9 @@ macro_rules! default_imp_for_create_customer {
default_imp_for_create_customer!(
connectors::Bambora,
connectors::Bitpay,
+ connectors::Cashtocode,
+ connectors::Coinbase,
+ connectors::Cryptopay,
connectors::Deutschebank,
connectors::Fiserv,
connectors::Fiservemea,
@@ -301,6 +319,9 @@ macro_rules! default_imp_for_connector_redirect_response {
default_imp_for_connector_redirect_response!(
connectors::Bitpay,
+ connectors::Cashtocode,
+ connectors::Coinbase,
+ connectors::Cryptopay,
connectors::Deutschebank,
connectors::Fiserv,
connectors::Fiservemea,
@@ -335,6 +356,9 @@ macro_rules! default_imp_for_pre_processing_steps{
default_imp_for_pre_processing_steps!(
connectors::Bambora,
connectors::Bitpay,
+ connectors::Cashtocode,
+ connectors::Coinbase,
+ connectors::Cryptopay,
connectors::Deutschebank,
connectors::Fiserv,
connectors::Fiservemea,
@@ -371,6 +395,9 @@ macro_rules! default_imp_for_post_processing_steps{
default_imp_for_post_processing_steps!(
connectors::Bambora,
connectors::Bitpay,
+ connectors::Cashtocode,
+ connectors::Coinbase,
+ connectors::Cryptopay,
connectors::Deutschebank,
connectors::Fiserv,
connectors::Fiservemea,
@@ -407,6 +434,9 @@ macro_rules! default_imp_for_approve {
default_imp_for_approve!(
connectors::Bambora,
connectors::Bitpay,
+ connectors::Cashtocode,
+ connectors::Coinbase,
+ connectors::Cryptopay,
connectors::Deutschebank,
connectors::Fiserv,
connectors::Fiservemea,
@@ -443,6 +473,9 @@ macro_rules! default_imp_for_reject {
default_imp_for_reject!(
connectors::Bambora,
connectors::Bitpay,
+ connectors::Cashtocode,
+ connectors::Coinbase,
+ connectors::Cryptopay,
connectors::Deutschebank,
connectors::Fiserv,
connectors::Fiservemea,
@@ -479,6 +512,9 @@ macro_rules! default_imp_for_webhook_source_verification {
default_imp_for_webhook_source_verification!(
connectors::Bambora,
connectors::Bitpay,
+ connectors::Cashtocode,
+ connectors::Coinbase,
+ connectors::Cryptopay,
connectors::Deutschebank,
connectors::Fiserv,
connectors::Fiservemea,
@@ -516,6 +552,9 @@ macro_rules! default_imp_for_accept_dispute {
default_imp_for_accept_dispute!(
connectors::Bambora,
connectors::Bitpay,
+ connectors::Cashtocode,
+ connectors::Coinbase,
+ connectors::Cryptopay,
connectors::Deutschebank,
connectors::Fiserv,
connectors::Fiservemea,
@@ -552,6 +591,9 @@ macro_rules! default_imp_for_submit_evidence {
default_imp_for_submit_evidence!(
connectors::Bambora,
connectors::Bitpay,
+ connectors::Cashtocode,
+ connectors::Coinbase,
+ connectors::Cryptopay,
connectors::Deutschebank,
connectors::Fiserv,
connectors::Fiservemea,
@@ -588,6 +630,9 @@ macro_rules! default_imp_for_defend_dispute {
default_imp_for_defend_dispute!(
connectors::Bambora,
connectors::Bitpay,
+ connectors::Cashtocode,
+ connectors::Coinbase,
+ connectors::Cryptopay,
connectors::Deutschebank,
connectors::Fiserv,
connectors::Fiservemea,
@@ -633,6 +678,9 @@ macro_rules! default_imp_for_file_upload {
default_imp_for_file_upload!(
connectors::Bambora,
connectors::Bitpay,
+ connectors::Cashtocode,
+ connectors::Coinbase,
+ connectors::Cryptopay,
connectors::Deutschebank,
connectors::Fiserv,
connectors::Fiservemea,
@@ -671,6 +719,9 @@ macro_rules! default_imp_for_payouts_create {
default_imp_for_payouts_create!(
connectors::Bambora,
connectors::Bitpay,
+ connectors::Cashtocode,
+ connectors::Coinbase,
+ connectors::Cryptopay,
connectors::Deutschebank,
connectors::Fiserv,
connectors::Fiservemea,
@@ -709,6 +760,9 @@ macro_rules! default_imp_for_payouts_retrieve {
default_imp_for_payouts_retrieve!(
connectors::Bambora,
connectors::Bitpay,
+ connectors::Cashtocode,
+ connectors::Coinbase,
+ connectors::Cryptopay,
connectors::Deutschebank,
connectors::Fiserv,
connectors::Fiservemea,
@@ -747,6 +801,9 @@ macro_rules! default_imp_for_payouts_eligibility {
default_imp_for_payouts_eligibility!(
connectors::Bambora,
connectors::Bitpay,
+ connectors::Cashtocode,
+ connectors::Coinbase,
+ connectors::Cryptopay,
connectors::Deutschebank,
connectors::Fiserv,
connectors::Fiservemea,
@@ -785,6 +842,9 @@ macro_rules! default_imp_for_payouts_fulfill {
default_imp_for_payouts_fulfill!(
connectors::Bambora,
connectors::Bitpay,
+ connectors::Cashtocode,
+ connectors::Coinbase,
+ connectors::Cryptopay,
connectors::Deutschebank,
connectors::Fiserv,
connectors::Fiservemea,
@@ -823,6 +883,9 @@ macro_rules! default_imp_for_payouts_cancel {
default_imp_for_payouts_cancel!(
connectors::Bambora,
connectors::Bitpay,
+ connectors::Cashtocode,
+ connectors::Coinbase,
+ connectors::Cryptopay,
connectors::Deutschebank,
connectors::Fiserv,
connectors::Fiservemea,
@@ -861,6 +924,9 @@ macro_rules! default_imp_for_payouts_quote {
default_imp_for_payouts_quote!(
connectors::Bambora,
connectors::Bitpay,
+ connectors::Cashtocode,
+ connectors::Coinbase,
+ connectors::Cryptopay,
connectors::Deutschebank,
connectors::Fiserv,
connectors::Fiservemea,
@@ -899,6 +965,9 @@ macro_rules! default_imp_for_payouts_recipient {
default_imp_for_payouts_recipient!(
connectors::Bambora,
connectors::Bitpay,
+ connectors::Cashtocode,
+ connectors::Coinbase,
+ connectors::Cryptopay,
connectors::Deutschebank,
connectors::Fiserv,
connectors::Fiservemea,
@@ -937,6 +1006,9 @@ macro_rules! default_imp_for_payouts_recipient_account {
default_imp_for_payouts_recipient_account!(
connectors::Bambora,
connectors::Bitpay,
+ connectors::Cashtocode,
+ connectors::Coinbase,
+ connectors::Cryptopay,
connectors::Deutschebank,
connectors::Fiserv,
connectors::Fiservemea,
@@ -975,6 +1047,9 @@ macro_rules! default_imp_for_frm_sale {
default_imp_for_frm_sale!(
connectors::Bambora,
connectors::Bitpay,
+ connectors::Cashtocode,
+ connectors::Coinbase,
+ connectors::Cryptopay,
connectors::Deutschebank,
connectors::Fiserv,
connectors::Fiservemea,
@@ -1013,6 +1088,9 @@ macro_rules! default_imp_for_frm_checkout {
default_imp_for_frm_checkout!(
connectors::Bambora,
connectors::Bitpay,
+ connectors::Cashtocode,
+ connectors::Coinbase,
+ connectors::Cryptopay,
connectors::Deutschebank,
connectors::Fiserv,
connectors::Fiservemea,
@@ -1051,6 +1129,9 @@ macro_rules! default_imp_for_frm_transaction {
default_imp_for_frm_transaction!(
connectors::Bambora,
connectors::Bitpay,
+ connectors::Cashtocode,
+ connectors::Coinbase,
+ connectors::Cryptopay,
connectors::Deutschebank,
connectors::Fiserv,
connectors::Fiservemea,
@@ -1089,6 +1170,9 @@ macro_rules! default_imp_for_frm_fulfillment {
default_imp_for_frm_fulfillment!(
connectors::Bambora,
connectors::Bitpay,
+ connectors::Cashtocode,
+ connectors::Coinbase,
+ connectors::Cryptopay,
connectors::Deutschebank,
connectors::Fiserv,
connectors::Fiservemea,
@@ -1127,6 +1211,9 @@ macro_rules! default_imp_for_frm_record_return {
default_imp_for_frm_record_return!(
connectors::Bambora,
connectors::Bitpay,
+ connectors::Cashtocode,
+ connectors::Coinbase,
+ connectors::Cryptopay,
connectors::Deutschebank,
connectors::Fiserv,
connectors::Fiservemea,
@@ -1162,6 +1249,9 @@ macro_rules! default_imp_for_revoking_mandates {
default_imp_for_revoking_mandates!(
connectors::Bambora,
connectors::Bitpay,
+ connectors::Cashtocode,
+ connectors::Coinbase,
+ connectors::Cryptopay,
connectors::Deutschebank,
connectors::Fiserv,
connectors::Fiservemea,
diff --git a/crates/hyperswitch_connectors/src/default_implementations_v2.rs b/crates/hyperswitch_connectors/src/default_implementations_v2.rs
index 3bb1abfef21..16e592688ac 100644
--- a/crates/hyperswitch_connectors/src/default_implementations_v2.rs
+++ b/crates/hyperswitch_connectors/src/default_implementations_v2.rs
@@ -198,6 +198,9 @@ macro_rules! default_imp_for_new_connector_integration_payment {
default_imp_for_new_connector_integration_payment!(
connectors::Bambora,
connectors::Bitpay,
+ connectors::Cashtocode,
+ connectors::Coinbase,
+ connectors::Cryptopay,
connectors::Deutschebank,
connectors::Fiserv,
connectors::Fiservemea,
@@ -235,6 +238,9 @@ macro_rules! default_imp_for_new_connector_integration_refund {
default_imp_for_new_connector_integration_refund!(
connectors::Bambora,
connectors::Bitpay,
+ connectors::Cashtocode,
+ connectors::Coinbase,
+ connectors::Cryptopay,
connectors::Deutschebank,
connectors::Fiserv,
connectors::Fiservemea,
@@ -267,6 +273,9 @@ macro_rules! default_imp_for_new_connector_integration_connector_access_token {
default_imp_for_new_connector_integration_connector_access_token!(
connectors::Bambora,
connectors::Bitpay,
+ connectors::Cashtocode,
+ connectors::Coinbase,
+ connectors::Cryptopay,
connectors::Deutschebank,
connectors::Fiserv,
connectors::Fiservemea,
@@ -305,6 +314,9 @@ macro_rules! default_imp_for_new_connector_integration_accept_dispute {
default_imp_for_new_connector_integration_accept_dispute!(
connectors::Bambora,
connectors::Bitpay,
+ connectors::Cashtocode,
+ connectors::Coinbase,
+ connectors::Cryptopay,
connectors::Deutschebank,
connectors::Fiserv,
connectors::Fiservemea,
@@ -342,6 +354,9 @@ macro_rules! default_imp_for_new_connector_integration_submit_evidence {
default_imp_for_new_connector_integration_submit_evidence!(
connectors::Bambora,
connectors::Bitpay,
+ connectors::Cashtocode,
+ connectors::Coinbase,
+ connectors::Cryptopay,
connectors::Deutschebank,
connectors::Fiserv,
connectors::Fiservemea,
@@ -379,6 +394,9 @@ macro_rules! default_imp_for_new_connector_integration_defend_dispute {
default_imp_for_new_connector_integration_defend_dispute!(
connectors::Bambora,
connectors::Bitpay,
+ connectors::Cashtocode,
+ connectors::Coinbase,
+ connectors::Cryptopay,
connectors::Deutschebank,
connectors::Fiserv,
connectors::Fiservemea,
@@ -426,6 +444,9 @@ macro_rules! default_imp_for_new_connector_integration_file_upload {
default_imp_for_new_connector_integration_file_upload!(
connectors::Bambora,
connectors::Bitpay,
+ connectors::Cashtocode,
+ connectors::Coinbase,
+ connectors::Cryptopay,
connectors::Deutschebank,
connectors::Fiserv,
connectors::Fiservemea,
@@ -465,6 +486,9 @@ macro_rules! default_imp_for_new_connector_integration_payouts_create {
default_imp_for_new_connector_integration_payouts_create!(
connectors::Bambora,
connectors::Bitpay,
+ connectors::Cashtocode,
+ connectors::Coinbase,
+ connectors::Cryptopay,
connectors::Deutschebank,
connectors::Fiserv,
connectors::Fiservemea,
@@ -504,6 +528,9 @@ macro_rules! default_imp_for_new_connector_integration_payouts_eligibility {
default_imp_for_new_connector_integration_payouts_eligibility!(
connectors::Bambora,
connectors::Bitpay,
+ connectors::Cashtocode,
+ connectors::Coinbase,
+ connectors::Cryptopay,
connectors::Deutschebank,
connectors::Fiserv,
connectors::Fiservemea,
@@ -543,6 +570,9 @@ macro_rules! default_imp_for_new_connector_integration_payouts_fulfill {
default_imp_for_new_connector_integration_payouts_fulfill!(
connectors::Bambora,
connectors::Bitpay,
+ connectors::Cashtocode,
+ connectors::Coinbase,
+ connectors::Cryptopay,
connectors::Deutschebank,
connectors::Fiserv,
connectors::Fiservemea,
@@ -582,6 +612,9 @@ macro_rules! default_imp_for_new_connector_integration_payouts_cancel {
default_imp_for_new_connector_integration_payouts_cancel!(
connectors::Bambora,
connectors::Bitpay,
+ connectors::Cashtocode,
+ connectors::Coinbase,
+ connectors::Cryptopay,
connectors::Deutschebank,
connectors::Fiserv,
connectors::Fiservemea,
@@ -621,6 +654,9 @@ macro_rules! default_imp_for_new_connector_integration_payouts_quote {
default_imp_for_new_connector_integration_payouts_quote!(
connectors::Bambora,
connectors::Bitpay,
+ connectors::Cashtocode,
+ connectors::Coinbase,
+ connectors::Cryptopay,
connectors::Deutschebank,
connectors::Fiserv,
connectors::Fiservemea,
@@ -660,6 +696,9 @@ macro_rules! default_imp_for_new_connector_integration_payouts_recipient {
default_imp_for_new_connector_integration_payouts_recipient!(
connectors::Bambora,
connectors::Bitpay,
+ connectors::Cashtocode,
+ connectors::Coinbase,
+ connectors::Cryptopay,
connectors::Deutschebank,
connectors::Fiserv,
connectors::Fiservemea,
@@ -699,6 +738,9 @@ macro_rules! default_imp_for_new_connector_integration_payouts_sync {
default_imp_for_new_connector_integration_payouts_sync!(
connectors::Bambora,
connectors::Bitpay,
+ connectors::Cashtocode,
+ connectors::Coinbase,
+ connectors::Cryptopay,
connectors::Deutschebank,
connectors::Fiserv,
connectors::Fiservemea,
@@ -738,6 +780,9 @@ macro_rules! default_imp_for_new_connector_integration_payouts_recipient_account
default_imp_for_new_connector_integration_payouts_recipient_account!(
connectors::Bambora,
connectors::Bitpay,
+ connectors::Cashtocode,
+ connectors::Coinbase,
+ connectors::Cryptopay,
connectors::Deutschebank,
connectors::Fiserv,
connectors::Fiservemea,
@@ -775,6 +820,9 @@ macro_rules! default_imp_for_new_connector_integration_webhook_source_verificati
default_imp_for_new_connector_integration_webhook_source_verification!(
connectors::Bambora,
connectors::Bitpay,
+ connectors::Cashtocode,
+ connectors::Coinbase,
+ connectors::Cryptopay,
connectors::Deutschebank,
connectors::Fiserv,
connectors::Fiservemea,
@@ -814,6 +862,9 @@ macro_rules! default_imp_for_new_connector_integration_frm_sale {
default_imp_for_new_connector_integration_frm_sale!(
connectors::Bambora,
connectors::Bitpay,
+ connectors::Cashtocode,
+ connectors::Coinbase,
+ connectors::Cryptopay,
connectors::Deutschebank,
connectors::Fiserv,
connectors::Fiservemea,
@@ -853,6 +904,9 @@ macro_rules! default_imp_for_new_connector_integration_frm_checkout {
default_imp_for_new_connector_integration_frm_checkout!(
connectors::Bambora,
connectors::Bitpay,
+ connectors::Cashtocode,
+ connectors::Coinbase,
+ connectors::Cryptopay,
connectors::Deutschebank,
connectors::Fiserv,
connectors::Fiservemea,
@@ -892,6 +946,9 @@ macro_rules! default_imp_for_new_connector_integration_frm_transaction {
default_imp_for_new_connector_integration_frm_transaction!(
connectors::Bambora,
connectors::Bitpay,
+ connectors::Cashtocode,
+ connectors::Coinbase,
+ connectors::Cryptopay,
connectors::Deutschebank,
connectors::Fiserv,
connectors::Fiservemea,
@@ -931,6 +988,9 @@ macro_rules! default_imp_for_new_connector_integration_frm_fulfillment {
default_imp_for_new_connector_integration_frm_fulfillment!(
connectors::Bambora,
connectors::Bitpay,
+ connectors::Cashtocode,
+ connectors::Coinbase,
+ connectors::Cryptopay,
connectors::Deutschebank,
connectors::Fiserv,
connectors::Fiservemea,
@@ -970,6 +1030,9 @@ macro_rules! default_imp_for_new_connector_integration_frm_record_return {
default_imp_for_new_connector_integration_frm_record_return!(
connectors::Bambora,
connectors::Bitpay,
+ connectors::Cashtocode,
+ connectors::Coinbase,
+ connectors::Cryptopay,
connectors::Deutschebank,
connectors::Fiserv,
connectors::Fiservemea,
@@ -1006,6 +1069,9 @@ macro_rules! default_imp_for_new_connector_integration_revoking_mandates {
default_imp_for_new_connector_integration_revoking_mandates!(
connectors::Bambora,
connectors::Bitpay,
+ connectors::Cashtocode,
+ connectors::Coinbase,
+ connectors::Cryptopay,
connectors::Deutschebank,
connectors::Fiserv,
connectors::Fiservemea,
diff --git a/crates/hyperswitch_connectors/src/utils.rs b/crates/hyperswitch_connectors/src/utils.rs
index b2979975e55..f96d715f5be 100644
--- a/crates/hyperswitch_connectors/src/utils.rs
+++ b/crates/hyperswitch_connectors/src/utils.rs
@@ -4,7 +4,7 @@ use api_models::payments::{self, Address, AddressDetails, OrderDetailsWithAmount
use base64::Engine;
use common_enums::{
enums,
- enums::{CanadaStatesAbbreviation, FutureUsage, UsStatesAbbreviation},
+ enums::{AttemptStatus, CanadaStatesAbbreviation, FutureUsage, UsStatesAbbreviation},
};
use common_utils::{
consts::BASE64_ENGINE,
@@ -163,6 +163,35 @@ pub(crate) fn convert_back_amount_to_minor_units<T>(
.change_context(errors::ConnectorError::AmountConversionFailed)
}
+pub(crate) fn is_payment_failure(status: AttemptStatus) -> bool {
+ match status {
+ AttemptStatus::AuthenticationFailed
+ | AttemptStatus::AuthorizationFailed
+ | AttemptStatus::CaptureFailed
+ | AttemptStatus::VoidFailed
+ | AttemptStatus::Failure => true,
+ AttemptStatus::Started
+ | AttemptStatus::RouterDeclined
+ | AttemptStatus::AuthenticationPending
+ | AttemptStatus::AuthenticationSuccessful
+ | AttemptStatus::Authorized
+ | AttemptStatus::Charged
+ | AttemptStatus::Authorizing
+ | AttemptStatus::CodInitiated
+ | AttemptStatus::Voided
+ | AttemptStatus::VoidInitiated
+ | AttemptStatus::CaptureInitiated
+ | AttemptStatus::AutoRefunded
+ | AttemptStatus::PartialCharged
+ | AttemptStatus::PartialChargedAndChargeable
+ | AttemptStatus::Unresolved
+ | AttemptStatus::Pending
+ | AttemptStatus::PaymentMethodAwaited
+ | AttemptStatus::ConfirmationAwaited
+ | AttemptStatus::DeviceDataCollectionPending => false,
+ }
+}
+
// TODO: Make all traits as `pub(crate) trait` once all connectors are moved.
pub trait RouterData {
fn get_billing(&self) -> Result<&Address, Error>;
@@ -1460,6 +1489,18 @@ fn get_header_field(
))?
}
+pub trait CryptoData {
+ fn get_pay_currency(&self) -> Result<String, Error>;
+}
+
+impl CryptoData for hyperswitch_domain_models::payment_method_data::CryptoData {
+ fn get_pay_currency(&self) -> Result<String, Error> {
+ self.pay_currency
+ .clone()
+ .ok_or_else(missing_field_err("crypto_data.pay_currency"))
+ }
+}
+
#[macro_export]
macro_rules! unimplemented_payment_method {
($payment_method:expr, $connector:expr) => {
diff --git a/crates/router/src/connector.rs b/crates/router/src/connector.rs
index b505f8c8c52..116fc67320f 100644
--- a/crates/router/src/connector.rs
+++ b/crates/router/src/connector.rs
@@ -9,10 +9,7 @@ pub mod billwerk;
pub mod bluesnap;
pub mod boku;
pub mod braintree;
-pub mod cashtocode;
pub mod checkout;
-pub mod coinbase;
-pub mod cryptopay;
pub mod cybersource;
pub mod datatrans;
pub mod dlocal;
@@ -62,12 +59,13 @@ pub mod zen;
pub mod zsl;
pub use hyperswitch_connectors::connectors::{
- bambora, bambora::Bambora, bitpay, bitpay::Bitpay, deutschebank, deutschebank::Deutschebank,
- fiserv, fiserv::Fiserv, fiservemea, fiservemea::Fiservemea, fiuu, fiuu::Fiuu, globepay,
- globepay::Globepay, helcim, helcim::Helcim, mollie, mollie::Mollie, nexixpay,
- nexixpay::Nexixpay, novalnet, novalnet::Novalnet, powertranz, powertranz::Powertranz, stax,
- stax::Stax, taxjar, taxjar::Taxjar, thunes, thunes::Thunes, tsys, tsys::Tsys, volt, volt::Volt,
- worldline, worldline::Worldline,
+ bambora, bambora::Bambora, bitpay, bitpay::Bitpay, cashtocode, cashtocode::Cashtocode,
+ coinbase, coinbase::Coinbase, cryptopay, cryptopay::Cryptopay, deutschebank,
+ deutschebank::Deutschebank, fiserv, fiserv::Fiserv, fiservemea, fiservemea::Fiservemea, fiuu,
+ fiuu::Fiuu, globepay, globepay::Globepay, helcim, helcim::Helcim, mollie, mollie::Mollie,
+ nexixpay, nexixpay::Nexixpay, novalnet, novalnet::Novalnet, powertranz, powertranz::Powertranz,
+ stax, stax::Stax, taxjar, taxjar::Taxjar, thunes, thunes::Thunes, tsys, tsys::Tsys, volt,
+ volt::Volt, worldline, worldline::Worldline,
};
#[cfg(feature = "dummy_connector")]
@@ -75,8 +73,7 @@ pub use self::dummyconnector::DummyConnector;
pub use self::{
aci::Aci, adyen::Adyen, adyenplatform::Adyenplatform, airwallex::Airwallex,
authorizedotnet::Authorizedotnet, bamboraapac::Bamboraapac, bankofamerica::Bankofamerica,
- billwerk::Billwerk, bluesnap::Bluesnap, boku::Boku, braintree::Braintree,
- cashtocode::Cashtocode, checkout::Checkout, coinbase::Coinbase, cryptopay::Cryptopay,
+ billwerk::Billwerk, bluesnap::Bluesnap, boku::Boku, braintree::Braintree, checkout::Checkout,
cybersource::Cybersource, datatrans::Datatrans, dlocal::Dlocal, ebanx::Ebanx, forte::Forte,
globalpay::Globalpay, gocardless::Gocardless, gpayments::Gpayments, iatapay::Iatapay,
itaubank::Itaubank, klarna::Klarna, mifinity::Mifinity, multisafepay::Multisafepay,
diff --git a/crates/router/src/core/payments/connector_integration_v2_impls.rs b/crates/router/src/core/payments/connector_integration_v2_impls.rs
index 041b5bb7359..3ff93cf9bf0 100644
--- a/crates/router/src/core/payments/connector_integration_v2_impls.rs
+++ b/crates/router/src/core/payments/connector_integration_v2_impls.rs
@@ -682,10 +682,7 @@ default_imp_for_new_connector_integration_payment!(
connector::Bluesnap,
connector::Boku,
connector::Braintree,
- connector::Cashtocode,
connector::Checkout,
- connector::Cryptopay,
- connector::Coinbase,
connector::Cybersource,
connector::Datatrans,
connector::Dlocal,
@@ -760,10 +757,7 @@ default_imp_for_new_connector_integration_refund!(
connector::Bluesnap,
connector::Boku,
connector::Braintree,
- connector::Cashtocode,
connector::Checkout,
- connector::Cryptopay,
- connector::Coinbase,
connector::Cybersource,
connector::Datatrans,
connector::Dlocal,
@@ -832,10 +826,7 @@ default_imp_for_new_connector_integration_connector_access_token!(
connector::Bluesnap,
connector::Boku,
connector::Braintree,
- connector::Cashtocode,
connector::Checkout,
- connector::Cryptopay,
- connector::Coinbase,
connector::Cybersource,
connector::Datatrans,
connector::Dlocal,
@@ -926,10 +917,7 @@ default_imp_for_new_connector_integration_accept_dispute!(
connector::Bluesnap,
connector::Boku,
connector::Braintree,
- connector::Cashtocode,
connector::Checkout,
- connector::Cryptopay,
- connector::Coinbase,
connector::Cybersource,
connector::Datatrans,
connector::Dlocal,
@@ -1002,10 +990,7 @@ default_imp_for_new_connector_integration_defend_dispute!(
connector::Bluesnap,
connector::Boku,
connector::Braintree,
- connector::Cashtocode,
connector::Checkout,
- connector::Cryptopay,
- connector::Coinbase,
connector::Cybersource,
connector::Datatrans,
connector::Dlocal,
@@ -1062,10 +1047,7 @@ default_imp_for_new_connector_integration_submit_evidence!(
connector::Bluesnap,
connector::Boku,
connector::Braintree,
- connector::Cashtocode,
connector::Checkout,
- connector::Cryptopay,
- connector::Coinbase,
connector::Cybersource,
connector::Datatrans,
connector::Dlocal,
@@ -1149,10 +1131,7 @@ default_imp_for_new_connector_integration_file_upload!(
connector::Bluesnap,
connector::Boku,
connector::Braintree,
- connector::Cashtocode,
connector::Checkout,
- connector::Cryptopay,
- connector::Coinbase,
connector::Cybersource,
connector::Datatrans,
connector::Dlocal,
@@ -1315,10 +1294,7 @@ default_imp_for_new_connector_integration_payouts_create!(
connector::Bluesnap,
connector::Boku,
connector::Braintree,
- connector::Cashtocode,
connector::Checkout,
- connector::Cryptopay,
- connector::Coinbase,
connector::Cybersource,
connector::Datatrans,
connector::Dlocal,
@@ -1394,10 +1370,7 @@ default_imp_for_new_connector_integration_payouts_eligibility!(
connector::Bluesnap,
connector::Boku,
connector::Braintree,
- connector::Cashtocode,
connector::Checkout,
- connector::Cryptopay,
- connector::Coinbase,
connector::Cybersource,
connector::Datatrans,
connector::Dlocal,
@@ -1473,10 +1446,7 @@ default_imp_for_new_connector_integration_payouts_fulfill!(
connector::Bluesnap,
connector::Boku,
connector::Braintree,
- connector::Cashtocode,
connector::Checkout,
- connector::Cryptopay,
- connector::Coinbase,
connector::Cybersource,
connector::Datatrans,
connector::Dlocal,
@@ -1552,10 +1522,7 @@ default_imp_for_new_connector_integration_payouts_cancel!(
connector::Bluesnap,
connector::Boku,
connector::Braintree,
- connector::Cashtocode,
connector::Checkout,
- connector::Cryptopay,
- connector::Coinbase,
connector::Cybersource,
connector::Datatrans,
connector::Dlocal,
@@ -1631,10 +1598,7 @@ default_imp_for_new_connector_integration_payouts_quote!(
connector::Bluesnap,
connector::Boku,
connector::Braintree,
- connector::Cashtocode,
connector::Checkout,
- connector::Cryptopay,
- connector::Coinbase,
connector::Cybersource,
connector::Datatrans,
connector::Dlocal,
@@ -1710,10 +1674,7 @@ default_imp_for_new_connector_integration_payouts_recipient!(
connector::Bluesnap,
connector::Boku,
connector::Braintree,
- connector::Cashtocode,
connector::Checkout,
- connector::Cryptopay,
- connector::Coinbase,
connector::Cybersource,
connector::Datatrans,
connector::Dlocal,
@@ -1789,10 +1750,7 @@ default_imp_for_new_connector_integration_payouts_sync!(
connector::Bluesnap,
connector::Boku,
connector::Braintree,
- connector::Cashtocode,
connector::Checkout,
- connector::Cryptopay,
- connector::Coinbase,
connector::Cybersource,
connector::Datatrans,
connector::Dlocal,
@@ -1868,10 +1826,7 @@ default_imp_for_new_connector_integration_payouts_recipient_account!(
connector::Bluesnap,
connector::Boku,
connector::Braintree,
- connector::Cashtocode,
connector::Checkout,
- connector::Cryptopay,
- connector::Coinbase,
connector::Cybersource,
connector::Datatrans,
connector::Dlocal,
@@ -1945,10 +1900,7 @@ default_imp_for_new_connector_integration_webhook_source_verification!(
connector::Bluesnap,
connector::Boku,
connector::Braintree,
- connector::Cashtocode,
connector::Checkout,
- connector::Cryptopay,
- connector::Coinbase,
connector::Cybersource,
connector::Datatrans,
connector::Dlocal,
@@ -2111,10 +2063,7 @@ default_imp_for_new_connector_integration_frm_sale!(
connector::Bluesnap,
connector::Boku,
connector::Braintree,
- connector::Cashtocode,
connector::Checkout,
- connector::Cryptopay,
- connector::Coinbase,
connector::Cybersource,
connector::Datatrans,
connector::Dlocal,
@@ -2190,10 +2139,7 @@ default_imp_for_new_connector_integration_frm_checkout!(
connector::Bluesnap,
connector::Boku,
connector::Braintree,
- connector::Cashtocode,
connector::Checkout,
- connector::Cryptopay,
- connector::Coinbase,
connector::Cybersource,
connector::Datatrans,
connector::Dlocal,
@@ -2269,10 +2215,7 @@ default_imp_for_new_connector_integration_frm_transaction!(
connector::Bluesnap,
connector::Boku,
connector::Braintree,
- connector::Cashtocode,
connector::Checkout,
- connector::Cryptopay,
- connector::Coinbase,
connector::Cybersource,
connector::Datatrans,
connector::Dlocal,
@@ -2348,10 +2291,7 @@ default_imp_for_new_connector_integration_frm_fulfillment!(
connector::Bluesnap,
connector::Boku,
connector::Braintree,
- connector::Cashtocode,
connector::Checkout,
- connector::Cryptopay,
- connector::Coinbase,
connector::Cybersource,
connector::Datatrans,
connector::Dlocal,
@@ -2427,10 +2367,7 @@ default_imp_for_new_connector_integration_frm_record_return!(
connector::Bluesnap,
connector::Boku,
connector::Braintree,
- connector::Cashtocode,
connector::Checkout,
- connector::Cryptopay,
- connector::Coinbase,
connector::Cybersource,
connector::Datatrans,
connector::Dlocal,
@@ -2503,10 +2440,7 @@ default_imp_for_new_connector_integration_revoking_mandates!(
connector::Bluesnap,
connector::Boku,
connector::Braintree,
- connector::Cashtocode,
connector::Checkout,
- connector::Cryptopay,
- connector::Coinbase,
connector::Cybersource,
connector::Datatrans,
connector::Dlocal,
diff --git a/crates/router/src/core/payments/flows.rs b/crates/router/src/core/payments/flows.rs
index e364d662e24..f9a6b461a13 100644
--- a/crates/router/src/core/payments/flows.rs
+++ b/crates/router/src/core/payments/flows.rs
@@ -209,10 +209,7 @@ default_imp_for_complete_authorize!(
connector::Bankofamerica,
connector::Billwerk,
connector::Boku,
- connector::Cashtocode,
connector::Checkout,
- connector::Coinbase,
- connector::Cryptopay,
connector::Datatrans,
connector::Dlocal,
connector::Ebanx,
@@ -288,10 +285,7 @@ default_imp_for_webhook_source_verification!(
connector::Bluesnap,
connector::Braintree,
connector::Boku,
- connector::Cashtocode,
connector::Checkout,
- connector::Coinbase,
- connector::Cryptopay,
connector::Cybersource,
connector::Datatrans,
connector::Dlocal,
@@ -376,10 +370,7 @@ default_imp_for_create_customer!(
connector::Bluesnap,
connector::Boku,
connector::Braintree,
- connector::Cashtocode,
connector::Checkout,
- connector::Coinbase,
- connector::Cryptopay,
connector::Cybersource,
connector::Datatrans,
connector::Dlocal,
@@ -461,9 +452,6 @@ default_imp_for_connector_redirect_response!(
connector::Bankofamerica,
connector::Billwerk,
connector::Boku,
- connector::Cashtocode,
- connector::Coinbase,
- connector::Cryptopay,
connector::Cybersource,
connector::Datatrans,
connector::Dlocal,
@@ -630,9 +618,6 @@ default_imp_for_accept_dispute!(
connector::Bluesnap,
connector::Boku,
connector::Braintree,
- connector::Cashtocode,
- connector::Coinbase,
- connector::Cryptopay,
connector::Cybersource,
connector::Datatrans,
connector::Dlocal,
@@ -739,9 +724,6 @@ default_imp_for_file_upload!(
connector::Bluesnap,
connector::Boku,
connector::Braintree,
- connector::Cashtocode,
- connector::Coinbase,
- connector::Cryptopay,
connector::Cybersource,
connector::Datatrans,
connector::Dlocal,
@@ -825,10 +807,7 @@ default_imp_for_submit_evidence!(
connector::Bluesnap,
connector::Boku,
connector::Braintree,
- connector::Cashtocode,
connector::Cybersource,
- connector::Coinbase,
- connector::Cryptopay,
connector::Datatrans,
connector::Dlocal,
connector::Ebanx,
@@ -911,10 +890,7 @@ default_imp_for_defend_dispute!(
connector::Bluesnap,
connector::Boku,
connector::Braintree,
- connector::Cashtocode,
connector::Cybersource,
- connector::Coinbase,
- connector::Cryptopay,
connector::Datatrans,
connector::Dlocal,
connector::Ebanx,
@@ -1012,10 +988,7 @@ default_imp_for_pre_processing_steps!(
connector::Bluesnap,
connector::Boku,
connector::Braintree,
- connector::Cashtocode,
connector::Checkout,
- connector::Coinbase,
- connector::Cryptopay,
connector::Datatrans,
connector::Dlocal,
connector::Ebanx,
@@ -1086,10 +1059,7 @@ default_imp_for_post_processing_steps!(
connector::Bluesnap,
connector::Boku,
connector::Braintree,
- connector::Cashtocode,
connector::Checkout,
- connector::Coinbase,
- connector::Cryptopay,
connector::Datatrans,
connector::Dlocal,
connector::Ebanx,
@@ -1247,11 +1217,8 @@ default_imp_for_payouts_create!(
connector::Bluesnap,
connector::Boku,
connector::Braintree,
- connector::Cashtocode,
connector::Checkout,
- connector::Cryptopay,
connector::Cybersource,
- connector::Coinbase,
connector::Datatrans,
connector::Dlocal,
connector::Forte,
@@ -1333,10 +1300,7 @@ default_imp_for_payouts_retrieve!(
connector::Bluesnap,
connector::Boku,
connector::Braintree,
- connector::Cashtocode,
connector::Checkout,
- connector::Cryptopay,
- connector::Coinbase,
connector::Cybersource,
connector::Datatrans,
connector::Dlocal,
@@ -1424,11 +1388,8 @@ default_imp_for_payouts_eligibility!(
connector::Bluesnap,
connector::Boku,
connector::Braintree,
- connector::Cashtocode,
connector::Checkout,
- connector::Cryptopay,
connector::Cybersource,
- connector::Coinbase,
connector::Datatrans,
connector::Dlocal,
connector::Forte,
@@ -1510,10 +1471,7 @@ default_imp_for_payouts_fulfill!(
connector::Bluesnap,
connector::Boku,
connector::Braintree,
- connector::Cashtocode,
connector::Checkout,
- connector::Cryptopay,
- connector::Coinbase,
connector::Datatrans,
connector::Dlocal,
connector::Forte,
@@ -1593,11 +1551,8 @@ default_imp_for_payouts_cancel!(
connector::Bluesnap,
connector::Boku,
connector::Braintree,
- connector::Cashtocode,
connector::Checkout,
- connector::Cryptopay,
connector::Cybersource,
- connector::Coinbase,
connector::Datatrans,
connector::Dlocal,
connector::Forte,
@@ -1680,11 +1635,8 @@ default_imp_for_payouts_quote!(
connector::Bluesnap,
connector::Boku,
connector::Braintree,
- connector::Cashtocode,
connector::Checkout,
- connector::Cryptopay,
connector::Cybersource,
- connector::Coinbase,
connector::Datatrans,
connector::Dlocal,
connector::Forte,
@@ -1768,11 +1720,8 @@ default_imp_for_payouts_recipient!(
connector::Bluesnap,
connector::Boku,
connector::Braintree,
- connector::Cashtocode,
connector::Checkout,
- connector::Cryptopay,
connector::Cybersource,
- connector::Coinbase,
connector::Datatrans,
connector::Dlocal,
connector::Forte,
@@ -1858,11 +1807,8 @@ default_imp_for_payouts_recipient_account!(
connector::Bluesnap,
connector::Boku,
connector::Braintree,
- connector::Cashtocode,
connector::Checkout,
- connector::Cryptopay,
connector::Cybersource,
- connector::Coinbase,
connector::Datatrans,
connector::Dlocal,
connector::Ebanx,
@@ -1946,11 +1892,8 @@ default_imp_for_approve!(
connector::Bluesnap,
connector::Boku,
connector::Braintree,
- connector::Cashtocode,
connector::Checkout,
- connector::Cryptopay,
connector::Cybersource,
- connector::Coinbase,
connector::Datatrans,
connector::Dlocal,
connector::Ebanx,
@@ -2035,11 +1978,8 @@ default_imp_for_reject!(
connector::Bluesnap,
connector::Boku,
connector::Braintree,
- connector::Cashtocode,
connector::Checkout,
- connector::Cryptopay,
connector::Cybersource,
- connector::Coinbase,
connector::Datatrans,
connector::Dlocal,
connector::Ebanx,
@@ -2214,11 +2154,8 @@ default_imp_for_frm_sale!(
connector::Bluesnap,
connector::Boku,
connector::Braintree,
- connector::Cashtocode,
connector::Checkout,
- connector::Cryptopay,
connector::Cybersource,
- connector::Coinbase,
connector::Datatrans,
connector::Dlocal,
connector::Ebanx,
@@ -2303,11 +2240,8 @@ default_imp_for_frm_checkout!(
connector::Bluesnap,
connector::Boku,
connector::Braintree,
- connector::Cashtocode,
connector::Checkout,
- connector::Cryptopay,
connector::Cybersource,
- connector::Coinbase,
connector::Datatrans,
connector::Dlocal,
connector::Ebanx,
@@ -2392,11 +2326,8 @@ default_imp_for_frm_transaction!(
connector::Bluesnap,
connector::Boku,
connector::Braintree,
- connector::Cashtocode,
connector::Checkout,
- connector::Cryptopay,
connector::Cybersource,
- connector::Coinbase,
connector::Datatrans,
connector::Dlocal,
connector::Ebanx,
@@ -2481,11 +2412,8 @@ default_imp_for_frm_fulfillment!(
connector::Bluesnap,
connector::Boku,
connector::Braintree,
- connector::Cashtocode,
connector::Checkout,
- connector::Cryptopay,
connector::Cybersource,
- connector::Coinbase,
connector::Datatrans,
connector::Dlocal,
connector::Ebanx,
@@ -2570,11 +2498,8 @@ default_imp_for_frm_record_return!(
connector::Bluesnap,
connector::Boku,
connector::Braintree,
- connector::Cashtocode,
connector::Checkout,
- connector::Cryptopay,
connector::Cybersource,
- connector::Coinbase,
connector::Datatrans,
connector::Dlocal,
connector::Ebanx,
@@ -2657,10 +2582,7 @@ default_imp_for_incremental_authorization!(
connector::Bluesnap,
connector::Boku,
connector::Braintree,
- connector::Cashtocode,
connector::Checkout,
- connector::Cryptopay,
- connector::Coinbase,
connector::Datatrans,
connector::Dlocal,
connector::Ebanx,
@@ -2742,10 +2664,7 @@ default_imp_for_revoking_mandates!(
connector::Bluesnap,
connector::Boku,
connector::Braintree,
- connector::Cashtocode,
connector::Checkout,
- connector::Cryptopay,
- connector::Coinbase,
connector::Datatrans,
connector::Dlocal,
connector::Ebanx,
@@ -2986,10 +2905,7 @@ default_imp_for_authorize_session_token!(
connector::Bluesnap,
connector::Boku,
connector::Braintree,
- connector::Cashtocode,
connector::Checkout,
- connector::Cryptopay,
- connector::Coinbase,
connector::Cybersource,
connector::Datatrans,
connector::Dlocal,
@@ -3071,10 +2987,7 @@ default_imp_for_calculate_tax!(
connector::Bluesnap,
connector::Boku,
connector::Braintree,
- connector::Cashtocode,
connector::Checkout,
- connector::Cryptopay,
- connector::Coinbase,
connector::Cybersource,
connector::Datatrans,
connector::Dlocal,
@@ -3158,10 +3071,7 @@ default_imp_for_session_update!(
connector::Bluesnap,
connector::Boku,
connector::Braintree,
- connector::Cashtocode,
connector::Checkout,
- connector::Cryptopay,
- connector::Coinbase,
connector::Cybersource,
connector::Datatrans,
connector::Dlocal,
|
2024-09-20T18:00:15Z
|
## Type of Change
<!-- Put an `x` in the boxes that apply -->
- [ ] Bugfix
- [ ] New feature
- [ ] Enhancement
- [x] Refactoring
- [ ] Dependency updates
- [ ] Documentation
- [ ] CI/CD
## Description
<!-- Describe your changes in detail -->
### Additional Changes
- [ ] This PR modifies the API contract
- [ ] This PR modifies the database schema
- [ ] This PR modifies application configuration/environment variables
<!--
Provide links to the files with corresponding changes.
Following are the paths where you can find config files:
1. `config`
2. `crates/router/src/configs`
3. `loadtest/config`
-->
## Motivation and Context
<!--
Why is this change required? What problem does it solve?
If it fixes an open issue, please link to the issue here.
If you don't have an issue, we'd recommend starting with one first so the PR
can focus on the implementation (unless it is an obvious bug or documentation fix
that will have little conversation).
-->
https://github.com/juspay/hyperswitch/issues/5629
## How did you test it?
<!--
Did you write an integration/unit/API test to verify the code changes?
Or did you test this change manually (provide relevant screenshots)?
-->
Cryptopay:
Request:
```
curl --location 'http://localhost:8080/payments' \
--header 'Content-Type: application/json' \
--header 'Accept: application/json' \
--header 'api-key: dev_23PxPwqBujt8VbpD0hwiNIqNHY5HNa82ZKPJEfN2Ex2y9CE2RcPNiNCeBMIMBifB' \
--data-raw '{
"amount": 300,
"currency": "USD",
"confirm": true,
"email": "guest@example.com",
"return_url": "https://google.com",
"payment_method": "crypto",
"payment_method_type": "crypto_currency",
"payment_experience": "redirect_to_url",
"payment_method_data": {
"crypto": {
"pay_currency": "LTC",
"network": "litecoin"
}
}
}'
```
Response:
```
{
"payment_id": "pay_D91HEOHsNOK0OJhfM4yo",
"merchant_id": "merchant_1727096693",
"status": "requires_customer_action",
"amount": 300,
"net_amount": 300,
"amount_capturable": 300,
"amount_received": 300,
"connector": "cryptopay",
"client_secret": "pay_D91HEOHsNOK0OJhfM4yo_secret_5vTYDEJXX4cI83WnlJ4N",
"created": "2024-09-23T13:19:07.696Z",
"currency": "USD",
"customer_id": null,
"customer": {
"id": null,
"name": null,
"email": "guest@example.com",
"phone": null,
"phone_country_code": null
},
"description": null,
"refunds": null,
"disputes": null,
"mandate_id": null,
"mandate_data": null,
"setup_future_usage": null,
"off_session": null,
"capture_on": null,
"capture_method": null,
"payment_method": "crypto",
"payment_method_data": {
"crypto": {
"pay_currency": "LTC",
"network": "litecoin"
},
"billing": null
},
"payment_token": null,
"shipping": null,
"billing": null,
"order_details": null,
"email": null,
"name": null,
"phone": null,
"return_url": "https://google.com/",
"authentication_type": "no_three_ds",
"statement_descriptor_name": null,
"statement_descriptor_suffix": null,
"next_action": {
"type": "redirect_to_url",
"redirect_to_url": "http://localhost:8080/payments/redirect/pay_D91HEOHsNOK0OJhfM4yo/merchant_1727096693/pay_D91HEOHsNOK0OJhfM4yo_1"
},
"cancellation_reason": null,
"error_code": null,
"error_message": null,
"unified_code": null,
"unified_message": null,
"payment_experience": "redirect_to_url",
"payment_method_type": "crypto_currency",
"connector_label": null,
"business_country": null,
"business_label": "default",
"business_sub_label": null,
"allowed_payment_method_types": null,
"ephemeral_key": null,
"manual_retry_allowed": null,
"connector_transaction_id": "63f933ba-aadb-446b-b80a-58f70abb38e1",
"frm_message": null,
"metadata": null,
"connector_metadata": null,
"feature_metadata": null,
"reference_id": "pay_D91HEOHsNOK0OJhfM4yo_1",
"payment_link": null,
"profile_id": "pro_1pHVbwpinQ6kPONiCARj",
"surcharge_details": null,
"attempt_count": 1,
"merchant_decision": null,
"merchant_connector_id": "mca_RsWL9yopYx8fWkdxALEU",
"incremental_authorization_allowed": null,
"authorization_count": null,
"incremental_authorizations": null,
"external_authentication_details": null,
"external_3ds_authentication_attempted": false,
"expires_on": "2024-09-23T13:34:07.695Z",
"fingerprint": null,
"browser_info": null,
"payment_method_id": null,
"payment_method_status": null,
"updated": "2024-09-23T13:19:09.657Z",
"charges": null,
"frm_metadata": null,
"merchant_order_reference_id": null,
"order_tax_amount": null
}
```
Note: Local testing not available for coinbase and cashtocode due to unavailability of credentials.
## Checklist
<!-- Put an `x` in the boxes that apply -->
- [x] I formatted the code `cargo +nightly fmt --all`
- [x] I addressed lints thrown by `cargo clippy`
- [x] I reviewed the submitted code
- [ ] I added unit tests for my changes where possible
|
d9270ace8ddde16eca8c45ceb79af3e4d815d7cd
|
|
juspay/hyperswitch
|
juspay__hyperswitch-5593
|
Bug: [FEATURE] handle redirections for iframed content served by HyperSwitch
### Feature Description
HyperSwitch's SDK / links is meant to work within top context at the client side. This behaviour changes when we introduce secure links - which are supposed to be iframed within merchant's top context. Any functionality which was consuming top context at the client side needs to be handled accordingly.
### Possible Implementation
Major things which needs to be handled
- client side redirections to happen at top context
- client side redirections happen within current window context - which is assumed to be top (since the SDK integration requires this to be at top level)
- when using iframed resources, SDK should handle redirection and make sure this happens in the top context
- accessing `protocol` and `hostname`
- this is also fetched from within the current window's context
- needs to happen at top context
### Have you spent some time checking if this feature request has been raised before?
- [X] I checked and didn't find a similar issue
### Have you read the Contributing Guidelines?
- [X] I have read the [Contributing Guidelines](https://github.com/juspay/hyperswitch/blob/main/docs/CONTRIBUTING.md)
### Are you willing to submit a PR?
Yes, I am willing to submit a PR!
|
diff --git a/crates/router/src/core/generic_link/payout_link/status/script.js b/crates/router/src/core/generic_link/payout_link/status/script.js
index 42b57903593..ffb554a6829 100644
--- a/crates/router/src/core/generic_link/payout_link/status/script.js
+++ b/crates/router/src/core/generic_link/payout_link/status/script.js
@@ -173,7 +173,17 @@ function redirectToEndUrl(returnUrl) {
}
if (secondsLeft === 0) {
setTimeout(function () {
- window.location.href = returnUrl.toString();
+ try {
+ window.top.location.href = returnUrl.toString();
+ } catch (error) {
+ console.error(
+ "CRITICAL ERROR",
+ "Failed to redirect top document. Error - ",
+ error
+ );
+ console.info("Redirecting in current document");
+ window.location.href = returnUrl.toString();
+ }
}, 1000);
}
}, i * 1000);
diff --git a/crates/router/src/core/payment_link/payment_link_initiate/payment_link.html b/crates/router/src/core/payment_link/payment_link_initiate/payment_link.html
index b66242305b6..54e48a5241f 100644
--- a/crates/router/src/core/payment_link/payment_link_initiate/payment_link.html
+++ b/crates/router/src/core/payment_link/payment_link_initiate/payment_link.html
@@ -325,10 +325,10 @@
</svg>
</div>
<script>
+ {{logging_template}}
{{locale_template}}
{{rendered_js}}
{{payment_link_initiator}}
- {{logging_template}}
</script>
{{ hyperloader_sdk_link }}
</body>
diff --git a/crates/router/src/core/payment_link/payment_link_initiate/secure_payment_link_initiator.js b/crates/router/src/core/payment_link/payment_link_initiate/secure_payment_link_initiator.js
index 777cfd8cadd..48974a564d5 100644
--- a/crates/router/src/core/payment_link/payment_link_initiate/secure_payment_link_initiator.js
+++ b/crates/router/src/core/payment_link/payment_link_initiate/secure_payment_link_initiator.js
@@ -57,7 +57,7 @@ if (!isFramed) {
});
var type =
paymentDetails.sdk_layout === "spaced_accordion" ||
- paymentDetails.sdk_layout === "accordion"
+ paymentDetails.sdk_layout === "accordion"
? "accordion"
: paymentDetails.sdk_layout;
@@ -103,6 +103,35 @@ if (!isFramed) {
arr.splice(0, 3);
arr.unshift("status");
arr.unshift("payment_link");
- window.location.href = window.location.origin + "/" + arr.join("/")+ "?locale=" + paymentDetails.locale;
+ let returnUrl =
+ window.location.origin +
+ "/" +
+ arr.join("/") +
+ "?locale=" +
+ paymentDetails.locale;
+ try {
+ window.top.location.href = returnUrl;
+
+ // Push logs to logs endpoint
+ } catch (error) {
+ var url = window.location.href;
+ var { paymentId, merchantId, attemptId, connector } = parseRoute(url);
+ var urlToPost = getEnvRoute(url);
+ var message = {
+ message: "CRITICAL ERROR - Failed to redirect top document. Falling back to redirecting using window.location",
+ reason: error.message,
+ }
+ var log = {
+ message,
+ url,
+ paymentId,
+ merchantId,
+ attemptId,
+ connector,
+ };
+ postLog(log, urlToPost);
+
+ window.location.href = returnUrl;
+ }
}
}
diff --git a/crates/router/src/core/payment_link/payment_link_status/status.html b/crates/router/src/core/payment_link/payment_link_status/status.html
index fdc0c3012bb..c78a0bb556d 100644
--- a/crates/router/src/core/payment_link/payment_link_status/status.html
+++ b/crates/router/src/core/payment_link/payment_link_status/status.html
@@ -11,9 +11,9 @@
href="https://fonts.googleapis.com/css2?family=Montserrat:wght@400;500;600;700;800"
/>
<script>
+ {{logging_template}}
{{locale_template}}
{{ rendered_js }}
- {{logging_template}}
</script>
</head>
<body onload="boot()">
|
2024-08-12T08:33:34Z
|
(cherry picked from commit db6df219a9cd12d619268f388b26c88692d858f8)
## Type of Change
<!-- Put an `x` in the boxes that apply -->
- [x] Bugfix
- [ ] New feature
- [ ] Enhancement
- [x] Refactoring
- [ ] Dependency updates
- [ ] Documentation
- [ ] CI/CD
## Description
### Additional Changes
- [ ] This PR modifies the API contract
- [ ] This PR modifies the database schema
- [ ] This PR modifies application configuration/environment variables
<!--
Provide links to the files with corresponding changes.
Following are the paths where you can find config files:
1. `config`
2. `crates/router/src/configs`
3. `loadtest/config`
-->
## How did you test it?
<details>
<summary>[Payments] open links (no auth redirections)</summary>
https://github.com/user-attachments/assets/ccca6292-a89c-4e4f-9fc6-8cbb41280337
</details>
<details>
<summary>[Payments] open links (with auth redirections)</summary>
https://github.com/user-attachments/assets/0ebe3c86-c6eb-450a-8e27-d0274306a033
</details>
<details>
<summary>[Payments] secure links (no auth redirections)</summary>
https://github.com/user-attachments/assets/97fc209a-faa7-4f92-892d-1dbb6f8390f3
</details>
<details>
<summary>[Payments] secure links (with auth redirections)</summary>
https://github.com/user-attachments/assets/ccc3510c-facb-4b08-a910-1e51f2090480
</details>
<details>
<summary>[Payouts] secure links (with status page redirection)</summary>
https://github.com/user-attachments/assets/3aa9f27b-7cf1-4256-8e38-002d7634ccff
</details>
## Checklist
<!-- Put an `x` in the boxes that apply -->
- [x] I formatted the code `cargo +nightly fmt --all`
- [x] I addressed lints thrown by `cargo clippy`
- [x] I reviewed the submitted code
- [ ] I added unit tests for my changes where possible
|
ed13ecac04f82b5c69b11636c1e355e7e17c60fd
|
|
juspay/hyperswitch
|
juspay__hyperswitch-5585
|
Bug: [FEATURE] List Pm Based on Profile
### Feature Description
List Pm Based on Profile for off_session payments
### Possible Implementation
List Pm Based on Profile for off_session payments
### Have you spent some time checking if this feature request has been raised before?
- [X] I checked and didn't find a similar issue
### Have you read the Contributing Guidelines?
- [X] I have read the [Contributing Guidelines](https://github.com/juspay/hyperswitch/blob/main/docs/CONTRIBUTING.md)
### Are you willing to submit a PR?
Yes, I am willing to submit a PR!
|
diff --git a/crates/router/src/core/payment_methods/cards.rs b/crates/router/src/core/payment_methods/cards.rs
index fa01437e5ed..e5c8ef57b29 100644
--- a/crates/router/src/core/payment_methods/cards.rs
+++ b/crates/router/src/core/payment_methods/cards.rs
@@ -3892,6 +3892,7 @@ pub async fn list_customer_payment_method(
let mca_enabled = get_mca_status(
state,
&key_store,
+ profile_id.clone(),
merchant_account.get_id(),
is_connector_agnostic_mit_enabled,
connector_mandate_details,
@@ -3932,7 +3933,9 @@ pub async fn list_customer_payment_method(
&& customer.default_payment_method_id == Some(pm.payment_method_id),
billing: payment_method_billing,
};
- customer_pms.push(pma.to_owned());
+ if requires_cvv || mca_enabled {
+ customer_pms.push(pma.to_owned());
+ }
let redis_conn = state
.store
@@ -4410,19 +4413,22 @@ async fn generate_saved_pm_response(
.change_context(errors::ApiErrorResponse::InternalServerError)
.attach_printable("Failed to deserialize to Payment Mandate Reference ")?;
- let (is_connector_agnostic_mit_enabled, requires_cvv, off_session_payment_flag) = payment_info
- .map(|pi| {
- (
- pi.is_connector_agnostic_mit_enabled,
- pi.requires_cvv,
- pi.off_session_payment_flag,
- )
- })
- .unwrap_or((false, false, false));
+ let (is_connector_agnostic_mit_enabled, requires_cvv, off_session_payment_flag, profile_id) =
+ payment_info
+ .map(|pi| {
+ (
+ pi.is_connector_agnostic_mit_enabled,
+ pi.requires_cvv,
+ pi.off_session_payment_flag,
+ pi.business_profile.map(|profile| profile.profile_id),
+ )
+ })
+ .unwrap_or((false, false, false, Default::default()));
let mca_enabled = get_mca_status(
state,
key_store,
+ profile_id,
merchant_account.get_id(),
is_connector_agnostic_mit_enabled,
connector_mandate_details,
@@ -4486,6 +4492,7 @@ async fn generate_saved_pm_response(
pub async fn get_mca_status(
state: &routes::SessionState,
key_store: &domain::MerchantKeyStore,
+ profile_id: Option<String>,
merchant_id: &id_type::MerchantId,
is_connector_agnostic_mit_enabled: bool,
connector_mandate_details: Option<storage::PaymentsMandateReference>,
@@ -4507,19 +4514,17 @@ pub async fn get_mca_status(
.change_context(errors::ApiErrorResponse::MerchantConnectorAccountNotFound {
id: merchant_id.get_string_repr().to_owned(),
})?;
-
let mut mca_ids = HashSet::new();
let mcas = mcas
.into_iter()
- .filter(|mca| mca.disabled == Some(true))
+ .filter(|mca| mca.disabled == Some(false) && profile_id.clone() == mca.profile_id)
.collect::<Vec<_>>();
for mca in mcas {
mca_ids.insert(mca.get_id());
}
-
for mca_id in connector_mandate_details.keys() {
- if !mca_ids.contains(mca_id) {
+ if mca_ids.contains(mca_id) {
return Ok(true);
}
}
|
2024-08-09T11:38:48Z
|
## Type of Change
<!-- Put an `x` in the boxes that apply -->
- [x] Bugfix
- [ ] New feature
- [ ] Enhancement
- [ ] Refactoring
- [ ] Dependency updates
- [ ] Documentation
- [ ] CI/CD
## Description
List cards on the basis of profiles, if it has a mandate details.The precedence order for off_session payments should be if network_txn_id is present , then show the pm irrespective of the profile, but if its not there then check for mandate_details for that profile and list it on that basis.
### Additional Changes
- [ ] This PR modifies the API contract
- [ ] This PR modifies the database schema
- [ ] This PR modifies application configuration/environment variables
<!--
Provide links to the files with corresponding changes.
Following are the paths where you can find config files:
1. `config`
2. `crates/router/src/configs`
3. `loadtest/config`
-->
## Motivation and Context
<!--
Why is this change required? What problem does it solve?
If it fixes an open issue, please link to the issue here.
If you don't have an issue, we'd recommend starting with one first so the PR
can focus on the implementation (unless it is an obvious bug or documentation fix
that will have little conversation).
-->
## How did you test it?
- Create a MA and 2 Profiles
- Create a MCA for Profile 1
- Create a `off_session` payment
```
Create
curl --location 'http://localhost:8080/payments' \
--header 'Content-Type: application/json' \
--header 'Accept: application/json' \
--header 'api-key: dev_jsssWAg0XyxGK0ycPunkFjlItYNs30X1IVOr1MIF7lwrDQgBBk7npwdkZB4t7EQd' \
--data-raw '{
"amount": 10000,
"currency": "USD",
"confirm": false,
"customer_id": "CustomerX7777",
"capture_method": "automatic",
"capture_on": "2022-09-10T10:11:12Z",
"authentication_type": "no_three_ds",
"return_url": "https://google.com",
"email": "something@gmail.com",
"name": "Joseph Doe",
"phone": "999999999",
"phone_country_code": "+65",
"description": "Its my first payment request",
"setup_future_usage":"off_session",
"billing": {
"address": {
"line1": "1467",
"line2": "Harrison Street",
"line3": "Harrison Street",
"city": "San Fransico",
"state": "California",
"zip": "94122",
"country": "US",
"first_name": "joseph",
"last_name": "Doe"
},
"phone": {
"number": "8056594427",
"country_code": "+91"
}
},
"shipping": {
"address": {
"line1": "1467",
"line2": "Harrison Street",
"line3": "Harrison Street",
"city": "San Fransico",
"state": "California",
"zip": "94122",
"country": "US",
"first_name": "joseph",
"last_name": "Doe"
},
"phone": {
"number": "8056594427",
"country_code": "+91"
}
},
"connector_metadata": {
"noon": {
"order_category": "pay"
}
}
, "profile_id": "pro_6RgaXF6EvoYBYoGpOISQ"
}'
```
```
Confirm
{
"confirm": true,
"client_secret":"{{client_secret}}",
"billing": {
"address": {
"line1": "1467",
"line2": "Harrison Street",
"line3": "Harrison Street",
"city": "San Fransico",
"state": "California",
"zip": "94122",
"country": "US",
"first_name": "joseph",
"last_name": "Doe"
},
"phone": {
"number": "8056594427",
"country_code": "+91"
}
},
"browser_info": {
"user_agent": "Mozilla\/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit\/537.36 (KHTML, like Gecko) Chrome\/70.0.3538.110 Safari\/537.36",
"accept_header": "text\/html,application\/xhtml+xml,application\/xml;q=0.9,image\/webp,image\/apng,*\/*;q=0.8",
"language": "nl-NL",
"color_depth": 24,
"screen_height": 723,
"screen_width": 1536,
"time_zone": 0,
"java_enabled": true,
"java_script_enabled": true,
"ip_address": "125.0.0.1"
},
"payment_method": "card",
// // "payment_token": "token_olUiqngeoftZLox6awiz"
// "payment_method_type": "debit",
"payment_method_data": {
"card": {
"card_number": "4242424242424242",
"card_exp_month": "06",
"card_exp_year": "2030",
"card_holder_name": "John T",
// "card_network": "Visa",
// "card_issuing_country": "UNITEDKINGDOM",
// "card_issuer": "STRIPE PAYMENTS UK LIMITED",
"card_cvc": "737"
}
}
}
```
- Do a PML it will show the PM
```
{
"customer_payment_methods": [
{
"payment_token": "token_UWLBwJH7yena1nKMTF3G",
"payment_method_id": "pm_EbbMg190tRVUKn9sLVcr",
"customer_id": "CustomerX7777",
"payment_method": "card",
"payment_method_type": null,
"payment_method_issuer": null,
"payment_method_issuer_code": null,
"recurring_enabled": true,
"installment_payment_enabled": false,
"payment_experience": [
"redirect_to_url"
],
"card": {
"scheme": null,
"issuer_country": null,
"last4_digits": "4242",
"expiry_month": "06",
"expiry_year": "2030",
"card_token": null,
"card_holder_name": "John T",
"card_fingerprint": null,
"nick_name": null,
"card_network": null,
"card_isin": "424242",
"card_issuer": null,
"card_type": null,
"saved_to_locker": true
},
"metadata": null,
"created": "2024-08-09T14:55:58.379Z",
"bank": null,
"surcharge_details": null,
"requires_cvv": false,
"last_used_at": "2024-08-09T14:55:58.379Z",
"default_payment_method_set": true,
"billing": {
"address": {
"city": "San Fransico",
"country": "US",
"line1": "1467",
"line2": "Harrison Street",
"line3": "Harrison Street",
"zip": "94122",
"state": "California",
"first_name": "joseph",
"last_name": "Doe"
},
"phone": {
"number": "8056594427",
"country_code": "+91"
},
"email": null
}
}
],
"is_guest_customer": false
}
```
- Create a intent for `off_session` with the Profile 2
```
Create
curl --location 'http://localhost:8080/payments' \
--header 'Content-Type: application/json' \
--header 'Accept: application/json' \
--header 'api-key: dev_jsssWAg0XyxGK0ycPunkFjlItYNs30X1IVOr1MIF7lwrDQgBBk7npwdkZB4t7EQd' \
--data-raw '{
"amount": 6777,
"currency": "USD",
"confirm": false,
"customer_id": "CustomerX7777",
"capture_method": "automatic",
"capture_on": "2022-09-10T10:11:12Z",
"authentication_type": "no_three_ds",
"return_url": "https://google.com",
"email": "something@gmail.com",
"name": "Joseph Doe",
"phone": "999999999",
"phone_country_code": "+65",
"description": "Its my first payment request",
"profile_id": "pro_NP3IjxxHEUdqVoYi6K4c",
"setup_future_usage":"off_session",
"billing": {
"address": {
"line1": "1467",
"line2": "Harrison Street",
"line3": "Harrison Street",
"city": "San Fransico",
"state": "California",
"zip": "94122",
"country": "US",
"first_name": "joseph",
"last_name": "Doe"
},
"phone": {
"number": "8056594427",
"country_code": "+91"
}
}
}'
```
- Do a PML it will not show the PM
```
curl --location 'http://localhost:8080/customers/payment_methods?client_secret=pay_Nk9H9hj64BiGm63EPJT9_secret_Ida6aZ1FR5LhAeO7l3HH' \
--header 'Accept: application/json' \
--header 'api-key: pk_dev_5c27d077a0b94ddb8a3869e4acbe8fe6'
```
```
{
"customer_payment_methods": [],
"is_guest_customer": false
}
```
- - Create a intent for `on_session` with the Profile 2
```
curl --location 'http://localhost:8080/payments' \
--header 'Content-Type: application/json' \
--header 'Accept: application/json' \
--header 'api-key: dev_jsssWAg0XyxGK0ycPunkFjlItYNs30X1IVOr1MIF7lwrDQgBBk7npwdkZB4t7EQd' \
--data-raw '{
"amount": 6777,
"currency": "USD",
"confirm": false,
"customer_id": "CustomerX7777",
"capture_method": "automatic",
"capture_on": "2022-09-10T10:11:12Z",
"authentication_type": "no_three_ds",
"return_url": "https://google.com",
"email": "something@gmail.com",
"name": "Joseph Doe",
"phone": "999999999",
"phone_country_code": "+65",
"description": "Its my first payment request",
"profile_id": "pro_NP3IjxxHEUdqVoYi6K4c",
"setup_future_usage":"on_session",
"billing": {
"address": {
"line1": "1467",
"line2": "Harrison Street",
"line3": "Harrison Street",
"city": "San Fransico",
"state": "California",
"zip": "94122",
"country": "US",
"first_name": "joseph",
"last_name": "Doe"
},
"phone": {
"number": "8056594427",
"country_code": "+91"
}
}
}'
```
- Do a PML it will show the PM
```
{
"customer_payment_methods": [
{
"payment_token": "token_rHJg2C54VdYsdF5ln4SQ",
"payment_method_id": "pm_EbbMg190tRVUKn9sLVcr",
"customer_id": "CustomerX7777",
"payment_method": "card",
"payment_method_type": null,
"payment_method_issuer": null,
"payment_method_issuer_code": null,
"recurring_enabled": false,
"installment_payment_enabled": false,
"payment_experience": [
"redirect_to_url"
],
"card": {
"scheme": null,
"issuer_country": null,
"last4_digits": "4242",
"expiry_month": "06",
"expiry_year": "2030",
"card_token": null,
"card_holder_name": "John T",
"card_fingerprint": null,
"nick_name": null,
"card_network": null,
"card_isin": "424242",
"card_issuer": null,
"card_type": null,
"saved_to_locker": true
},
"metadata": null,
"created": "2024-08-09T14:55:58.379Z",
"bank": null,
"surcharge_details": null,
"requires_cvv": true,
"last_used_at": "2024-08-09T14:55:58.379Z",
"default_payment_method_set": true,
"billing": {
"address": {
"city": "San Fransico",
"country": "US",
"line1": "1467",
"line2": "Harrison Street",
"line3": "Harrison Street",
"zip": "94122",
"state": "California",
"first_name": "joseph",
"last_name": "Doe"
},
"phone": {
"number": "8056594427",
"country_code": "+91"
},
"email": null
}
}
],
"is_guest_customer": false
}
```
## Checklist
<!-- Put an `x` in the boxes that apply -->
- [ ] I formatted the code `cargo +nightly fmt --all`
- [ ] I addressed lints thrown by `cargo clippy`
- [ ] I reviewed the submitted code
- [ ] I added unit tests for my changes where possible
|
f81416e4df6fa430fd7f6eb910b55464cd72f3f0
|
|
juspay/hyperswitch
|
juspay__hyperswitch-5574
|
Bug: Add profile_id in kafka and clickhouse
Add profile_id in kafka topic `payment-intent` and clickhouse table payment-intent.
|
diff --git a/crates/analytics/docs/clickhouse/scripts/payment_intents.sql b/crates/analytics/docs/clickhouse/scripts/payment_intents.sql
index 6889a1ff79d..09101e9aa2d 100644
--- a/crates/analytics/docs/clickhouse/scripts/payment_intents.sql
+++ b/crates/analytics/docs/clickhouse/scripts/payment_intents.sql
@@ -19,6 +19,7 @@ CREATE TABLE payment_intents_queue
`business_country` LowCardinality(String),
`business_label` String,
`attempt_count` UInt8,
+ `profile_id` Nullable(String),
`modified_at` DateTime CODEC(T64, LZ4),
`created_at` DateTime CODEC(T64, LZ4),
`last_synced` Nullable(DateTime) CODEC(T64, LZ4),
@@ -50,6 +51,7 @@ CREATE TABLE payment_intents
`business_country` LowCardinality(String),
`business_label` String,
`attempt_count` UInt8,
+ `profile_id` Nullable(String),
`modified_at` DateTime DEFAULT now() CODEC(T64, LZ4),
`created_at` DateTime DEFAULT now() CODEC(T64, LZ4),
`last_synced` Nullable(DateTime) CODEC(T64, LZ4),
@@ -86,6 +88,7 @@ CREATE MATERIALIZED VIEW payment_intents_mv TO payment_intents
`business_country` LowCardinality(String),
`business_label` String,
`attempt_count` UInt8,
+ `profile_id` Nullable(String),
`modified_at` DateTime64(3),
`created_at` DateTime64(3),
`last_synced` Nullable(DateTime64(3)),
@@ -112,6 +115,7 @@ SELECT
business_country,
business_label,
attempt_count,
+ profile_id,
modified_at,
created_at,
last_synced,
diff --git a/crates/router/src/services/kafka/payment_intent.rs b/crates/router/src/services/kafka/payment_intent.rs
index d1bd5b2a549..3296956797b 100644
--- a/crates/router/src/services/kafka/payment_intent.rs
+++ b/crates/router/src/services/kafka/payment_intent.rs
@@ -33,6 +33,7 @@ pub struct KafkaPaymentIntent<'a> {
pub business_country: Option<storage_enums::CountryAlpha2>,
pub business_label: Option<&'a String>,
pub attempt_count: i16,
+ pub profile_id: Option<&'a String>,
pub payment_confirm_source: Option<storage_enums::PaymentSource>,
pub billing_details: Option<Encryptable<Secret<Value>>>,
pub shipping_details: Option<Encryptable<Secret<Value>>>,
@@ -67,6 +68,7 @@ impl<'a> KafkaPaymentIntent<'a> {
business_country: intent.business_country,
business_label: intent.business_label.as_ref(),
attempt_count: intent.attempt_count,
+ profile_id: intent.profile_id.as_ref(),
payment_confirm_source: intent.payment_confirm_source,
// TODO: use typed information here to avoid PII logging
billing_details: None,
diff --git a/crates/router/src/services/kafka/payment_intent_event.rs b/crates/router/src/services/kafka/payment_intent_event.rs
index cce53cbd596..f5186a0b2bb 100644
--- a/crates/router/src/services/kafka/payment_intent_event.rs
+++ b/crates/router/src/services/kafka/payment_intent_event.rs
@@ -34,6 +34,7 @@ pub struct KafkaPaymentIntentEvent<'a> {
pub business_country: Option<storage_enums::CountryAlpha2>,
pub business_label: Option<&'a String>,
pub attempt_count: i16,
+ pub profile_id: Option<&'a String>,
pub payment_confirm_source: Option<storage_enums::PaymentSource>,
pub billing_details: Option<Encryptable<Secret<Value>>>,
pub shipping_details: Option<Encryptable<Secret<Value>>>,
@@ -68,6 +69,7 @@ impl<'a> KafkaPaymentIntentEvent<'a> {
business_country: intent.business_country,
business_label: intent.business_label.as_ref(),
attempt_count: intent.attempt_count,
+ profile_id: intent.profile_id.as_ref(),
payment_confirm_source: intent.payment_confirm_source,
// TODO: use typed information here to avoid PII logging
billing_details: None,
|
2024-08-08T12:12:20Z
|
## Type of Change
<!-- Put an `x` in the boxes that apply -->
- [ ] Bugfix
- [x] New feature
- [ ] Enhancement
- [ ] Refactoring
- [ ] Dependency updates
- [ ] Documentation
- [ ] CI/CD
## Description
<!-- Describe your changes in detail -->
### Additional Changes
- [ ] This PR modifies the API contract
- [x] This PR modifies the database schema
- [ ] This PR modifies application configuration/environment variables
<!--
Provide links to the files with corresponding changes.
Following are the paths where you can find config files:
1. `config`
2. `crates/router/src/configs`
3. `loadtest/config`
-->
## Motivation and Context
To add profile_id.
<!--
Why is this change required? What problem does it solve?
If it fixes an open issue, please link to the issue here.
If you don't have an issue, we'd recommend starting with one first so the PR
can focus on the implementation (unless it is an obvious bug or documentation fix
that will have little conversation).
-->
## How did you test it?
By making a payment can see the profile_id is added in kafka topic `hyperswitch-payment-intent-events` and same in clickhouse table. Can also test in loki topic and clickhouse-sbx
<!--
Did you write an integration/unit/API test to verify the code changes?
Or did you test this change manually (provide relevant screenshots)?
-->
<img width="1728" alt="Screenshot 2024-08-08 at 5 15 37 PM" src="https://github.com/user-attachments/assets/88b13327-4a16-4cff-9782-4fa76c7fd3fa">
<img width="1728" alt="Screenshot 2024-08-08 at 5 09 28 PM" src="https://github.com/user-attachments/assets/97a000c5-0323-4002-9001-83a4b83e96e0">
## Checklist
<!-- Put an `x` in the boxes that apply -->
- [x] I formatted the code `cargo +nightly fmt --all`
- [x] I addressed lints thrown by `cargo clippy`
- [ ] I reviewed the submitted code
- [ ] I added unit tests for my changes where possible
|
e56ad0d6884c6505d73df048e73d6210db3aae46
|
|
juspay/hyperswitch
|
juspay__hyperswitch-5590
|
Bug: Feat(connector): [Paybox] Implement Paybox Payment Flows
### Feature Description
Payone is payment connector
Documentation link: http://www1.paybox.com/wp-content/uploads/2017/08/ManuelIntegrationVerifone_PayboxDirect_V8.1_EN.pdf
Website url: [Paybox.com](http://paybox.com/)
### Have you spent some time to check if this feature request has been raised before?
- [X] I checked and didn't find similar issue
### Have you read the Contributing Guidelines?
- [X] I have read the [Contributing Guidelines](https://github.com/juspay/hyperswitch/blob/main/docs/CONTRIBUTING.md)
### Are you willing to submit a PR?
Yes I am willing to submit a PR!
|
diff --git a/api-reference-v2/openapi_spec.json b/api-reference-v2/openapi_spec.json
index 8974f940bac..0498c52cd36 100644
--- a/api-reference-v2/openapi_spec.json
+++ b/api-reference-v2/openapi_spec.json
@@ -3577,6 +3577,7 @@
"noon",
"nuvei",
"opennode",
+ "paybox",
"payme",
"payone",
"paypal",
@@ -15493,6 +15494,7 @@
"noon",
"nuvei",
"opennode",
+ "paybox",
"payme",
"payone",
"paypal",
diff --git a/config/deployments/production.toml b/config/deployments/production.toml
index b27f3696e30..bac5ec206e6 100644
--- a/config/deployments/production.toml
+++ b/config/deployments/production.toml
@@ -70,7 +70,7 @@ noon.key_mode = "Live"
nuvei.base_url = "https://ppp-test.nuvei.com/"
opayo.base_url = "https://pi-live.sagepay.com/"
opennode.base_url = "https://api.opennode.com"
-paybox.base_url = "https://preprod-ppps.paybox.com/PPPS.php"
+paybox.base_url = "https://ppps.paybox.com/PPPS.php"
payeezy.base_url = "https://api.payeezy.com/"
payme.base_url = "https://live.payme.io/"
payone.base_url = "https://payment.payone.com/"
diff --git a/crates/api_models/src/enums.rs b/crates/api_models/src/enums.rs
index 06ac98f59d3..a7738133ca0 100644
--- a/crates/api_models/src/enums.rs
+++ b/crates/api_models/src/enums.rs
@@ -116,7 +116,7 @@ pub enum Connector {
Nuvei,
// Opayo, added as template code for future usage
Opennode,
- // Paybox, added as template code for future usage
+ Paybox,
// Payeezy, As psync and rsync are not supported by this connector, it is added as template code for future usage
Payme,
Payone,
@@ -244,8 +244,8 @@ impl Connector {
| Self::Nexinets
| Self::Nuvei
| Self::Opennode
- // | Self::Paybox added as template code for future usage
- | Self::Payme
+ | Self::Paybox
+ | Self::Payme
| Self::Payone
| Self::Paypal
| Self::Payu
diff --git a/crates/common_enums/src/enums.rs b/crates/common_enums/src/enums.rs
index 015bf2d6c68..f4807bd0b0a 100644
--- a/crates/common_enums/src/enums.rs
+++ b/crates/common_enums/src/enums.rs
@@ -229,7 +229,7 @@ pub enum RoutableConnectors {
// Opayo, added as template code for future usage
Opennode,
// Payeezy, As psync and rsync are not supported by this connector, it is added as template code for future usage
- // Paybox, added as template code for future usage
+ Paybox,
Payme,
Payone,
Paypal,
diff --git a/crates/connector_configs/src/connector.rs b/crates/connector_configs/src/connector.rs
index 6cc32fe9553..51713f6166f 100644
--- a/crates/connector_configs/src/connector.rs
+++ b/crates/connector_configs/src/connector.rs
@@ -175,7 +175,7 @@ pub struct ConnectorConfig {
pub nmi: Option<ConnectorTomlConfig>,
pub noon: Option<ConnectorTomlConfig>,
pub nuvei: Option<ConnectorTomlConfig>,
- // pub paybox: Option<ConnectorTomlConfig>, added for future usage
+ pub paybox: Option<ConnectorTomlConfig>,
pub payme: Option<ConnectorTomlConfig>,
#[cfg(feature = "payouts")]
pub payone_payout: Option<ConnectorTomlConfig>,
@@ -323,6 +323,7 @@ impl ConnectorConfig {
Connector::Nmi => Ok(connector_data.nmi),
Connector::Noon => Ok(connector_data.noon),
Connector::Nuvei => Ok(connector_data.nuvei),
+ Connector::Paybox => Ok(connector_data.paybox),
Connector::Payme => Ok(connector_data.payme),
Connector::Payone => Err("Use get_payout_connector_config".to_string()),
Connector::Paypal => Ok(connector_data.paypal),
@@ -363,7 +364,6 @@ impl ConnectorConfig {
#[cfg(feature = "dummy_connector")]
Connector::DummyConnector7 => Ok(connector_data.paypal_test),
Connector::Netcetera => Ok(connector_data.netcetera),
- // Connector::Paybox => Ok(connector_data.paybox), added for future usage
}
}
}
diff --git a/crates/connector_configs/toml/development.toml b/crates/connector_configs/toml/development.toml
index 95b22f8f77f..cc2ad85e56c 100644
--- a/crates/connector_configs/toml/development.toml
+++ b/crates/connector_configs/toml/development.toml
@@ -3803,6 +3803,46 @@ key1="Public Api Key"
api_key = "Passcode"
key1 = "datatrans MerchantId"
+[paybox]
+[[paybox.credit]]
+ payment_method_type = "Mastercard"
+[[paybox.credit]]
+ payment_method_type = "Visa"
+[[paybox.credit]]
+ payment_method_type = "Interac"
+[[paybox.credit]]
+ payment_method_type = "AmericanExpress"
+[[paybox.credit]]
+ payment_method_type = "JCB"
+[[paybox.credit]]
+ payment_method_type = "DinersClub"
+[[paybox.credit]]
+ payment_method_type = "Discover"
+[[paybox.credit]]
+ payment_method_type = "CartesBancaires"
+[[paybox.credit]]
+ payment_method_type = "UnionPay"
+[[paybox.debit]]
+ payment_method_type = "Mastercard"
+[[paybox.debit]]
+ payment_method_type = "Visa"
+[[paybox.debit]]
+ payment_method_type = "Interac"
+[[paybox.debit]]
+ payment_method_type = "AmericanExpress"
+[[paybox.debit]]
+ payment_method_type = "JCB"
+[[paybox.debit]]
+ payment_method_type = "DinersClub"
+[[paybox.debit]]
+ payment_method_type = "Discover"
+[[paybox.debit]]
+ payment_method_type = "CartesBancaires"
+[paybox.connector_auth.SignatureKey]
+api_key="SITE Key"
+key1="Rang Identifier"
+api_secret="CLE Secret"
+
[wellsfargo]
[[wellsfargo.credit]]
payment_method_type = "Mastercard"
diff --git a/crates/connector_configs/toml/production.toml b/crates/connector_configs/toml/production.toml
index a2c118f572b..a61911b9da1 100644
--- a/crates/connector_configs/toml/production.toml
+++ b/crates/connector_configs/toml/production.toml
@@ -2680,6 +2680,46 @@ key1 = "Merchant ID"
api_key="Private Api Key"
key1="Public Api Key"
+[paybox]
+[[paybox.credit]]
+ payment_method_type = "Mastercard"
+[[paybox.credit]]
+ payment_method_type = "Visa"
+[[paybox.credit]]
+ payment_method_type = "Interac"
+[[paybox.credit]]
+ payment_method_type = "AmericanExpress"
+[[paybox.credit]]
+ payment_method_type = "JCB"
+[[paybox.credit]]
+ payment_method_type = "DinersClub"
+[[paybox.credit]]
+ payment_method_type = "Discover"
+[[paybox.credit]]
+ payment_method_type = "CartesBancaires"
+[[paybox.credit]]
+ payment_method_type = "UnionPay"
+[[paybox.debit]]
+ payment_method_type = "Mastercard"
+[[paybox.debit]]
+ payment_method_type = "Visa"
+[[paybox.debit]]
+ payment_method_type = "Interac"
+[[paybox.debit]]
+ payment_method_type = "AmericanExpress"
+[[paybox.debit]]
+ payment_method_type = "JCB"
+[[paybox.debit]]
+ payment_method_type = "DinersClub"
+[[paybox.debit]]
+ payment_method_type = "Discover"
+[[paybox.debit]]
+ payment_method_type = "CartesBancaires"
+[paybox.connector_auth.SignatureKey]
+api_key="SITE Key"
+key1="Rang Identifier"
+api_secret="CLE Secret"
+
[datatrans]
[[datatrans.credit]]
payment_method_type = "Mastercard"
diff --git a/crates/connector_configs/toml/sandbox.toml b/crates/connector_configs/toml/sandbox.toml
index 1c4b61db41c..b61187def75 100644
--- a/crates/connector_configs/toml/sandbox.toml
+++ b/crates/connector_configs/toml/sandbox.toml
@@ -3796,6 +3796,46 @@ key1="Public Api Key"
api_key = "Passcode"
key1 = "datatrans MerchantId"
+[paybox]
+[[paybox.credit]]
+ payment_method_type = "Mastercard"
+[[paybox.credit]]
+ payment_method_type = "Visa"
+[[paybox.credit]]
+ payment_method_type = "Interac"
+[[paybox.credit]]
+ payment_method_type = "AmericanExpress"
+[[paybox.credit]]
+ payment_method_type = "JCB"
+[[paybox.credit]]
+ payment_method_type = "DinersClub"
+[[paybox.credit]]
+ payment_method_type = "Discover"
+[[paybox.credit]]
+ payment_method_type = "CartesBancaires"
+[[paybox.credit]]
+ payment_method_type = "UnionPay"
+[[paybox.debit]]
+ payment_method_type = "Mastercard"
+[[paybox.debit]]
+ payment_method_type = "Visa"
+[[paybox.debit]]
+ payment_method_type = "Interac"
+[[paybox.debit]]
+ payment_method_type = "AmericanExpress"
+[[paybox.debit]]
+ payment_method_type = "JCB"
+[[paybox.debit]]
+ payment_method_type = "DinersClub"
+[[paybox.debit]]
+ payment_method_type = "Discover"
+[[paybox.debit]]
+ payment_method_type = "CartesBancaires"
+[paybox.connector_auth.SignatureKey]
+api_key="SITE Key"
+key1="Rang Identifier"
+api_secret="CLE Secret"
+
[wellsfargo]
[[wellsfargo.credit]]
payment_method_type = "Mastercard"
diff --git a/crates/router/src/connector/paybox.rs b/crates/router/src/connector/paybox.rs
index 720f0a00c6a..0a7f74a048f 100644
--- a/crates/router/src/connector/paybox.rs
+++ b/crates/router/src/connector/paybox.rs
@@ -1,5 +1,6 @@
pub mod transformers;
+use common_enums::enums;
use common_utils::types::{AmountConvertor, MinorUnit, MinorUnitForConnector};
use error_stack::{report, ResultExt};
use masking::ExposeInterface;
@@ -8,6 +9,7 @@ use transformers as paybox;
use super::utils::{self as connector_utils};
use crate::{
configs::settings,
+ connector::utils,
core::errors::{self, CustomResult},
events::connector_api_logs::ConnectorEvent,
headers,
@@ -49,6 +51,10 @@ impl api::Refund for Paybox {}
impl api::RefundExecute for Paybox {}
impl api::RefundSync for Paybox {}
impl api::PaymentToken for Paybox {}
+impl ConnectorIntegration<api::Void, types::PaymentsCancelData, types::PaymentsResponseData>
+ for Paybox
+{
+}
impl
ConnectorIntegration<
@@ -57,7 +63,6 @@ impl
types::PaymentsResponseData,
> for Paybox
{
- // Not Implemented (R)
}
impl<Flow, Request, Response> ConnectorCommonExt<Flow, Request, Response> for Paybox
@@ -66,15 +71,13 @@ where
{
fn build_headers(
&self,
- req: &types::RouterData<Flow, Request, Response>,
+ _req: &types::RouterData<Flow, Request, Response>,
_connectors: &settings::Connectors,
) -> CustomResult<Vec<(String, request::Maskable<String>)>, errors::ConnectorError> {
- let mut header = vec![(
+ let header = vec![(
headers::CONTENT_TYPE.to_string(),
self.get_content_type().to_string().into(),
)];
- let mut api_key = self.get_auth_header(&req.connector_auth_type)?;
- header.append(&mut api_key);
Ok(header)
}
}
@@ -84,15 +87,8 @@ impl ConnectorCommon for Paybox {
"paybox"
}
- // fn get_currency_unit(&self) -> api::CurrencyUnit {
- // // todo!()
- // // TODO! Check connector documentation, on which unit they are processing the currency.
- // // If the connector accepts amount in lower unit ( i.e cents for USD) then return api::CurrencyUnit::Minor,
- // // if connector accepts amount in base unit (i.e dollars for USD) then return api::CurrencyUnit::Base
- // }
-
fn common_get_content_type(&self) -> &'static str {
- "application/json"
+ "application/x-www-form-urlencoded"
}
fn base_url<'a>(&self, connectors: &'a settings::Connectors) -> &'a str {
@@ -107,7 +103,7 @@ impl ConnectorCommon for Paybox {
.change_context(errors::ConnectorError::FailedToObtainAuthType)?;
Ok(vec![(
headers::AUTHORIZATION.to_string(),
- auth.api_key.expose().into_masked(),
+ auth.cle.expose().into_masked(),
)])
}
@@ -136,13 +132,24 @@ impl ConnectorCommon for Paybox {
}
impl ConnectorValidation for Paybox {
- //TODO: implement functions when support enabled
+ fn validate_capture_method(
+ &self,
+ capture_method: Option<enums::CaptureMethod>,
+ _pmt: Option<enums::PaymentMethodType>,
+ ) -> CustomResult<(), errors::ConnectorError> {
+ let capture_method = capture_method.unwrap_or_default();
+ match capture_method {
+ enums::CaptureMethod::Automatic | enums::CaptureMethod::Manual => Ok(()),
+ enums::CaptureMethod::ManualMultiple | enums::CaptureMethod::Scheduled => Err(
+ utils::construct_not_implemented_error_report(capture_method, self.id()),
+ ),
+ }
+ }
}
impl ConnectorIntegration<api::Session, types::PaymentsSessionData, types::PaymentsResponseData>
for Paybox
{
- //TODO: implement sessions flow
}
impl ConnectorIntegration<api::AccessTokenAuth, types::AccessTokenRequestData, types::AccessToken>
@@ -158,7 +165,6 @@ impl
> for Paybox
{
}
-
impl ConnectorIntegration<api::Authorize, types::PaymentsAuthorizeData, types::PaymentsResponseData>
for Paybox
{
@@ -177,9 +183,9 @@ impl ConnectorIntegration<api::Authorize, types::PaymentsAuthorizeData, types::P
fn get_url(
&self,
_req: &types::PaymentsAuthorizeRouterData,
- _connectors: &settings::Connectors,
+ connectors: &settings::Connectors,
) -> CustomResult<String, errors::ConnectorError> {
- Err(errors::ConnectorError::NotImplemented("get_url method".to_string()).into())
+ Ok(self.base_url(connectors).to_string())
}
fn get_request_body(
@@ -195,7 +201,7 @@ impl ConnectorIntegration<api::Authorize, types::PaymentsAuthorizeData, types::P
let connector_router_data = paybox::PayboxRouterData::from((amount, req));
let connector_req = paybox::PayboxPaymentsRequest::try_from(&connector_router_data)?;
- Ok(RequestContent::Json(Box::new(connector_req)))
+ Ok(RequestContent::FormUrlEncoded(Box::new(connector_req)))
}
fn build_request(
@@ -210,9 +216,6 @@ impl ConnectorIntegration<api::Authorize, types::PaymentsAuthorizeData, types::P
self, req, connectors,
)?)
.attach_default_headers()
- .headers(types::PaymentsAuthorizeType::get_headers(
- self, req, connectors,
- )?)
.set_body(types::PaymentsAuthorizeType::get_request_body(
self, req, connectors,
)?)
@@ -226,10 +229,7 @@ impl ConnectorIntegration<api::Authorize, types::PaymentsAuthorizeData, types::P
event_builder: Option<&mut ConnectorEvent>,
res: Response,
) -> CustomResult<types::PaymentsAuthorizeRouterData, errors::ConnectorError> {
- let response: paybox::PayboxPaymentsResponse = res
- .response
- .parse_struct("Paybox PaymentsAuthorizeResponse")
- .change_context(errors::ConnectorError::ResponseDeserializationFailed)?;
+ let response: paybox::PayboxResponse = paybox::parse_url_encoded_to_struct(res.response)?;
event_builder.map(|i| i.set_response_body(&response));
router_env::logger::info!(connector_response=?response);
types::RouterData::try_from(types::ResponseRouterData {
@@ -262,13 +262,20 @@ impl ConnectorIntegration<api::PSync, types::PaymentsSyncData, types::PaymentsRe
fn get_content_type(&self) -> &'static str {
self.common_get_content_type()
}
-
+ fn get_request_body(
+ &self,
+ req: &types::PaymentsSyncRouterData,
+ _connectors: &settings::Connectors,
+ ) -> CustomResult<RequestContent, errors::ConnectorError> {
+ let connector_req = paybox::PayboxPSyncRequest::try_from(req)?;
+ Ok(RequestContent::FormUrlEncoded(Box::new(connector_req)))
+ }
fn get_url(
&self,
_req: &types::PaymentsSyncRouterData,
- _connectors: &settings::Connectors,
+ connectors: &settings::Connectors,
) -> CustomResult<String, errors::ConnectorError> {
- Err(errors::ConnectorError::NotImplemented("get_url method".to_string()).into())
+ Ok(self.base_url(connectors).to_string())
}
fn build_request(
@@ -278,10 +285,12 @@ impl ConnectorIntegration<api::PSync, types::PaymentsSyncData, types::PaymentsRe
) -> CustomResult<Option<services::Request>, errors::ConnectorError> {
Ok(Some(
services::RequestBuilder::new()
- .method(services::Method::Get)
+ .method(services::Method::Post)
.url(&types::PaymentsSyncType::get_url(self, req, connectors)?)
.attach_default_headers()
- .headers(types::PaymentsSyncType::get_headers(self, req, connectors)?)
+ .set_body(types::PaymentsSyncType::get_request_body(
+ self, req, connectors,
+ )?)
.build(),
))
}
@@ -292,10 +301,8 @@ impl ConnectorIntegration<api::PSync, types::PaymentsSyncData, types::PaymentsRe
event_builder: Option<&mut ConnectorEvent>,
res: Response,
) -> CustomResult<types::PaymentsSyncRouterData, errors::ConnectorError> {
- let response: paybox::PayboxPaymentsResponse = res
- .response
- .parse_struct("paybox PaymentsSyncResponse")
- .change_context(errors::ConnectorError::ResponseDeserializationFailed)?;
+ let response: paybox::PayboxSyncResponse =
+ paybox::parse_url_encoded_to_struct(res.response)?;
event_builder.map(|i| i.set_response_body(&response));
router_env::logger::info!(connector_response=?response);
types::RouterData::try_from(types::ResponseRouterData {
@@ -332,17 +339,25 @@ impl ConnectorIntegration<api::Capture, types::PaymentsCaptureData, types::Payme
fn get_url(
&self,
_req: &types::PaymentsCaptureRouterData,
- _connectors: &settings::Connectors,
+ connectors: &settings::Connectors,
) -> CustomResult<String, errors::ConnectorError> {
- Err(errors::ConnectorError::NotImplemented("get_url method".to_string()).into())
+ Ok(self.base_url(connectors).to_string())
}
fn get_request_body(
&self,
- _req: &types::PaymentsCaptureRouterData,
+ req: &types::PaymentsCaptureRouterData,
_connectors: &settings::Connectors,
) -> CustomResult<RequestContent, errors::ConnectorError> {
- Err(errors::ConnectorError::NotImplemented("get_request_body method".to_string()).into())
+ let amount = connector_utils::convert_amount(
+ self.amount_converter,
+ req.request.minor_amount_to_capture,
+ req.request.currency,
+ )?;
+
+ let connector_router_data = paybox::PayboxRouterData::from((amount, req));
+ let connector_req = paybox::PayboxCaptureRequest::try_from(&connector_router_data)?;
+ Ok(RequestContent::FormUrlEncoded(Box::new(connector_req)))
}
fn build_request(
@@ -355,9 +370,6 @@ impl ConnectorIntegration<api::Capture, types::PaymentsCaptureData, types::Payme
.method(services::Method::Post)
.url(&types::PaymentsCaptureType::get_url(self, req, connectors)?)
.attach_default_headers()
- .headers(types::PaymentsCaptureType::get_headers(
- self, req, connectors,
- )?)
.set_body(types::PaymentsCaptureType::get_request_body(
self, req, connectors,
)?)
@@ -371,10 +383,9 @@ impl ConnectorIntegration<api::Capture, types::PaymentsCaptureData, types::Payme
event_builder: Option<&mut ConnectorEvent>,
res: Response,
) -> CustomResult<types::PaymentsCaptureRouterData, errors::ConnectorError> {
- let response: paybox::PayboxPaymentsResponse = res
- .response
- .parse_struct("Paybox PaymentsCaptureResponse")
- .change_context(errors::ConnectorError::ResponseDeserializationFailed)?;
+ let response: paybox::PayboxCaptureResponse =
+ paybox::parse_url_encoded_to_struct(res.response)?;
+
event_builder.map(|i| i.set_response_body(&response));
router_env::logger::info!(connector_response=?response);
types::RouterData::try_from(types::ResponseRouterData {
@@ -393,11 +404,6 @@ impl ConnectorIntegration<api::Capture, types::PaymentsCaptureData, types::Payme
}
}
-impl ConnectorIntegration<api::Void, types::PaymentsCancelData, types::PaymentsResponseData>
- for Paybox
-{
-}
-
impl ConnectorIntegration<api::Execute, types::RefundsData, types::RefundsResponseData> for Paybox {
fn get_headers(
&self,
@@ -414,9 +420,9 @@ impl ConnectorIntegration<api::Execute, types::RefundsData, types::RefundsRespon
fn get_url(
&self,
_req: &types::RefundsRouterData<api::Execute>,
- _connectors: &settings::Connectors,
+ connectors: &settings::Connectors,
) -> CustomResult<String, errors::ConnectorError> {
- Err(errors::ConnectorError::NotImplemented("get_url method".to_string()).into())
+ Ok(self.base_url(connectors).to_string())
}
fn get_request_body(
@@ -432,7 +438,7 @@ impl ConnectorIntegration<api::Execute, types::RefundsData, types::RefundsRespon
let connector_router_data = paybox::PayboxRouterData::from((refund_amount, req));
let connector_req = paybox::PayboxRefundRequest::try_from(&connector_router_data)?;
- Ok(RequestContent::Json(Box::new(connector_req)))
+ Ok(RequestContent::FormUrlEncoded(Box::new(connector_req)))
}
fn build_request(
@@ -444,9 +450,6 @@ impl ConnectorIntegration<api::Execute, types::RefundsData, types::RefundsRespon
.method(services::Method::Post)
.url(&types::RefundExecuteType::get_url(self, req, connectors)?)
.attach_default_headers()
- .headers(types::RefundExecuteType::get_headers(
- self, req, connectors,
- )?)
.set_body(types::RefundExecuteType::get_request_body(
self, req, connectors,
)?)
@@ -460,10 +463,7 @@ impl ConnectorIntegration<api::Execute, types::RefundsData, types::RefundsRespon
event_builder: Option<&mut ConnectorEvent>,
res: Response,
) -> CustomResult<types::RefundsRouterData<api::Execute>, errors::ConnectorError> {
- let response: paybox::RefundResponse =
- res.response
- .parse_struct("paybox RefundResponse")
- .change_context(errors::ConnectorError::ResponseDeserializationFailed)?;
+ let response: paybox::PayboxResponse = paybox::parse_url_encoded_to_struct(res.response)?;
event_builder.map(|i| i.set_response_body(&response));
router_env::logger::info!(connector_response=?response);
types::RouterData::try_from(types::ResponseRouterData {
@@ -498,9 +498,18 @@ impl ConnectorIntegration<api::RSync, types::RefundsData, types::RefundsResponse
fn get_url(
&self,
_req: &types::RefundSyncRouterData,
- _connectors: &settings::Connectors,
+ connectors: &settings::Connectors,
) -> CustomResult<String, errors::ConnectorError> {
- Err(errors::ConnectorError::NotImplemented("get_url method".to_string()).into())
+ Ok(self.base_url(connectors).to_string())
+ }
+
+ fn get_request_body(
+ &self,
+ req: &types::RefundSyncRouterData,
+ _connectors: &settings::Connectors,
+ ) -> CustomResult<RequestContent, errors::ConnectorError> {
+ let connector_req = paybox::PayboxRsyncRequest::try_from(req)?;
+ Ok(RequestContent::FormUrlEncoded(Box::new(connector_req)))
}
fn build_request(
@@ -510,10 +519,9 @@ impl ConnectorIntegration<api::RSync, types::RefundsData, types::RefundsResponse
) -> CustomResult<Option<services::Request>, errors::ConnectorError> {
Ok(Some(
services::RequestBuilder::new()
- .method(services::Method::Get)
+ .method(services::Method::Post)
.url(&types::RefundSyncType::get_url(self, req, connectors)?)
.attach_default_headers()
- .headers(types::RefundSyncType::get_headers(self, req, connectors)?)
.set_body(types::RefundSyncType::get_request_body(
self, req, connectors,
)?)
@@ -527,10 +535,8 @@ impl ConnectorIntegration<api::RSync, types::RefundsData, types::RefundsResponse
event_builder: Option<&mut ConnectorEvent>,
res: Response,
) -> CustomResult<types::RefundSyncRouterData, errors::ConnectorError> {
- let response: paybox::RefundResponse = res
- .response
- .parse_struct("paybox RefundSyncResponse")
- .change_context(errors::ConnectorError::ResponseDeserializationFailed)?;
+ let response: paybox::PayboxSyncResponse =
+ paybox::parse_url_encoded_to_struct(res.response)?;
event_builder.map(|i| i.set_response_body(&response));
router_env::logger::info!(connector_response=?response);
types::RouterData::try_from(types::ResponseRouterData {
diff --git a/crates/router/src/connector/paybox/transformers.rs b/crates/router/src/connector/paybox/transformers.rs
index d83c4261c19..fd9129c8a84 100644
--- a/crates/router/src/connector/paybox/transformers.rs
+++ b/crates/router/src/connector/paybox/transformers.rs
@@ -1,14 +1,17 @@
-use common_utils::types::MinorUnit;
+use bytes::Bytes;
+use common_utils::{date_time::DateFormat, errors::CustomResult, types::MinorUnit};
+use error_stack::ResultExt;
+use hyperswitch_connectors::utils::CardData;
+use hyperswitch_domain_models::router_data::ConnectorAuthType;
use masking::Secret;
-use serde::{Deserialize, Serialize};
+use serde::{de::DeserializeOwned, Deserialize, Serialize};
use crate::{
- connector::utils::PaymentsAuthorizeRequestData,
+ connector::utils,
core::errors,
types::{self, api, domain, storage::enums},
};
-//TODO: Fill the struct with respective fields
pub struct PayboxRouterData<T> {
pub amount: MinorUnit, // The type of amount that a connector accepts, for example, String, i64, f64, etc.
pub router_data: T,
@@ -16,7 +19,6 @@ pub struct PayboxRouterData<T> {
impl<T> From<(MinorUnit, T)> for PayboxRouterData<T> {
fn from((amount, item): (MinorUnit, T)) -> Self {
- //Todo : use utils to convert the amount to the type of amount that a connector accepts
Self {
amount,
router_data: item,
@@ -24,20 +26,294 @@ impl<T> From<(MinorUnit, T)> for PayboxRouterData<T> {
}
}
-//TODO: Fill the struct with respective fields
-#[derive(Default, Debug, Serialize, PartialEq)]
+const AUTH_REQUEST: &str = "00001";
+const CAPTURE_REQUEST: &str = "00002";
+const AUTH_AND_CAPTURE_REQUEST: &str = "00003";
+const SYNC_REQUEST: &str = "00017";
+const REFUND_REQUEST: &str = "00014";
+
+const SUCCESS_CODE: &str = "00000";
+
+const VERSION_PAYBOX: &str = "00104";
+
+const PAY_ORIGIN_INTERNET: &str = "024";
+
+type Error = error_stack::Report<errors::ConnectorError>;
+
+#[derive(Debug, Serialize, Eq, PartialEq)]
pub struct PayboxPaymentsRequest {
- amount: MinorUnit,
- card: PayboxCard,
+ #[serde(rename = "DATEQ")]
+ pub date: String,
+
+ #[serde(rename = "TYPE")]
+ pub transaction_type: String,
+
+ #[serde(rename = "NUMQUESTION")]
+ pub paybox_request_number: String,
+
+ #[serde(rename = "MONTANT")]
+ pub amount: MinorUnit,
+
+ #[serde(rename = "REFERENCE")]
+ pub description_reference: String,
+
+ #[serde(rename = "VERSION")]
+ pub version: String,
+
+ #[serde(rename = "DEVISE")]
+ pub currency: String,
+
+ #[serde(rename = "PORTEUR")]
+ pub card_number: cards::CardNumber,
+
+ #[serde(rename = "DATEVAL")]
+ pub expiration_date: Secret<String>,
+
+ #[serde(rename = "CVV")]
+ pub cvv: Secret<String>,
+
+ #[serde(rename = "ACTIVITE")]
+ pub activity: String,
+
+ #[serde(rename = "SITE")]
+ pub site: Secret<String>,
+
+ #[serde(rename = "RANG")]
+ pub rank: Secret<String>,
+
+ #[serde(rename = "CLE")]
+ pub key: Secret<String>,
+}
+
+#[derive(Debug, Serialize, Eq, PartialEq)]
+pub struct PayboxCaptureRequest {
+ #[serde(rename = "DATEQ")]
+ pub date: String,
+
+ #[serde(rename = "TYPE")]
+ pub transaction_type: String,
+
+ #[serde(rename = "NUMQUESTION")]
+ pub paybox_request_number: String,
+
+ #[serde(rename = "MONTANT")]
+ pub amount: MinorUnit,
+
+ #[serde(rename = "REFERENCE")]
+ pub reference: String,
+
+ #[serde(rename = "VERSION")]
+ pub version: String,
+
+ #[serde(rename = "DEVISE")]
+ pub currency: String,
+
+ #[serde(rename = "SITE")]
+ pub site: Secret<String>,
+
+ #[serde(rename = "RANG")]
+ pub rank: Secret<String>,
+
+ #[serde(rename = "CLE")]
+ pub key: Secret<String>,
+
+ #[serde(rename = "NUMTRANS")]
+ pub transaction_number: String,
+
+ #[serde(rename = "NUMAPPEL")]
+ pub paybox_order_id: String,
+}
+
+impl TryFrom<&PayboxRouterData<&types::PaymentsCaptureRouterData>> for PayboxCaptureRequest {
+ type Error = error_stack::Report<errors::ConnectorError>;
+ fn try_from(
+ item: &PayboxRouterData<&types::PaymentsCaptureRouterData>,
+ ) -> Result<Self, Self::Error> {
+ let auth_data: PayboxAuthType =
+ PayboxAuthType::try_from(&item.router_data.connector_auth_type)
+ .change_context(errors::ConnectorError::FailedToObtainAuthType)?;
+ let currency = diesel_models::enums::Currency::iso_4217(&item.router_data.request.currency)
+ .to_string();
+ let paybox_meta_data: PayboxMeta =
+ utils::to_connector_meta(item.router_data.request.connector_meta.clone())?;
+ let format_time = common_utils::date_time::format_date(
+ common_utils::date_time::now(),
+ DateFormat::YYYYMMDDHHmmss,
+ )
+ .change_context(errors::ConnectorError::RequestEncodingFailed)?;
+ Ok(Self {
+ date: format_time.clone(),
+ transaction_type: CAPTURE_REQUEST.to_string(),
+ paybox_request_number: get_paybox_request_number()?,
+ version: VERSION_PAYBOX.to_string(),
+ currency,
+ site: auth_data.site,
+ rank: auth_data.rang,
+ key: auth_data.cle,
+ transaction_number: paybox_meta_data.connector_request_id,
+ paybox_order_id: item.router_data.request.connector_transaction_id.clone(),
+ amount: item.amount,
+ reference: item.router_data.connector_request_reference_id.to_string(),
+ })
+ }
}
-#[derive(Default, Debug, Serialize, Eq, PartialEq)]
-pub struct PayboxCard {
- number: cards::CardNumber,
- expiry_month: Secret<String>,
- expiry_year: Secret<String>,
- cvc: Secret<String>,
- complete: bool,
+#[derive(Debug, Serialize, Eq, PartialEq)]
+pub struct PayboxRsyncRequest {
+ #[serde(rename = "DATEQ")]
+ pub date: String,
+
+ #[serde(rename = "TYPE")]
+ pub transaction_type: String,
+
+ #[serde(rename = "NUMQUESTION")]
+ pub paybox_request_number: String,
+
+ #[serde(rename = "VERSION")]
+ pub version: String,
+
+ #[serde(rename = "SITE")]
+ pub site: Secret<String>,
+
+ #[serde(rename = "RANG")]
+ pub rank: Secret<String>,
+
+ #[serde(rename = "CLE")]
+ pub key: Secret<String>,
+
+ #[serde(rename = "NUMTRANS")]
+ pub transaction_number: String,
+
+ #[serde(rename = "NUMAPPEL")]
+ pub paybox_order_id: String,
+}
+
+impl TryFrom<&types::RefundSyncRouterData> for PayboxRsyncRequest {
+ type Error = error_stack::Report<errors::ConnectorError>;
+ fn try_from(item: &types::RefundSyncRouterData) -> Result<Self, Self::Error> {
+ let auth_data: PayboxAuthType = PayboxAuthType::try_from(&item.connector_auth_type)
+ .change_context(errors::ConnectorError::FailedToObtainAuthType)?;
+ let format_time = common_utils::date_time::format_date(
+ common_utils::date_time::now(),
+ DateFormat::YYYYMMDDHHmmss,
+ )
+ .change_context(errors::ConnectorError::RequestEncodingFailed)?;
+ Ok(Self {
+ date: format_time.clone(),
+ transaction_type: SYNC_REQUEST.to_string(),
+ paybox_request_number: get_paybox_request_number()?,
+ version: VERSION_PAYBOX.to_string(),
+ site: auth_data.site,
+ rank: auth_data.rang,
+ key: auth_data.cle,
+ transaction_number: item
+ .request
+ .connector_refund_id
+ .clone()
+ .ok_or(errors::ConnectorError::RequestEncodingFailed)?,
+ paybox_order_id: item.request.connector_transaction_id.clone(),
+ })
+ }
+}
+#[derive(Debug, Serialize, Eq, PartialEq)]
+pub struct PayboxPSyncRequest {
+ #[serde(rename = "DATEQ")]
+ pub date: String,
+
+ #[serde(rename = "TYPE")]
+ pub transaction_type: String,
+
+ #[serde(rename = "NUMQUESTION")]
+ pub paybox_request_number: String,
+
+ #[serde(rename = "VERSION")]
+ pub version: String,
+
+ #[serde(rename = "SITE")]
+ pub site: Secret<String>,
+
+ #[serde(rename = "RANG")]
+ pub rank: Secret<String>,
+
+ #[serde(rename = "CLE")]
+ pub key: Secret<String>,
+
+ #[serde(rename = "NUMTRANS")]
+ pub transaction_number: String,
+
+ #[serde(rename = "NUMAPPEL")]
+ pub paybox_order_id: String,
+}
+
+impl TryFrom<&types::PaymentsSyncRouterData> for PayboxPSyncRequest {
+ type Error = error_stack::Report<errors::ConnectorError>;
+ fn try_from(item: &types::PaymentsSyncRouterData) -> Result<Self, Self::Error> {
+ let auth_data: PayboxAuthType = PayboxAuthType::try_from(&item.connector_auth_type)
+ .change_context(errors::ConnectorError::FailedToObtainAuthType)?;
+ let format_time = common_utils::date_time::format_date(
+ common_utils::date_time::now(),
+ DateFormat::YYYYMMDDHHmmss,
+ )
+ .change_context(errors::ConnectorError::RequestEncodingFailed)?;
+ let paybox_meta_data: PayboxMeta =
+ utils::to_connector_meta(item.request.connector_meta.clone())?;
+ Ok(Self {
+ date: format_time.clone(),
+ transaction_type: SYNC_REQUEST.to_string(),
+ paybox_request_number: get_paybox_request_number()?,
+ version: VERSION_PAYBOX.to_string(),
+ site: auth_data.site,
+ rank: auth_data.rang,
+ key: auth_data.cle,
+ transaction_number: paybox_meta_data.connector_request_id,
+ paybox_order_id: item
+ .request
+ .connector_transaction_id
+ .get_connector_transaction_id()
+ .change_context(errors::ConnectorError::MissingConnectorTransactionID)?,
+ })
+ }
+}
+
+#[derive(Debug, Serialize, Deserialize)]
+pub struct PayboxMeta {
+ pub connector_request_id: String,
+}
+
+#[derive(Debug, Serialize, Eq, PartialEq)]
+pub struct PayboxRefundRequest {
+ #[serde(rename = "DATEQ")]
+ pub date: String,
+
+ #[serde(rename = "TYPE")]
+ pub transaction_type: String,
+
+ #[serde(rename = "NUMQUESTION")]
+ pub paybox_request_number: String,
+
+ #[serde(rename = "MONTANT")]
+ pub amount: MinorUnit,
+
+ #[serde(rename = "VERSION")]
+ pub version: String,
+
+ #[serde(rename = "DEVISE")]
+ pub currency: String,
+
+ #[serde(rename = "SITE")]
+ pub site: Secret<String>,
+
+ #[serde(rename = "RANG")]
+ pub rank: Secret<String>,
+
+ #[serde(rename = "CLE")]
+ pub key: Secret<String>,
+
+ #[serde(rename = "NUMTRANS")]
+ pub transaction_number: String,
+
+ #[serde(rename = "NUMAPPEL")]
+ pub paybox_order_id: String,
}
impl TryFrom<&PayboxRouterData<&types::PaymentsAuthorizeRouterData>> for PayboxPaymentsRequest {
@@ -47,16 +323,37 @@ impl TryFrom<&PayboxRouterData<&types::PaymentsAuthorizeRouterData>> for PayboxP
) -> Result<Self, Self::Error> {
match item.router_data.request.payment_method_data.clone() {
domain::PaymentMethodData::Card(req_card) => {
- let card = PayboxCard {
- number: req_card.card_number,
- expiry_month: req_card.card_exp_month,
- expiry_year: req_card.card_exp_year,
- cvc: req_card.card_cvc,
- complete: item.router_data.request.is_auto_capture()?,
- };
+ let auth_data: PayboxAuthType =
+ PayboxAuthType::try_from(&item.router_data.connector_auth_type)
+ .change_context(errors::ConnectorError::FailedToObtainAuthType)?;
+ let transaction_type =
+ get_transaction_type(item.router_data.request.capture_method)?;
+ let currency =
+ diesel_models::enums::Currency::iso_4217(&item.router_data.request.currency)
+ .to_string();
+ let expiration_date =
+ req_card.get_card_expiry_month_year_2_digit_with_delimiter("".to_owned())?;
+ let format_time = common_utils::date_time::format_date(
+ common_utils::date_time::now(),
+ DateFormat::YYYYMMDDHHmmss,
+ )
+ .change_context(errors::ConnectorError::RequestEncodingFailed)?;
+
Ok(Self {
+ date: format_time.clone(),
+ transaction_type,
+ paybox_request_number: get_paybox_request_number()?,
amount: item.amount,
- card,
+ description_reference: item.router_data.connector_request_reference_id.clone(),
+ version: VERSION_PAYBOX.to_string(),
+ currency,
+ card_number: req_card.card_number,
+ expiration_date,
+ cvv: req_card.card_cvc,
+ activity: PAY_ORIGIN_INTERNET.to_string(),
+ site: auth_data.site,
+ rank: auth_data.rang,
+ key: auth_data.cle,
})
}
_ => Err(errors::ConnectorError::NotImplemented("Payment methods".to_string()).into()),
@@ -64,31 +361,59 @@ impl TryFrom<&PayboxRouterData<&types::PaymentsAuthorizeRouterData>> for PayboxP
}
}
-//TODO: Fill the struct with respective fields
-// Auth Struct
+fn get_transaction_type(capture_method: Option<enums::CaptureMethod>) -> Result<String, Error> {
+ match capture_method {
+ Some(enums::CaptureMethod::Automatic) => Ok(AUTH_AND_CAPTURE_REQUEST.to_string()),
+ Some(enums::CaptureMethod::Manual) => Ok(AUTH_REQUEST.to_string()),
+ _ => Err(errors::ConnectorError::CaptureMethodNotSupported)?,
+ }
+}
+fn get_paybox_request_number() -> Result<String, Error> {
+ let time_stamp = std::time::SystemTime::now()
+ .duration_since(std::time::UNIX_EPOCH)
+ .ok()
+ .ok_or(errors::ConnectorError::RequestEncodingFailed)?
+ .as_millis()
+ .to_string();
+ // unix time (in milliseconds) has 13 digits.if we consider 8 digits(the number digits to make day deterministic) there is no collision in the paybox_request_number as it will reset the paybox_request_number for each day and paybox accepting maximum length is 10 so we gonna take 9 (13-9)
+ let request_number = time_stamp
+ .get(4..)
+ .ok_or(errors::ConnectorError::ParsingFailed)?;
+ Ok(request_number.to_string())
+}
+
+#[derive(Debug, Serialize, Eq, PartialEq)]
pub struct PayboxAuthType {
- pub(super) api_key: Secret<String>,
+ pub(super) site: Secret<String>,
+ pub(super) rang: Secret<String>,
+ pub(super) cle: Secret<String>,
}
-impl TryFrom<&types::ConnectorAuthType> for PayboxAuthType {
+impl TryFrom<&ConnectorAuthType> for PayboxAuthType {
type Error = error_stack::Report<errors::ConnectorError>;
- fn try_from(auth_type: &types::ConnectorAuthType) -> Result<Self, Self::Error> {
- match auth_type {
- types::ConnectorAuthType::HeaderKey { api_key } => Ok(Self {
- api_key: api_key.to_owned(),
- }),
- _ => Err(errors::ConnectorError::FailedToObtainAuthType.into()),
+ fn try_from(auth_type: &ConnectorAuthType) -> Result<Self, Self::Error> {
+ if let ConnectorAuthType::SignatureKey {
+ api_key,
+ key1,
+ api_secret,
+ } = auth_type
+ {
+ Ok(Self {
+ site: api_key.to_owned(),
+ rang: key1.to_owned(),
+ cle: api_secret.to_owned(),
+ })
+ } else {
+ Err(errors::ConnectorError::FailedToObtainAuthType)?
}
}
}
-// PaymentsResponse
-//TODO: Append the remaining status flags
-#[derive(Debug, Clone, Default, Serialize, Deserialize, PartialEq)]
+
+#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
#[serde(rename_all = "lowercase")]
pub enum PayboxPaymentStatus {
Succeeded,
Failed,
- #[default]
Processing,
}
@@ -102,96 +427,279 @@ impl From<PayboxPaymentStatus> for enums::AttemptStatus {
}
}
-//TODO: Fill the struct with respective fields
-#[derive(Default, Debug, Clone, Serialize, Deserialize, PartialEq)]
-pub struct PayboxPaymentsResponse {
- status: PayboxPaymentStatus,
- id: String,
+#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
+pub struct PayboxResponse {
+ #[serde(rename = "NUMTRANS")]
+ pub transaction_number: String,
+
+ #[serde(rename = "NUMAPPEL")]
+ pub paybox_order_id: String,
+
+ #[serde(rename = "CODEREPONSE")]
+ pub response_code: String,
+
+ #[serde(rename = "COMMENTAIRE")]
+ pub response_message: String,
+}
+
+pub fn parse_url_encoded_to_struct<T: DeserializeOwned>(
+ query_bytes: Bytes,
+) -> CustomResult<T, errors::ConnectorError> {
+ let (cow, _, _) = encoding_rs::ISO_8859_10.decode(&query_bytes);
+ serde_qs::from_str::<T>(cow.as_ref()).change_context(errors::ConnectorError::ParsingFailed)
+}
+
+#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
+pub enum PayboxStatus {
+ #[serde(rename = "Remboursé")]
+ Refunded,
+
+ #[serde(rename = "Annulé")]
+ Cancelled,
+
+ #[serde(rename = "Autorisé")]
+ Authorised,
+
+ #[serde(rename = "Capturé")]
+ Captured,
+
+ #[serde(rename = "Refusé")]
+ Rejected,
+}
+
+#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
+pub struct PayboxSyncResponse {
+ #[serde(rename = "NUMTRANS")]
+ pub transaction_number: String,
+
+ #[serde(rename = "NUMAPPEL")]
+ pub paybox_order_id: String,
+
+ #[serde(rename = "CODEREPONSE")]
+ pub response_code: String,
+
+ #[serde(rename = "COMMENTAIRE")]
+ pub response_message: String,
+
+ #[serde(rename = "STATUS")]
+ pub status: PayboxStatus,
+}
+
+#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
+pub struct PayboxCaptureResponse {
+ #[serde(rename = "NUMTRANS")]
+ pub transaction_number: String,
+
+ #[serde(rename = "NUMAPPEL")]
+ pub paybox_order_id: String,
+
+ #[serde(rename = "CODEREPONSE")]
+ pub response_code: String,
+
+ #[serde(rename = "COMMENTAIRE")]
+ pub response_message: String,
}
impl<F, T>
- TryFrom<types::ResponseRouterData<F, PayboxPaymentsResponse, T, types::PaymentsResponseData>>
+ TryFrom<types::ResponseRouterData<F, PayboxCaptureResponse, T, types::PaymentsResponseData>>
for types::RouterData<F, T, types::PaymentsResponseData>
{
type Error = error_stack::Report<errors::ConnectorError>;
fn try_from(
- item: types::ResponseRouterData<F, PayboxPaymentsResponse, T, types::PaymentsResponseData>,
+ item: types::ResponseRouterData<F, PayboxCaptureResponse, T, types::PaymentsResponseData>,
) -> Result<Self, Self::Error> {
- Ok(Self {
- status: enums::AttemptStatus::from(item.response.status),
- response: Ok(types::PaymentsResponseData::TransactionResponse {
- resource_id: types::ResponseId::ConnectorTransactionId(item.response.id),
- redirection_data: None,
- mandate_reference: None,
- connector_metadata: None,
- network_txn_id: None,
- connector_response_reference_id: None,
- incremental_authorization_allowed: None,
- charge_id: None,
+ let response = item.response.clone();
+ let status = get_status_of_request(response.response_code.clone());
+ match status {
+ true => Ok(Self {
+ status: enums::AttemptStatus::Pending,
+ response: Ok(types::PaymentsResponseData::TransactionResponse {
+ resource_id: types::ResponseId::ConnectorTransactionId(
+ response.paybox_order_id,
+ ),
+ redirection_data: None,
+ mandate_reference: None,
+ connector_metadata: Some(serde_json::json!(PayboxMeta {
+ connector_request_id: response.transaction_number.clone()
+ })),
+ network_txn_id: None,
+ connector_response_reference_id: None,
+ incremental_authorization_allowed: None,
+ charge_id: None,
+ }),
+ amount_captured: None,
+ ..item.data
}),
- ..item.data
- })
+ false => Ok(Self {
+ response: Err(types::ErrorResponse {
+ code: response.response_code.clone(),
+ message: response.response_message.clone(),
+ reason: Some(response.response_message),
+ status_code: item.http_code,
+ attempt_status: None,
+ connector_transaction_id: Some(item.response.transaction_number),
+ }),
+ ..item.data
+ }),
+ }
}
}
-//TODO: Fill the struct with respective fields
-// REFUND :
-// Type definition for RefundRequest
-#[derive(Default, Debug, Serialize)]
-pub struct PayboxRefundRequest {
- pub amount: MinorUnit,
-}
-
-impl<F> TryFrom<&PayboxRouterData<&types::RefundsRouterData<F>>> for PayboxRefundRequest {
+impl<F, T> TryFrom<types::ResponseRouterData<F, PayboxResponse, T, types::PaymentsResponseData>>
+ for types::RouterData<F, T, types::PaymentsResponseData>
+{
type Error = error_stack::Report<errors::ConnectorError>;
fn try_from(
- item: &PayboxRouterData<&types::RefundsRouterData<F>>,
+ item: types::ResponseRouterData<F, PayboxResponse, T, types::PaymentsResponseData>,
) -> Result<Self, Self::Error> {
- Ok(Self {
- amount: item.amount.to_owned(),
- })
+ let response = item.response.clone();
+ let status = get_status_of_request(response.response_code.clone());
+ match status {
+ true => Ok(Self {
+ response: Ok(types::PaymentsResponseData::TransactionResponse {
+ resource_id: types::ResponseId::ConnectorTransactionId(
+ response.paybox_order_id,
+ ),
+ redirection_data: None,
+ mandate_reference: None,
+ connector_metadata: Some(serde_json::json!(PayboxMeta {
+ connector_request_id: response.transaction_number.clone()
+ })),
+ network_txn_id: None,
+ connector_response_reference_id: None,
+ incremental_authorization_allowed: None,
+ charge_id: None,
+ }),
+ ..item.data
+ }),
+ false => Ok(Self {
+ response: Err(types::ErrorResponse {
+ code: response.response_code.clone(),
+ message: response.response_message.clone(),
+ reason: Some(response.response_message),
+ status_code: item.http_code,
+ attempt_status: None,
+ connector_transaction_id: Some(item.response.transaction_number),
+ }),
+ ..item.data
+ }),
+ }
}
}
-// Type definition for Refund Response
+impl<F, T> TryFrom<types::ResponseRouterData<F, PayboxSyncResponse, T, types::PaymentsResponseData>>
+ for types::RouterData<F, T, types::PaymentsResponseData>
+{
+ type Error = error_stack::Report<errors::ConnectorError>;
+ fn try_from(
+ item: types::ResponseRouterData<F, PayboxSyncResponse, T, types::PaymentsResponseData>,
+ ) -> Result<Self, Self::Error> {
+ let response = item.response.clone();
+ let status = get_status_of_request(response.response_code.clone());
+ let connector_payment_status = item.response.status;
+ match status {
+ true => Ok(Self {
+ status: enums::AttemptStatus::from(connector_payment_status),
-#[allow(dead_code)]
-#[derive(Debug, Serialize, Default, Deserialize, Clone)]
-pub enum RefundStatus {
- Succeeded,
- Failed,
- #[default]
- Processing,
+ response: Ok(types::PaymentsResponseData::TransactionResponse {
+ resource_id: types::ResponseId::ConnectorTransactionId(
+ response.paybox_order_id,
+ ),
+ redirection_data: None,
+ mandate_reference: None,
+ connector_metadata: Some(serde_json::json!(PayboxMeta {
+ connector_request_id: response.transaction_number.clone()
+ })),
+ network_txn_id: None,
+ connector_response_reference_id: None,
+ incremental_authorization_allowed: None,
+ charge_id: None,
+ }),
+ ..item.data
+ }),
+ false => Ok(Self {
+ response: Err(types::ErrorResponse {
+ code: response.response_code.clone(),
+ message: response.response_message.clone(),
+ reason: Some(response.response_message),
+ status_code: item.http_code,
+ attempt_status: None,
+ connector_transaction_id: Some(item.response.transaction_number),
+ }),
+ ..item.data
+ }),
+ }
+ }
}
-impl From<RefundStatus> for enums::RefundStatus {
- fn from(item: RefundStatus) -> Self {
+impl From<PayboxStatus> for common_enums::RefundStatus {
+ fn from(item: PayboxStatus) -> Self {
+ match item {
+ PayboxStatus::Refunded => Self::Success,
+ PayboxStatus::Cancelled
+ | PayboxStatus::Authorised
+ | PayboxStatus::Captured
+ | PayboxStatus::Rejected => Self::Failure,
+ }
+ }
+}
+impl From<PayboxStatus> for enums::AttemptStatus {
+ fn from(item: PayboxStatus) -> Self {
match item {
- RefundStatus::Succeeded => Self::Success,
- RefundStatus::Failed => Self::Failure,
- RefundStatus::Processing => Self::Pending,
- //TODO: Review mapping
+ PayboxStatus::Cancelled => Self::Voided,
+ PayboxStatus::Authorised => Self::Authorized,
+ PayboxStatus::Captured | PayboxStatus::Refunded => Self::Charged,
+ PayboxStatus::Rejected => Self::Failure,
}
}
}
+fn get_status_of_request(item: String) -> bool {
+ item == *SUCCESS_CODE
+}
-//TODO: Fill the struct with respective fields
-#[derive(Default, Debug, Clone, Serialize, Deserialize)]
-pub struct RefundResponse {
- id: String,
- status: RefundStatus,
+impl<F> TryFrom<&PayboxRouterData<&types::RefundsRouterData<F>>> for PayboxRefundRequest {
+ type Error = error_stack::Report<errors::ConnectorError>;
+ fn try_from(
+ item: &PayboxRouterData<&types::RefundsRouterData<F>>,
+ ) -> Result<Self, Self::Error> {
+ let auth_data: PayboxAuthType =
+ PayboxAuthType::try_from(&item.router_data.connector_auth_type)
+ .change_context(errors::ConnectorError::FailedToObtainAuthType)?;
+ let currency = diesel_models::enums::Currency::iso_4217(&item.router_data.request.currency)
+ .to_string();
+ let format_time = common_utils::date_time::format_date(
+ common_utils::date_time::now(),
+ DateFormat::YYYYMMDDHHmmss,
+ )
+ .change_context(errors::ConnectorError::RequestEncodingFailed)?;
+ let paybox_meta_data: PayboxMeta =
+ utils::to_connector_meta(item.router_data.request.connector_metadata.clone())?;
+ Ok(Self {
+ date: format_time.clone(),
+ transaction_type: REFUND_REQUEST.to_string(),
+ paybox_request_number: get_paybox_request_number()?,
+ version: VERSION_PAYBOX.to_string(),
+ currency,
+ site: auth_data.site,
+ rank: auth_data.rang,
+ key: auth_data.cle,
+ transaction_number: paybox_meta_data.connector_request_id,
+ paybox_order_id: item.router_data.request.connector_transaction_id.clone(),
+ amount: item.amount,
+ })
+ }
}
-impl TryFrom<types::RefundsResponseRouterData<api::Execute, RefundResponse>>
- for types::RefundsRouterData<api::Execute>
+impl TryFrom<types::RefundsResponseRouterData<api::RSync, PayboxSyncResponse>>
+ for types::RefundsRouterData<api::RSync>
{
type Error = error_stack::Report<errors::ConnectorError>;
fn try_from(
- item: types::RefundsResponseRouterData<api::Execute, RefundResponse>,
+ item: types::RefundsResponseRouterData<api::RSync, PayboxSyncResponse>,
) -> Result<Self, Self::Error> {
Ok(Self {
response: Ok(types::RefundsResponseData {
- connector_refund_id: item.response.id.to_string(),
+ connector_refund_id: item.response.transaction_number,
refund_status: enums::RefundStatus::from(item.response.status),
}),
..item.data
@@ -199,25 +707,23 @@ impl TryFrom<types::RefundsResponseRouterData<api::Execute, RefundResponse>>
}
}
-impl TryFrom<types::RefundsResponseRouterData<api::RSync, RefundResponse>>
- for types::RefundsRouterData<api::RSync>
+impl TryFrom<types::RefundsResponseRouterData<api::Execute, PayboxResponse>>
+ for types::RefundsRouterData<api::Execute>
{
type Error = error_stack::Report<errors::ConnectorError>;
fn try_from(
- item: types::RefundsResponseRouterData<api::RSync, RefundResponse>,
+ item: types::RefundsResponseRouterData<api::Execute, PayboxResponse>,
) -> Result<Self, Self::Error> {
Ok(Self {
response: Ok(types::RefundsResponseData {
- connector_refund_id: item.response.id.to_string(),
- refund_status: enums::RefundStatus::from(item.response.status),
+ connector_refund_id: item.response.transaction_number,
+ refund_status: common_enums::RefundStatus::Pending,
}),
..item.data
})
}
}
-
-//TODO: Fill the struct with respective fields
-#[derive(Default, Debug, Serialize, Deserialize, PartialEq)]
+#[derive(Debug, Serialize, Deserialize, PartialEq)]
pub struct PayboxErrorResponse {
pub status_code: u16,
pub code: String,
diff --git a/crates/router/src/core/admin.rs b/crates/router/src/core/admin.rs
index 89cd956c995..aca76322722 100644
--- a/crates/router/src/core/admin.rs
+++ b/crates/router/src/core/admin.rs
@@ -1434,7 +1434,10 @@ impl<'a> ConnectorAuthTypeAndMetadataValidation<'a> {
opennode::transformers::OpennodeAuthType::try_from(self.auth_type)?;
Ok(())
}
- // api_enums::Connector::Paybox => todo!(), added for future usage
+ api_enums::Connector::Paybox => {
+ paybox::transformers::PayboxAuthType::try_from(self.auth_type)?;
+ Ok(())
+ }
api_enums::Connector::Payme => {
payme::transformers::PaymeAuthType::try_from(self.auth_type)?;
Ok(())
diff --git a/crates/router/src/types/api.rs b/crates/router/src/types/api.rs
index aa4f3d8a1a3..5f125ab9939 100644
--- a/crates/router/src/types/api.rs
+++ b/crates/router/src/types/api.rs
@@ -418,7 +418,9 @@ impl ConnectorData {
enums::Connector::Opennode => {
Ok(ConnectorEnum::Old(Box::new(&connector::Opennode)))
}
- // enums::Connector::Paybox => Ok(ConnectorEnum::Old(Box::new(connector::Paybox::new()))), // added for future use
+ enums::Connector::Paybox => {
+ Ok(ConnectorEnum::Old(Box::new(connector::Paybox::new())))
+ }
// "payeezy" => Ok(ConnectorIntegrationEnum::Old(Box::new(&connector::Payeezy)), As psync and rsync are not supported by this connector, it is added as template code for future usage
enums::Connector::Payme => {
Ok(ConnectorEnum::Old(Box::new(connector::Payme::new())))
diff --git a/crates/router/src/types/transformers.rs b/crates/router/src/types/transformers.rs
index cc8d947738b..67af63b154e 100644
--- a/crates/router/src/types/transformers.rs
+++ b/crates/router/src/types/transformers.rs
@@ -271,7 +271,7 @@ impl ForeignTryFrom<api_enums::Connector> for common_enums::RoutableConnectors {
api_enums::Connector::Noon => Self::Noon,
api_enums::Connector::Nuvei => Self::Nuvei,
api_enums::Connector::Opennode => Self::Opennode,
- // api_enums::Connector::Paybox => Self::Paybox, added for future usage
+ api_enums::Connector::Paybox => Self::Paybox,
api_enums::Connector::Payme => Self::Payme,
api_enums::Connector::Payone => Self::Payone,
api_enums::Connector::Paypal => Self::Paypal,
|
2024-08-08T21:55:10Z
|
## Type of Change
<!-- Put an `x` in the boxes that apply -->
- [x] New feature
## Description
<!-- Describe your changes in detail -->
Implemented Flows Authorize,Capture,PSync,Refund and RSync for card Payments.
For Paybox after the Payment we have to to do PSync as Force to get the status of Payment and same applies for Refund also.
### Additional Changes
- [ ] This PR modifies the API contract
- [ ] This PR modifies the database schema
- [ ] This PR modifies application configuration/environment variables
<!--
Provide links to the files with corresponding changes.
Following are the paths where you can find config files:
1. `config`
2. `crates/router/src/configs`
3. `loadtest/config`
-->
## Motivation and Context
<!--
Why is this change required? What problem does it solve?
If it fixes an open issue, please link to the issue here.
If you don't have an issue, we'd recommend starting with one first so the PR
can focus on the implementation (unless it is an obvious bug or documentation fix
that will have little conversation).
-->
https://github.com/juspay/hyperswitch/issues/5590
## How did you test it?
<!--
Did you write an integration/unit/API test to verify the code changes?
Or did you test this change manually (provide relevant screenshots)?
-->
Payment:
```
curl --location 'http://127.0.0.1:8080/payments' \
--header 'Content-Type: application/json' \
--header 'Accept: application/json' \
--header 'api-key: dev_IUCGqoaqFnbYXDFcyRerYSYqx44KRHsJNsCHetqjQ0kqjsijMmBzZKsNOfcjDsUa' \
--data-raw '{
"amount": 1000,
"currency": "EUR",
"confirm": true,
"capture_method": "automatic",
"capture_on": "2022-09-10T10:11:12Z",
"amount_to_capture": 1000,
"customer_id": "BamboraCustomer",
"email": "guest@example.com",
"name": "John Doe",
"phone": "999999999",
"phone_country_code": "+1",
"description": "Its my first payment request",
"authentication_type": "no_three_ds",
"return_url": "https://duck.com",
"payment_method": "card",
"payment_method_type": "credit",
"payment_method_data": {
"card": {
"card_number": "1111222233334444",
"card_exp_month": "05",
"card_exp_year": "27",
"card_holder_name": "John Doe",
"card_cvc": "222"
}
},
"billing": {
"address": {
"line1": "1467",
"line2": "Harrison Street",
"line3": "Harrison Street",
"city": "San Fransico",
"state": "California",
"zip": "94122",
"country": "US",
"first_name": "joseph",
"last_name": "Doe"
},
"phone": {
"number": "9123456789",
"country_code": "+91"
}
},
"shipping": {
"address": {
"line1": "1467",
"line2": "Harrison Street",
"line3": "Harrison Street",
"city": "San Fransico",
"state": "California",
"zip": "94122",
"country": "US",
"first_name": "joseph",
"last_name": "Doe"
},
"phone": {
"number": "9123456789",
"country_code": "+91"
}
},
"statement_descriptor_name": "joseph",
"statement_descriptor_suffix": "JS"
}'
```
Response:
```
{
"payment_id": "pay_dA1GIgbVyqaXsDcES4dw",
"merchant_id": "postman_merchant_GHAction_f962d351-d38d-431c-9c09-788d9fd68c8a",
"status": "processing",
"amount": 1000,
"net_amount": 1000,
"amount_capturable": 0,
"amount_received": null,
"connector": "paybox",
"client_secret": "pay_dA1GIgbVyqaXsDcES4dw_secret_zAS5Q8sgJonxnvIq9WRy",
"created": "2024-08-12T05:18:40.883Z",
"currency": "EUR",
"customer_id": "BamboraCustomer",
"customer": {
"id": "BamboraCustomer",
"name": "John Doe",
"email": "guest@example.com",
"phone": "999999999",
"phone_country_code": "+1"
},
"description": "Its my first payment request",
"refunds": null,
"disputes": null,
"mandate_id": null,
"mandate_data": null,
"setup_future_usage": null,
"off_session": null,
"capture_on": null,
"capture_method": "automatic",
"payment_method": "card",
"payment_method_data": {
"card": {
"last4": "4444",
"card_type": null,
"card_network": null,
"card_issuer": null,
"card_issuing_country": null,
"card_isin": "111122",
"card_extended_bin": null,
"card_exp_month": "05",
"card_exp_year": "27",
"card_holder_name": "John Doe",
"payment_checks": null,
"authentication_data": null
},
"billing": null
},
"payment_token": null,
"shipping": {
"address": {
"city": "San Fransico",
"country": "US",
"line1": "1467",
"line2": "Harrison Street",
"line3": "Harrison Street",
"zip": "94122",
"state": "California",
"first_name": "joseph",
"last_name": "Doe"
},
"phone": {
"number": "9123456789",
"country_code": "+91"
},
"email": null
},
"billing": {
"address": {
"city": "San Fransico",
"country": "US",
"line1": "1467",
"line2": "Harrison Street",
"line3": "Harrison Street",
"zip": "94122",
"state": "California",
"first_name": "joseph",
"last_name": "Doe"
},
"phone": {
"number": "9123456789",
"country_code": "+91"
},
"email": null
},
"order_details": null,
"email": "guest@example.com",
"name": "John Doe",
"phone": "999999999",
"return_url": "https://duck.com/",
"authentication_type": "no_three_ds",
"statement_descriptor_name": "joseph",
"statement_descriptor_suffix": "JS",
"next_action": null,
"cancellation_reason": null,
"error_code": null,
"error_message": null,
"unified_code": null,
"unified_message": null,
"payment_experience": null,
"payment_method_type": "credit",
"connector_label": null,
"business_country": null,
"business_label": "default",
"business_sub_label": null,
"allowed_payment_method_types": null,
"ephemeral_key": {
"customer_id": "BamboraCustomer",
"created_at": 1723439920,
"expires": 1723443520,
"secret": "epk_0cfd96fa1dbc4391bea59a4bdcd49dc1"
},
"manual_retry_allowed": false,
"connector_transaction_id": "0079564764",
"frm_message": null,
"metadata": null,
"connector_metadata": null,
"feature_metadata": null,
"reference_id": "0038137048",
"payment_link": null,
"profile_id": "pro_lBL8sGEInU4ElAMrG82j",
"surcharge_details": null,
"attempt_count": 1,
"merchant_decision": null,
"merchant_connector_id": "mca_gNU267CSqzmqeBjI31Xz",
"incremental_authorization_allowed": null,
"authorization_count": null,
"incremental_authorizations": null,
"external_authentication_details": null,
"external_3ds_authentication_attempted": false,
"expires_on": "2024-08-12T05:33:40.881Z",
"fingerprint": null,
"browser_info": null,
"payment_method_id": null,
"payment_method_status": null,
"updated": "2024-08-12T05:18:43.645Z",
"charges": null,
"frm_metadata": null,
"merchant_order_reference_id": null
}
```
Force Psync:
request:
```
curl --location 'http://127.0.0.1:8080/payments/pay_dA1GIgbVyqaXsDcES4dw?force_sync=true' \
--header 'Accept: application/json' \
--header 'api-key: dev_IUCGqoaqFnbYXDFcyRerYSYqx44KRHsJNsCHetqjQ0kqjsijMmBzZKsNOfcjDsUa'
```
response:
```
{
"payment_id": "pay_dA1GIgbVyqaXsDcES4dw",
"merchant_id": "postman_merchant_GHAction_f962d351-d38d-431c-9c09-788d9fd68c8a",
"status": "succeeded",
"amount": 1000,
"net_amount": 1000,
"amount_capturable": 0,
"amount_received": 1000,
"connector": "paybox",
"client_secret": "pay_dA1GIgbVyqaXsDcES4dw_secret_zAS5Q8sgJonxnvIq9WRy",
"created": "2024-08-12T05:18:40.883Z",
"currency": "EUR",
"customer_id": "BamboraCustomer",
"customer": {
"id": "BamboraCustomer",
"name": "John Doe",
"email": "guest@example.com",
"phone": "999999999",
"phone_country_code": "+1"
},
"description": "Its my first payment request",
"refunds": null,
"disputes": null,
"mandate_id": null,
"mandate_data": null,
"setup_future_usage": null,
"off_session": null,
"capture_on": null,
"capture_method": "automatic",
"payment_method": "card",
"payment_method_data": {
"card": {
"last4": "4444",
"card_type": null,
"card_network": null,
"card_issuer": null,
"card_issuing_country": null,
"card_isin": "111122",
"card_extended_bin": null,
"card_exp_month": "05",
"card_exp_year": "27",
"card_holder_name": "John Doe",
"payment_checks": null,
"authentication_data": null
},
"billing": null
},
"payment_token": null,
"shipping": {
"address": {
"city": "San Fransico",
"country": "US",
"line1": "1467",
"line2": "Harrison Street",
"line3": "Harrison Street",
"zip": "94122",
"state": "California",
"first_name": "joseph",
"last_name": "Doe"
},
"phone": {
"number": "9123456789",
"country_code": "+91"
},
"email": null
},
"billing": {
"address": {
"city": "San Fransico",
"country": "US",
"line1": "1467",
"line2": "Harrison Street",
"line3": "Harrison Street",
"zip": "94122",
"state": "California",
"first_name": "joseph",
"last_name": "Doe"
},
"phone": {
"number": "9123456789",
"country_code": "+91"
},
"email": null
},
"order_details": null,
"email": "guest@example.com",
"name": "John Doe",
"phone": "999999999",
"return_url": "https://duck.com/",
"authentication_type": "no_three_ds",
"statement_descriptor_name": "joseph",
"statement_descriptor_suffix": "JS",
"next_action": null,
"cancellation_reason": null,
"error_code": null,
"error_message": null,
"unified_code": null,
"unified_message": null,
"payment_experience": null,
"payment_method_type": "credit",
"connector_label": null,
"business_country": null,
"business_label": "default",
"business_sub_label": null,
"allowed_payment_method_types": null,
"ephemeral_key": null,
"manual_retry_allowed": false,
"connector_transaction_id": "0079564764",
"frm_message": null,
"metadata": null,
"connector_metadata": null,
"feature_metadata": null,
"reference_id": "0038137048",
"payment_link": null,
"profile_id": "pro_lBL8sGEInU4ElAMrG82j",
"surcharge_details": null,
"attempt_count": 1,
"merchant_decision": null,
"merchant_connector_id": "mca_gNU267CSqzmqeBjI31Xz",
"incremental_authorization_allowed": null,
"authorization_count": null,
"incremental_authorizations": null,
"external_authentication_details": null,
"external_3ds_authentication_attempted": false,
"expires_on": "2024-08-12T05:33:40.881Z",
"fingerprint": null,
"browser_info": null,
"payment_method_id": null,
"payment_method_status": null,
"updated": "2024-08-12T05:24:12.303Z",
"charges": null,
"frm_metadata": null,
"merchant_order_reference_id": null
}
```
Refund:
request:
```
curl --location 'http://127.0.0.1:8080/refunds' \
--header 'Content-Type: application/json' \
--header 'Accept: application/json' \
--header 'api-key: dev_IUCGqoaqFnbYXDFcyRerYSYqx44KRHsJNsCHetqjQ0kqjsijMmBzZKsNOfcjDsUa' \
--data '{
"payment_id": "pay_dA1GIgbVyqaXsDcES4dw",
"amount": 1000,
"reason": "Customer returned product",
"refund_type": "instant",
"metadata": {
"udf1": "value1",
"new_customer": "true",
"login_date": "2019-09-10T10:11:12Z"
}
}'
```
response:
```
{
"refund_id": "ref_CL9wUYOMtrvST4IaY7pX",
"payment_id": "pay_dA1GIgbVyqaXsDcES4dw",
"amount": 1000,
"currency": "EUR",
"status": "pending",
"reason": "Customer returned product",
"metadata": {
"udf1": "value1",
"new_customer": "true",
"login_date": "2019-09-10T10:11:12Z"
},
"error_message": null,
"error_code": null,
"created_at": "2024-08-12T05:24:44.370Z",
"updated_at": "2024-08-12T05:24:46.081Z",
"connector": "paybox",
"profile_id": "pro_lBL8sGEInU4ElAMrG82j",
"merchant_connector_id": "mca_gNU267CSqzmqeBjI31Xz",
"charges": null
}
```
Refund ForceSync:
request:
```
curl --location 'http://127.0.0.1:8080/refunds/ref_7FR2uWPPcB3BCu0SPgoQ?force_sync=true' \
--header 'Accept: application/json' \
--header 'api-key: dev_IUCGqoaqFnbYXDFcyRerYSYqx44KRHsJNsCHetqjQ0kqjsijMmBzZKsNOfcjDsUa'
```
response:
```
{
"refund_id": "ref_7FR2uWPPcB3BCu0SPgoQ",
"payment_id": "pay_I355vemf48KDFwqGPpyy",
"amount": 1000,
"currency": "EUR",
"status": "succeeded",
"reason": "Customer returned product",
"metadata": {
"udf1": "value1",
"new_customer": "true",
"login_date": "2019-09-10T10:11:12Z"
},
"error_message": null,
"error_code": null,
"created_at": "2024-08-10T20:18:24.724Z",
"updated_at": "2024-08-11T10:46:31.950Z",
"connector": "paybox",
"profile_id": "pro_lBL8sGEInU4ElAMrG82j",
"merchant_connector_id": "mca_gNU267CSqzmqeBjI31Xz",
"charges": null
}
```
Cypress Test Results:
<img width="687" alt="image" src="https://github.com/user-attachments/assets/ef572471-2ca5-408d-a71d-791ab5b7d622">
## Checklist
<!-- Put an `x` in the boxes that apply -->
- [x] I formatted the code `cargo +nightly fmt --all`
- [ ] I addressed lints thrown by `cargo clippy`
- [ ] I reviewed the submitted code
- [ ] I added unit tests for my changes where possible
|
d43648b9f5f87ce2e46e9e2dc49327c8a6af0f7d
|
|
juspay/hyperswitch
|
juspay__hyperswitch-5562
|
Bug: [FIX] fix cache invalidation for multitenancy
|
diff --git a/crates/redis_interface/src/types.rs b/crates/redis_interface/src/types.rs
index 6469df50778..f40b81af68e 100644
--- a/crates/redis_interface/src/types.rs
+++ b/crates/redis_interface/src/types.rs
@@ -27,6 +27,12 @@ impl RedisValue {
pub fn into_inner(self) -> FredRedisValue {
self.inner
}
+
+ pub fn from_bytes(val: Vec<u8>) -> Self {
+ Self {
+ inner: FredRedisValue::Bytes(val.into()),
+ }
+ }
pub fn from_string(value: String) -> Self {
Self {
inner: FredRedisValue::String(value.into()),
@@ -34,6 +40,12 @@ impl RedisValue {
}
}
+impl From<RedisValue> for FredRedisValue {
+ fn from(v: RedisValue) -> Self {
+ v.inner
+ }
+}
+
#[derive(Debug, serde::Deserialize, Clone)]
#[serde(default)]
pub struct RedisSettings {
diff --git a/crates/storage_impl/src/redis/cache.rs b/crates/storage_impl/src/redis/cache.rs
index 6cfadbcb256..ba4a8200fa7 100644
--- a/crates/storage_impl/src/redis/cache.rs
+++ b/crates/storage_impl/src/redis/cache.rs
@@ -2,7 +2,7 @@ use std::{any::Any, borrow::Cow, fmt::Debug, sync::Arc};
use common_utils::{
errors::{self, CustomResult},
- ext_traits::AsyncExt,
+ ext_traits::{AsyncExt, ByteSliceExt},
};
use dyn_clone::DynClone;
use error_stack::{Report, ResultExt};
@@ -23,30 +23,6 @@ use crate::{
/// Redis channel name used for publishing invalidation messages
pub const IMC_INVALIDATION_CHANNEL: &str = "hyperswitch_invalidate";
-/// Prefix for config cache key
-const CONFIG_CACHE_PREFIX: &str = "config";
-
-/// Prefix for accounts cache key
-const ACCOUNTS_CACHE_PREFIX: &str = "accounts";
-
-/// Prefix for routing cache key
-const ROUTING_CACHE_PREFIX: &str = "routing";
-
-/// Prefix for three ds decision manager cache key
-const DECISION_MANAGER_CACHE_PREFIX: &str = "decision_manager";
-
-/// Prefix for surcharge cache key
-const SURCHARGE_CACHE_PREFIX: &str = "surcharge";
-
-/// Prefix for cgraph cache key
-const CGRAPH_CACHE_PREFIX: &str = "cgraph";
-
-/// Prefix for all kinds of cache key
-const ALL_CACHE_PREFIX: &str = "all_cache_kind";
-
-/// Prefix for PM Filter cgraph cache key
-const PM_FILTERS_CGRAPH_CACHE_PREFIX: &str = "pm_filters_cgraph";
-
/// Time to live 30 mins
const CACHE_TTL: u64 = 30 * 60;
@@ -101,6 +77,13 @@ pub trait Cacheable: Any + Send + Sync + DynClone {
fn as_any(&self) -> &dyn Any;
}
+#[derive(serde::Serialize, serde::Deserialize)]
+pub struct CacheRedact<'a> {
+ pub tenant: String,
+ pub kind: CacheKind<'a>,
+}
+
+#[derive(serde::Serialize, serde::Deserialize)]
pub enum CacheKind<'a> {
Config(Cow<'a, str>),
Accounts(Cow<'a, str>),
@@ -112,45 +95,30 @@ pub enum CacheKind<'a> {
All(Cow<'a, str>),
}
-impl<'a> From<CacheKind<'a>> for RedisValue {
- fn from(kind: CacheKind<'a>) -> Self {
- let value = match kind {
- CacheKind::Config(s) => format!("{CONFIG_CACHE_PREFIX},{s}"),
- CacheKind::Accounts(s) => format!("{ACCOUNTS_CACHE_PREFIX},{s}"),
- CacheKind::Routing(s) => format!("{ROUTING_CACHE_PREFIX},{s}"),
- CacheKind::DecisionManager(s) => format!("{DECISION_MANAGER_CACHE_PREFIX},{s}"),
- CacheKind::Surcharge(s) => format!("{SURCHARGE_CACHE_PREFIX},{s}"),
- CacheKind::CGraph(s) => format!("{CGRAPH_CACHE_PREFIX},{s}"),
- CacheKind::PmFiltersCGraph(s) => format!("{PM_FILTERS_CGRAPH_CACHE_PREFIX},{s}"),
- CacheKind::All(s) => format!("{ALL_CACHE_PREFIX},{s}"),
- };
- Self::from_string(value)
+impl<'a> TryFrom<CacheRedact<'a>> for RedisValue {
+ type Error = Report<errors::ValidationError>;
+ fn try_from(v: CacheRedact<'a>) -> Result<Self, Self::Error> {
+ Ok(Self::from_bytes(serde_json::to_vec(&v).change_context(
+ errors::ValidationError::InvalidValue {
+ message: "Invalid publish key provided in pubsub".into(),
+ },
+ )?))
}
}
-impl<'a> TryFrom<RedisValue> for CacheKind<'a> {
+impl<'a> TryFrom<RedisValue> for CacheRedact<'a> {
type Error = Report<errors::ValidationError>;
- fn try_from(kind: RedisValue) -> Result<Self, Self::Error> {
- let validation_err = errors::ValidationError::InvalidValue {
- message: "Invalid publish key provided in pubsub".into(),
- };
- let kind = kind.as_string().ok_or(validation_err.clone())?;
- let split = kind.split_once(',').ok_or(validation_err.clone())?;
- match split.0 {
- ACCOUNTS_CACHE_PREFIX => Ok(Self::Accounts(Cow::Owned(split.1.to_string()))),
- CONFIG_CACHE_PREFIX => Ok(Self::Config(Cow::Owned(split.1.to_string()))),
- ROUTING_CACHE_PREFIX => Ok(Self::Routing(Cow::Owned(split.1.to_string()))),
- DECISION_MANAGER_CACHE_PREFIX => {
- Ok(Self::DecisionManager(Cow::Owned(split.1.to_string())))
- }
- SURCHARGE_CACHE_PREFIX => Ok(Self::Surcharge(Cow::Owned(split.1.to_string()))),
- CGRAPH_CACHE_PREFIX => Ok(Self::CGraph(Cow::Owned(split.1.to_string()))),
- PM_FILTERS_CGRAPH_CACHE_PREFIX => {
- Ok(Self::PmFiltersCGraph(Cow::Owned(split.1.to_string())))
- }
- ALL_CACHE_PREFIX => Ok(Self::All(Cow::Owned(split.1.to_string()))),
- _ => Err(validation_err.into()),
- }
+
+ fn try_from(v: RedisValue) -> Result<Self, Self::Error> {
+ let bytes = v.as_bytes().ok_or(errors::ValidationError::InvalidValue {
+ message: "InvalidValue received in pubsub".to_string(),
+ })?;
+
+ bytes
+ .parse_struct("CacheRedact")
+ .change_context(errors::ValidationError::InvalidValue {
+ message: "Unable to deserialize the value from pubsub".to_string(),
+ })
}
}
diff --git a/crates/storage_impl/src/redis/pub_sub.rs b/crates/storage_impl/src/redis/pub_sub.rs
index 89877f7e8dd..8f24b62fcaf 100644
--- a/crates/storage_impl/src/redis/pub_sub.rs
+++ b/crates/storage_impl/src/redis/pub_sub.rs
@@ -5,8 +5,8 @@ use redis_interface::{errors as redis_errors, PubsubInterface, RedisValue};
use router_env::{logger, tracing::Instrument};
use crate::redis::cache::{
- CacheKey, CacheKind, ACCOUNTS_CACHE, CGRAPH_CACHE, CONFIG_CACHE, DECISION_MANAGER_CACHE,
- PM_FILTERS_CGRAPH_CACHE, ROUTING_CACHE, SURCHARGE_CACHE,
+ CacheKey, CacheKind, CacheRedact, ACCOUNTS_CACHE, CGRAPH_CACHE, CONFIG_CACHE,
+ DECISION_MANAGER_CACHE, PM_FILTERS_CGRAPH_CACHE, ROUTING_CACHE, SURCHARGE_CACHE,
};
#[async_trait::async_trait]
@@ -66,15 +66,23 @@ impl PubSubInterface for std::sync::Arc<redis_interface::RedisConnectionPool> {
channel: &str,
key: CacheKind<'a>,
) -> error_stack::Result<usize, redis_errors::RedisError> {
+ let key = CacheRedact {
+ kind: key,
+ tenant: self.key_prefix.clone(),
+ };
+
self.publisher
- .publish(channel, RedisValue::from(key).into_inner())
+ .publish(
+ channel,
+ RedisValue::try_from(key).change_context(redis_errors::RedisError::PublishError)?,
+ )
.await
.change_context(redis_errors::RedisError::SubscribeError)
}
#[inline]
async fn on_message(&self) -> error_stack::Result<(), redis_errors::RedisError> {
- logger::debug!("Started on message: {:?}", self.key_prefix);
+ logger::debug!("Started on message");
let mut rx = self.subscriber.on_message();
while let Ok(message) = rx.recv().await {
let channel_name = message.channel.to_string();
@@ -82,7 +90,7 @@ impl PubSubInterface for std::sync::Arc<redis_interface::RedisConnectionPool> {
match channel_name.as_str() {
super::cache::IMC_INVALIDATION_CHANNEL => {
- let key = match CacheKind::try_from(RedisValue::new(message.value))
+ let message = match CacheRedact::try_from(RedisValue::new(message.value))
.change_context(redis_errors::RedisError::OnMessageError)
{
Ok(value) => value,
@@ -92,12 +100,12 @@ impl PubSubInterface for std::sync::Arc<redis_interface::RedisConnectionPool> {
}
};
- let key = match key {
+ let key = match message.kind {
CacheKind::Config(key) => {
CONFIG_CACHE
.remove(CacheKey {
key: key.to_string(),
- prefix: self.key_prefix.clone(),
+ prefix: message.tenant.clone(),
})
.await;
key
@@ -106,7 +114,7 @@ impl PubSubInterface for std::sync::Arc<redis_interface::RedisConnectionPool> {
ACCOUNTS_CACHE
.remove(CacheKey {
key: key.to_string(),
- prefix: self.key_prefix.clone(),
+ prefix: message.tenant.clone(),
})
.await;
key
@@ -115,7 +123,7 @@ impl PubSubInterface for std::sync::Arc<redis_interface::RedisConnectionPool> {
CGRAPH_CACHE
.remove(CacheKey {
key: key.to_string(),
- prefix: self.key_prefix.clone(),
+ prefix: message.tenant.clone(),
})
.await;
key
@@ -124,7 +132,7 @@ impl PubSubInterface for std::sync::Arc<redis_interface::RedisConnectionPool> {
PM_FILTERS_CGRAPH_CACHE
.remove(CacheKey {
key: key.to_string(),
- prefix: self.key_prefix.clone(),
+ prefix: message.tenant.clone(),
})
.await;
key
@@ -133,7 +141,7 @@ impl PubSubInterface for std::sync::Arc<redis_interface::RedisConnectionPool> {
ROUTING_CACHE
.remove(CacheKey {
key: key.to_string(),
- prefix: self.key_prefix.clone(),
+ prefix: message.tenant.clone(),
})
.await;
key
@@ -142,7 +150,7 @@ impl PubSubInterface for std::sync::Arc<redis_interface::RedisConnectionPool> {
DECISION_MANAGER_CACHE
.remove(CacheKey {
key: key.to_string(),
- prefix: self.key_prefix.clone(),
+ prefix: message.tenant.clone(),
})
.await;
key
@@ -151,7 +159,7 @@ impl PubSubInterface for std::sync::Arc<redis_interface::RedisConnectionPool> {
SURCHARGE_CACHE
.remove(CacheKey {
key: key.to_string(),
- prefix: self.key_prefix.clone(),
+ prefix: message.tenant.clone(),
})
.await;
key
@@ -160,43 +168,43 @@ impl PubSubInterface for std::sync::Arc<redis_interface::RedisConnectionPool> {
CONFIG_CACHE
.remove(CacheKey {
key: key.to_string(),
- prefix: self.key_prefix.clone(),
+ prefix: message.tenant.clone(),
})
.await;
ACCOUNTS_CACHE
.remove(CacheKey {
key: key.to_string(),
- prefix: self.key_prefix.clone(),
+ prefix: message.tenant.clone(),
})
.await;
CGRAPH_CACHE
.remove(CacheKey {
key: key.to_string(),
- prefix: self.key_prefix.clone(),
+ prefix: message.tenant.clone(),
})
.await;
PM_FILTERS_CGRAPH_CACHE
.remove(CacheKey {
key: key.to_string(),
- prefix: self.key_prefix.clone(),
+ prefix: message.tenant.clone(),
})
.await;
ROUTING_CACHE
.remove(CacheKey {
key: key.to_string(),
- prefix: self.key_prefix.clone(),
+ prefix: message.tenant.clone(),
})
.await;
DECISION_MANAGER_CACHE
.remove(CacheKey {
key: key.to_string(),
- prefix: self.key_prefix.clone(),
+ prefix: message.tenant.clone(),
})
.await;
SURCHARGE_CACHE
.remove(CacheKey {
key: key.to_string(),
- prefix: self.key_prefix.clone(),
+ prefix: message.tenant.clone(),
})
.await;
@@ -210,7 +218,9 @@ impl PubSubInterface for std::sync::Arc<redis_interface::RedisConnectionPool> {
.ok();
logger::debug!(
- "Handled message on channel {channel_name} - Done invalidating {key}"
+ key_prefix=?message.tenant.clone(),
+ channel_name=?channel_name,
+ "Done invalidating {key}"
);
}
_ => {
|
2024-08-07T16:47:35Z
|
## Type of Change
<!-- Put an `x` in the boxes that apply -->
- [x] Bugfix
## Description
<!-- Describe your changes in detail -->
Added a tenant field in the pubsub redact message. To give the information for the subscriber to delete the message for the appropriate tenant
## Motivation and Context
<!--
Why is this change required? What problem does it solve?
If it fixes an open issue, please link to the issue here.
If you don't have an issue, we'd recommend starting with one first so the PR
can focus on the implementation (unless it is an obvious bug or documentation fix
that will have little conversation).
-->
In the current implementation, the pub-sub message does not have any context of the tenant key for the cache it's supposed to invalidate cache for. Rather it was designed to spawn n number of tasks for cache invalidation for n tenants (This was fixed few weeks ago). Now the problem is there's only one thread which is spawned for n tenants, so whenever the cache is invalidated it will only be invalidated for the first tenant in the list.
This PR fixes it by passing the tenant information in the pub-sub message, from which we can take the tenant id and invalidate cache for the particular tenant.
## How did you test it?
<!--
Did you write an integration/unit/API test to verify the code changes?
Or did you test this change manually (provide relevant screenshots)?
-->
**This cannot be tested on sandbox without enabling multi tenancy or adding `redis_key_prefix` for the tenant**
1. Enable multitenancy by adding another tenant
```bash
[multitenancy]
enabled = true
global_tenant = { schema = "public", redis_key_prefix = "", clickhouse_database = "default"}
[multitenancy.tenants]
public = { name = "hyperswitch", base_url = "http://localhost:8080", schema = "public", redis_key_prefix = "hyperswitch", clickhouse_database = "default"}
foo = { name = "bar", base_url = "http://localhost:8080", schema = "public", redis_key_prefix = "bar", clickhouse_database = "default"}
```
2. Create merchant account with X-tenant-id as foo
```bash
curl --location 'http://localhost:8080/accounts' \
--header 'Content-Type: application/json' \
--header 'Accept: application/json' \
--header 'x-feature: integ-custom' \
--header 'x-tenant-id: foo' \
--header 'api-key: test_admin' \
--data-raw '{
"merchant_id": "merchant_1723049018",
"locker_id": "m0010",
"merchant_name": "NewAge Retailer",
"merchant_details": {
"primary_contact_person": "John Test",
"primary_email": "JohnTest@test.com",
"primary_phone": "sunt laborum",
"secondary_contact_person": "John Test2",
"secondary_email": "JohnTest2@test.com",
"secondary_phone": "cillum do dolor id",
"website": "www.example.com",
"about_business": "Online Retail with a wide selection of organic products for North America",
"address": {
"line1": "1467",
"line2": "Harrison Street",
"line3": "Harrison Street",
"city": "San Fransico",
"state": "California",
"zip": "94122",
"country": "US"
}
},
"return_url": "https://google.com/success",
"webhook_details": {
"webhook_version": "1.0.1",
"webhook_username": "ekart_retail",
"webhook_password": "password_ekart@123",
"payment_created_enabled": true,
"payment_succeeded_enabled": true,
"payment_failed_enabled": true
},
"sub_merchants_enabled": false,
"metadata": {
"city": "NY",
"unit": "245"
},
"primary_business_details": [
{
"country": "US",
"business": "default"
}
]
}'
```
Check that key is invalidated for the subsequent `redis_key_prefix` of the tenant

3. Create merchant account with x-tenant-id as public
```bash
curl --location 'http://localhost:8080/accounts' \
--header 'Content-Type: application/json' \
--header 'Accept: application/json' \
--header 'x-feature: integ-custom' \
--header 'x-tenant-id: public' \
--header 'api-key: test_admin' \
--data-raw '{
"merchant_id": "merchant_1723049152",
"locker_id": "m0010",
"merchant_name": "NewAge Retailer",
"merchant_details": {
"primary_contact_person": "John Test",
"primary_email": "JohnTest@test.com",
"primary_phone": "sunt laborum",
"secondary_contact_person": "John Test2",
"secondary_email": "JohnTest2@test.com",
"secondary_phone": "cillum do dolor id",
"website": "www.example.com",
"about_business": "Online Retail with a wide selection of organic products for North America",
"address": {
"line1": "1467",
"line2": "Harrison Street",
"line3": "Harrison Street",
"city": "San Fransico",
"state": "California",
"zip": "94122",
"country": "US"
}
},
"return_url": "https://google.com/success",
"webhook_details": {
"webhook_version": "1.0.1",
"webhook_username": "ekart_retail",
"webhook_password": "password_ekart@123",
"payment_created_enabled": true,
"payment_succeeded_enabled": true,
"payment_failed_enabled": true
},
"sub_merchants_enabled": false,
"metadata": {
"city": "NY",
"unit": "245"
},
"primary_business_details": [
{
"country": "US",
"business": "default"
}
]
}'
```
Check that key is invalidated for the subsequent `redis_key_prefix` of the tenant

## Checklist
<!-- Put an `x` in the boxes that apply -->
- [x] I formatted the code `cargo +nightly fmt --all`
- [x] I addressed lints thrown by `cargo clippy`
- [x] I reviewed the submitted code
|
732472204d835ef0ceb60bfec89f872c7098621e
|
|
juspay/hyperswitch
|
juspay__hyperswitch-5569
|
Bug: [REFACTOR] Refactor connector template generation
### Feature Description
Connector template code needs to be refactored so that the new connectors are added directly into the crate `hyperswitch_connectors`
### Possible Implementation
Connector template code needs to be refactored so that the new connectors are added directly into the crate `hyperswitch_connectors`
### Have you spent some time checking if this feature request has been raised before?
- [X] I checked and didn't find a similar issue
### Have you read the Contributing Guidelines?
- [X] I have read the [Contributing Guidelines](https://github.com/juspay/hyperswitch/blob/main/docs/CONTRIBUTING.md)
### Are you willing to submit a PR?
Yes, I am willing to submit a PR!
|
diff --git a/connector-template/mod.rs b/connector-template/mod.rs
index ce189a33fca..ae450aecf20 100644
--- a/connector-template/mod.rs
+++ b/connector-template/mod.rs
@@ -1,26 +1,48 @@
pub mod transformers;
use error_stack::{report, ResultExt};
-use masking::ExposeInterface;
+use masking::{ExposeInterface, Mask};
use common_utils::{
- types::{AmountConvertor, StringMinorUnit, StringMinorUnitForConnector}
+ errors::CustomResult,
+ ext_traits::BytesExt,
+ types::{AmountConvertor, StringMinorUnit, StringMinorUnitForConnector},
+ request::{Method, Request, RequestBuilder, RequestContent},
};
-use super::utils::{self as connector_utils};
-use crate::{
- events::connector_api_logs::ConnectorEvent,
- configs::settings,
- utils::BytesExt,
- core::{
- errors::{self, CustomResult},
+
+use hyperswitch_domain_models::{
+ router_data::{AccessToken, ConnectorAuthType, ErrorResponse, RouterData},
+ router_flow_types::{
+ access_token_auth::AccessTokenAuth,
+ payments::{
+ Authorize, Capture, PSync, PaymentMethodToken, Session,
+ SetupMandate, Void,
+ },
+ refunds::{Execute, RSync},
},
- headers, services::{self, ConnectorIntegration, ConnectorValidation, request::{self, Mask}},
+ router_request_types::{
+ AccessTokenRequestData, PaymentMethodTokenizationData,
+ PaymentsAuthorizeData, PaymentsCancelData, PaymentsCaptureData, PaymentsSessionData,
+ PaymentsSyncData, RefundsData, SetupMandateRequestData,
+ },
+ router_response_types::{PaymentsResponseData, RefundsResponseData},
types::{
- self,
- api::{self, ConnectorCommon, ConnectorCommonExt},
- ErrorResponse, Response,
- RequestContent
- }
+ PaymentsAuthorizeRouterData,
+ PaymentsCaptureRouterData, PaymentsSyncRouterData, RefundSyncRouterData, RefundsRouterData,
+ },
+};
+use hyperswitch_interfaces::{
+ api::{self, ConnectorCommon, ConnectorCommonExt, ConnectorIntegration, ConnectorValidation},
+ configs::Connectors,
+ errors,
+ events::connector_api_logs::ConnectorEvent,
+ types::{self, Response},
+ webhooks,
+};
+use crate::{
+ constants::headers,
+ types::ResponseRouterData,
+ utils,
};
use transformers as {{project-name | downcase}};
@@ -53,9 +75,9 @@ impl api::PaymentToken for {{project-name | downcase | pascal_case}} {}
impl
ConnectorIntegration<
- api::PaymentMethodToken,
- types::PaymentMethodTokenizationData,
- types::PaymentsResponseData,
+ PaymentMethodToken,
+ PaymentMethodTokenizationData,
+ PaymentsResponseData,
> for {{project-name | downcase | pascal_case}}
{
// Not Implemented (R)
@@ -66,9 +88,9 @@ where
Self: ConnectorIntegration<Flow, Request, Response>,{
fn build_headers(
&self,
- req: &types::RouterData<Flow, Request, Response>,
- _connectors: &settings::Connectors,
- ) -> CustomResult<Vec<(String, request::Maskable<String>)>, errors::ConnectorError> {
+ req: &RouterData<Flow, Request, Response>,
+ _connectors: &Connectors,
+ ) -> CustomResult<Vec<(String, masking::Maskable<String>)>, errors::ConnectorError> {
let mut header = vec![(
headers::CONTENT_TYPE.to_string(),
self.get_content_type().to_string().into(),
@@ -95,11 +117,11 @@ impl ConnectorCommon for {{project-name | downcase | pascal_case}} {
"application/json"
}
- fn base_url<'a>(&self, connectors: &'a settings::Connectors) -> &'a str {
+ fn base_url<'a>(&self, connectors: &'a Connectors) -> &'a str {
connectors.{{project-name}}.base_url.as_ref()
}
- fn get_auth_header(&self, auth_type:&types::ConnectorAuthType)-> CustomResult<Vec<(String,request::Maskable<String>)>,errors::ConnectorError> {
+ fn get_auth_header(&self, auth_type:&ConnectorAuthType)-> CustomResult<Vec<(String,masking::Maskable<String>)>,errors::ConnectorError> {
let auth = {{project-name | downcase}}::{{project-name | downcase | pascal_case}}AuthType::try_from(auth_type)
.change_context(errors::ConnectorError::FailedToObtainAuthType)?;
Ok(vec![(headers::AUTHORIZATION.to_string(), auth.api_key.expose().into_masked())])
@@ -136,35 +158,35 @@ impl ConnectorValidation for {{project-name | downcase | pascal_case}}
impl
ConnectorIntegration<
- api::Session,
- types::PaymentsSessionData,
- types::PaymentsResponseData,
+ Session,
+ PaymentsSessionData,
+ PaymentsResponseData,
> for {{project-name | downcase | pascal_case}}
{
//TODO: implement sessions flow
}
-impl ConnectorIntegration<api::AccessTokenAuth, types::AccessTokenRequestData, types::AccessToken>
+impl ConnectorIntegration<AccessTokenAuth, AccessTokenRequestData, AccessToken>
for {{project-name | downcase | pascal_case}}
{
}
impl
ConnectorIntegration<
- api::SetupMandate,
- types::SetupMandateRequestData,
- types::PaymentsResponseData,
+ SetupMandate,
+ SetupMandateRequestData,
+ PaymentsResponseData,
> for {{project-name | downcase | pascal_case}}
{
}
impl
ConnectorIntegration<
- api::Authorize,
- types::PaymentsAuthorizeData,
- types::PaymentsResponseData,
+ Authorize,
+ PaymentsAuthorizeData,
+ PaymentsResponseData,
> for {{project-name | downcase | pascal_case}} {
- fn get_headers(&self, req: &types::PaymentsAuthorizeRouterData, connectors: &settings::Connectors,) -> CustomResult<Vec<(String, request::Maskable<String>)>,errors::ConnectorError> {
+ fn get_headers(&self, req: &PaymentsAuthorizeRouterData, connectors: &Connectors,) -> CustomResult<Vec<(String, masking::Maskable<String>)>,errors::ConnectorError> {
self.build_headers(req, connectors)
}
@@ -172,12 +194,12 @@ impl
self.common_get_content_type()
}
- fn get_url(&self, _req: &types::PaymentsAuthorizeRouterData, _connectors: &settings::Connectors,) -> CustomResult<String,errors::ConnectorError> {
+ fn get_url(&self, _req: &PaymentsAuthorizeRouterData, _connectors: &Connectors,) -> CustomResult<String,errors::ConnectorError> {
Err(errors::ConnectorError::NotImplemented("get_url method".to_string()).into())
}
- fn get_request_body(&self, req: &types::PaymentsAuthorizeRouterData, _connectors: &settings::Connectors,) -> CustomResult<RequestContent, errors::ConnectorError> {
- let amount = connector_utils::convert_amount(
+ fn get_request_body(&self, req: &PaymentsAuthorizeRouterData, _connectors: &Connectors,) -> CustomResult<RequestContent, errors::ConnectorError> {
+ let amount = utils::convert_amount(
self.amount_converter,
req.request.minor_amount,
req.request.currency,
@@ -194,12 +216,12 @@ impl
fn build_request(
&self,
- req: &types::PaymentsAuthorizeRouterData,
- connectors: &settings::Connectors,
- ) -> CustomResult<Option<services::Request>, errors::ConnectorError> {
+ req: &PaymentsAuthorizeRouterData,
+ connectors: &Connectors,
+ ) -> CustomResult<Option<Request>, errors::ConnectorError> {
Ok(Some(
- services::RequestBuilder::new()
- .method(services::Method::Post)
+ RequestBuilder::new()
+ .method(Method::Post)
.url(&types::PaymentsAuthorizeType::get_url(
self, req, connectors,
)?)
@@ -214,14 +236,14 @@ impl
fn handle_response(
&self,
- data: &types::PaymentsAuthorizeRouterData,
+ data: &PaymentsAuthorizeRouterData,
event_builder: Option<&mut ConnectorEvent>,
res: Response,
- ) -> CustomResult<types::PaymentsAuthorizeRouterData,errors::ConnectorError> {
+ ) -> CustomResult<PaymentsAuthorizeRouterData,errors::ConnectorError> {
let response: {{project-name | downcase}}::{{project-name | downcase | pascal_case}}PaymentsResponse = res.response.parse_struct("{{project-name | downcase | pascal_case}} PaymentsAuthorizeResponse").change_context(errors::ConnectorError::ResponseDeserializationFailed)?;
event_builder.map(|i| i.set_response_body(&response));
router_env::logger::info!(connector_response=?response);
- types::RouterData::try_from(types::ResponseRouterData {
+ RouterData::try_from(ResponseRouterData {
response,
data: data.clone(),
http_code: res.status_code,
@@ -234,14 +256,14 @@ impl
}
impl
- ConnectorIntegration<api::PSync, types::PaymentsSyncData, types::PaymentsResponseData>
+ ConnectorIntegration<PSync, PaymentsSyncData, PaymentsResponseData>
for {{project-name | downcase | pascal_case}}
{
fn get_headers(
&self,
- req: &types::PaymentsSyncRouterData,
- connectors: &settings::Connectors,
- ) -> CustomResult<Vec<(String, request::Maskable<String>)>, errors::ConnectorError> {
+ req: &PaymentsSyncRouterData,
+ connectors: &Connectors,
+ ) -> CustomResult<Vec<(String, masking::Maskable<String>)>, errors::ConnectorError> {
self.build_headers(req, connectors)
}
@@ -251,20 +273,20 @@ impl
fn get_url(
&self,
- _req: &types::PaymentsSyncRouterData,
- _connectors: &settings::Connectors,
+ _req: &PaymentsSyncRouterData,
+ _connectors: &Connectors,
) -> CustomResult<String, errors::ConnectorError> {
Err(errors::ConnectorError::NotImplemented("get_url method".to_string()).into())
}
fn build_request(
&self,
- req: &types::PaymentsSyncRouterData,
- connectors: &settings::Connectors,
- ) -> CustomResult<Option<services::Request>, errors::ConnectorError> {
+ req: &PaymentsSyncRouterData,
+ connectors: &Connectors,
+ ) -> CustomResult<Option<Request>, errors::ConnectorError> {
Ok(Some(
- services::RequestBuilder::new()
- .method(services::Method::Get)
+ RequestBuilder::new()
+ .method(Method::Get)
.url(&types::PaymentsSyncType::get_url(self, req, connectors)?)
.attach_default_headers()
.headers(types::PaymentsSyncType::get_headers(self, req, connectors)?)
@@ -274,17 +296,17 @@ impl
fn handle_response(
&self,
- data: &types::PaymentsSyncRouterData,
+ data: &PaymentsSyncRouterData,
event_builder: Option<&mut ConnectorEvent>,
res: Response,
- ) -> CustomResult<types::PaymentsSyncRouterData, errors::ConnectorError> {
+ ) -> CustomResult<PaymentsSyncRouterData, errors::ConnectorError> {
let response: {{project-name | downcase}}:: {{project-name | downcase | pascal_case}}PaymentsResponse = res
.response
.parse_struct("{{project-name | downcase}} PaymentsSyncResponse")
.change_context(errors::ConnectorError::ResponseDeserializationFailed)?;
event_builder.map(|i| i.set_response_body(&response));
router_env::logger::info!(connector_response=?response);
- types::RouterData::try_from(types::ResponseRouterData {
+ RouterData::try_from(ResponseRouterData {
response,
data: data.clone(),
http_code: res.status_code,
@@ -302,16 +324,16 @@ impl
impl
ConnectorIntegration<
- api::Capture,
- types::PaymentsCaptureData,
- types::PaymentsResponseData,
+ Capture,
+ PaymentsCaptureData,
+ PaymentsResponseData,
> for {{project-name | downcase | pascal_case}}
{
fn get_headers(
&self,
- req: &types::PaymentsCaptureRouterData,
- connectors: &settings::Connectors,
- ) -> CustomResult<Vec<(String, request::Maskable<String>)>, errors::ConnectorError> {
+ req: &PaymentsCaptureRouterData,
+ connectors: &Connectors,
+ ) -> CustomResult<Vec<(String, masking::Maskable<String>)>, errors::ConnectorError> {
self.build_headers(req, connectors)
}
@@ -321,28 +343,28 @@ impl
fn get_url(
&self,
- _req: &types::PaymentsCaptureRouterData,
- _connectors: &settings::Connectors,
+ _req: &PaymentsCaptureRouterData,
+ _connectors: &Connectors,
) -> CustomResult<String, errors::ConnectorError> {
Err(errors::ConnectorError::NotImplemented("get_url method".to_string()).into())
}
fn get_request_body(
&self,
- _req: &types::PaymentsCaptureRouterData,
- _connectors: &settings::Connectors,
+ _req: &PaymentsCaptureRouterData,
+ _connectors: &Connectors,
) -> CustomResult<RequestContent, errors::ConnectorError> {
Err(errors::ConnectorError::NotImplemented("get_request_body method".to_string()).into())
}
fn build_request(
&self,
- req: &types::PaymentsCaptureRouterData,
- connectors: &settings::Connectors,
- ) -> CustomResult<Option<services::Request>, errors::ConnectorError> {
+ req: &PaymentsCaptureRouterData,
+ connectors: &Connectors,
+ ) -> CustomResult<Option<Request>, errors::ConnectorError> {
Ok(Some(
- services::RequestBuilder::new()
- .method(services::Method::Post)
+ RequestBuilder::new()
+ .method(Method::Post)
.url(&types::PaymentsCaptureType::get_url(self, req, connectors)?)
.attach_default_headers()
.headers(types::PaymentsCaptureType::get_headers(
@@ -355,17 +377,17 @@ impl
fn handle_response(
&self,
- data: &types::PaymentsCaptureRouterData,
+ data: &PaymentsCaptureRouterData,
event_builder: Option<&mut ConnectorEvent>,
res: Response,
- ) -> CustomResult<types::PaymentsCaptureRouterData, errors::ConnectorError> {
+ ) -> CustomResult<PaymentsCaptureRouterData, errors::ConnectorError> {
let response: {{project-name | downcase }}::{{project-name | downcase | pascal_case}}PaymentsResponse = res
.response
.parse_struct("{{project-name | downcase | pascal_case}} PaymentsCaptureResponse")
.change_context(errors::ConnectorError::ResponseDeserializationFailed)?;
event_builder.map(|i| i.set_response_body(&response));
router_env::logger::info!(connector_response=?response);
- types::RouterData::try_from(types::ResponseRouterData {
+ RouterData::try_from(ResponseRouterData {
response,
data: data.clone(),
http_code: res.status_code,
@@ -383,19 +405,19 @@ impl
impl
ConnectorIntegration<
- api::Void,
- types::PaymentsCancelData,
- types::PaymentsResponseData,
+ Void,
+ PaymentsCancelData,
+ PaymentsResponseData,
> for {{project-name | downcase | pascal_case}}
{}
impl
ConnectorIntegration<
- api::Execute,
- types::RefundsData,
- types::RefundsResponseData,
+ Execute,
+ RefundsData,
+ RefundsResponseData,
> for {{project-name | downcase | pascal_case}} {
- fn get_headers(&self, req: &types::RefundsRouterData<api::Execute>, connectors: &settings::Connectors,) -> CustomResult<Vec<(String,request::Maskable<String>)>,errors::ConnectorError> {
+ fn get_headers(&self, req: &RefundsRouterData<Execute>, connectors: &Connectors,) -> CustomResult<Vec<(String,masking::Maskable<String>)>,errors::ConnectorError> {
self.build_headers(req, connectors)
}
@@ -403,12 +425,12 @@ impl
self.common_get_content_type()
}
- fn get_url(&self, _req: &types::RefundsRouterData<api::Execute>, _connectors: &settings::Connectors,) -> CustomResult<String,errors::ConnectorError> {
+ fn get_url(&self, _req: &RefundsRouterData<Execute>, _connectors: &Connectors,) -> CustomResult<String,errors::ConnectorError> {
Err(errors::ConnectorError::NotImplemented("get_url method".to_string()).into())
}
- fn get_request_body(&self, req: &types::RefundsRouterData<api::Execute>, _connectors: &settings::Connectors,) -> CustomResult<RequestContent, errors::ConnectorError> {
- let refund_amount = connector_utils::convert_amount(
+ fn get_request_body(&self, req: &RefundsRouterData<Execute>, _connectors: &Connectors,) -> CustomResult<RequestContent, errors::ConnectorError> {
+ let refund_amount = utils::convert_amount(
self.amount_converter,
req.request.minor_refund_amount,
req.request.currency,
@@ -423,9 +445,9 @@ impl
Ok(RequestContent::Json(Box::new(connector_req)))
}
- fn build_request(&self, req: &types::RefundsRouterData<api::Execute>, connectors: &settings::Connectors,) -> CustomResult<Option<services::Request>,errors::ConnectorError> {
- let request = services::RequestBuilder::new()
- .method(services::Method::Post)
+ fn build_request(&self, req: &RefundsRouterData<Execute>, connectors: &Connectors,) -> CustomResult<Option<Request>,errors::ConnectorError> {
+ let request = RequestBuilder::new()
+ .method(Method::Post)
.url(&types::RefundExecuteType::get_url(self, req, connectors)?)
.attach_default_headers()
.headers(types::RefundExecuteType::get_headers(self, req, connectors)?)
@@ -436,14 +458,14 @@ impl
fn handle_response(
&self,
- data: &types::RefundsRouterData<api::Execute>,
+ data: &RefundsRouterData<Execute>,
event_builder: Option<&mut ConnectorEvent>,
res: Response,
- ) -> CustomResult<types::RefundsRouterData<api::Execute>,errors::ConnectorError> {
+ ) -> CustomResult<RefundsRouterData<Execute>,errors::ConnectorError> {
let response: {{project-name| downcase}}::RefundResponse = res.response.parse_struct("{{project-name | downcase}} RefundResponse").change_context(errors::ConnectorError::ResponseDeserializationFailed)?;
event_builder.map(|i| i.set_response_body(&response));
router_env::logger::info!(connector_response=?response);
- types::RouterData::try_from(types::ResponseRouterData {
+ RouterData::try_from(ResponseRouterData {
response,
data: data.clone(),
http_code: res.status_code,
@@ -456,8 +478,8 @@ impl
}
impl
- ConnectorIntegration<api::RSync, types::RefundsData, types::RefundsResponseData> for {{project-name | downcase | pascal_case}} {
- fn get_headers(&self, req: &types::RefundSyncRouterData,connectors: &settings::Connectors,) -> CustomResult<Vec<(String, request::Maskable<String>)>,errors::ConnectorError> {
+ ConnectorIntegration<RSync, RefundsData, RefundsResponseData> for {{project-name | downcase | pascal_case}} {
+ fn get_headers(&self, req: &RefundSyncRouterData,connectors: &Connectors,) -> CustomResult<Vec<(String, masking::Maskable<String>)>,errors::ConnectorError> {
self.build_headers(req, connectors)
}
@@ -465,18 +487,18 @@ impl
self.common_get_content_type()
}
- fn get_url(&self, _req: &types::RefundSyncRouterData,_connectors: &settings::Connectors,) -> CustomResult<String,errors::ConnectorError> {
+ fn get_url(&self, _req: &RefundSyncRouterData,_connectors: &Connectors,) -> CustomResult<String,errors::ConnectorError> {
Err(errors::ConnectorError::NotImplemented("get_url method".to_string()).into())
}
fn build_request(
&self,
- req: &types::RefundSyncRouterData,
- connectors: &settings::Connectors,
- ) -> CustomResult<Option<services::Request>, errors::ConnectorError> {
+ req: &RefundSyncRouterData,
+ connectors: &Connectors,
+ ) -> CustomResult<Option<Request>, errors::ConnectorError> {
Ok(Some(
- services::RequestBuilder::new()
- .method(services::Method::Get)
+ RequestBuilder::new()
+ .method(Method::Get)
.url(&types::RefundSyncType::get_url(self, req, connectors)?)
.attach_default_headers()
.headers(types::RefundSyncType::get_headers(self, req, connectors)?)
@@ -487,14 +509,14 @@ impl
fn handle_response(
&self,
- data: &types::RefundSyncRouterData,
+ data: &RefundSyncRouterData,
event_builder: Option<&mut ConnectorEvent>,
res: Response,
- ) -> CustomResult<types::RefundSyncRouterData,errors::ConnectorError,> {
+ ) -> CustomResult<RefundSyncRouterData,errors::ConnectorError,> {
let response: {{project-name | downcase}}::RefundResponse = res.response.parse_struct("{{project-name | downcase}} RefundSyncResponse").change_context(errors::ConnectorError::ResponseDeserializationFailed)?;
event_builder.map(|i| i.set_response_body(&response));
router_env::logger::info!(connector_response=?response);
- types::RouterData::try_from(types::ResponseRouterData {
+ RouterData::try_from(ResponseRouterData {
response,
data: data.clone(),
http_code: res.status_code,
@@ -507,24 +529,24 @@ impl
}
#[async_trait::async_trait]
-impl api::IncomingWebhook for {{project-name | downcase | pascal_case}} {
+impl webhooks::IncomingWebhook for {{project-name | downcase | pascal_case}} {
fn get_webhook_object_reference_id(
&self,
- _request: &api::IncomingWebhookRequestDetails<'_>,
- ) -> CustomResult<api::webhooks::ObjectReferenceId, errors::ConnectorError> {
+ _request: &webhooks::IncomingWebhookRequestDetails<'_>,
+ ) -> CustomResult<api_models::webhooks::ObjectReferenceId, errors::ConnectorError> {
Err(report!(errors::ConnectorError::WebhooksNotImplemented))
}
fn get_webhook_event_type(
&self,
- _request: &api::IncomingWebhookRequestDetails<'_>,
- ) -> CustomResult<api::IncomingWebhookEvent, errors::ConnectorError> {
+ _request: &webhooks::IncomingWebhookRequestDetails<'_>,
+ ) -> CustomResult<api_models::webhooks::IncomingWebhookEvent, errors::ConnectorError> {
Err(report!(errors::ConnectorError::WebhooksNotImplemented))
}
fn get_webhook_resource_object(
&self,
- _request: &api::IncomingWebhookRequestDetails<'_>,
+ _request: &webhooks::IncomingWebhookRequestDetails<'_>,
) -> CustomResult<Box<dyn masking::ErasedMaskSerialize>, errors::ConnectorError> {
Err(report!(errors::ConnectorError::WebhooksNotImplemented))
}
diff --git a/connector-template/transformers.rs b/connector-template/transformers.rs
index 9ba5dd7e354..7c81a750465 100644
--- a/connector-template/transformers.rs
+++ b/connector-template/transformers.rs
@@ -1,7 +1,20 @@
+use common_enums::enums;
use serde::{Deserialize, Serialize};
use masking::Secret;
use common_utils::types::{StringMinorUnit};
-use crate::{connector::utils::{PaymentsAuthorizeRequestData},core::errors,types::{self, domain, api, storage::enums}};
+use hyperswitch_domain_models::{
+ payment_method_data::PaymentMethodData,
+ router_data::{ConnectorAuthType, RouterData},
+ router_flow_types::refunds::{Execute, RSync},
+ router_request_types::ResponseId,
+ router_response_types::{PaymentsResponseData, RefundsResponseData},
+ types::{PaymentsAuthorizeRouterData, RefundsRouterData},
+};
+use hyperswitch_interfaces::errors;
+use crate::{
+ types::{RefundsResponseRouterData, ResponseRouterData},
+ utils::PaymentsAuthorizeRequestData,
+};
//TODO: Fill the struct with respective fields
pub struct {{project-name | downcase | pascal_case}}RouterData<T> {
@@ -45,11 +58,11 @@ pub struct {{project-name | downcase | pascal_case}}Card {
complete: bool,
}
-impl TryFrom<&{{project-name | downcase | pascal_case}}RouterData<&types::PaymentsAuthorizeRouterData>> for {{project-name | downcase | pascal_case}}PaymentsRequest {
+impl TryFrom<&{{project-name | downcase | pascal_case}}RouterData<&PaymentsAuthorizeRouterData>> for {{project-name | downcase | pascal_case}}PaymentsRequest {
type Error = error_stack::Report<errors::ConnectorError>;
- fn try_from(item: &{{project-name | downcase | pascal_case}}RouterData<&types::PaymentsAuthorizeRouterData>) -> Result<Self,Self::Error> {
+ fn try_from(item: &{{project-name | downcase | pascal_case}}RouterData<&PaymentsAuthorizeRouterData>) -> Result<Self,Self::Error> {
match item.router_data.request.payment_method_data.clone() {
- domain::PaymentMethodData::Card(req_card) => {
+ PaymentMethodData::Card(req_card) => {
let card = {{project-name | downcase | pascal_case}}Card {
number: req_card.card_number,
expiry_month: req_card.card_exp_month,
@@ -73,11 +86,11 @@ pub struct {{project-name | downcase | pascal_case}}AuthType {
pub(super) api_key: Secret<String>
}
-impl TryFrom<&types::ConnectorAuthType> for {{project-name | downcase | pascal_case}}AuthType {
+impl TryFrom<&ConnectorAuthType> for {{project-name | downcase | pascal_case}}AuthType {
type Error = error_stack::Report<errors::ConnectorError>;
- fn try_from(auth_type: &types::ConnectorAuthType) -> Result<Self, Self::Error> {
+ fn try_from(auth_type: &ConnectorAuthType) -> Result<Self, Self::Error> {
match auth_type {
- types::ConnectorAuthType::HeaderKey { api_key } => Ok(Self {
+ ConnectorAuthType::HeaderKey { api_key } => Ok(Self {
api_key: api_key.to_owned(),
}),
_ => Err(errors::ConnectorError::FailedToObtainAuthType.into()),
@@ -95,7 +108,7 @@ pub enum {{project-name | downcase | pascal_case}}PaymentStatus {
Processing,
}
-impl From<{{project-name | downcase | pascal_case}}PaymentStatus> for enums::AttemptStatus {
+impl From<{{project-name | downcase | pascal_case}}PaymentStatus> for common_enums::AttemptStatus {
fn from(item: {{project-name | downcase | pascal_case}}PaymentStatus) -> Self {
match item {
{{project-name | downcase | pascal_case}}PaymentStatus::Succeeded => Self::Charged,
@@ -112,13 +125,13 @@ pub struct {{project-name | downcase | pascal_case}}PaymentsResponse {
id: String,
}
-impl<F,T> TryFrom<types::ResponseRouterData<F, {{project-name | downcase | pascal_case}}PaymentsResponse, T, types::PaymentsResponseData>> for types::RouterData<F, T, types::PaymentsResponseData> {
+impl<F,T> TryFrom<ResponseRouterData<F, {{project-name | downcase | pascal_case}}PaymentsResponse, T, PaymentsResponseData>> for RouterData<F, T, PaymentsResponseData> {
type Error = error_stack::Report<errors::ConnectorError>;
- fn try_from(item: types::ResponseRouterData<F, {{project-name | downcase | pascal_case}}PaymentsResponse, T, types::PaymentsResponseData>) -> Result<Self,Self::Error> {
+ fn try_from(item: ResponseRouterData<F, {{project-name | downcase | pascal_case}}PaymentsResponse, T, PaymentsResponseData>) -> Result<Self,Self::Error> {
Ok(Self {
- status: enums::AttemptStatus::from(item.response.status),
- response: Ok(types::PaymentsResponseData::TransactionResponse {
- resource_id: types::ResponseId::ConnectorTransactionId(item.response.id),
+ status: common_enums::AttemptStatus::from(item.response.status),
+ response: Ok(PaymentsResponseData::TransactionResponse {
+ resource_id: ResponseId::ConnectorTransactionId(item.response.id),
redirection_data: None,
mandate_reference: None,
connector_metadata: None,
@@ -140,9 +153,9 @@ pub struct {{project-name | downcase | pascal_case}}RefundRequest {
pub amount: StringMinorUnit
}
-impl<F> TryFrom<&{{project-name | downcase | pascal_case}}RouterData<&types::RefundsRouterData<F>>> for {{project-name | downcase | pascal_case}}RefundRequest {
+impl<F> TryFrom<&{{project-name | downcase | pascal_case}}RouterData<&RefundsRouterData<F>>> for {{project-name | downcase | pascal_case}}RefundRequest {
type Error = error_stack::Report<errors::ConnectorError>;
- fn try_from(item: &{{project-name | downcase | pascal_case}}RouterData<&types::RefundsRouterData<F>>) -> Result<Self,Self::Error> {
+ fn try_from(item: &{{project-name | downcase | pascal_case}}RouterData<&RefundsRouterData<F>>) -> Result<Self,Self::Error> {
Ok(Self {
amount: item.amount.to_owned(),
})
@@ -178,15 +191,15 @@ pub struct RefundResponse {
status: RefundStatus
}
-impl TryFrom<types::RefundsResponseRouterData<api::Execute, RefundResponse>>
- for types::RefundsRouterData<api::Execute>
+impl TryFrom<RefundsResponseRouterData<Execute, RefundResponse>>
+ for RefundsRouterData<Execute>
{
type Error = error_stack::Report<errors::ConnectorError>;
fn try_from(
- item: types::RefundsResponseRouterData<api::Execute, RefundResponse>,
+ item: RefundsResponseRouterData<Execute, RefundResponse>,
) -> Result<Self, Self::Error> {
Ok(Self {
- response: Ok(types::RefundsResponseData {
+ response: Ok(RefundsResponseData {
connector_refund_id: item.response.id.to_string(),
refund_status: enums::RefundStatus::from(item.response.status),
}),
@@ -195,12 +208,12 @@ impl TryFrom<types::RefundsResponseRouterData<api::Execute, RefundResponse>>
}
}
-impl TryFrom<types::RefundsResponseRouterData<api::RSync, RefundResponse>> for types::RefundsRouterData<api::RSync>
+impl TryFrom<RefundsResponseRouterData<RSync, RefundResponse>> for RefundsRouterData<RSync>
{
type Error = error_stack::Report<errors::ConnectorError>;
- fn try_from(item: types::RefundsResponseRouterData<api::RSync, RefundResponse>) -> Result<Self,Self::Error> {
+ fn try_from(item: RefundsResponseRouterData<RSync, RefundResponse>) -> Result<Self,Self::Error> {
Ok(Self {
- response: Ok(types::RefundsResponseData {
+ response: Ok(RefundsResponseData {
connector_refund_id: item.response.id.to_string(),
refund_status: enums::RefundStatus::from(item.response.status),
}),
diff --git a/scripts/add_connector.sh b/scripts/add_connector.sh
index b29972b9e3b..21740df39fa 100755
--- a/scripts/add_connector.sh
+++ b/scripts/add_connector.sh
@@ -29,7 +29,7 @@ payment_gateway=$(echo $1 | tr '[:upper:]' '[:lower:]')
base_url=$2;
payment_gateway_camelcase="$(tr '[:lower:]' '[:upper:]' <<< ${payment_gateway:0:1})${payment_gateway:1}"
src="crates/router/src"
-conn="$src/connector"
+conn="crates/hyperswitch_connectors/src/connectors"
tests="../../tests/connectors"
test_utils="../../../test_utils/src"
SCRIPT="$( cd -- "$(dirname "$0")" >/dev/null 2>&1 ; pwd -P )"
@@ -52,10 +52,11 @@ previous_connector=''
find_prev_connector $payment_gateway previous_connector
previous_connector_camelcase="$(tr '[:lower:]' '[:upper:]' <<< ${previous_connector:0:1})${previous_connector:1}"
sed -i'' -e "s|pub mod $previous_connector;|pub mod $previous_connector;\npub mod ${payment_gateway};|" $conn.rs
-sed -i'' -e "s/};/${payment_gateway}::${payment_gateway_camelcase},\n};/" $conn.rs
-sed -i'' -e "s|$previous_connector_camelcase \(.*\)|$previous_connector_camelcase \1\n\t\t\tenums::Connector::${payment_gateway_camelcase} => Ok(Box::new(\connector::${payment_gateway_camelcase}::new())),|" $src/types/api.rs
+sed -i'' -e "s/};/, ${payment_gateway}::${payment_gateway_camelcase},\n};/" $conn.rs
+sed -i'' -e "0,/};/s/};/, ${payment_gateway}, ${payment_gateway}::${payment_gateway_camelcase},\n};/" $src/connector.rs
+sed -i'' -e "s|$previous_connector_camelcase \(.*\)|$previous_connector_camelcase \1\n\t\t\tenums::Connector::${payment_gateway_camelcase} => Ok(ConnectorEnum::Old(\Box::new(\connector::${payment_gateway_camelcase}))),|" $src/types/api.rs
sed -i'' -e "s|$previous_connector_camelcase \(.*\)|$previous_connector_camelcase \1\n\t\t\tRoutableConnectors::${payment_gateway_camelcase} => euclid_enums::Connector::${payment_gateway_camelcase},|" crates/api_models/src/routing.rs
-sed -i'' -e "s/pub $previous_connector: \(.*\)/pub $previous_connector: \1\n\tpub ${payment_gateway}: ConnectorParams,/" $src/configs/settings.rs
+sed -i'' -e "s/pub $previous_connector: \(.*\)/pub $previous_connector: \1\n\tpub ${payment_gateway}: ConnectorParams,/" crates/hyperswitch_interfaces/src/configs.rs
sed -i'' -e "s|$previous_connector.base_url \(.*\)|$previous_connector.base_url \1\n${payment_gateway}.base_url = \"$base_url\"|" config/development.toml config/docker_compose.toml config/config.example.toml loadtest/config/development.toml
sed -r -i'' -e "s/\"$previous_connector\",/\"$previous_connector\",\n \"${payment_gateway}\",/" config/development.toml config/docker_compose.toml config/config.example.toml loadtest/config/development.toml
sed -i '' -e "s/\(pub enum Connector {\)/\1\n\t${payment_gateway_camelcase},/" crates/api_models/src/enums.rs
@@ -64,7 +65,8 @@ sed -i '' -e "s/\(match connector_name {\)/\1\n\t\tapi_enums::Connector::${payme
sed -i'' -e "s/\(pub enum RoutableConnectors {\)/\1\n\t${payment_gateway_camelcase},/" crates/common_enums/src/enums.rs
sed -i '' -e "s/\(pub enum Connector {\)/\1\n\t${payment_gateway_camelcase},/" crates/euclid/src/enums.rs
sed -i'' -e "s|$previous_connector_camelcase \(.*\)|$previous_connector_camelcase \1\n\t\t\tapi_enums::Connector::${payment_gateway_camelcase} => Self::${payment_gateway_camelcase},|" $src/types/transformers.rs
-sed -i'' -e "s/^default_imp_for_\(.*\)/default_imp_for_\1\n\tconnector::${payment_gateway_camelcase},/" $src/core/payments/flows.rs
+sed -i'' -e "s/^default_imp_for_\(.*\)/default_imp_for_\1\n\tconnectors::${payment_gateway_camelcase},/" crates/hyperswitch_connectors/src/default_implementations.rs
+sed -i'' -e "s/^default_imp_for_\(.*\)/default_imp_for_\1\n\tconnectors::${payment_gateway_camelcase},/" crates/hyperswitch_connectors/src/default_implementations_v2.rs
# Remove temporary files created in above step
rm $conn.rs-e $src/types/api.rs-e $src/configs/settings.rs-e config/development.toml-e config/docker_compose.toml-e config/config.example.toml-e loadtest/config/development.toml-e crates/api_models/src/enums.rs-e crates/euclid/src/enums.rs-e crates/api_models/src/routing.rs-e $src/core/payments/flows.rs-e crates/common_enums/src/enums.rs-e $src/types/transformers.rs-e $src/core/admin.rs-e
|
2024-08-08T09:13:09Z
|
## Type of Change
<!-- Put an `x` in the boxes that apply -->
- [ ] Bugfix
- [ ] New feature
- [ ] Enhancement
- [x] Refactoring
- [ ] Dependency updates
- [ ] Documentation
- [ ] CI/CD
## Description
<!-- Describe your changes in detail -->
Connector template code ise refactored so that the new connectors are added directly into the crate `hyperswitch_connectors`
### Additional Changes
- [ ] This PR modifies the API contract
- [ ] This PR modifies the database schema
- [ ] This PR modifies application configuration/environment variables
<!--
Provide links to the files with corresponding changes.
Following are the paths where you can find config files:
1. `config`
2. `crates/router/src/configs`
3. `loadtest/config`
-->
## Motivation and Context
<!--
Why is this change required? What problem does it solve?
If it fixes an open issue, please link to the issue here.
If you don't have an issue, we'd recommend starting with one first so the PR
can focus on the implementation (unless it is an obvious bug or documentation fix
that will have little conversation).
-->
https://github.com/juspay/hyperswitch/issues/5569
## How did you test it?
<!--
Did you write an integration/unit/API test to verify the code changes?
Or did you test this change manually (provide relevant screenshots)?
-->
Only connector template generation script modified, hence no testing required.
The template generation has been tested on local.
## Checklist
<!-- Put an `x` in the boxes that apply -->
- [x] I formatted the code `cargo +nightly fmt --all`
- [x] I addressed lints thrown by `cargo clippy`
- [x] I reviewed the submitted code
- [ ] I added unit tests for my changes where possible
|
baaa73cff98a2377e854b992d5ec9e84f49a4a92
|
|
juspay/hyperswitch
|
juspay__hyperswitch-5582
|
Bug: [FEATURE] [FISERVEMEA] Add template code
### Feature Description
Template code needs to be added for new connector Fiserv-EMEA
https://docs.fiserv.dev/
### Possible Implementation
Template code needs to be added for new connector Fiserv-EMEA
https://docs.fiserv.dev/
### Have you spent some time checking if this feature request has been raised before?
- [X] I checked and didn't find a similar issue
### Have you read the Contributing Guidelines?
- [X] I have read the [Contributing Guidelines](https://github.com/juspay/hyperswitch/blob/main/docs/CONTRIBUTING.md)
### Are you willing to submit a PR?
Yes, I am willing to submit a PR!
|
diff --git a/config/config.example.toml b/config/config.example.toml
index b9ac37705a3..cd315a542de 100644
--- a/config/config.example.toml
+++ b/config/config.example.toml
@@ -205,6 +205,7 @@ dlocal.base_url = "https://sandbox.dlocal.com/"
dummyconnector.base_url = "http://localhost:8080/dummy-connector"
ebanx.base_url = "https://sandbox.ebanxpay.com/"
fiserv.base_url = "https://cert.api.fiservapps.com/"
+fiservemea.base_url = "https://prod.emea.api.fiservapps.com/sandbox/ipp/payments-gateway/v2"
forte.base_url = "https://sandbox.forte.net/api/v3"
globalpay.base_url = "https://apis.sandbox.globalpay.com/ucp/"
globepay.base_url = "https://pay.globepay.co/"
diff --git a/config/deployments/integration_test.toml b/config/deployments/integration_test.toml
index 32af0a86b12..1e829e81cfe 100644
--- a/config/deployments/integration_test.toml
+++ b/config/deployments/integration_test.toml
@@ -45,6 +45,7 @@ dlocal.base_url = "https://sandbox.dlocal.com/"
dummyconnector.base_url = "http://localhost:8080/dummy-connector"
ebanx.base_url = "https://sandbox.ebanxpay.com/"
fiserv.base_url = "https://cert.api.fiservapps.com/"
+fiservemea.base_url = "https://prod.emea.api.fiservapps.com/sandbox/ipp/payments-gateway/v2"
forte.base_url = "https://sandbox.forte.net/api/v3"
globalpay.base_url = "https://apis.sandbox.globalpay.com/ucp/"
globepay.base_url = "https://pay.globepay.co/"
diff --git a/config/deployments/production.toml b/config/deployments/production.toml
index 48414e7618a..762ecdc96cd 100644
--- a/config/deployments/production.toml
+++ b/config/deployments/production.toml
@@ -49,6 +49,7 @@ dlocal.base_url = "https://sandbox.dlocal.com/"
dummyconnector.base_url = "http://localhost:8080/dummy-connector"
ebanx.base_url = "https://sandbox.ebanxpay.com/"
fiserv.base_url = "https://cert.api.fiservapps.com/"
+fiservemea.base_url = "https://prod.emea.api.fiservapps.com/ipp/payments-gateway/v2"
forte.base_url = "https://sandbox.forte.net/api/v3"
globalpay.base_url = "https://apis.sandbox.globalpay.com/ucp/"
globepay.base_url = "https://pay.globepay.co/"
diff --git a/config/deployments/sandbox.toml b/config/deployments/sandbox.toml
index 9450548bcfa..8b1335b0c55 100644
--- a/config/deployments/sandbox.toml
+++ b/config/deployments/sandbox.toml
@@ -49,6 +49,7 @@ dlocal.base_url = "https://sandbox.dlocal.com/"
dummyconnector.base_url = "http://localhost:8080/dummy-connector"
ebanx.base_url = "https://sandbox.ebanxpay.com/"
fiserv.base_url = "https://cert.api.fiservapps.com/"
+fiservemea.base_url = "https://prod.emea.api.fiservapps.com/sandbox/ipp/payments-gateway/v2"
forte.base_url = "https://sandbox.forte.net/api/v3"
globalpay.base_url = "https://apis.sandbox.globalpay.com/ucp/"
globepay.base_url = "https://pay.globepay.co/"
diff --git a/config/development.toml b/config/development.toml
index 45c5b1a2a25..dcb627d7e91 100644
--- a/config/development.toml
+++ b/config/development.toml
@@ -118,6 +118,7 @@ cards = [
"dummyconnector",
"ebanx",
"fiserv",
+ "fiservemea",
"forte",
"globalpay",
"globepay",
@@ -207,6 +208,7 @@ dlocal.base_url = "https://sandbox.dlocal.com/"
dummyconnector.base_url = "http://localhost:8080/dummy-connector"
ebanx.base_url = "https://sandbox.ebanxpay.com/"
fiserv.base_url = "https://cert.api.fiservapps.com/"
+fiservemea.base_url = "https://prod.emea.api.fiservapps.com/sandbox/ipp/payments-gateway/v2"
forte.base_url = "https://sandbox.forte.net/api/v3"
globalpay.base_url = "https://apis.sandbox.globalpay.com/ucp/"
globepay.base_url = "https://pay.globepay.co/"
diff --git a/config/docker_compose.toml b/config/docker_compose.toml
index fb8de667290..8ba38fcf8e0 100644
--- a/config/docker_compose.toml
+++ b/config/docker_compose.toml
@@ -134,6 +134,7 @@ dlocal.base_url = "https://sandbox.dlocal.com/"
dummyconnector.base_url = "http://localhost:8080/dummy-connector"
ebanx.base_url = "https://sandbox.ebanxpay.com/"
fiserv.base_url = "https://cert.api.fiservapps.com/"
+fiservemea.base_url = "https://prod.emea.api.fiservapps.com/sandbox/ipp/payments-gateway/v2"
forte.base_url = "https://sandbox.forte.net/api/v3"
globalpay.base_url = "https://apis.sandbox.globalpay.com/ucp/"
globepay.base_url = "https://pay.globepay.co/"
@@ -219,6 +220,7 @@ cards = [
"dummyconnector",
"ebanx",
"fiserv",
+ "fiservemea",
"forte",
"globalpay",
"globepay",
diff --git a/crates/api_models/src/enums.rs b/crates/api_models/src/enums.rs
index cf5585b4dc2..0b2d88ee296 100644
--- a/crates/api_models/src/enums.rs
+++ b/crates/api_models/src/enums.rs
@@ -46,6 +46,7 @@ pub enum RoutingAlgorithm {
#[serde(rename_all = "snake_case")]
#[strum(serialize_all = "snake_case")]
pub enum Connector {
+ // Fiservemea,
Adyenplatform,
#[cfg(feature = "dummy_connector")]
#[serde(rename = "phonypay")]
@@ -207,6 +208,7 @@ impl Connector {
| Self::DummyConnector7 => false,
Self::Aci
// Add Separate authentication support for connectors
+ // | Self::Fiservemea
| Self::Adyen
| Self::Adyenplatform
| Self::Airwallex
diff --git a/crates/common_enums/src/enums.rs b/crates/common_enums/src/enums.rs
index a76a0203c1e..2fd8b8447f3 100644
--- a/crates/common_enums/src/enums.rs
+++ b/crates/common_enums/src/enums.rs
@@ -210,6 +210,7 @@ pub enum RoutableConnectors {
Dlocal,
Ebanx,
Fiserv,
+ // Fiservemea,
Forte,
Globalpay,
Globepay,
diff --git a/crates/hyperswitch_connectors/src/connectors.rs b/crates/hyperswitch_connectors/src/connectors.rs
index 473ba5f6c85..5f94c780b94 100644
--- a/crates/hyperswitch_connectors/src/connectors.rs
+++ b/crates/hyperswitch_connectors/src/connectors.rs
@@ -1,7 +1,11 @@
pub mod bambora;
pub mod bitpay;
pub mod fiserv;
+pub mod fiservemea;
pub mod helcim;
pub mod stax;
-pub use self::{bambora::Bambora, bitpay::Bitpay, fiserv::Fiserv, helcim::Helcim, stax::Stax};
+pub use self::{
+ bambora::Bambora, bitpay::Bitpay, fiserv::Fiserv, fiservemea::Fiservemea, helcim::Helcim,
+ stax::Stax,
+};
diff --git a/crates/hyperswitch_connectors/src/connectors/fiservemea.rs b/crates/hyperswitch_connectors/src/connectors/fiservemea.rs
new file mode 100644
index 00000000000..83674893724
--- /dev/null
+++ b/crates/hyperswitch_connectors/src/connectors/fiservemea.rs
@@ -0,0 +1,567 @@
+pub mod transformers;
+
+use common_utils::{
+ errors::CustomResult,
+ ext_traits::BytesExt,
+ request::{Method, Request, RequestBuilder, RequestContent},
+ types::{AmountConvertor, StringMinorUnit, StringMinorUnitForConnector},
+};
+use error_stack::{report, ResultExt};
+use hyperswitch_domain_models::{
+ router_data::{AccessToken, ConnectorAuthType, ErrorResponse, RouterData},
+ router_flow_types::{
+ access_token_auth::AccessTokenAuth,
+ payments::{Authorize, Capture, PSync, PaymentMethodToken, Session, SetupMandate, Void},
+ refunds::{Execute, RSync},
+ },
+ router_request_types::{
+ AccessTokenRequestData, PaymentMethodTokenizationData, PaymentsAuthorizeData,
+ PaymentsCancelData, PaymentsCaptureData, PaymentsSessionData, PaymentsSyncData,
+ RefundsData, SetupMandateRequestData,
+ },
+ router_response_types::{PaymentsResponseData, RefundsResponseData},
+ types::{
+ PaymentsAuthorizeRouterData, PaymentsCaptureRouterData, PaymentsSyncRouterData,
+ RefundSyncRouterData, RefundsRouterData,
+ },
+};
+use hyperswitch_interfaces::{
+ api::{self, ConnectorCommon, ConnectorCommonExt, ConnectorIntegration, ConnectorValidation},
+ configs::Connectors,
+ errors,
+ events::connector_api_logs::ConnectorEvent,
+ types::{self, Response},
+ webhooks,
+};
+use masking::{ExposeInterface, Mask};
+use transformers as fiservemea;
+
+use crate::{constants::headers, types::ResponseRouterData, utils};
+
+#[derive(Clone)]
+pub struct Fiservemea {
+ amount_converter: &'static (dyn AmountConvertor<Output = StringMinorUnit> + Sync),
+}
+
+impl Fiservemea {
+ pub fn new() -> &'static Self {
+ &Self {
+ amount_converter: &StringMinorUnitForConnector,
+ }
+ }
+}
+
+impl api::Payment for Fiservemea {}
+impl api::PaymentSession for Fiservemea {}
+impl api::ConnectorAccessToken for Fiservemea {}
+impl api::MandateSetup for Fiservemea {}
+impl api::PaymentAuthorize for Fiservemea {}
+impl api::PaymentSync for Fiservemea {}
+impl api::PaymentCapture for Fiservemea {}
+impl api::PaymentVoid for Fiservemea {}
+impl api::Refund for Fiservemea {}
+impl api::RefundExecute for Fiservemea {}
+impl api::RefundSync for Fiservemea {}
+impl api::PaymentToken for Fiservemea {}
+
+impl ConnectorIntegration<PaymentMethodToken, PaymentMethodTokenizationData, PaymentsResponseData>
+ for Fiservemea
+{
+ // Not Implemented (R)
+}
+
+impl<Flow, Request, Response> ConnectorCommonExt<Flow, Request, Response> for Fiservemea
+where
+ Self: ConnectorIntegration<Flow, Request, Response>,
+{
+ fn build_headers(
+ &self,
+ req: &RouterData<Flow, Request, Response>,
+ _connectors: &Connectors,
+ ) -> CustomResult<Vec<(String, masking::Maskable<String>)>, errors::ConnectorError> {
+ let mut header = vec![(
+ headers::CONTENT_TYPE.to_string(),
+ self.get_content_type().to_string().into(),
+ )];
+ let mut api_key = self.get_auth_header(&req.connector_auth_type)?;
+ header.append(&mut api_key);
+ Ok(header)
+ }
+}
+
+impl ConnectorCommon for Fiservemea {
+ fn id(&self) -> &'static str {
+ "fiservemea"
+ }
+
+ fn get_currency_unit(&self) -> api::CurrencyUnit {
+ api::CurrencyUnit::Base
+ // TODO! Check connector documentation, on which unit they are processing the currency.
+ // If the connector accepts amount in lower unit ( i.e cents for USD) then return api::CurrencyUnit::Minor,
+ // if connector accepts amount in base unit (i.e dollars for USD) then return api::CurrencyUnit::Base
+ }
+
+ fn common_get_content_type(&self) -> &'static str {
+ "application/json"
+ }
+
+ fn base_url<'a>(&self, connectors: &'a Connectors) -> &'a str {
+ connectors.fiservemea.base_url.as_ref()
+ }
+
+ fn get_auth_header(
+ &self,
+ auth_type: &ConnectorAuthType,
+ ) -> CustomResult<Vec<(String, masking::Maskable<String>)>, errors::ConnectorError> {
+ let auth = fiservemea::FiservemeaAuthType::try_from(auth_type)
+ .change_context(errors::ConnectorError::FailedToObtainAuthType)?;
+ Ok(vec![(
+ headers::AUTHORIZATION.to_string(),
+ auth.api_key.expose().into_masked(),
+ )])
+ }
+
+ fn build_error_response(
+ &self,
+ res: Response,
+ event_builder: Option<&mut ConnectorEvent>,
+ ) -> CustomResult<ErrorResponse, errors::ConnectorError> {
+ let response: fiservemea::FiservemeaErrorResponse = res
+ .response
+ .parse_struct("FiservemeaErrorResponse")
+ .change_context(errors::ConnectorError::ResponseDeserializationFailed)?;
+
+ event_builder.map(|i| i.set_response_body(&response));
+ router_env::logger::info!(connector_response=?response);
+
+ Ok(ErrorResponse {
+ status_code: res.status_code,
+ code: response.code,
+ message: response.message,
+ reason: response.reason,
+ attempt_status: None,
+ connector_transaction_id: None,
+ })
+ }
+}
+
+impl ConnectorValidation for Fiservemea {
+ //TODO: implement functions when support enabled
+}
+
+impl ConnectorIntegration<Session, PaymentsSessionData, PaymentsResponseData> for Fiservemea {
+ //TODO: implement sessions flow
+}
+
+impl ConnectorIntegration<AccessTokenAuth, AccessTokenRequestData, AccessToken> for Fiservemea {}
+
+impl ConnectorIntegration<SetupMandate, SetupMandateRequestData, PaymentsResponseData>
+ for Fiservemea
+{
+}
+
+impl ConnectorIntegration<Authorize, PaymentsAuthorizeData, PaymentsResponseData> for Fiservemea {
+ fn get_headers(
+ &self,
+ req: &PaymentsAuthorizeRouterData,
+ connectors: &Connectors,
+ ) -> CustomResult<Vec<(String, masking::Maskable<String>)>, errors::ConnectorError> {
+ self.build_headers(req, connectors)
+ }
+
+ fn get_content_type(&self) -> &'static str {
+ self.common_get_content_type()
+ }
+
+ fn get_url(
+ &self,
+ _req: &PaymentsAuthorizeRouterData,
+ _connectors: &Connectors,
+ ) -> CustomResult<String, errors::ConnectorError> {
+ Err(errors::ConnectorError::NotImplemented("get_url method".to_string()).into())
+ }
+
+ fn get_request_body(
+ &self,
+ req: &PaymentsAuthorizeRouterData,
+ _connectors: &Connectors,
+ ) -> CustomResult<RequestContent, errors::ConnectorError> {
+ let amount = utils::convert_amount(
+ self.amount_converter,
+ req.request.minor_amount,
+ req.request.currency,
+ )?;
+
+ let connector_router_data = fiservemea::FiservemeaRouterData::from((amount, req));
+ let connector_req =
+ fiservemea::FiservemeaPaymentsRequest::try_from(&connector_router_data)?;
+ Ok(RequestContent::Json(Box::new(connector_req)))
+ }
+
+ fn build_request(
+ &self,
+ req: &PaymentsAuthorizeRouterData,
+ connectors: &Connectors,
+ ) -> CustomResult<Option<Request>, errors::ConnectorError> {
+ Ok(Some(
+ RequestBuilder::new()
+ .method(Method::Post)
+ .url(&types::PaymentsAuthorizeType::get_url(
+ self, req, connectors,
+ )?)
+ .attach_default_headers()
+ .headers(types::PaymentsAuthorizeType::get_headers(
+ self, req, connectors,
+ )?)
+ .set_body(types::PaymentsAuthorizeType::get_request_body(
+ self, req, connectors,
+ )?)
+ .build(),
+ ))
+ }
+
+ fn handle_response(
+ &self,
+ data: &PaymentsAuthorizeRouterData,
+ event_builder: Option<&mut ConnectorEvent>,
+ res: Response,
+ ) -> CustomResult<PaymentsAuthorizeRouterData, errors::ConnectorError> {
+ let response: fiservemea::FiservemeaPaymentsResponse = res
+ .response
+ .parse_struct("Fiservemea PaymentsAuthorizeResponse")
+ .change_context(errors::ConnectorError::ResponseDeserializationFailed)?;
+ event_builder.map(|i| i.set_response_body(&response));
+ router_env::logger::info!(connector_response=?response);
+ RouterData::try_from(ResponseRouterData {
+ response,
+ data: data.clone(),
+ http_code: res.status_code,
+ })
+ }
+
+ fn get_error_response(
+ &self,
+ res: Response,
+ event_builder: Option<&mut ConnectorEvent>,
+ ) -> CustomResult<ErrorResponse, errors::ConnectorError> {
+ self.build_error_response(res, event_builder)
+ }
+}
+
+impl ConnectorIntegration<PSync, PaymentsSyncData, PaymentsResponseData> for Fiservemea {
+ fn get_headers(
+ &self,
+ req: &PaymentsSyncRouterData,
+ connectors: &Connectors,
+ ) -> CustomResult<Vec<(String, masking::Maskable<String>)>, errors::ConnectorError> {
+ self.build_headers(req, connectors)
+ }
+
+ fn get_content_type(&self) -> &'static str {
+ self.common_get_content_type()
+ }
+
+ fn get_url(
+ &self,
+ _req: &PaymentsSyncRouterData,
+ _connectors: &Connectors,
+ ) -> CustomResult<String, errors::ConnectorError> {
+ Err(errors::ConnectorError::NotImplemented("get_url method".to_string()).into())
+ }
+
+ fn build_request(
+ &self,
+ req: &PaymentsSyncRouterData,
+ connectors: &Connectors,
+ ) -> CustomResult<Option<Request>, errors::ConnectorError> {
+ Ok(Some(
+ RequestBuilder::new()
+ .method(Method::Get)
+ .url(&types::PaymentsSyncType::get_url(self, req, connectors)?)
+ .attach_default_headers()
+ .headers(types::PaymentsSyncType::get_headers(self, req, connectors)?)
+ .build(),
+ ))
+ }
+
+ fn handle_response(
+ &self,
+ data: &PaymentsSyncRouterData,
+ event_builder: Option<&mut ConnectorEvent>,
+ res: Response,
+ ) -> CustomResult<PaymentsSyncRouterData, errors::ConnectorError> {
+ let response: fiservemea::FiservemeaPaymentsResponse = res
+ .response
+ .parse_struct("fiservemea PaymentsSyncResponse")
+ .change_context(errors::ConnectorError::ResponseDeserializationFailed)?;
+ event_builder.map(|i| i.set_response_body(&response));
+ router_env::logger::info!(connector_response=?response);
+ RouterData::try_from(ResponseRouterData {
+ response,
+ data: data.clone(),
+ http_code: res.status_code,
+ })
+ }
+
+ fn get_error_response(
+ &self,
+ res: Response,
+ event_builder: Option<&mut ConnectorEvent>,
+ ) -> CustomResult<ErrorResponse, errors::ConnectorError> {
+ self.build_error_response(res, event_builder)
+ }
+}
+
+impl ConnectorIntegration<Capture, PaymentsCaptureData, PaymentsResponseData> for Fiservemea {
+ fn get_headers(
+ &self,
+ req: &PaymentsCaptureRouterData,
+ connectors: &Connectors,
+ ) -> CustomResult<Vec<(String, masking::Maskable<String>)>, errors::ConnectorError> {
+ self.build_headers(req, connectors)
+ }
+
+ fn get_content_type(&self) -> &'static str {
+ self.common_get_content_type()
+ }
+
+ fn get_url(
+ &self,
+ _req: &PaymentsCaptureRouterData,
+ _connectors: &Connectors,
+ ) -> CustomResult<String, errors::ConnectorError> {
+ Err(errors::ConnectorError::NotImplemented("get_url method".to_string()).into())
+ }
+
+ fn get_request_body(
+ &self,
+ _req: &PaymentsCaptureRouterData,
+ _connectors: &Connectors,
+ ) -> CustomResult<RequestContent, errors::ConnectorError> {
+ Err(errors::ConnectorError::NotImplemented("get_request_body method".to_string()).into())
+ }
+
+ fn build_request(
+ &self,
+ req: &PaymentsCaptureRouterData,
+ connectors: &Connectors,
+ ) -> CustomResult<Option<Request>, errors::ConnectorError> {
+ Ok(Some(
+ RequestBuilder::new()
+ .method(Method::Post)
+ .url(&types::PaymentsCaptureType::get_url(self, req, connectors)?)
+ .attach_default_headers()
+ .headers(types::PaymentsCaptureType::get_headers(
+ self, req, connectors,
+ )?)
+ .set_body(types::PaymentsCaptureType::get_request_body(
+ self, req, connectors,
+ )?)
+ .build(),
+ ))
+ }
+
+ fn handle_response(
+ &self,
+ data: &PaymentsCaptureRouterData,
+ event_builder: Option<&mut ConnectorEvent>,
+ res: Response,
+ ) -> CustomResult<PaymentsCaptureRouterData, errors::ConnectorError> {
+ let response: fiservemea::FiservemeaPaymentsResponse = res
+ .response
+ .parse_struct("Fiservemea PaymentsCaptureResponse")
+ .change_context(errors::ConnectorError::ResponseDeserializationFailed)?;
+ event_builder.map(|i| i.set_response_body(&response));
+ router_env::logger::info!(connector_response=?response);
+ RouterData::try_from(ResponseRouterData {
+ response,
+ data: data.clone(),
+ http_code: res.status_code,
+ })
+ }
+
+ fn get_error_response(
+ &self,
+ res: Response,
+ event_builder: Option<&mut ConnectorEvent>,
+ ) -> CustomResult<ErrorResponse, errors::ConnectorError> {
+ self.build_error_response(res, event_builder)
+ }
+}
+
+impl ConnectorIntegration<Void, PaymentsCancelData, PaymentsResponseData> for Fiservemea {}
+
+impl ConnectorIntegration<Execute, RefundsData, RefundsResponseData> for Fiservemea {
+ fn get_headers(
+ &self,
+ req: &RefundsRouterData<Execute>,
+ connectors: &Connectors,
+ ) -> CustomResult<Vec<(String, masking::Maskable<String>)>, errors::ConnectorError> {
+ self.build_headers(req, connectors)
+ }
+
+ fn get_content_type(&self) -> &'static str {
+ self.common_get_content_type()
+ }
+
+ fn get_url(
+ &self,
+ _req: &RefundsRouterData<Execute>,
+ _connectors: &Connectors,
+ ) -> CustomResult<String, errors::ConnectorError> {
+ Err(errors::ConnectorError::NotImplemented("get_url method".to_string()).into())
+ }
+
+ fn get_request_body(
+ &self,
+ req: &RefundsRouterData<Execute>,
+ _connectors: &Connectors,
+ ) -> CustomResult<RequestContent, errors::ConnectorError> {
+ let refund_amount = utils::convert_amount(
+ self.amount_converter,
+ req.request.minor_refund_amount,
+ req.request.currency,
+ )?;
+
+ let connector_router_data = fiservemea::FiservemeaRouterData::from((refund_amount, req));
+ let connector_req = fiservemea::FiservemeaRefundRequest::try_from(&connector_router_data)?;
+ Ok(RequestContent::Json(Box::new(connector_req)))
+ }
+
+ fn build_request(
+ &self,
+ req: &RefundsRouterData<Execute>,
+ connectors: &Connectors,
+ ) -> CustomResult<Option<Request>, errors::ConnectorError> {
+ let request = RequestBuilder::new()
+ .method(Method::Post)
+ .url(&types::RefundExecuteType::get_url(self, req, connectors)?)
+ .attach_default_headers()
+ .headers(types::RefundExecuteType::get_headers(
+ self, req, connectors,
+ )?)
+ .set_body(types::RefundExecuteType::get_request_body(
+ self, req, connectors,
+ )?)
+ .build();
+ Ok(Some(request))
+ }
+
+ fn handle_response(
+ &self,
+ data: &RefundsRouterData<Execute>,
+ event_builder: Option<&mut ConnectorEvent>,
+ res: Response,
+ ) -> CustomResult<RefundsRouterData<Execute>, errors::ConnectorError> {
+ let response: fiservemea::RefundResponse = res
+ .response
+ .parse_struct("fiservemea RefundResponse")
+ .change_context(errors::ConnectorError::ResponseDeserializationFailed)?;
+ event_builder.map(|i| i.set_response_body(&response));
+ router_env::logger::info!(connector_response=?response);
+ RouterData::try_from(ResponseRouterData {
+ response,
+ data: data.clone(),
+ http_code: res.status_code,
+ })
+ }
+
+ fn get_error_response(
+ &self,
+ res: Response,
+ event_builder: Option<&mut ConnectorEvent>,
+ ) -> CustomResult<ErrorResponse, errors::ConnectorError> {
+ self.build_error_response(res, event_builder)
+ }
+}
+
+impl ConnectorIntegration<RSync, RefundsData, RefundsResponseData> for Fiservemea {
+ fn get_headers(
+ &self,
+ req: &RefundSyncRouterData,
+ connectors: &Connectors,
+ ) -> CustomResult<Vec<(String, masking::Maskable<String>)>, errors::ConnectorError> {
+ self.build_headers(req, connectors)
+ }
+
+ fn get_content_type(&self) -> &'static str {
+ self.common_get_content_type()
+ }
+
+ fn get_url(
+ &self,
+ _req: &RefundSyncRouterData,
+ _connectors: &Connectors,
+ ) -> CustomResult<String, errors::ConnectorError> {
+ Err(errors::ConnectorError::NotImplemented("get_url method".to_string()).into())
+ }
+
+ fn build_request(
+ &self,
+ req: &RefundSyncRouterData,
+ connectors: &Connectors,
+ ) -> CustomResult<Option<Request>, errors::ConnectorError> {
+ Ok(Some(
+ RequestBuilder::new()
+ .method(Method::Get)
+ .url(&types::RefundSyncType::get_url(self, req, connectors)?)
+ .attach_default_headers()
+ .headers(types::RefundSyncType::get_headers(self, req, connectors)?)
+ .set_body(types::RefundSyncType::get_request_body(
+ self, req, connectors,
+ )?)
+ .build(),
+ ))
+ }
+
+ fn handle_response(
+ &self,
+ data: &RefundSyncRouterData,
+ event_builder: Option<&mut ConnectorEvent>,
+ res: Response,
+ ) -> CustomResult<RefundSyncRouterData, errors::ConnectorError> {
+ let response: fiservemea::RefundResponse = res
+ .response
+ .parse_struct("fiservemea RefundSyncResponse")
+ .change_context(errors::ConnectorError::ResponseDeserializationFailed)?;
+ event_builder.map(|i| i.set_response_body(&response));
+ router_env::logger::info!(connector_response=?response);
+ RouterData::try_from(ResponseRouterData {
+ response,
+ data: data.clone(),
+ http_code: res.status_code,
+ })
+ }
+
+ fn get_error_response(
+ &self,
+ res: Response,
+ event_builder: Option<&mut ConnectorEvent>,
+ ) -> CustomResult<ErrorResponse, errors::ConnectorError> {
+ self.build_error_response(res, event_builder)
+ }
+}
+
+#[async_trait::async_trait]
+impl webhooks::IncomingWebhook for Fiservemea {
+ fn get_webhook_object_reference_id(
+ &self,
+ _request: &webhooks::IncomingWebhookRequestDetails<'_>,
+ ) -> CustomResult<api_models::webhooks::ObjectReferenceId, errors::ConnectorError> {
+ Err(report!(errors::ConnectorError::WebhooksNotImplemented))
+ }
+
+ fn get_webhook_event_type(
+ &self,
+ _request: &webhooks::IncomingWebhookRequestDetails<'_>,
+ ) -> CustomResult<api_models::webhooks::IncomingWebhookEvent, errors::ConnectorError> {
+ Err(report!(errors::ConnectorError::WebhooksNotImplemented))
+ }
+
+ fn get_webhook_resource_object(
+ &self,
+ _request: &webhooks::IncomingWebhookRequestDetails<'_>,
+ ) -> CustomResult<Box<dyn masking::ErasedMaskSerialize>, errors::ConnectorError> {
+ Err(report!(errors::ConnectorError::WebhooksNotImplemented))
+ }
+}
diff --git a/crates/hyperswitch_connectors/src/connectors/fiservemea/transformers.rs b/crates/hyperswitch_connectors/src/connectors/fiservemea/transformers.rs
new file mode 100644
index 00000000000..e6307b4bdf5
--- /dev/null
+++ b/crates/hyperswitch_connectors/src/connectors/fiservemea/transformers.rs
@@ -0,0 +1,228 @@
+use common_enums::enums;
+use common_utils::types::StringMinorUnit;
+use hyperswitch_domain_models::{
+ payment_method_data::PaymentMethodData,
+ router_data::{ConnectorAuthType, RouterData},
+ router_flow_types::refunds::{Execute, RSync},
+ router_request_types::ResponseId,
+ router_response_types::{PaymentsResponseData, RefundsResponseData},
+ types::{PaymentsAuthorizeRouterData, RefundsRouterData},
+};
+use hyperswitch_interfaces::errors;
+use masking::Secret;
+use serde::{Deserialize, Serialize};
+
+use crate::{
+ types::{RefundsResponseRouterData, ResponseRouterData},
+ utils::PaymentsAuthorizeRequestData,
+};
+
+//TODO: Fill the struct with respective fields
+pub struct FiservemeaRouterData<T> {
+ pub amount: StringMinorUnit, // The type of amount that a connector accepts, for example, String, i64, f64, etc.
+ pub router_data: T,
+}
+
+impl<T> From<(StringMinorUnit, T)> for FiservemeaRouterData<T> {
+ fn from((amount, item): (StringMinorUnit, T)) -> Self {
+ //Todo : use utils to convert the amount to the type of amount that a connector accepts
+ Self {
+ amount,
+ router_data: item,
+ }
+ }
+}
+
+//TODO: Fill the struct with respective fields
+#[derive(Default, Debug, Serialize, PartialEq)]
+pub struct FiservemeaPaymentsRequest {
+ amount: StringMinorUnit,
+ card: FiservemeaCard,
+}
+
+#[derive(Default, Debug, Serialize, Eq, PartialEq)]
+pub struct FiservemeaCard {
+ number: cards::CardNumber,
+ expiry_month: Secret<String>,
+ expiry_year: Secret<String>,
+ cvc: Secret<String>,
+ complete: bool,
+}
+
+impl TryFrom<&FiservemeaRouterData<&PaymentsAuthorizeRouterData>> for FiservemeaPaymentsRequest {
+ type Error = error_stack::Report<errors::ConnectorError>;
+ fn try_from(
+ item: &FiservemeaRouterData<&PaymentsAuthorizeRouterData>,
+ ) -> Result<Self, Self::Error> {
+ match item.router_data.request.payment_method_data.clone() {
+ PaymentMethodData::Card(req_card) => {
+ let card = FiservemeaCard {
+ number: req_card.card_number,
+ expiry_month: req_card.card_exp_month,
+ expiry_year: req_card.card_exp_year,
+ cvc: req_card.card_cvc,
+ complete: item.router_data.request.is_auto_capture()?,
+ };
+ Ok(Self {
+ amount: item.amount.clone(),
+ card,
+ })
+ }
+ _ => Err(errors::ConnectorError::NotImplemented("Payment methods".to_string()).into()),
+ }
+ }
+}
+
+//TODO: Fill the struct with respective fields
+// Auth Struct
+pub struct FiservemeaAuthType {
+ pub(super) api_key: Secret<String>,
+}
+
+impl TryFrom<&ConnectorAuthType> for FiservemeaAuthType {
+ type Error = error_stack::Report<errors::ConnectorError>;
+ fn try_from(auth_type: &ConnectorAuthType) -> Result<Self, Self::Error> {
+ match auth_type {
+ ConnectorAuthType::HeaderKey { api_key } => Ok(Self {
+ api_key: api_key.to_owned(),
+ }),
+ _ => Err(errors::ConnectorError::FailedToObtainAuthType.into()),
+ }
+ }
+}
+// PaymentsResponse
+//TODO: Append the remaining status flags
+#[derive(Debug, Clone, Default, Serialize, Deserialize, PartialEq)]
+#[serde(rename_all = "lowercase")]
+pub enum FiservemeaPaymentStatus {
+ Succeeded,
+ Failed,
+ #[default]
+ Processing,
+}
+
+impl From<FiservemeaPaymentStatus> for common_enums::AttemptStatus {
+ fn from(item: FiservemeaPaymentStatus) -> Self {
+ match item {
+ FiservemeaPaymentStatus::Succeeded => Self::Charged,
+ FiservemeaPaymentStatus::Failed => Self::Failure,
+ FiservemeaPaymentStatus::Processing => Self::Authorizing,
+ }
+ }
+}
+
+//TODO: Fill the struct with respective fields
+#[derive(Default, Debug, Clone, Serialize, Deserialize, PartialEq)]
+pub struct FiservemeaPaymentsResponse {
+ status: FiservemeaPaymentStatus,
+ id: String,
+}
+
+impl<F, T> TryFrom<ResponseRouterData<F, FiservemeaPaymentsResponse, T, PaymentsResponseData>>
+ for RouterData<F, T, PaymentsResponseData>
+{
+ type Error = error_stack::Report<errors::ConnectorError>;
+ fn try_from(
+ item: ResponseRouterData<F, FiservemeaPaymentsResponse, T, PaymentsResponseData>,
+ ) -> Result<Self, Self::Error> {
+ Ok(Self {
+ status: common_enums::AttemptStatus::from(item.response.status),
+ response: Ok(PaymentsResponseData::TransactionResponse {
+ resource_id: ResponseId::ConnectorTransactionId(item.response.id),
+ redirection_data: None,
+ mandate_reference: None,
+ connector_metadata: None,
+ network_txn_id: None,
+ connector_response_reference_id: None,
+ incremental_authorization_allowed: None,
+ charge_id: None,
+ }),
+ ..item.data
+ })
+ }
+}
+
+//TODO: Fill the struct with respective fields
+// REFUND :
+// Type definition for RefundRequest
+#[derive(Default, Debug, Serialize)]
+pub struct FiservemeaRefundRequest {
+ pub amount: StringMinorUnit,
+}
+
+impl<F> TryFrom<&FiservemeaRouterData<&RefundsRouterData<F>>> for FiservemeaRefundRequest {
+ type Error = error_stack::Report<errors::ConnectorError>;
+ fn try_from(item: &FiservemeaRouterData<&RefundsRouterData<F>>) -> Result<Self, Self::Error> {
+ Ok(Self {
+ amount: item.amount.to_owned(),
+ })
+ }
+}
+
+// Type definition for Refund Response
+
+#[allow(dead_code)]
+#[derive(Debug, Serialize, Default, Deserialize, Clone)]
+pub enum RefundStatus {
+ Succeeded,
+ Failed,
+ #[default]
+ Processing,
+}
+
+impl From<RefundStatus> for enums::RefundStatus {
+ fn from(item: RefundStatus) -> Self {
+ match item {
+ RefundStatus::Succeeded => Self::Success,
+ RefundStatus::Failed => Self::Failure,
+ RefundStatus::Processing => Self::Pending,
+ //TODO: Review mapping
+ }
+ }
+}
+
+//TODO: Fill the struct with respective fields
+#[derive(Default, Debug, Clone, Serialize, Deserialize)]
+pub struct RefundResponse {
+ id: String,
+ status: RefundStatus,
+}
+
+impl TryFrom<RefundsResponseRouterData<Execute, RefundResponse>> for RefundsRouterData<Execute> {
+ type Error = error_stack::Report<errors::ConnectorError>;
+ fn try_from(
+ item: RefundsResponseRouterData<Execute, RefundResponse>,
+ ) -> Result<Self, Self::Error> {
+ Ok(Self {
+ response: Ok(RefundsResponseData {
+ connector_refund_id: item.response.id.to_string(),
+ refund_status: enums::RefundStatus::from(item.response.status),
+ }),
+ ..item.data
+ })
+ }
+}
+
+impl TryFrom<RefundsResponseRouterData<RSync, RefundResponse>> for RefundsRouterData<RSync> {
+ type Error = error_stack::Report<errors::ConnectorError>;
+ fn try_from(
+ item: RefundsResponseRouterData<RSync, RefundResponse>,
+ ) -> Result<Self, Self::Error> {
+ Ok(Self {
+ response: Ok(RefundsResponseData {
+ connector_refund_id: item.response.id.to_string(),
+ refund_status: enums::RefundStatus::from(item.response.status),
+ }),
+ ..item.data
+ })
+ }
+}
+
+//TODO: Fill the struct with respective fields
+#[derive(Default, Debug, Serialize, Deserialize, PartialEq)]
+pub struct FiservemeaErrorResponse {
+ pub status_code: u16,
+ pub code: String,
+ pub message: String,
+ pub reason: Option<String>,
+}
diff --git a/crates/hyperswitch_connectors/src/default_implementations.rs b/crates/hyperswitch_connectors/src/default_implementations.rs
index dd3f2152cd8..5851443a2c4 100644
--- a/crates/hyperswitch_connectors/src/default_implementations.rs
+++ b/crates/hyperswitch_connectors/src/default_implementations.rs
@@ -89,6 +89,7 @@ default_imp_for_authorize_session_token!(
connectors::Bambora,
connectors::Bitpay,
connectors::Fiserv,
+ connectors::Fiservemea,
connectors::Helcim,
connectors::Stax
);
@@ -112,6 +113,7 @@ macro_rules! default_imp_for_complete_authorize {
default_imp_for_complete_authorize!(
connectors::Bitpay,
connectors::Fiserv,
+ connectors::Fiservemea,
connectors::Helcim,
connectors::Stax
);
@@ -135,6 +137,7 @@ default_imp_for_incremental_authorization!(
connectors::Bambora,
connectors::Bitpay,
connectors::Fiserv,
+ connectors::Fiservemea,
connectors::Helcim,
connectors::Stax
);
@@ -158,6 +161,7 @@ default_imp_for_create_customer!(
connectors::Bambora,
connectors::Bitpay,
connectors::Fiserv,
+ connectors::Fiservemea,
connectors::Helcim
);
@@ -181,6 +185,7 @@ macro_rules! default_imp_for_connector_redirect_response {
default_imp_for_connector_redirect_response!(
connectors::Bitpay,
connectors::Fiserv,
+ connectors::Fiservemea,
connectors::Helcim,
connectors::Stax
);
@@ -204,6 +209,7 @@ default_imp_for_pre_processing_steps!(
connectors::Bambora,
connectors::Bitpay,
connectors::Fiserv,
+ connectors::Fiservemea,
connectors::Helcim,
connectors::Stax
);
@@ -227,6 +233,7 @@ default_imp_for_post_processing_steps!(
connectors::Bambora,
connectors::Bitpay,
connectors::Fiserv,
+ connectors::Fiservemea,
connectors::Helcim,
connectors::Stax
);
@@ -250,6 +257,7 @@ default_imp_for_approve!(
connectors::Bambora,
connectors::Bitpay,
connectors::Fiserv,
+ connectors::Fiservemea,
connectors::Helcim,
connectors::Stax
);
@@ -273,6 +281,7 @@ default_imp_for_reject!(
connectors::Bambora,
connectors::Bitpay,
connectors::Fiserv,
+ connectors::Fiservemea,
connectors::Helcim,
connectors::Stax
);
@@ -296,6 +305,7 @@ default_imp_for_webhook_source_verification!(
connectors::Bambora,
connectors::Bitpay,
connectors::Fiserv,
+ connectors::Fiservemea,
connectors::Helcim,
connectors::Stax
);
@@ -320,6 +330,7 @@ default_imp_for_accept_dispute!(
connectors::Bambora,
connectors::Bitpay,
connectors::Fiserv,
+ connectors::Fiservemea,
connectors::Helcim,
connectors::Stax
);
@@ -343,6 +354,7 @@ default_imp_for_submit_evidence!(
connectors::Bambora,
connectors::Bitpay,
connectors::Fiserv,
+ connectors::Fiservemea,
connectors::Helcim,
connectors::Stax
);
@@ -366,6 +378,7 @@ default_imp_for_defend_dispute!(
connectors::Bambora,
connectors::Bitpay,
connectors::Fiserv,
+ connectors::Fiservemea,
connectors::Helcim,
connectors::Stax
);
@@ -398,6 +411,7 @@ default_imp_for_file_upload!(
connectors::Bambora,
connectors::Bitpay,
connectors::Fiserv,
+ connectors::Fiservemea,
connectors::Helcim,
connectors::Stax
);
@@ -423,6 +437,7 @@ default_imp_for_payouts_create!(
connectors::Bambora,
connectors::Bitpay,
connectors::Fiserv,
+ connectors::Fiservemea,
connectors::Helcim,
connectors::Stax
);
@@ -448,6 +463,7 @@ default_imp_for_payouts_retrieve!(
connectors::Bambora,
connectors::Bitpay,
connectors::Fiserv,
+ connectors::Fiservemea,
connectors::Helcim,
connectors::Stax
);
@@ -473,6 +489,7 @@ default_imp_for_payouts_eligibility!(
connectors::Bambora,
connectors::Bitpay,
connectors::Fiserv,
+ connectors::Fiservemea,
connectors::Helcim,
connectors::Stax
);
@@ -498,6 +515,7 @@ default_imp_for_payouts_fulfill!(
connectors::Bambora,
connectors::Bitpay,
connectors::Fiserv,
+ connectors::Fiservemea,
connectors::Helcim,
connectors::Stax
);
@@ -523,6 +541,7 @@ default_imp_for_payouts_cancel!(
connectors::Bambora,
connectors::Bitpay,
connectors::Fiserv,
+ connectors::Fiservemea,
connectors::Helcim,
connectors::Stax
);
@@ -548,6 +567,7 @@ default_imp_for_payouts_quote!(
connectors::Bambora,
connectors::Bitpay,
connectors::Fiserv,
+ connectors::Fiservemea,
connectors::Helcim,
connectors::Stax
);
@@ -573,6 +593,7 @@ default_imp_for_payouts_recipient!(
connectors::Bambora,
connectors::Bitpay,
connectors::Fiserv,
+ connectors::Fiservemea,
connectors::Helcim,
connectors::Stax
);
@@ -598,6 +619,7 @@ default_imp_for_payouts_recipient_account!(
connectors::Bambora,
connectors::Bitpay,
connectors::Fiserv,
+ connectors::Fiservemea,
connectors::Helcim,
connectors::Stax
);
@@ -623,6 +645,7 @@ default_imp_for_frm_sale!(
connectors::Bambora,
connectors::Bitpay,
connectors::Fiserv,
+ connectors::Fiservemea,
connectors::Helcim,
connectors::Stax
);
@@ -648,6 +671,7 @@ default_imp_for_frm_checkout!(
connectors::Bambora,
connectors::Bitpay,
connectors::Fiserv,
+ connectors::Fiservemea,
connectors::Helcim,
connectors::Stax
);
@@ -673,6 +697,7 @@ default_imp_for_frm_transaction!(
connectors::Bambora,
connectors::Bitpay,
connectors::Fiserv,
+ connectors::Fiservemea,
connectors::Helcim,
connectors::Stax
);
@@ -698,6 +723,7 @@ default_imp_for_frm_fulfillment!(
connectors::Bambora,
connectors::Bitpay,
connectors::Fiserv,
+ connectors::Fiservemea,
connectors::Helcim,
connectors::Stax
);
@@ -723,6 +749,7 @@ default_imp_for_frm_record_return!(
connectors::Bambora,
connectors::Bitpay,
connectors::Fiserv,
+ connectors::Fiservemea,
connectors::Helcim,
connectors::Stax
);
@@ -745,6 +772,7 @@ default_imp_for_revoking_mandates!(
connectors::Bambora,
connectors::Bitpay,
connectors::Fiserv,
+ connectors::Fiservemea,
connectors::Helcim,
connectors::Stax
);
diff --git a/crates/hyperswitch_connectors/src/default_implementations_v2.rs b/crates/hyperswitch_connectors/src/default_implementations_v2.rs
index 050c8687d89..32e89b3f8bb 100644
--- a/crates/hyperswitch_connectors/src/default_implementations_v2.rs
+++ b/crates/hyperswitch_connectors/src/default_implementations_v2.rs
@@ -184,6 +184,7 @@ default_imp_for_new_connector_integration_payment!(
connectors::Bambora,
connectors::Bitpay,
connectors::Fiserv,
+ connectors::Fiservemea,
connectors::Helcim,
connectors::Stax
);
@@ -208,6 +209,7 @@ default_imp_for_new_connector_integration_refund!(
connectors::Bambora,
connectors::Bitpay,
connectors::Fiserv,
+ connectors::Fiservemea,
connectors::Helcim,
connectors::Stax
);
@@ -227,6 +229,7 @@ default_imp_for_new_connector_integration_connector_access_token!(
connectors::Bambora,
connectors::Bitpay,
connectors::Fiserv,
+ connectors::Fiservemea,
connectors::Helcim,
connectors::Stax
);
@@ -252,6 +255,7 @@ default_imp_for_new_connector_integration_accept_dispute!(
connectors::Bambora,
connectors::Bitpay,
connectors::Fiserv,
+ connectors::Fiservemea,
connectors::Helcim,
connectors::Stax
);
@@ -276,6 +280,7 @@ default_imp_for_new_connector_integration_submit_evidence!(
connectors::Bambora,
connectors::Bitpay,
connectors::Fiserv,
+ connectors::Fiservemea,
connectors::Helcim,
connectors::Stax
);
@@ -300,6 +305,7 @@ default_imp_for_new_connector_integration_defend_dispute!(
connectors::Bambora,
connectors::Bitpay,
connectors::Fiserv,
+ connectors::Fiservemea,
connectors::Helcim,
connectors::Stax
);
@@ -334,6 +340,7 @@ default_imp_for_new_connector_integration_file_upload!(
connectors::Bambora,
connectors::Bitpay,
connectors::Fiserv,
+ connectors::Fiservemea,
connectors::Helcim,
connectors::Stax
);
@@ -360,6 +367,7 @@ default_imp_for_new_connector_integration_payouts_create!(
connectors::Bambora,
connectors::Bitpay,
connectors::Fiserv,
+ connectors::Fiservemea,
connectors::Helcim,
connectors::Stax
);
@@ -386,6 +394,7 @@ default_imp_for_new_connector_integration_payouts_eligibility!(
connectors::Bambora,
connectors::Bitpay,
connectors::Fiserv,
+ connectors::Fiservemea,
connectors::Helcim,
connectors::Stax
);
@@ -412,6 +421,7 @@ default_imp_for_new_connector_integration_payouts_fulfill!(
connectors::Bambora,
connectors::Bitpay,
connectors::Fiserv,
+ connectors::Fiservemea,
connectors::Helcim,
connectors::Stax
);
@@ -438,6 +448,7 @@ default_imp_for_new_connector_integration_payouts_cancel!(
connectors::Bambora,
connectors::Bitpay,
connectors::Fiserv,
+ connectors::Fiservemea,
connectors::Helcim,
connectors::Stax
);
@@ -464,6 +475,7 @@ default_imp_for_new_connector_integration_payouts_quote!(
connectors::Bambora,
connectors::Bitpay,
connectors::Fiserv,
+ connectors::Fiservemea,
connectors::Helcim,
connectors::Stax
);
@@ -490,6 +502,7 @@ default_imp_for_new_connector_integration_payouts_recipient!(
connectors::Bambora,
connectors::Bitpay,
connectors::Fiserv,
+ connectors::Fiservemea,
connectors::Helcim,
connectors::Stax
);
@@ -516,6 +529,7 @@ default_imp_for_new_connector_integration_payouts_sync!(
connectors::Bambora,
connectors::Bitpay,
connectors::Fiserv,
+ connectors::Fiservemea,
connectors::Helcim,
connectors::Stax
);
@@ -542,6 +556,7 @@ default_imp_for_new_connector_integration_payouts_recipient_account!(
connectors::Bambora,
connectors::Bitpay,
connectors::Fiserv,
+ connectors::Fiservemea,
connectors::Helcim,
connectors::Stax
);
@@ -566,6 +581,7 @@ default_imp_for_new_connector_integration_webhook_source_verification!(
connectors::Bambora,
connectors::Bitpay,
connectors::Fiserv,
+ connectors::Fiservemea,
connectors::Helcim,
connectors::Stax
);
@@ -592,6 +608,7 @@ default_imp_for_new_connector_integration_frm_sale!(
connectors::Bambora,
connectors::Bitpay,
connectors::Fiserv,
+ connectors::Fiservemea,
connectors::Helcim,
connectors::Stax
);
@@ -618,6 +635,7 @@ default_imp_for_new_connector_integration_frm_checkout!(
connectors::Bambora,
connectors::Bitpay,
connectors::Fiserv,
+ connectors::Fiservemea,
connectors::Helcim,
connectors::Stax
);
@@ -644,6 +662,7 @@ default_imp_for_new_connector_integration_frm_transaction!(
connectors::Bambora,
connectors::Bitpay,
connectors::Fiserv,
+ connectors::Fiservemea,
connectors::Helcim,
connectors::Stax
);
@@ -670,6 +689,7 @@ default_imp_for_new_connector_integration_frm_fulfillment!(
connectors::Bambora,
connectors::Bitpay,
connectors::Fiserv,
+ connectors::Fiservemea,
connectors::Helcim,
connectors::Stax
);
@@ -696,6 +716,7 @@ default_imp_for_new_connector_integration_frm_record_return!(
connectors::Bambora,
connectors::Bitpay,
connectors::Fiserv,
+ connectors::Fiservemea,
connectors::Helcim,
connectors::Stax
);
@@ -719,6 +740,7 @@ default_imp_for_new_connector_integration_revoking_mandates!(
connectors::Bambora,
connectors::Bitpay,
connectors::Fiserv,
+ connectors::Fiservemea,
connectors::Helcim,
connectors::Stax
);
diff --git a/crates/hyperswitch_interfaces/src/configs.rs b/crates/hyperswitch_interfaces/src/configs.rs
index 60dc93d0576..a2dd4675c8c 100644
--- a/crates/hyperswitch_interfaces/src/configs.rs
+++ b/crates/hyperswitch_interfaces/src/configs.rs
@@ -37,6 +37,7 @@ pub struct Connectors {
pub dummyconnector: ConnectorParams,
pub ebanx: ConnectorParams,
pub fiserv: ConnectorParams,
+ pub fiservemea: ConnectorParams,
pub forte: ConnectorParams,
pub globalpay: ConnectorParams,
pub globepay: ConnectorParams,
diff --git a/crates/router/src/connector.rs b/crates/router/src/connector.rs
index 5ceb8845b70..7ca10f75855 100644
--- a/crates/router/src/connector.rs
+++ b/crates/router/src/connector.rs
@@ -68,8 +68,8 @@ pub mod zen;
pub mod zsl;
pub use hyperswitch_connectors::connectors::{
- bambora, bambora::Bambora, bitpay, bitpay::Bitpay, fiserv, fiserv::Fiserv, helcim,
- helcim::Helcim, stax, stax::Stax,
+ bambora, bambora::Bambora, bitpay, bitpay::Bitpay, fiserv, fiserv::Fiserv, fiservemea,
+ fiservemea::Fiservemea, helcim, helcim::Helcim, stax, stax::Stax,
};
#[cfg(feature = "dummy_connector")]
diff --git a/crates/router/src/core/payments/connector_integration_v2_impls.rs b/crates/router/src/core/payments/connector_integration_v2_impls.rs
index fc530d192e6..b79e62d11ba 100644
--- a/crates/router/src/core/payments/connector_integration_v2_impls.rs
+++ b/crates/router/src/core/payments/connector_integration_v2_impls.rs
@@ -1234,6 +1234,7 @@ default_imp_for_new_connector_integration_payouts!(
connector::Dlocal,
connector::Ebanx,
connector::Fiserv,
+ connector::Fiservemea,
connector::Forte,
connector::Globalpay,
connector::Globepay,
@@ -2077,6 +2078,7 @@ default_imp_for_new_connector_integration_frm!(
connector::Dlocal,
connector::Ebanx,
connector::Fiserv,
+ connector::Fiservemea,
connector::Forte,
connector::Globalpay,
connector::Globepay,
@@ -2699,6 +2701,7 @@ default_imp_for_new_connector_integration_connector_authentication!(
connector::Dlocal,
connector::Ebanx,
connector::Fiserv,
+ connector::Fiservemea,
connector::Forte,
connector::Globalpay,
connector::Globepay,
diff --git a/crates/router/src/core/payments/flows.rs b/crates/router/src/core/payments/flows.rs
index 5a346d2368b..7b531aa09e9 100644
--- a/crates/router/src/core/payments/flows.rs
+++ b/crates/router/src/core/payments/flows.rs
@@ -541,6 +541,7 @@ default_imp_for_connector_request_id!(
connector::Dlocal,
connector::Ebanx,
connector::Fiserv,
+ connector::Fiservemea,
connector::Forte,
connector::Globalpay,
connector::Globepay,
@@ -1195,6 +1196,7 @@ default_imp_for_payouts!(
connector::Datatrans,
connector::Dlocal,
connector::Fiserv,
+ connector::Fiservemea,
connector::Forte,
connector::Globalpay,
connector::Globepay,
@@ -2212,6 +2214,7 @@ default_imp_for_fraud_check!(
connector::Dlocal,
connector::Ebanx,
connector::Fiserv,
+ connector::Fiservemea,
connector::Forte,
connector::Globalpay,
connector::Globepay,
@@ -3026,6 +3029,7 @@ default_imp_for_connector_authentication!(
connector::Dlocal,
connector::Ebanx,
connector::Fiserv,
+ connector::Fiservemea,
connector::Forte,
connector::Globalpay,
connector::Globepay,
diff --git a/crates/router/src/types/api.rs b/crates/router/src/types/api.rs
index 7384b67367f..b9a05674fd3 100644
--- a/crates/router/src/types/api.rs
+++ b/crates/router/src/types/api.rs
@@ -388,6 +388,9 @@ impl ConnectorData {
))),
enums::Connector::Ebanx => Ok(ConnectorEnum::Old(Box::new(&connector::Ebanx))),
enums::Connector::Fiserv => Ok(ConnectorEnum::Old(Box::new(&connector::Fiserv))),
+ // enums::Connector::Fiservemea => {
+ // Ok(ConnectorEnum::Old(Box::new(connector::Fiservemea)))
+ // }
enums::Connector::Forte => Ok(ConnectorEnum::Old(Box::new(&connector::Forte))),
enums::Connector::Globalpay => {
Ok(ConnectorEnum::Old(Box::new(connector::Globalpay::new())))
diff --git a/crates/router/src/types/transformers.rs b/crates/router/src/types/transformers.rs
index a6bc5175b46..ebfd4b099ba 100644
--- a/crates/router/src/types/transformers.rs
+++ b/crates/router/src/types/transformers.rs
@@ -244,6 +244,7 @@ impl ForeignTryFrom<api_enums::Connector> for common_enums::RoutableConnectors {
api_enums::Connector::Dlocal => Self::Dlocal,
api_enums::Connector::Ebanx => Self::Ebanx,
api_enums::Connector::Fiserv => Self::Fiserv,
+ // api_enums::Connector::Fiservemea => Self::Fiservemea,
api_enums::Connector::Forte => Self::Forte,
api_enums::Connector::Globalpay => Self::Globalpay,
api_enums::Connector::Globepay => Self::Globepay,
diff --git a/crates/router/tests/connectors/fiservemea.rs b/crates/router/tests/connectors/fiservemea.rs
new file mode 100644
index 00000000000..d8c73304202
--- /dev/null
+++ b/crates/router/tests/connectors/fiservemea.rs
@@ -0,0 +1,421 @@
+use hyperswitch_domain_models::payment_method_data::{Card, PaymentMethodData};
+use masking::Secret;
+use router::types::{self, api, storage::enums};
+use test_utils::connector_auth;
+
+use crate::utils::{self, ConnectorActions};
+
+#[derive(Clone, Copy)]
+struct FiservemeaTest;
+impl ConnectorActions for FiservemeaTest {}
+impl utils::Connector for FiservemeaTest {
+ fn get_data(&self) -> api::ConnectorData {
+ use router::connector::Fiservemea;
+ utils::construct_connector_data_old(
+ Box::new(Fiservemea::new()),
+ types::Connector::Plaid,
+ api::GetToken::Connector,
+ None,
+ )
+ }
+
+ fn get_auth_token(&self) -> types::ConnectorAuthType {
+ utils::to_connector_auth_type(
+ connector_auth::ConnectorAuthentication::new()
+ .fiservemea
+ .expect("Missing connector authentication configuration")
+ .into(),
+ )
+ }
+
+ fn get_name(&self) -> String {
+ "fiservemea".to_string()
+ }
+}
+
+static CONNECTOR: FiservemeaTest = FiservemeaTest {};
+
+fn get_default_payment_info() -> Option<utils::PaymentInfo> {
+ None
+}
+
+fn payment_method_details() -> Option<types::PaymentsAuthorizeData> {
+ None
+}
+
+// Cards Positive Tests
+// Creates a payment using the manual capture flow (Non 3DS).
+#[actix_web::test]
+async fn should_only_authorize_payment() {
+ let response = CONNECTOR
+ .authorize_payment(payment_method_details(), get_default_payment_info())
+ .await
+ .expect("Authorize payment response");
+ assert_eq!(response.status, enums::AttemptStatus::Authorized);
+}
+
+// Captures a payment using the manual capture flow (Non 3DS).
+#[actix_web::test]
+async fn should_capture_authorized_payment() {
+ let response = CONNECTOR
+ .authorize_and_capture_payment(payment_method_details(), None, get_default_payment_info())
+ .await
+ .expect("Capture payment response");
+ assert_eq!(response.status, enums::AttemptStatus::Charged);
+}
+
+// Partially captures a payment using the manual capture flow (Non 3DS).
+#[actix_web::test]
+async fn should_partially_capture_authorized_payment() {
+ let response = CONNECTOR
+ .authorize_and_capture_payment(
+ payment_method_details(),
+ Some(types::PaymentsCaptureData {
+ amount_to_capture: 50,
+ ..utils::PaymentCaptureType::default().0
+ }),
+ get_default_payment_info(),
+ )
+ .await
+ .expect("Capture payment response");
+ assert_eq!(response.status, enums::AttemptStatus::Charged);
+}
+
+// Synchronizes a payment using the manual capture flow (Non 3DS).
+#[actix_web::test]
+async fn should_sync_authorized_payment() {
+ let authorize_response = CONNECTOR
+ .authorize_payment(payment_method_details(), get_default_payment_info())
+ .await
+ .expect("Authorize payment response");
+ let txn_id = utils::get_connector_transaction_id(authorize_response.response);
+ let response = CONNECTOR
+ .psync_retry_till_status_matches(
+ enums::AttemptStatus::Authorized,
+ Some(types::PaymentsSyncData {
+ connector_transaction_id: types::ResponseId::ConnectorTransactionId(
+ txn_id.unwrap(),
+ ),
+ ..Default::default()
+ }),
+ get_default_payment_info(),
+ )
+ .await
+ .expect("PSync response");
+ assert_eq!(response.status, enums::AttemptStatus::Authorized,);
+}
+
+// Voids a payment using the manual capture flow (Non 3DS).
+#[actix_web::test]
+async fn should_void_authorized_payment() {
+ let response = CONNECTOR
+ .authorize_and_void_payment(
+ payment_method_details(),
+ Some(types::PaymentsCancelData {
+ connector_transaction_id: String::from(""),
+ cancellation_reason: Some("requested_by_customer".to_string()),
+ ..Default::default()
+ }),
+ get_default_payment_info(),
+ )
+ .await
+ .expect("Void payment response");
+ assert_eq!(response.status, enums::AttemptStatus::Voided);
+}
+
+// Refunds a payment using the manual capture flow (Non 3DS).
+#[actix_web::test]
+async fn should_refund_manually_captured_payment() {
+ let response = CONNECTOR
+ .capture_payment_and_refund(
+ payment_method_details(),
+ None,
+ None,
+ get_default_payment_info(),
+ )
+ .await
+ .unwrap();
+ assert_eq!(
+ response.response.unwrap().refund_status,
+ enums::RefundStatus::Success,
+ );
+}
+
+// Partially refunds a payment using the manual capture flow (Non 3DS).
+#[actix_web::test]
+async fn should_partially_refund_manually_captured_payment() {
+ let response = CONNECTOR
+ .capture_payment_and_refund(
+ payment_method_details(),
+ None,
+ Some(types::RefundsData {
+ refund_amount: 50,
+ ..utils::PaymentRefundType::default().0
+ }),
+ get_default_payment_info(),
+ )
+ .await
+ .unwrap();
+ assert_eq!(
+ response.response.unwrap().refund_status,
+ enums::RefundStatus::Success,
+ );
+}
+
+// Synchronizes a refund using the manual capture flow (Non 3DS).
+#[actix_web::test]
+async fn should_sync_manually_captured_refund() {
+ let refund_response = CONNECTOR
+ .capture_payment_and_refund(
+ payment_method_details(),
+ None,
+ None,
+ get_default_payment_info(),
+ )
+ .await
+ .unwrap();
+ let response = CONNECTOR
+ .rsync_retry_till_status_matches(
+ enums::RefundStatus::Success,
+ refund_response.response.unwrap().connector_refund_id,
+ None,
+ get_default_payment_info(),
+ )
+ .await
+ .unwrap();
+ assert_eq!(
+ response.response.unwrap().refund_status,
+ enums::RefundStatus::Success,
+ );
+}
+
+// Creates a payment using the automatic capture flow (Non 3DS).
+#[actix_web::test]
+async fn should_make_payment() {
+ let authorize_response = CONNECTOR
+ .make_payment(payment_method_details(), get_default_payment_info())
+ .await
+ .unwrap();
+ assert_eq!(authorize_response.status, enums::AttemptStatus::Charged);
+}
+
+// Synchronizes a payment using the automatic capture flow (Non 3DS).
+#[actix_web::test]
+async fn should_sync_auto_captured_payment() {
+ let authorize_response = CONNECTOR
+ .make_payment(payment_method_details(), get_default_payment_info())
+ .await
+ .unwrap();
+ assert_eq!(authorize_response.status, enums::AttemptStatus::Charged);
+ let txn_id = utils::get_connector_transaction_id(authorize_response.response);
+ assert_ne!(txn_id, None, "Empty connector transaction id");
+ let response = CONNECTOR
+ .psync_retry_till_status_matches(
+ enums::AttemptStatus::Charged,
+ Some(types::PaymentsSyncData {
+ connector_transaction_id: types::ResponseId::ConnectorTransactionId(
+ txn_id.unwrap(),
+ ),
+ capture_method: Some(enums::CaptureMethod::Automatic),
+ ..Default::default()
+ }),
+ get_default_payment_info(),
+ )
+ .await
+ .unwrap();
+ assert_eq!(response.status, enums::AttemptStatus::Charged,);
+}
+
+// Refunds a payment using the automatic capture flow (Non 3DS).
+#[actix_web::test]
+async fn should_refund_auto_captured_payment() {
+ let response = CONNECTOR
+ .make_payment_and_refund(payment_method_details(), None, get_default_payment_info())
+ .await
+ .unwrap();
+ assert_eq!(
+ response.response.unwrap().refund_status,
+ enums::RefundStatus::Success,
+ );
+}
+
+// Partially refunds a payment using the automatic capture flow (Non 3DS).
+#[actix_web::test]
+async fn should_partially_refund_succeeded_payment() {
+ let refund_response = CONNECTOR
+ .make_payment_and_refund(
+ payment_method_details(),
+ Some(types::RefundsData {
+ refund_amount: 50,
+ ..utils::PaymentRefundType::default().0
+ }),
+ get_default_payment_info(),
+ )
+ .await
+ .unwrap();
+ assert_eq!(
+ refund_response.response.unwrap().refund_status,
+ enums::RefundStatus::Success,
+ );
+}
+
+// Creates multiple refunds against a payment using the automatic capture flow (Non 3DS).
+#[actix_web::test]
+async fn should_refund_succeeded_payment_multiple_times() {
+ CONNECTOR
+ .make_payment_and_multiple_refund(
+ payment_method_details(),
+ Some(types::RefundsData {
+ refund_amount: 50,
+ ..utils::PaymentRefundType::default().0
+ }),
+ get_default_payment_info(),
+ )
+ .await;
+}
+
+// Synchronizes a refund using the automatic capture flow (Non 3DS).
+#[actix_web::test]
+async fn should_sync_refund() {
+ let refund_response = CONNECTOR
+ .make_payment_and_refund(payment_method_details(), None, get_default_payment_info())
+ .await
+ .unwrap();
+ let response = CONNECTOR
+ .rsync_retry_till_status_matches(
+ enums::RefundStatus::Success,
+ refund_response.response.unwrap().connector_refund_id,
+ None,
+ get_default_payment_info(),
+ )
+ .await
+ .unwrap();
+ assert_eq!(
+ response.response.unwrap().refund_status,
+ enums::RefundStatus::Success,
+ );
+}
+
+// Cards Negative scenarios
+// Creates a payment with incorrect CVC.
+#[actix_web::test]
+async fn should_fail_payment_for_incorrect_cvc() {
+ let response = CONNECTOR
+ .make_payment(
+ Some(types::PaymentsAuthorizeData {
+ payment_method_data: PaymentMethodData::Card(Card {
+ card_cvc: Secret::new("12345".to_string()),
+ ..utils::CCardType::default().0
+ }),
+ ..utils::PaymentAuthorizeType::default().0
+ }),
+ get_default_payment_info(),
+ )
+ .await
+ .unwrap();
+ assert_eq!(
+ response.response.unwrap_err().message,
+ "Your card's security code is invalid.".to_string(),
+ );
+}
+
+// Creates a payment with incorrect expiry month.
+#[actix_web::test]
+async fn should_fail_payment_for_invalid_exp_month() {
+ let response = CONNECTOR
+ .make_payment(
+ Some(types::PaymentsAuthorizeData {
+ payment_method_data: PaymentMethodData::Card(Card {
+ card_exp_month: Secret::new("20".to_string()),
+ ..utils::CCardType::default().0
+ }),
+ ..utils::PaymentAuthorizeType::default().0
+ }),
+ get_default_payment_info(),
+ )
+ .await
+ .unwrap();
+ assert_eq!(
+ response.response.unwrap_err().message,
+ "Your card's expiration month is invalid.".to_string(),
+ );
+}
+
+// Creates a payment with incorrect expiry year.
+#[actix_web::test]
+async fn should_fail_payment_for_incorrect_expiry_year() {
+ let response = CONNECTOR
+ .make_payment(
+ Some(types::PaymentsAuthorizeData {
+ payment_method_data: PaymentMethodData::Card(Card {
+ card_exp_year: Secret::new("2000".to_string()),
+ ..utils::CCardType::default().0
+ }),
+ ..utils::PaymentAuthorizeType::default().0
+ }),
+ get_default_payment_info(),
+ )
+ .await
+ .unwrap();
+ assert_eq!(
+ response.response.unwrap_err().message,
+ "Your card's expiration year is invalid.".to_string(),
+ );
+}
+
+// Voids a payment using automatic capture flow (Non 3DS).
+#[actix_web::test]
+async fn should_fail_void_payment_for_auto_capture() {
+ let authorize_response = CONNECTOR
+ .make_payment(payment_method_details(), get_default_payment_info())
+ .await
+ .unwrap();
+ assert_eq!(authorize_response.status, enums::AttemptStatus::Charged);
+ let txn_id = utils::get_connector_transaction_id(authorize_response.response);
+ assert_ne!(txn_id, None, "Empty connector transaction id");
+ let void_response = CONNECTOR
+ .void_payment(txn_id.unwrap(), None, get_default_payment_info())
+ .await
+ .unwrap();
+ assert_eq!(
+ void_response.response.unwrap_err().message,
+ "You cannot cancel this PaymentIntent because it has a status of succeeded."
+ );
+}
+
+// Captures a payment using invalid connector payment id.
+#[actix_web::test]
+async fn should_fail_capture_for_invalid_payment() {
+ let capture_response = CONNECTOR
+ .capture_payment("123456789".to_string(), None, get_default_payment_info())
+ .await
+ .unwrap();
+ assert_eq!(
+ capture_response.response.unwrap_err().message,
+ String::from("No such payment_intent: '123456789'")
+ );
+}
+
+// Refunds a payment with refund amount higher than payment amount.
+#[actix_web::test]
+async fn should_fail_for_refund_amount_higher_than_payment_amount() {
+ let response = CONNECTOR
+ .make_payment_and_refund(
+ payment_method_details(),
+ Some(types::RefundsData {
+ refund_amount: 150,
+ ..utils::PaymentRefundType::default().0
+ }),
+ get_default_payment_info(),
+ )
+ .await
+ .unwrap();
+ assert_eq!(
+ response.response.unwrap_err().message,
+ "Refund amount (₹1.50) is greater than charge amount (₹1.00)",
+ );
+}
+
+// Connector dependent test cases goes here
+
+// [#478]: add unit tests for non 3DS, wallets & webhooks in connector tests
diff --git a/crates/router/tests/connectors/main.rs b/crates/router/tests/connectors/main.rs
index 4c220a0a34d..7fdccfaadeb 100644
--- a/crates/router/tests/connectors/main.rs
+++ b/crates/router/tests/connectors/main.rs
@@ -31,6 +31,7 @@ mod dlocal;
mod dummyconnector;
mod ebanx;
mod fiserv;
+mod fiservemea;
mod forte;
mod globalpay;
mod globepay;
diff --git a/crates/router/tests/connectors/sample_auth.toml b/crates/router/tests/connectors/sample_auth.toml
index d3accafdbcf..891f5991c66 100644
--- a/crates/router/tests/connectors/sample_auth.toml
+++ b/crates/router/tests/connectors/sample_auth.toml
@@ -258,6 +258,9 @@ api_secret = "Secret key"
[paybox]
api_key="API Key"
+[fiservemea]
+api_key="API Key"
+
[wellsfargopayout]
api_key = "Consumer Key"
key1 = "Gateway Entity Id"
diff --git a/crates/test_utils/src/connector_auth.rs b/crates/test_utils/src/connector_auth.rs
index 671f9dae5ca..66384a2d92f 100644
--- a/crates/test_utils/src/connector_auth.rs
+++ b/crates/test_utils/src/connector_auth.rs
@@ -36,6 +36,7 @@ pub struct ConnectorAuthentication {
pub dummyconnector: Option<HeaderKey>,
pub ebanx: Option<HeaderKey>,
pub fiserv: Option<SignatureKey>,
+ pub fiservemea: Option<HeaderKey>,
pub forte: Option<MultiAuthKey>,
pub globalpay: Option<BodyKey>,
pub globepay: Option<BodyKey>,
diff --git a/loadtest/config/development.toml b/loadtest/config/development.toml
index 237c773e851..c74a1151416 100644
--- a/loadtest/config/development.toml
+++ b/loadtest/config/development.toml
@@ -99,6 +99,7 @@ dlocal.base_url = "https://sandbox.dlocal.com/"
dummyconnector.base_url = "http://localhost:8080/dummy-connector"
ebanx.base_url = "https://sandbox.ebanxpay.com/"
fiserv.base_url = "https://cert.api.fiservapps.com/"
+fiservemea.base_url = "https://prod.emea.api.fiservapps.com/sandbox/ipp/payments-gateway/v2"
forte.base_url = "https://sandbox.forte.net/api/v3"
globalpay.base_url = "https://apis.sandbox.globalpay.com/ucp/"
globepay.base_url = "https://pay.globepay.co/"
@@ -184,6 +185,7 @@ cards = [
"dummyconnector",
"ebanx",
"fiserv",
+ "fiservemea",
"forte",
"globalpay",
"globepay",
diff --git a/scripts/add_connector.sh b/scripts/add_connector.sh
index 5fec357f157..f025b8cf38b 100755
--- a/scripts/add_connector.sh
+++ b/scripts/add_connector.sh
@@ -6,7 +6,7 @@ function find_prev_connector() {
git checkout $self
cp $self $self.tmp
# Add new connector to existing list and sort it
- connectors=(aci adyen adyenplatform airwallex applepay authorizedotnet bambora bamboraapac bankofamerica billwerk bitpay bluesnap boku braintree cashtocode checkout coinbase cryptopay cybersource datatrans dlocal dummyconnector ebanx fiserv forte globalpay globepay gocardless gpayments helcim iatapay itaubank klarna mifinity mollie multisafepay netcetera nexinets noon nuvei opayo opennode paybox payeezy payme payone paypal payu placetopay plaid powertranz prophetpay rapyd razorpay shift4 square stax stripe threedsecureio trustpay tsys volt wellsfargo wellsfargopayout wise worldline worldpay zsl "$1")
+ connectors=(aci adyen adyenplatform airwallex applepay authorizedotnet bambora bamboraapac bankofamerica billwerk bitpay bluesnap boku braintree cashtocode checkout coinbase cryptopay cybersource datatrans dlocal dummyconnector ebanx fiserv fiservemea forte globalpay globepay gocardless gpayments helcim iatapay itaubank klarna mifinity mollie multisafepay netcetera nexinets noon nuvei opayo opennode paybox payeezy payme payone paypal payu placetopay plaid powertranz prophetpay rapyd razorpay shift4 square stax stripe threedsecureio trustpay tsys volt wellsfargo wellsfargopayout wise worldline worldpay zsl "$1")
IFS=$'\n' sorted=($(sort <<<"${connectors[*]}")); unset IFS
res=`echo ${sorted[@]}`
sed -i'' -e "s/^ connectors=.*/ connectors=($res \"\$1\")/" $self.tmp
|
2024-08-09T11:09:39Z
|
## Type of Change
<!-- Put an `x` in the boxes that apply -->
- [ ] Bugfix
- [x] New feature
- [ ] Enhancement
- [ ] Refactoring
- [ ] Dependency updates
- [ ] Documentation
- [ ] CI/CD
## Description
<!-- Describe your changes in detail -->
Template code added for new connector Fiserv-EMEA
https://docs.fiserv.dev/
### Additional Changes
- [ ] This PR modifies the API contract
- [ ] This PR modifies the database schema
- [ ] This PR modifies application configuration/environment variables
<!--
Provide links to the files with corresponding changes.
Following are the paths where you can find config files:
1. `config`
2. `crates/router/src/configs`
3. `loadtest/config`
-->
## Motivation and Context
<!--
Why is this change required? What problem does it solve?
If it fixes an open issue, please link to the issue here.
If you don't have an issue, we'd recommend starting with one first so the PR
can focus on the implementation (unless it is an obvious bug or documentation fix
that will have little conversation).
-->
https://github.com/juspay/hyperswitch/issues/5582
## How did you test it?
<!--
Did you write an integration/unit/API test to verify the code changes?
Or did you test this change manually (provide relevant screenshots)?
-->
Only template code added hence no testing required.
## Checklist
<!-- Put an `x` in the boxes that apply -->
- [x] I formatted the code `cargo +nightly fmt --all`
- [x] I addressed lints thrown by `cargo clippy`
- [x] I reviewed the submitted code
- [ ] I added unit tests for my changes where possible
|
6a5b49397adc402f7ce50543c817df3f11ca46ea
|
|
juspay/hyperswitch
|
juspay__hyperswitch-5554
|
Bug: fix(opensearch): add "@timestamp" field for opensearch locally
Add the `@timestamp` field to OpenSearch locally while creating index-patterns, as it is present in Elasticsearch and is causing mismatched results while using the ` /search ` api on SBX
|
diff --git a/config/vector.yaml b/config/vector.yaml
index 1511e09a05c..17049677fe5 100644
--- a/config/vector.yaml
+++ b/config/vector.yaml
@@ -60,6 +60,7 @@ transforms:
- plus_1_events
source: |-
.timestamp = from_unix_timestamp!(.created_at, unit: "seconds")
+ ."@timestamp" = from_unix_timestamp(.created_at, unit: "seconds") ?? now()
sdk_transformed:
type: throttle
diff --git a/crates/analytics/src/opensearch.rs b/crates/analytics/src/opensearch.rs
index 11ea4e4f7ab..e74622a054a 100644
--- a/crates/analytics/src/opensearch.rs
+++ b/crates/analytics/src/opensearch.rs
@@ -493,7 +493,7 @@ impl OpenSearchQueryBuilder {
let range = json!(time_range);
filter_array.push(json!({
"range": {
- "timestamp": range
+ "@timestamp": range
}
}));
}
|
2024-08-07T11:57:50Z
|
## Type of Change
<!-- Put an `x` in the boxes that apply -->
- [x] Bugfix
- [ ] New feature
- [ ] Enhancement
- [ ] Refactoring
- [ ] Dependency updates
- [ ] Documentation
- [ ] CI/CD
## Description
<!-- Describe your changes in detail -->
Added the `@timestamp` field to OpenSearch locally while creating index-patterns, as it is present in Elasticsearch and is causing mismatched results while using the /search api on SBX
### Additional Changes
- [ ] This PR modifies the API contract
- [ ] This PR modifies the database schema
- [ ] This PR modifies application configuration/environment variables
<!--
Provide links to the files with corresponding changes.
Following are the paths where you can find config files:
1. `config`
2. `crates/router/src/configs`
3. `loadtest/config`
-->
## Motivation and Context
<!--
Why is this change required? What problem does it solve?
If it fixes an open issue, please link to the issue here.
If you don't have an issue, we'd recommend starting with one first so the PR
can focus on the implementation (unless it is an obvious bug or documentation fix
that will have little conversation).
-->
To prevent mismatched data while using `/search` api
## How did you test it?
<!--
Did you write an integration/unit/API test to verify the code changes?
Or did you test this change manually (provide relevant screenshots)?
-->
- Hit the `/search` API
```bash
curl --location 'http://localhost:8080/analytics/v1/search' \
--header 'Accept: */*' \
--header 'Accept-Language: en-US,en;q=0.9' \
--header 'Connection: keep-alive' \
--header 'Content-Type: application/json' \
--header 'Origin: http://localhost:9000' \
--header 'Referer: http://localhost:9000/' \
--header 'Sec-Fetch-Dest: empty' \
--header 'Sec-Fetch-Mode: cors' \
--header 'Sec-Fetch-Site: same-site' \
--header 'User-Agent: Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/126.0.0.0 Safari/537.36' \
--header 'api-key: hyperswitch' \
--header 'authorization: Bearer eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJ1c2VyX2lkIjoiYjc2ZDVmZjMtNGI1ZS00OTMyLTk1ZDItNmE3MTEyZWZiNTNlIiwibWVyY2hhbnRfaWQiOiJtZXJjaGFudF8xNzIxODE1MjkwIiwicm9sZV9pZCI6Im9yZ19hZG1pbiIsImV4cCI6MTcyMzEwMDIwMCwib3JnX2lkIjoib3JnX3VFNk1LbExxalU5MWlGUEVGck1rIiwicHJvZmlsZV9pZCI6bnVsbH0._jkEBwHNVeJ_sstB4fqttU2mWVI4pPQbuOkqyovHRcE' \
--header 'sec-ch-ua: "Not/A)Brand";v="8", "Chromium";v="126", "Google Chrome";v="126"' \
--header 'sec-ch-ua-mobile: ?0' \
--header 'sec-ch-ua-platform: "macOS"' \
--data '{
"query": "usd",
"filters": {
"status": [
"success"
]
},
"timeRange": {
"startTime": "2024-07-23T00:30:00Z",
"endTime": "2024-08-08T18:45:00Z"
}
}'
```

## Checklist
<!-- Put an `x` in the boxes that apply -->
- [x] I formatted the code `cargo +nightly fmt --all`
- [ ] I addressed lints thrown by `cargo clippy`
- [x] I reviewed the submitted code
- [ ] I added unit tests for my changes where possible
|
7e545e36ebdcfe46a1fcb29687af542e34d00e93
|
|
juspay/hyperswitch
|
juspay__hyperswitch-5587
|
Bug: [FEATURE] Adapt routing id and payout algorithm id in routing core
### Feature Description
In this PR we adapt the usage of routing_algorithm_id as well as payout_routing_algorithm_id in routing and payments core for v2.
### Possible Implementation
All the places that were being fetched as `serve_json::value` must be able to accept the id instead
### Have you spent some time checking if this feature request has been raised before?
- [X] I checked and didn't find a similar issue
### Have you read the Contributing Guidelines?
- [X] I have read the [Contributing Guidelines](https://github.com/juspay/hyperswitch/blob/main/docs/CONTRIBUTING.md)
### Are you willing to submit a PR?
Yes, I am willing to submit a PR!
|
diff --git a/crates/api_models/src/events/routing.rs b/crates/api_models/src/events/routing.rs
index 4c2c5ca2c0b..9cfcafc8733 100644
--- a/crates/api_models/src/events/routing.rs
+++ b/crates/api_models/src/events/routing.rs
@@ -3,7 +3,8 @@ use common_utils::events::{ApiEventMetric, ApiEventsType};
use crate::routing::{
LinkedRoutingConfigRetrieveResponse, MerchantRoutingAlgorithm, ProfileDefaultRoutingConfig,
RoutingAlgorithmId, RoutingConfigRequest, RoutingDictionaryRecord, RoutingKind,
- RoutingLinkWrapper, RoutingPayloadWrapper, RoutingRetrieveLinkQuery, RoutingRetrieveQuery,
+ RoutingLinkWrapper, RoutingPayloadWrapper, RoutingRetrieveLinkQuery,
+ RoutingRetrieveLinkQueryWrapper, RoutingRetrieveQuery,
};
impl ApiEventMetric for RoutingKind {
@@ -70,3 +71,8 @@ impl ApiEventMetric for RoutingLinkWrapper {
Some(ApiEventsType::Routing)
}
}
+impl ApiEventMetric for RoutingRetrieveLinkQueryWrapper {
+ fn get_api_event_type(&self) -> Option<ApiEventsType> {
+ Some(ApiEventsType::Routing)
+ }
+}
diff --git a/crates/api_models/src/routing.rs b/crates/api_models/src/routing.rs
index aca7bfaebe3..04ca1fd4429 100644
--- a/crates/api_models/src/routing.rs
+++ b/crates/api_models/src/routing.rs
@@ -58,8 +58,6 @@ pub struct ProfileDefaultRoutingConfig {
pub struct RoutingRetrieveQuery {
pub limit: Option<u16>,
pub offset: Option<u8>,
-
- pub profile_id: Option<String>,
}
#[derive(Debug, serde::Deserialize, serde::Serialize)]
@@ -67,6 +65,11 @@ pub struct RoutingRetrieveLinkQuery {
pub profile_id: Option<String>,
}
+#[derive(Debug, serde::Deserialize, serde::Serialize)]
+pub struct RoutingRetrieveLinkQueryWrapper {
+ pub routing_query: RoutingRetrieveQuery,
+ pub profile_id: String,
+}
#[derive(Debug, Clone, serde::Serialize, serde::Deserialize, ToSchema)]
/// Response of the retrieved routing configs for a merchant account
pub struct RoutingRetrieveResponse {
diff --git a/crates/diesel_models/src/business_profile.rs b/crates/diesel_models/src/business_profile.rs
index b6efa7ea272..bb4aa21cda6 100644
--- a/crates/diesel_models/src/business_profile.rs
+++ b/crates/diesel_models/src/business_profile.rs
@@ -1,8 +1,8 @@
use std::collections::{HashMap, HashSet};
use common_enums::AuthenticationConnectors;
-#[cfg(all(feature = "v2", feature = "business_profile_v2"))]
-use common_enums::OrderFulfillmentTimeOrigin;
+// #[cfg(all(feature = "v2", feature = "business_profile_v2"))]
+// use common_enums::OrderFulfillmentTimeOrigin;
use common_utils::{encryption::Encryption, pii};
use diesel::{AsChangeset, Identifiable, Insertable, Queryable, Selectable};
use masking::Secret;
@@ -231,6 +231,7 @@ pub struct BusinessProfile {
pub redirect_to_merchant_with_http_post: bool,
pub webhook_details: Option<WebhookDetails>,
pub metadata: Option<pii::SecretSerdeValue>,
+ pub intent_fulfillment_time: Option<i64>,
pub is_recon_enabled: bool,
#[diesel(deserialize_as = super::OptionalDieselArray<String>)]
pub applepay_verified_domains: Option<Vec<String>>,
@@ -246,11 +247,11 @@ pub struct BusinessProfile {
pub collect_billing_details_from_wallet_connector: Option<bool>,
pub outgoing_webhook_custom_http_headers: Option<Encryption>,
pub routing_algorithm_id: Option<String>,
- pub order_fulfillment_time: Option<i64>,
- pub order_fulfillment_time_origin: Option<OrderFulfillmentTimeOrigin>,
+ // pub order_fulfillment_time: Option<i64>,
+ // pub order_fulfillment_time_origin: Option<OrderFulfillmentTimeOrigin>,
pub frm_routing_algorithm_id: Option<String>,
pub payout_routing_algorithm_id: Option<String>,
- pub default_fallback_routing: Option<pii::SecretSerdeValue>,
+ // pub default_fallback_routing: Option<pii::SecretSerdeValue>,
}
#[cfg(all(feature = "v2", feature = "business_profile_v2"))]
@@ -268,6 +269,7 @@ pub struct BusinessProfileNew {
pub redirect_to_merchant_with_http_post: bool,
pub webhook_details: Option<WebhookDetails>,
pub metadata: Option<pii::SecretSerdeValue>,
+ pub intent_fulfillment_time: Option<i64>,
pub is_recon_enabled: bool,
#[diesel(deserialize_as = super::OptionalDieselArray<String>)]
pub applepay_verified_domains: Option<Vec<String>>,
@@ -283,11 +285,11 @@ pub struct BusinessProfileNew {
pub collect_billing_details_from_wallet_connector: Option<bool>,
pub outgoing_webhook_custom_http_headers: Option<Encryption>,
pub routing_algorithm_id: Option<String>,
- pub order_fulfillment_time: Option<i64>,
- pub order_fulfillment_time_origin: Option<OrderFulfillmentTimeOrigin>,
+ // pub order_fulfillment_time: Option<i64>,
+ // pub order_fulfillment_time_origin: Option<OrderFulfillmentTimeOrigin>,
pub frm_routing_algorithm_id: Option<String>,
pub payout_routing_algorithm_id: Option<String>,
- pub default_fallback_routing: Option<pii::SecretSerdeValue>,
+ // pub default_fallback_routing: Option<pii::SecretSerdeValue>,
}
#[cfg(all(feature = "v2", feature = "business_profile_v2"))]
@@ -302,6 +304,7 @@ pub struct BusinessProfileUpdateInternal {
pub redirect_to_merchant_with_http_post: Option<bool>,
pub webhook_details: Option<WebhookDetails>,
pub metadata: Option<pii::SecretSerdeValue>,
+ pub intent_fulfillment_time: Option<i64>,
pub is_recon_enabled: Option<bool>,
#[diesel(deserialize_as = super::OptionalDieselArray<String>)]
pub applepay_verified_domains: Option<Vec<String>>,
@@ -317,11 +320,11 @@ pub struct BusinessProfileUpdateInternal {
pub collect_billing_details_from_wallet_connector: Option<bool>,
pub outgoing_webhook_custom_http_headers: Option<Encryption>,
pub routing_algorithm_id: Option<String>,
- pub order_fulfillment_time: Option<i64>,
- pub order_fulfillment_time_origin: Option<OrderFulfillmentTimeOrigin>,
+ // pub order_fulfillment_time: Option<i64>,
+ // pub order_fulfillment_time_origin: Option<OrderFulfillmentTimeOrigin>,
pub frm_routing_algorithm_id: Option<String>,
pub payout_routing_algorithm_id: Option<String>,
- pub default_fallback_routing: Option<pii::SecretSerdeValue>,
+ // pub default_fallback_routing: Option<pii::SecretSerdeValue>,
}
#[cfg(all(feature = "v2", feature = "business_profile_v2"))]
@@ -350,11 +353,12 @@ impl BusinessProfileUpdateInternal {
collect_billing_details_from_wallet_connector,
outgoing_webhook_custom_http_headers,
routing_algorithm_id,
- order_fulfillment_time,
- order_fulfillment_time_origin,
+ intent_fulfillment_time,
+ // order_fulfillment_time,
+ // order_fulfillment_time_origin,
frm_routing_algorithm_id,
payout_routing_algorithm_id,
- default_fallback_routing,
+ // default_fallback_routing,
} = self;
BusinessProfile {
profile_id: source.profile_id,
@@ -396,13 +400,14 @@ impl BusinessProfileUpdateInternal {
outgoing_webhook_custom_http_headers: outgoing_webhook_custom_http_headers
.or(source.outgoing_webhook_custom_http_headers),
routing_algorithm_id: routing_algorithm_id.or(source.routing_algorithm_id),
- order_fulfillment_time: order_fulfillment_time.or(source.order_fulfillment_time),
- order_fulfillment_time_origin: order_fulfillment_time_origin
- .or(source.order_fulfillment_time_origin),
+ intent_fulfillment_time: intent_fulfillment_time.or(source.intent_fulfillment_time),
+ // order_fulfillment_time: order_fulfillment_time.or(source.order_fulfillment_time),
+ // order_fulfillment_time_origin: order_fulfillment_time_origin
+ // .or(source.order_fulfillment_time_origin),
frm_routing_algorithm_id: frm_routing_algorithm_id.or(source.frm_routing_algorithm_id),
payout_routing_algorithm_id: payout_routing_algorithm_id
.or(source.payout_routing_algorithm_id),
- default_fallback_routing: default_fallback_routing.or(source.default_fallback_routing),
+ // default_fallback_routing: default_fallback_routing.or(source.default_fallback_routing),
}
}
}
@@ -441,11 +446,12 @@ impl From<BusinessProfileNew> for BusinessProfile {
.collect_billing_details_from_wallet_connector,
outgoing_webhook_custom_http_headers: new.outgoing_webhook_custom_http_headers,
routing_algorithm_id: new.routing_algorithm_id,
- order_fulfillment_time: new.order_fulfillment_time,
- order_fulfillment_time_origin: new.order_fulfillment_time_origin,
+ intent_fulfillment_time: new.intent_fulfillment_time,
+ // order_fulfillment_time: new.order_fulfillment_time,
+ // order_fulfillment_time_origin: new.order_fulfillment_time_origin,
frm_routing_algorithm_id: new.frm_routing_algorithm_id,
payout_routing_algorithm_id: new.payout_routing_algorithm_id,
- default_fallback_routing: new.default_fallback_routing,
+ // default_fallback_routing: new.default_fallback_routing,
}
}
}
diff --git a/crates/diesel_models/src/query/routing_algorithm.rs b/crates/diesel_models/src/query/routing_algorithm.rs
index 6598733f0e5..0f3b709d264 100644
--- a/crates/diesel_models/src/query/routing_algorithm.rs
+++ b/crates/diesel_models/src/query/routing_algorithm.rs
@@ -7,7 +7,7 @@ use crate::{
enums,
errors::DatabaseError,
query::generics,
- routing_algorithm::{RoutingAlgorithm, RoutingAlgorithmMetadata, RoutingProfileMetadata},
+ routing_algorithm::{RoutingAlgorithm, RoutingProfileMetadata},
schema::routing_algorithm::dsl,
PgPooledConn, StorageResult,
};
@@ -112,10 +112,11 @@ impl RoutingAlgorithm {
profile_id: &str,
limit: i64,
offset: i64,
- ) -> StorageResult<Vec<RoutingAlgorithmMetadata>> {
+ ) -> StorageResult<Vec<RoutingProfileMetadata>> {
Ok(Self::table()
.select((
dsl::algorithm_id,
+ dsl::profile_id,
dsl::name,
dsl::description,
dsl::kind,
@@ -127,6 +128,7 @@ impl RoutingAlgorithm {
.limit(limit)
.offset(offset)
.load_async::<(
+ String,
String,
String,
Option<String>,
@@ -141,6 +143,7 @@ impl RoutingAlgorithm {
.map(
|(
algorithm_id,
+ profile_id,
name,
description,
kind,
@@ -148,7 +151,7 @@ impl RoutingAlgorithm {
modified_at,
algorithm_for,
)| {
- RoutingAlgorithmMetadata {
+ RoutingProfileMetadata {
algorithm_id,
name,
description,
@@ -156,6 +159,7 @@ impl RoutingAlgorithm {
created_at,
modified_at,
algorithm_for,
+ profile_id,
}
},
)
diff --git a/crates/diesel_models/src/schema_v2.rs b/crates/diesel_models/src/schema_v2.rs
index 8821c7c8976..b5a4ff384ad 100644
--- a/crates/diesel_models/src/schema_v2.rs
+++ b/crates/diesel_models/src/schema_v2.rs
@@ -188,6 +188,7 @@ diesel::table! {
redirect_to_merchant_with_http_post -> Bool,
webhook_details -> Nullable<Json>,
metadata -> Nullable<Json>,
+ intent_fulfillment_time -> Nullable<Int8>,
is_recon_enabled -> Bool,
applepay_verified_domains -> Nullable<Array<Nullable<Text>>>,
payment_link_config -> Nullable<Jsonb>,
@@ -203,13 +204,10 @@ diesel::table! {
outgoing_webhook_custom_http_headers -> Nullable<Bytea>,
#[max_length = 64]
routing_algorithm_id -> Nullable<Varchar>,
- order_fulfillment_time -> Nullable<Int8>,
- order_fulfillment_time_origin -> Nullable<OrderFulfillmentTimeOrigin>,
#[max_length = 64]
frm_routing_algorithm_id -> Nullable<Varchar>,
#[max_length = 64]
payout_routing_algorithm_id -> Nullable<Varchar>,
- default_fallback_routing -> Nullable<Jsonb>,
}
}
diff --git a/crates/hyperswitch_domain_models/src/business_profile.rs b/crates/hyperswitch_domain_models/src/business_profile.rs
index 08903748c01..dcc6a88c824 100644
--- a/crates/hyperswitch_domain_models/src/business_profile.rs
+++ b/crates/hyperswitch_domain_models/src/business_profile.rs
@@ -1,5 +1,5 @@
-#[cfg(all(feature = "v2", feature = "business_profile_v2"))]
-use common_enums::OrderFulfillmentTimeOrigin;
+// #[cfg(all(feature = "v2", feature = "business_profile_v2"))]
+// use common_enums::OrderFulfillmentTimeOrigin;
use common_utils::{
crypto::OptionalEncryptableValue,
date_time,
@@ -420,6 +420,7 @@ pub struct BusinessProfile {
pub redirect_to_merchant_with_http_post: bool,
pub webhook_details: Option<WebhookDetails>,
pub metadata: Option<pii::SecretSerdeValue>,
+ pub intent_fulfillment_time: Option<i64>,
pub is_recon_enabled: bool,
pub applepay_verified_domains: Option<Vec<String>>,
pub payment_link_config: Option<BusinessPaymentLinkConfig>,
@@ -434,11 +435,11 @@ pub struct BusinessProfile {
pub collect_billing_details_from_wallet_connector: Option<bool>,
pub outgoing_webhook_custom_http_headers: OptionalEncryptableValue,
pub routing_algorithm_id: Option<String>,
- pub order_fulfillment_time: Option<i64>,
- pub order_fulfillment_time_origin: Option<OrderFulfillmentTimeOrigin>,
+ // pub order_fulfillment_time: Option<i64>,
+ // pub order_fulfillment_time_origin: Option<OrderFulfillmentTimeOrigin>,
pub frm_routing_algorithm_id: Option<String>,
pub payout_routing_algorithm_id: Option<String>,
- pub default_fallback_routing: Option<pii::SecretSerdeValue>,
+ // pub default_fallback_routing: Option<pii::SecretSerdeValue>,
}
#[cfg(all(feature = "v2", feature = "business_profile_v2"))]
@@ -451,6 +452,7 @@ pub struct BusinessProfileGeneralUpdate {
pub redirect_to_merchant_with_http_post: Option<bool>,
pub webhook_details: Option<WebhookDetails>,
pub metadata: Option<pii::SecretSerdeValue>,
+ pub intent_fulfillment_time: Option<i64>,
pub is_recon_enabled: Option<bool>,
pub applepay_verified_domains: Option<Vec<String>>,
pub payment_link_config: Option<BusinessPaymentLinkConfig>,
@@ -464,11 +466,11 @@ pub struct BusinessProfileGeneralUpdate {
pub is_connector_agnostic_mit_enabled: Option<bool>,
pub outgoing_webhook_custom_http_headers: OptionalEncryptableValue,
pub routing_algorithm_id: Option<String>,
- pub order_fulfillment_time: Option<i64>,
- pub order_fulfillment_time_origin: Option<OrderFulfillmentTimeOrigin>,
+ // pub order_fulfillment_time: Option<i64>,
+ // pub order_fulfillment_time_origin: Option<OrderFulfillmentTimeOrigin>,
pub frm_routing_algorithm_id: Option<String>,
pub payout_routing_algorithm_id: Option<String>,
- pub default_fallback_routing: Option<pii::SecretSerdeValue>,
+ // pub default_fallback_routing: Option<pii::SecretSerdeValue>,
}
#[cfg(all(feature = "v2", feature = "business_profile_v2"))]
@@ -502,6 +504,7 @@ impl From<BusinessProfileUpdate> for BusinessProfileUpdateInternal {
redirect_to_merchant_with_http_post,
webhook_details,
metadata,
+ intent_fulfillment_time,
is_recon_enabled,
applepay_verified_domains,
payment_link_config,
@@ -515,11 +518,11 @@ impl From<BusinessProfileUpdate> for BusinessProfileUpdateInternal {
is_connector_agnostic_mit_enabled,
outgoing_webhook_custom_http_headers,
routing_algorithm_id,
- order_fulfillment_time,
- order_fulfillment_time_origin,
+ // order_fulfillment_time,
+ // order_fulfillment_time_origin,
frm_routing_algorithm_id,
payout_routing_algorithm_id,
- default_fallback_routing,
+ // default_fallback_routing,
} = *update;
Self {
profile_name,
@@ -530,6 +533,7 @@ impl From<BusinessProfileUpdate> for BusinessProfileUpdateInternal {
redirect_to_merchant_with_http_post,
webhook_details,
metadata,
+ intent_fulfillment_time,
is_recon_enabled,
applepay_verified_domains,
payment_link_config,
@@ -545,11 +549,11 @@ impl From<BusinessProfileUpdate> for BusinessProfileUpdateInternal {
outgoing_webhook_custom_http_headers: outgoing_webhook_custom_http_headers
.map(Encryption::from),
routing_algorithm_id,
- order_fulfillment_time,
- order_fulfillment_time_origin,
+ // order_fulfillment_time,
+ // order_fulfillment_time_origin,
frm_routing_algorithm_id,
payout_routing_algorithm_id,
- default_fallback_routing,
+ // default_fallback_routing,
}
}
BusinessProfileUpdate::RoutingAlgorithmUpdate {
@@ -578,11 +582,12 @@ impl From<BusinessProfileUpdate> for BusinessProfileUpdateInternal {
collect_billing_details_from_wallet_connector: None,
outgoing_webhook_custom_http_headers: None,
routing_algorithm_id,
- order_fulfillment_time: None,
- order_fulfillment_time_origin: None,
+ intent_fulfillment_time: None,
+ // order_fulfillment_time: None,
+ // order_fulfillment_time_origin: None,
frm_routing_algorithm_id: None,
payout_routing_algorithm_id,
- default_fallback_routing: None,
+ // default_fallback_routing: None,
},
BusinessProfileUpdate::ExtendedCardInfoUpdate {
is_extended_card_info_enabled,
@@ -609,11 +614,12 @@ impl From<BusinessProfileUpdate> for BusinessProfileUpdateInternal {
collect_billing_details_from_wallet_connector: None,
outgoing_webhook_custom_http_headers: None,
routing_algorithm_id: None,
- order_fulfillment_time: None,
- order_fulfillment_time_origin: None,
- frm_routing_algorithm_id: None,
payout_routing_algorithm_id: None,
- default_fallback_routing: None,
+ intent_fulfillment_time: None,
+ // order_fulfillment_time: None,
+ // order_fulfillment_time_origin: None,
+ frm_routing_algorithm_id: None,
+ // default_fallback_routing: None,
},
BusinessProfileUpdate::ConnectorAgnosticMitUpdate {
is_connector_agnostic_mit_enabled,
@@ -640,11 +646,12 @@ impl From<BusinessProfileUpdate> for BusinessProfileUpdateInternal {
collect_billing_details_from_wallet_connector: None,
outgoing_webhook_custom_http_headers: None,
routing_algorithm_id: None,
- order_fulfillment_time: None,
- order_fulfillment_time_origin: None,
- frm_routing_algorithm_id: None,
payout_routing_algorithm_id: None,
- default_fallback_routing: None,
+ intent_fulfillment_time: None,
+ // order_fulfillment_time: None,
+ // order_fulfillment_time_origin: None,
+ frm_routing_algorithm_id: None,
+ // default_fallback_routing: None,
},
}
}
@@ -687,11 +694,12 @@ impl super::behaviour::Conversion for BusinessProfile {
.outgoing_webhook_custom_http_headers
.map(Encryption::from),
routing_algorithm_id: self.routing_algorithm_id,
- order_fulfillment_time: self.order_fulfillment_time,
- order_fulfillment_time_origin: self.order_fulfillment_time_origin,
- frm_routing_algorithm_id: self.frm_routing_algorithm_id,
payout_routing_algorithm_id: self.payout_routing_algorithm_id,
- default_fallback_routing: self.default_fallback_routing,
+ intent_fulfillment_time: self.intent_fulfillment_time,
+ // order_fulfillment_time: self.order_fulfillment_time,
+ // order_fulfillment_time_origin: self.order_fulfillment_time_origin,
+ frm_routing_algorithm_id: self.frm_routing_algorithm_id,
+ // default_fallback_routing: self.default_fallback_routing,
})
}
@@ -746,11 +754,13 @@ impl super::behaviour::Conversion for BusinessProfile {
})
.await?,
routing_algorithm_id: item.routing_algorithm_id,
- order_fulfillment_time: item.order_fulfillment_time,
- order_fulfillment_time_origin: item.order_fulfillment_time_origin,
+
+ intent_fulfillment_time: item.intent_fulfillment_time,
+ // order_fulfillment_time: item.order_fulfillment_time,
+ // order_fulfillment_time_origin: item.order_fulfillment_time_origin,
frm_routing_algorithm_id: item.frm_routing_algorithm_id,
payout_routing_algorithm_id: item.payout_routing_algorithm_id,
- default_fallback_routing: item.default_fallback_routing,
+ // default_fallback_routing: item.default_fallback_routing,
})
}
.await
@@ -790,11 +800,12 @@ impl super::behaviour::Conversion for BusinessProfile {
.outgoing_webhook_custom_http_headers
.map(Encryption::from),
routing_algorithm_id: self.routing_algorithm_id,
- order_fulfillment_time: self.order_fulfillment_time,
- order_fulfillment_time_origin: self.order_fulfillment_time_origin,
+ intent_fulfillment_time: self.intent_fulfillment_time,
+ // order_fulfillment_time: self.order_fulfillment_time,
+ // order_fulfillment_time_origin: self.order_fulfillment_time_origin,
frm_routing_algorithm_id: self.frm_routing_algorithm_id,
payout_routing_algorithm_id: self.payout_routing_algorithm_id,
- default_fallback_routing: self.default_fallback_routing,
+ // default_fallback_routing: self.default_fallback_routing,
})
}
}
diff --git a/crates/router/Cargo.toml b/crates/router/Cargo.toml
index 3e0470cc08d..01568aa8518 100644
--- a/crates/router/Cargo.toml
+++ b/crates/router/Cargo.toml
@@ -33,7 +33,7 @@ recon = ["email", "api_models/recon"]
retry = []
v2 = ["api_models/v2", "diesel_models/v2", "hyperswitch_domain_models/v2", "storage_impl/v2", "kgraph_utils/v2"]
v1 = ["api_models/v1", "diesel_models/v1", "hyperswitch_domain_models/v1", "storage_impl/v1", "hyperswitch_interfaces/v1", "kgraph_utils/v1"]
-# business_profile_v2 = ["api_models/business_profile_v2", "diesel_models/business_profile_v2", "hyperswitch_domain_models/business_profile_v2"]
+business_profile_v2 = ["api_models/business_profile_v2", "diesel_models/business_profile_v2", "hyperswitch_domain_models/business_profile_v2"]
customer_v2 = ["api_models/customer_v2", "diesel_models/customer_v2", "hyperswitch_domain_models/customer_v2", "storage_impl/customer_v2"]
merchant_account_v2 = ["api_models/merchant_account_v2", "diesel_models/merchant_account_v2", "hyperswitch_domain_models/merchant_account_v2"]
payment_v2 = ["api_models/payment_v2", "diesel_models/payment_v2", "hyperswitch_domain_models/payment_v2"]
diff --git a/crates/router/src/core/admin.rs b/crates/router/src/core/admin.rs
index 5c800a0dc24..2b3360f35da 100644
--- a/crates/router/src/core/admin.rs
+++ b/crates/router/src/core/admin.rs
@@ -21,6 +21,12 @@ use regex::Regex;
use router_env::metrics::add_attributes;
use uuid::Uuid;
+#[cfg(all(
+ feature = "v2",
+ feature = "routing_v2",
+ feature = "business_profile_v2"
+))]
+use crate::core::routing;
#[cfg(any(feature = "v1", feature = "v2"))]
use crate::types::transformers::ForeignFrom;
use crate::{
@@ -28,10 +34,7 @@ use crate::{
core::{
encryption::transfer_encryption_key,
errors::{self, RouterResponse, RouterResult, StorageErrorExt},
- payment_methods::{
- cards::{self, create_encrypted_data},
- transformers,
- },
+ payment_methods::{cards, transformers},
payments::helpers,
pm_auth::helpers::PaymentAuthConnectorDataExt,
routing::helpers as routing_helpers,
@@ -52,7 +55,6 @@ use crate::{
},
utils,
};
-
const IBAN_MAX_LENGTH: usize = 34;
const BACS_SORT_CODE_LENGTH: usize = 6;
const BACS_MAX_ACCOUNT_NUMBER_LENGTH: usize = 8;
@@ -3311,7 +3313,7 @@ pub async fn create_and_insert_business_profile(
#[cfg(all(
any(feature = "v1", feature = "v2"),
- not(feature = "merchant_account_v2")
+ not(any(feature = "merchant_account_v2", feature = "business_profile_v2"))
))]
pub async fn create_business_profile(
state: SessionState,
@@ -3377,7 +3379,11 @@ pub async fn create_business_profile(
))
}
-#[cfg(all(feature = "v2", feature = "merchant_account_v2"))]
+#[cfg(all(
+ feature = "v2",
+ feature = "merchant_account_v2",
+ feature = "business_profile_v2"
+))]
pub async fn create_business_profile(
_state: SessionState,
_request: api::BusinessProfileCreate,
@@ -3460,6 +3466,10 @@ pub async fn delete_business_profile(
Ok(service_api::ApplicationResponse::Json(delete_result))
}
+#[cfg(all(
+ any(feature = "v1", feature = "v2"),
+ not(feature = "business_profile_v2")
+))]
pub async fn update_business_profile(
state: SessionState,
profile_id: &str,
@@ -3535,7 +3545,7 @@ pub async fn update_business_profile(
.map(Secret::new);
let outgoing_webhook_custom_http_headers = request
.outgoing_webhook_custom_http_headers
- .async_map(|headers| create_encrypted_data(&state, &key_store, headers))
+ .async_map(|headers| cards::create_encrypted_data(&state, &key_store, headers))
.await
.transpose()
.change_context(errors::ApiErrorResponse::InternalServerError)
@@ -3604,6 +3614,111 @@ pub async fn update_business_profile(
.attach_printable("Failed to parse business profile details")?,
))
}
+#[cfg(all(feature = "v2", feature = "business_profile_v2"))]
+pub async fn update_business_profile(
+ _state: SessionState,
+ _profile_id: &str,
+ _merchant_id: &id_type::MerchantId,
+ _request: api::BusinessProfileUpdate,
+) -> RouterResponse<api::BusinessProfileResponse> {
+ todo!()
+}
+#[cfg(all(
+ feature = "v2",
+ feature = "routing_v2",
+ feature = "business_profile_v2"
+))]
+#[derive(Clone, Debug)]
+pub struct BusinessProfileWrapper {
+ pub profile: domain::BusinessProfile,
+}
+
+#[cfg(all(
+ feature = "v2",
+ feature = "routing_v2",
+ feature = "business_profile_v2"
+))]
+impl BusinessProfileWrapper {
+ pub fn new(profile: domain::BusinessProfile) -> Self {
+ Self { profile }
+ }
+ fn get_routing_config_cache_key(self) -> storage_impl::redis::cache::CacheKind<'static> {
+ let merchant_id = self.profile.merchant_id.clone();
+
+ let profile_id = self.profile.profile_id.clone();
+
+ storage_impl::redis::cache::CacheKind::Routing(
+ format!(
+ "routing_config_{}_{profile_id}",
+ merchant_id.get_string_repr()
+ )
+ .into(),
+ )
+ }
+
+ pub async fn update_business_profile_and_invalidate_routing_config_for_active_algorithm_id_update(
+ self,
+ db: &dyn StorageInterface,
+ key_manager_state: &KeyManagerState,
+ merchant_key_store: &domain::MerchantKeyStore,
+ algorithm_id: String,
+ transaction_type: &storage::enums::TransactionType,
+ ) -> RouterResult<()> {
+ let routing_cache_key = self.clone().get_routing_config_cache_key();
+
+ let (routing_algorithm_id, payout_routing_algorithm_id) = match transaction_type {
+ storage::enums::TransactionType::Payment => (Some(algorithm_id), None),
+ #[cfg(feature = "payouts")]
+ storage::enums::TransactionType::Payout => (None, Some(algorithm_id)),
+ };
+
+ let business_profile_update = domain::BusinessProfileUpdate::RoutingAlgorithmUpdate {
+ routing_algorithm_id,
+ payout_routing_algorithm_id,
+ };
+
+ let profile = self.profile;
+
+ db.update_business_profile_by_profile_id(
+ key_manager_state,
+ merchant_key_store,
+ profile,
+ business_profile_update,
+ )
+ .await
+ .change_context(errors::ApiErrorResponse::InternalServerError)
+ .attach_printable("Failed to update routing algorithm ref in business profile")?;
+
+ storage_impl::redis::cache::publish_into_redact_channel(
+ db.get_cache_store().as_ref(),
+ [routing_cache_key],
+ )
+ .await
+ .change_context(errors::ApiErrorResponse::InternalServerError)
+ .attach_printable("Failed to invalidate routing cache")?;
+ Ok(())
+ }
+
+ pub fn get_profile_id_and_routing_algorithm_id<F>(
+ &self,
+ transaction_data: &routing::TransactionData<'_, F>,
+ ) -> (Option<String>, Option<String>)
+ where
+ F: Send + Clone,
+ {
+ match transaction_data {
+ routing::TransactionData::Payment(payment_data) => (
+ payment_data.payment_intent.profile_id.clone(),
+ self.profile.routing_algorithm_id.clone(),
+ ),
+ #[cfg(feature = "payouts")]
+ routing::TransactionData::Payout(payout_data) => (
+ Some(payout_data.payout_attempt.profile_id.clone()),
+ self.profile.payout_routing_algorithm_id.clone(),
+ ),
+ }
+ }
+}
pub async fn extended_card_info_toggle(
state: SessionState,
diff --git a/crates/router/src/core/payment_methods/cards.rs b/crates/router/src/core/payment_methods/cards.rs
index 145f8d63f83..db731848dbb 100644
--- a/crates/router/src/core/payment_methods/cards.rs
+++ b/crates/router/src/core/payment_methods/cards.rs
@@ -3305,15 +3305,9 @@ pub async fn call_surcharge_decision_management(
.attach_printable("Could not decode the routing algorithm")?
.unwrap_or_default();
+ // TODO: Move to business profile surcharge decision column
#[cfg(all(feature = "v2", feature = "merchant_account_v2"))]
- let algorithm_ref: routing_types::RoutingAlgorithmRef = business_profile
- .routing_algorithm
- .clone()
- .map(|val| val.parse_value("routing algorithm"))
- .transpose()
- .change_context(errors::ApiErrorResponse::InternalServerError)
- .attach_printable("Could not decode the routing algorithm")?
- .unwrap_or_default();
+ let algorithm_ref: routing_types::RoutingAlgorithmRef = todo!();
let (surcharge_results, merchant_sucharge_configs) =
perform_surcharge_decision_management_for_payment_method_list(
@@ -3371,16 +3365,9 @@ pub async fn call_surcharge_decision_management_for_saved_card(
.change_context(errors::ApiErrorResponse::InternalServerError)
.attach_printable("Could not decode the routing algorithm")?
.unwrap_or_default();
-
+ // TODO: Move to business profile surcharge column
#[cfg(all(feature = "v2", feature = "merchant_account_v2"))]
- let algorithm_ref: routing_types::RoutingAlgorithmRef = business_profile
- .routing_algorithm
- .clone()
- .map(|val| val.parse_value("routing algorithm"))
- .transpose()
- .change_context(errors::ApiErrorResponse::InternalServerError)
- .attach_printable("Could not decode the routing algorithm")?
- .unwrap_or_default();
+ let algorithm_ref: routing_types::RoutingAlgorithmRef = todo!();
let surcharge_results = perform_surcharge_decision_management_for_saved_cards(
state,
diff --git a/crates/router/src/core/payments.rs b/crates/router/src/core/payments.rs
index 6b8c19925ee..60a5581d39b 100644
--- a/crates/router/src/core/payments.rs
+++ b/crates/router/src/core/payments.rs
@@ -647,15 +647,9 @@ where
.attach_printable("Could not decode the routing algorithm")?
.unwrap_or_default();
+ // TODO: Move to business profile surcharge column
#[cfg(all(feature = "v2", feature = "merchant_account_v2"))]
- let algorithm_ref: api::routing::RoutingAlgorithmRef = _business_profile
- .routing_algorithm
- .clone()
- .map(|val| val.parse_value("routing algorithm"))
- .transpose()
- .change_context(errors::ApiErrorResponse::InternalServerError)
- .attach_printable("Could not decode the routing algorithm")?
- .unwrap_or_default();
+ let algorithm_ref: api::routing::RoutingAlgorithmRef = todo!();
let output = perform_decision_management(
state,
@@ -800,15 +794,9 @@ where
.attach_printable("Could not decode the routing algorithm")?
.unwrap_or_default();
+ // TODO: Move to business profile surcharge column
#[cfg(all(feature = "v2", feature = "merchant_account_v2"))]
- let algorithm_ref: api::routing::RoutingAlgorithmRef = _business_profile
- .routing_algorithm
- .clone()
- .map(|val| val.parse_value("routing algorithm"))
- .transpose()
- .change_context(errors::ApiErrorResponse::InternalServerError)
- .attach_printable("Could not decode the routing algorithm")?
- .unwrap_or_default();
+ let algorithm_ref: api::routing::RoutingAlgorithmRef = todo!();
let surcharge_results =
surcharge_decision_configs::perform_surcharge_decision_management_for_session_flow(
@@ -3953,7 +3941,11 @@ where
Ok(final_list)
}
-#[allow(clippy::too_many_arguments)]
+#[cfg(all(
+ feature = "v2",
+ feature = "routing_v2",
+ feature = "business_profile_v2"
+))]
pub async fn route_connector_v1<F>(
state: &SessionState,
merchant_account: &domain::MerchantAccount,
@@ -3967,35 +3959,124 @@ pub async fn route_connector_v1<F>(
where
F: Send + Clone,
{
- #[allow(unused_variables)]
- let (profile_id, routing_algorithm) = match &transaction_data {
- TransactionData::Payment(payment_data) => (
- payment_data.payment_intent.profile_id.clone(),
- business_profile.routing_algorithm.clone(),
- ),
- #[cfg(feature = "payouts")]
- TransactionData::Payout(payout_data) => (
- Some(payout_data.payout_attempt.profile_id.clone()),
- business_profile.payout_routing_algorithm.clone(),
- ),
- };
+ let (profile_id, routing_algorithm_id) =
+ super::admin::BusinessProfileWrapper::new(business_profile.clone())
+ .get_profile_id_and_routing_algorithm_id(&transaction_data);
- let algorithm_ref = routing_algorithm
- .map(|ra| ra.parse_value::<api::routing::RoutingAlgorithmRef>("RoutingAlgorithmRef"))
- .transpose()
+ let connectors = routing::perform_static_routing_v1(
+ state,
+ merchant_account.get_id(),
+ routing_algorithm_id,
+ &transaction_data,
+ )
+ .await
+ .change_context(errors::ApiErrorResponse::InternalServerError)?;
+
+ let connectors = routing::perform_eligibility_analysis_with_fallback(
+ &state.clone(),
+ key_store,
+ connectors,
+ &transaction_data,
+ eligible_connectors,
+ profile_id,
+ )
+ .await
+ .change_context(errors::ApiErrorResponse::InternalServerError)
+ .attach_printable("failed eligibility analysis and fallback")?;
+
+ #[cfg(feature = "payouts")]
+ let first_connector_choice = connectors
+ .first()
+ .ok_or(errors::ApiErrorResponse::IncorrectPaymentMethodConfiguration)
+ .attach_printable("Empty connector list returned")?
+ .clone();
+
+ let connector_data = connectors
+ .into_iter()
+ .map(|conn| {
+ api::ConnectorData::get_connector_by_name(
+ &state.conf.connectors,
+ &conn.connector.to_string(),
+ api::GetToken::Connector,
+ conn.merchant_connector_id,
+ )
+ })
+ .collect::<CustomResult<Vec<_>, _>>()
.change_context(errors::ApiErrorResponse::InternalServerError)
- .attach_printable("Could not decode merchant routing algorithm ref")?
- .unwrap_or_default();
+ .attach_printable("Invalid connector name received")?;
+
+ match transaction_data {
+ TransactionData::Payment(payment_data) => {
+ decide_multiplex_connector_for_normal_or_recurring_payment(
+ state,
+ payment_data,
+ routing_data,
+ connector_data,
+ mandate_type,
+ business_profile.is_connector_agnostic_mit_enabled.clone(),
+ )
+ .await
+ }
+
+ #[cfg(feature = "payouts")]
+ TransactionData::Payout(_) => {
+ routing_data.routed_through = Some(first_connector_choice.connector.to_string());
+
+ routing_data.merchant_connector_id = first_connector_choice.merchant_connector_id;
+
+ Ok(ConnectorCallType::Retryable(connector_data))
+ }
+ }
+}
+
+#[cfg(all(
+ any(feature = "v1", feature = "v2"),
+ not(any(feature = "routing_v2", feature = "business_profile_v2"))
+))]
+#[allow(clippy::too_many_arguments)]
+pub async fn route_connector_v1<F>(
+ state: &SessionState,
+ merchant_account: &domain::MerchantAccount,
+ business_profile: &domain::BusinessProfile,
+ key_store: &domain::MerchantKeyStore,
+ transaction_data: TransactionData<'_, F>,
+ routing_data: &mut storage::RoutingData,
+ eligible_connectors: Option<Vec<enums::RoutableConnectors>>,
+ mandate_type: Option<api::MandateTransactionType>,
+) -> RouterResult<ConnectorCallType>
+where
+ F: Send + Clone,
+{
+ let (profile_id, routing_algorithm_id) = {
+ let (profile_id, routing_algorithm) = match &transaction_data {
+ TransactionData::Payment(payment_data) => (
+ payment_data.payment_intent.profile_id.clone(),
+ business_profile.routing_algorithm.clone(),
+ ),
+ #[cfg(feature = "payouts")]
+ TransactionData::Payout(payout_data) => (
+ Some(payout_data.payout_attempt.profile_id.clone()),
+ business_profile.payout_routing_algorithm.clone(),
+ ),
+ };
+
+ let algorithm_ref = routing_algorithm
+ .map(|ra| ra.parse_value::<api::routing::RoutingAlgorithmRef>("RoutingAlgorithmRef"))
+ .transpose()
+ .change_context(errors::ApiErrorResponse::InternalServerError)
+ .attach_printable("Could not decode merchant routing algorithm ref")?
+ .unwrap_or_default();
+ (profile_id, algorithm_ref.algorithm_id)
+ };
let connectors = routing::perform_static_routing_v1(
state,
merchant_account.get_id(),
- algorithm_ref,
+ routing_algorithm_id,
&transaction_data,
)
.await
.change_context(errors::ApiErrorResponse::InternalServerError)?;
-
let connectors = routing::perform_eligibility_analysis_with_fallback(
&state.clone(),
key_store,
diff --git a/crates/router/src/core/payments/routing.rs b/crates/router/src/core/payments/routing.rs
index a989e30d8ea..c029e2d289c 100644
--- a/crates/router/src/core/payments/routing.rs
+++ b/crates/router/src/core/payments/routing.rs
@@ -80,18 +80,37 @@ pub struct SessionRoutingPmTypeInput<'a> {
type RoutingResult<O> = oss_errors::CustomResult<O, errors::RoutingError>;
+#[cfg(all(
+ any(feature = "v1", feature = "v2"),
+ not(any(feature = "routing_v2", feature = "business_profile_v2"))
+))]
#[derive(Debug, serde::Serialize, serde::Deserialize)]
#[serde(untagged)]
enum MerchantAccountRoutingAlgorithm {
V1(routing_types::RoutingAlgorithmRef),
}
+#[cfg(all(
+ any(feature = "v1", feature = "v2"),
+ not(any(feature = "routing_v2", feature = "business_profile_v2"))
+))]
impl Default for MerchantAccountRoutingAlgorithm {
fn default() -> Self {
Self::V1(routing_types::RoutingAlgorithmRef::default())
}
}
+#[cfg(all(
+ feature = "v2",
+ feature = "routing_v2",
+ feature = "business_profile_v2"
+))]
+#[derive(Debug, serde::Serialize, serde::Deserialize)]
+#[serde(untagged)]
+enum MerchantAccountRoutingAlgorithm {
+ V1(Option<String>),
+}
+
#[cfg(feature = "payouts")]
pub fn make_dsl_input_for_payouts(
payout_data: &payouts::PayoutData,
@@ -253,7 +272,7 @@ where
pub async fn perform_static_routing_v1<F: Clone>(
state: &SessionState,
merchant_id: &common_utils::id_type::MerchantId,
- algorithm_ref: routing_types::RoutingAlgorithmRef,
+ algorithm_id: Option<String>,
transaction_data: &routing::TransactionData<'_, F>,
) -> RoutingResult<Vec<routing_types::RoutableConnectorChoice>> {
let profile_id = match transaction_data {
@@ -266,7 +285,7 @@ pub async fn perform_static_routing_v1<F: Clone>(
#[cfg(feature = "payouts")]
routing::TransactionData::Payout(payout_data) => &payout_data.payout_attempt.profile_id,
};
- let algorithm_id = if let Some(id) = algorithm_ref.algorithm_id {
+ let algorithm_id = if let Some(id) = algorithm_id {
id
} else {
let fallback_config = routing_helpers::get_merchant_default_config(
@@ -789,26 +808,36 @@ pub async fn perform_session_flow_routing(
{
let mut pm_type_map: FxHashMap<api_enums::PaymentMethodType, FxHashMap<String, api::GetToken>> =
FxHashMap::default();
+ let profile_id = session_input
+ .payment_intent
+ .profile_id
+ .clone()
+ .get_required_value("profile_id")
+ .change_context(errors::RoutingError::ProfileIdMissing)?;
+ let business_profile = session_input
+ .state
+ .store
+ .find_business_profile_by_profile_id(
+ &session_input.state.into(),
+ session_input.key_store,
+ &profile_id,
+ )
+ .await
+ .change_context(errors::RoutingError::ProfileNotFound)?;
+ #[cfg(all(
+ feature = "v2",
+ feature = "routing_v2",
+ feature = "business_profile_v2"
+ ))]
+ let routing_algorithm =
+ MerchantAccountRoutingAlgorithm::V1(business_profile.routing_algorithm_id);
+
+ #[cfg(all(
+ any(feature = "v1", feature = "v2"),
+ not(any(feature = "routing_v2", feature = "business_profile_v2"))
+ ))]
let routing_algorithm: MerchantAccountRoutingAlgorithm = {
- let profile_id = session_input
- .payment_intent
- .profile_id
- .clone()
- .get_required_value("profile_id")
- .change_context(errors::RoutingError::ProfileIdMissing)?;
-
- let business_profile = session_input
- .state
- .store
- .find_business_profile_by_profile_id(
- &session_input.state.into(),
- session_input.key_store,
- &profile_id,
- )
- .await
- .change_context(errors::RoutingError::ProfileNotFound)?;
-
business_profile
.routing_algorithm
.clone()
@@ -940,45 +969,56 @@ async fn perform_session_routing_for_pm_type(
transaction_type: &api_enums::TransactionType,
) -> RoutingResult<Option<Vec<api_models::routing::RoutableConnectorChoice>>> {
let merchant_id = &session_pm_input.key_store.merchant_id;
+ #[cfg(all(
+ any(feature = "v1", feature = "v2"),
+ not(any(feature = "routing_v2", feature = "business_profile_v2"))
+ ))]
+ let algorithm_id = match session_pm_input.routing_algorithm {
+ MerchantAccountRoutingAlgorithm::V1(algorithm_ref) => &algorithm_ref.algorithm_id,
+ };
+ #[cfg(all(
+ feature = "v2",
+ feature = "routing_v2",
+ feature = "business_profile_v2"
+ ))]
+ let algorithm_id = match session_pm_input.routing_algorithm {
+ MerchantAccountRoutingAlgorithm::V1(algorithm_id) => algorithm_id,
+ };
- let chosen_connectors = match session_pm_input.routing_algorithm {
- MerchantAccountRoutingAlgorithm::V1(algorithm_ref) => {
- if let Some(ref algorithm_id) = algorithm_ref.algorithm_id {
- let cached_algorithm = ensure_algorithm_cached_v1(
- &session_pm_input.state.clone(),
- merchant_id,
- algorithm_id,
- session_pm_input.profile_id.clone(),
- transaction_type,
- )
- .await?;
-
- match cached_algorithm.as_ref() {
- CachedAlgorithm::Single(conn) => vec![(**conn).clone()],
- CachedAlgorithm::Priority(plist) => plist.clone(),
- CachedAlgorithm::VolumeSplit(splits) => {
- perform_volume_split(splits.to_vec(), Some(session_pm_input.attempt_id))
- .change_context(errors::RoutingError::ConnectorSelectionFailed)?
- }
- CachedAlgorithm::Advanced(interpreter) => execute_dsl_and_get_connector_v1(
- session_pm_input.backend_input.clone(),
- interpreter,
- )?,
- }
- } else {
- routing_helpers::get_merchant_default_config(
- &*session_pm_input.state.clone().store,
- session_pm_input
- .profile_id
- .as_ref()
- .get_required_value("profile_id")
- .change_context(errors::RoutingError::ProfileIdMissing)?,
- transaction_type,
- )
- .await
- .change_context(errors::RoutingError::FallbackConfigFetchFailed)?
+ let chosen_connectors = if let Some(ref algorithm_id) = algorithm_id {
+ let cached_algorithm = ensure_algorithm_cached_v1(
+ &session_pm_input.state.clone(),
+ merchant_id,
+ algorithm_id,
+ session_pm_input.profile_id.clone(),
+ transaction_type,
+ )
+ .await?;
+
+ match cached_algorithm.as_ref() {
+ CachedAlgorithm::Single(conn) => vec![(**conn).clone()],
+ CachedAlgorithm::Priority(plist) => plist.clone(),
+ CachedAlgorithm::VolumeSplit(splits) => {
+ perform_volume_split(splits.to_vec(), Some(session_pm_input.attempt_id))
+ .change_context(errors::RoutingError::ConnectorSelectionFailed)?
}
+ CachedAlgorithm::Advanced(interpreter) => execute_dsl_and_get_connector_v1(
+ session_pm_input.backend_input.clone(),
+ interpreter,
+ )?,
}
+ } else {
+ routing_helpers::get_merchant_default_config(
+ &*session_pm_input.state.clone().store,
+ session_pm_input
+ .profile_id
+ .as_ref()
+ .get_required_value("profile_id")
+ .change_context(errors::RoutingError::ProfileIdMissing)?,
+ transaction_type,
+ )
+ .await
+ .change_context(errors::RoutingError::FallbackConfigFetchFailed)?
};
let mut final_selection = perform_cgraph_filtering(
diff --git a/crates/router/src/core/routing.rs b/crates/router/src/core/routing.rs
index 3992438a747..9d819f8df9f 100644
--- a/crates/router/src/core/routing.rs
+++ b/crates/router/src/core/routing.rs
@@ -1,21 +1,19 @@
pub mod helpers;
pub mod transformers;
-#[cfg(all(feature = "v2", feature = "routing_v2"))]
-use api_models::routing::RoutingConfigRequest;
use api_models::{
enums,
- routing::{self as routing_types, RoutingRetrieveLinkQuery, RoutingRetrieveQuery},
+ routing::{self as routing_types, RoutingRetrieveQuery},
};
use diesel_models::routing_algorithm::RoutingAlgorithm;
use error_stack::ResultExt;
-#[cfg(all(feature = "v2", feature = "routing_v2"))]
-use masking::Secret;
use rustc_hash::FxHashSet;
use super::payments;
#[cfg(feature = "payouts")]
use super::payouts;
+#[cfg(all(any(feature = "v1", feature = "v2"), not(feature = "routing_v2")))]
+use crate::utils::ValueExt;
use crate::{
consts,
core::{
@@ -28,10 +26,13 @@ use crate::{
domain,
transformers::{ForeignInto, ForeignTryFrom},
},
- utils::{self, OptionExt, ValueExt},
+ utils::{self, OptionExt},
};
#[cfg(all(feature = "v2", feature = "routing_v2"))]
-use crate::{core::errors::RouterResult, db::StorageInterface};
+use crate::{
+ core::{admin, errors::RouterResult},
+ db::StorageInterface,
+};
pub enum TransactionData<'a, F>
where
F: Clone,
@@ -47,7 +48,7 @@ struct RoutingAlgorithmUpdate(RoutingAlgorithm);
#[cfg(all(feature = "v2", feature = "routing_v2"))]
impl RoutingAlgorithmUpdate {
pub fn create_new_routing_algorithm(
- request: &RoutingConfigRequest,
+ request: &routing_types::RoutingConfigRequest,
merchant_id: &common_utils::id_type::MerchantId,
profile_id: String,
transaction_type: &enums::TransactionType,
@@ -82,32 +83,6 @@ impl RoutingAlgorithmUpdate {
.change_context(errors::ApiErrorResponse::ResourceIdNotFound)?;
Ok(Self(routing_algo))
}
-
- pub fn update_routing_ref_with_algorithm_id(
- &self,
- transaction_type: &enums::TransactionType,
- routing_ref: &mut routing_types::RoutingAlgorithmRef,
- ) -> RouterResult<()> {
- utils::when(self.0.algorithm_for != *transaction_type, || {
- Err(errors::ApiErrorResponse::PreconditionFailed {
- message: format!(
- "Cannot use {}'s routing algorithm for {} operation",
- self.0.algorithm_for, transaction_type
- ),
- })
- })?;
-
- utils::when(
- routing_ref.algorithm_id == Some(self.0.algorithm_id.clone()),
- || {
- Err(errors::ApiErrorResponse::PreconditionFailed {
- message: "Algorithm is already active".to_string(),
- })
- },
- )?;
- routing_ref.update_algorithm_id(self.0.algorithm_id.clone());
- Ok(())
- }
}
pub async fn retrieve_merchant_routing_dictionary(
@@ -140,11 +115,11 @@ pub async fn retrieve_merchant_routing_dictionary(
}
#[cfg(all(feature = "v2", feature = "routing_v2"))]
-pub async fn create_routing_config(
+pub async fn create_routing_algorithm_under_profile(
state: SessionState,
merchant_account: domain::MerchantAccount,
key_store: domain::MerchantKeyStore,
- request: RoutingConfigRequest,
+ request: routing_types::RoutingConfigRequest,
transaction_type: &enums::TransactionType,
) -> RouterResponse<routing_types::RoutingDictionaryRecord> {
metrics::ROUTING_CREATE_REQUEST_RECEIVED.add(&metrics::CONTEXT, 1, &[]);
@@ -170,7 +145,7 @@ pub async fn create_routing_config(
let name_mca_id_set = helpers::ConnectNameAndMCAIdForProfile(
all_mcas.filter_by_profile(&business_profile.profile_id, |mca| {
- (&mca.connector_name, &mca.id)
+ (&mca.connector_name, mca.get_id())
}),
);
@@ -207,7 +182,7 @@ pub async fn create_routing_config(
}
#[cfg(all(any(feature = "v1", feature = "v2"), not(feature = "routing_v2")))]
-pub async fn create_routing_config(
+pub async fn create_routing_algorithm_under_profile(
state: SessionState,
merchant_account: domain::MerchantAccount,
key_store: domain::MerchantKeyStore,
@@ -295,8 +270,12 @@ pub async fn create_routing_config(
Ok(service_api::ApplicationResponse::Json(new_record))
}
-#[cfg(all(feature = "v2", feature = "routing_v2"))]
-pub async fn link_routing_config(
+#[cfg(all(
+ feature = "v2",
+ feature = "routing_v2",
+ feature = "business_profile_v2"
+))]
+pub async fn link_routing_config_under_profile(
state: SessionState,
merchant_account: domain::MerchantAccount,
key_store: domain::MerchantKeyStore,
@@ -328,31 +307,47 @@ pub async fn link_routing_config(
.await?
.get_required_value("BusinessProfile")?;
- let mut routing_ref = routing_types::RoutingAlgorithmRef::parse_routing_algorithm(
- business_profile.routing_algorithm.clone().map(Secret::new),
- )
- .change_context(errors::ApiErrorResponse::InternalServerError)
- .attach_printable("unable to deserialize routing algorithm ref from merchant account")?
- .unwrap_or_default();
+ utils::when(
+ routing_algorithm.0.algorithm_for != *transaction_type,
+ || {
+ Err(errors::ApiErrorResponse::PreconditionFailed {
+ message: format!(
+ "Cannot use {}'s routing algorithm for {} operation",
+ routing_algorithm.0.algorithm_for, transaction_type
+ ),
+ })
+ },
+ )?;
- routing_algorithm.update_routing_ref_with_algorithm_id(transaction_type, &mut routing_ref)?;
+ utils::when(
+ business_profile.routing_algorithm_id == Some(algorithm_id.clone())
+ || business_profile.payout_routing_algorithm_id == Some(algorithm_id.clone()),
+ || {
+ Err(errors::ApiErrorResponse::PreconditionFailed {
+ message: "Algorithm is already active".to_string(),
+ })
+ },
+ )?;
+ admin::BusinessProfileWrapper::new(business_profile)
+ .update_business_profile_and_invalidate_routing_config_for_active_algorithm_id_update(
+ db,
+ key_manager_state,
+ &key_store,
+ algorithm_id,
+ transaction_type,
+ )
+ .await?;
- helpers::update_business_profile_active_algorithm_ref(
- db,
- key_manager_state,
- &key_store,
- business_profile,
- routing_ref,
- transaction_type,
- )
- .await?;
metrics::ROUTING_LINK_CONFIG_SUCCESS_RESPONSE.add(&metrics::CONTEXT, 1, &[]);
Ok(service_api::ApplicationResponse::Json(
routing_algorithm.0.foreign_into(),
))
}
-#[cfg(all(any(feature = "v1", feature = "v2"), not(feature = "routing_v2")))]
+#[cfg(all(
+ any(feature = "v1", feature = "v2"),
+ not(any(feature = "routing_v2", feature = "business_profile_v2"))
+))]
pub async fn link_routing_config(
state: SessionState,
merchant_account: domain::MerchantAccount,
@@ -428,8 +423,8 @@ pub async fn link_routing_config(
))
}
-#[cfg(all(feature = "v2", feature = "routing_v2"))]
-pub async fn retrieve_routing_config(
+#[cfg(all(feature = "v2", feature = "routing_v2",))]
+pub async fn retrieve_active_routing_config(
state: SessionState,
merchant_account: domain::MerchantAccount,
key_store: domain::MerchantKeyStore,
@@ -462,7 +457,7 @@ pub async fn retrieve_routing_config(
}
#[cfg(all(any(feature = "v1", feature = "v2"), not(feature = "routing_v2")))]
-pub async fn retrieve_routing_config(
+pub async fn retrieve_active_routing_config(
state: SessionState,
merchant_account: domain::MerchantAccount,
key_store: domain::MerchantKeyStore,
@@ -499,8 +494,12 @@ pub async fn retrieve_routing_config(
Ok(service_api::ApplicationResponse::Json(response))
}
-#[cfg(all(feature = "v2", feature = "routing_v2"))]
-pub async fn unlink_routing_config(
+#[cfg(all(
+ feature = "v2",
+ feature = "routing_v2",
+ feature = "business_profile_v2"
+))]
+pub async fn unlink_routing_config_under_profile(
state: SessionState,
merchant_account: domain::MerchantAccount,
key_store: domain::MerchantKeyStore,
@@ -521,27 +520,13 @@ pub async fn unlink_routing_config(
.await?
.get_required_value("BusinessProfile")?;
- let routing_algo_ref = routing_types::RoutingAlgorithmRef::parse_routing_algorithm(
- match transaction_type {
- enums::TransactionType::Payment => business_profile.routing_algorithm.clone(),
- #[cfg(feature = "payouts")]
- enums::TransactionType::Payout => business_profile.payout_routing_algorithm.clone(),
- }
- .map(Secret::new),
- )
- .change_context(errors::ApiErrorResponse::InternalServerError)
- .attach_printable("unable to deserialize routing algorithm ref from merchant account")?
- .unwrap_or_default();
-
- if let Some(algorithm_id) = routing_algo_ref.algorithm_id {
- let timestamp = common_utils::date_time::now_unix_timestamp();
- let routing_algorithm: routing_types::RoutingAlgorithmRef =
- routing_types::RoutingAlgorithmRef {
- algorithm_id: None,
- timestamp,
- config_algo_id: routing_algo_ref.config_algo_id.clone(),
- surcharge_config_algo_id: routing_algo_ref.surcharge_config_algo_id,
- };
+ let routing_algo_id = match transaction_type {
+ enums::TransactionType::Payment => business_profile.routing_algorithm_id.clone(),
+ #[cfg(feature = "payouts")]
+ enums::TransactionType::Payout => business_profile.payout_routing_algorithm_id.clone(),
+ };
+
+ if let Some(algorithm_id) = routing_algo_id {
let record = RoutingAlgorithmUpdate::fetch_routing_algo(
merchant_account.get_id(),
&algorithm_id,
@@ -549,16 +534,15 @@ pub async fn unlink_routing_config(
)
.await?;
let response = record.0.foreign_into();
- helpers::update_business_profile_active_algorithm_ref(
- db,
- key_manager_state,
- &key_store,
- business_profile,
- routing_algorithm,
- transaction_type,
- )
- .await?;
-
+ admin::BusinessProfileWrapper::new(business_profile)
+ .update_business_profile_and_invalidate_routing_config_for_active_algorithm_id_update(
+ db,
+ key_manager_state,
+ &key_store,
+ algorithm_id,
+ transaction_type,
+ )
+ .await?;
metrics::ROUTING_UNLINK_CONFIG_SUCCESS_RESPONSE.add(&metrics::CONTEXT, 1, &[]);
Ok(service_api::ApplicationResponse::Json(response))
} else {
@@ -568,7 +552,10 @@ pub async fn unlink_routing_config(
}
}
-#[cfg(all(any(feature = "v1", feature = "v2"), not(feature = "routing_v2")))]
+#[cfg(all(
+ any(feature = "v1", feature = "v2"),
+ not(any(feature = "routing_v2", feature = "business_profile_v2"))
+))]
pub async fn unlink_routing_config(
state: SessionState,
merchant_account: domain::MerchantAccount,
@@ -726,11 +713,63 @@ pub async fn retrieve_default_routing_config(
})
}
+#[cfg(all(
+ feature = "v2",
+ feature = "routing_v2",
+ feature = "business_profile_v2"
+))]
+pub async fn retrieve_routing_config_under_profile(
+ state: SessionState,
+ merchant_account: domain::MerchantAccount,
+ key_store: domain::MerchantKeyStore,
+ query_params: RoutingRetrieveQuery,
+ profile_id: String,
+ transaction_type: &enums::TransactionType,
+) -> RouterResponse<routing_types::LinkedRoutingConfigRetrieveResponse> {
+ metrics::ROUTING_RETRIEVE_LINK_CONFIG.add(&metrics::CONTEXT, 1, &[]);
+ let db = state.store.as_ref();
+ let key_manager_state = &(&state).into();
+
+ let business_profile = core_utils::validate_and_get_business_profile(
+ db,
+ key_manager_state,
+ &key_store,
+ Some(&profile_id),
+ merchant_account.get_id(),
+ )
+ .await?
+ .get_required_value("BusinessProfile")?;
+
+ let record = db
+ .list_routing_algorithm_metadata_by_profile_id(
+ &business_profile.profile_id,
+ i64::from(query_params.limit.unwrap_or_default()),
+ i64::from(query_params.offset.unwrap_or_default()),
+ )
+ .await
+ .to_not_found_response(errors::ApiErrorResponse::ResourceIdNotFound)?;
+
+ let active_algorithms = record
+ .into_iter()
+ .filter(|routing_rec| &routing_rec.algorithm_for == transaction_type)
+ .map(|routing_algo| routing_algo.foreign_into())
+ .collect::<Vec<_>>();
+
+ metrics::ROUTING_RETRIEVE_LINK_CONFIG_SUCCESS_RESPONSE.add(&metrics::CONTEXT, 1, &[]);
+ Ok(service_api::ApplicationResponse::Json(
+ routing_types::LinkedRoutingConfigRetrieveResponse::ProfileBased(active_algorithms),
+ ))
+}
+
+#[cfg(all(
+ any(feature = "v1", feature = "v2"),
+ not(any(feature = "routing_v2", feature = "business_profile_v2"))
+))]
pub async fn retrieve_linked_routing_config(
state: SessionState,
merchant_account: domain::MerchantAccount,
key_store: domain::MerchantKeyStore,
- query_params: RoutingRetrieveLinkQuery,
+ query_params: routing_types::RoutingRetrieveLinkQuery,
transaction_type: &enums::TransactionType,
) -> RouterResponse<routing_types::LinkedRoutingConfigRetrieveResponse> {
metrics::ROUTING_RETRIEVE_LINK_CONFIG.add(&metrics::CONTEXT, 1, &[]);
diff --git a/crates/router/src/core/routing/helpers.rs b/crates/router/src/core/routing/helpers.rs
index e388be764d2..9255c2bad0b 100644
--- a/crates/router/src/core/routing/helpers.rs
+++ b/crates/router/src/core/routing/helpers.rs
@@ -173,7 +173,6 @@ pub async fn update_merchant_active_algorithm_ref(
Ok(())
}
-#[cfg(all(any(feature = "v1", feature = "v2"), feature = "merchant_account_v2"))]
#[cfg(all(feature = "v2", feature = "merchant_account_v2"))]
pub async fn update_merchant_active_algorithm_ref(
_state: &SessionState,
@@ -181,9 +180,14 @@ pub async fn update_merchant_active_algorithm_ref(
_config_key: cache::CacheKind<'_>,
_algorithm_id: routing_types::RoutingAlgorithmRef,
) -> RouterResult<()> {
+ // TODO: handle updating the active routing algorithm for v2 in merchant account
todo!()
}
+#[cfg(all(
+ any(feature = "v1", feature = "v2"),
+ not(any(feature = "routing_v2", feature = "business_profile_v2"))
+))]
pub async fn update_business_profile_active_algorithm_ref(
db: &dyn StorageInterface,
key_manager_state: &KeyManagerState,
@@ -246,7 +250,7 @@ pub struct RoutingAlgorithmHelpers<'h> {
}
#[derive(Clone, Debug)]
-pub struct ConnectNameAndMCAIdForProfile<'a>(pub FxHashSet<(&'a String, &'a String)>);
+pub struct ConnectNameAndMCAIdForProfile<'a>(pub FxHashSet<(&'a String, String)>);
#[derive(Clone, Debug)]
pub struct ConnectNameForProfile<'a>(pub FxHashSet<&'a String>);
@@ -314,7 +318,7 @@ impl<'h> RoutingAlgorithmHelpers<'h> {
) -> RouterResult<()> {
if let Some(ref mca_id) = choice.merchant_connector_id {
error_stack::ensure!(
- self.name_mca_id_set.0.contains(&(&choice.connector.to_string(), mca_id)),
+ self.name_mca_id_set.0.contains(&(&choice.connector.to_string(), mca_id.clone())),
errors::ApiErrorResponse::InvalidRequestData {
message: format!(
"connector with name '{}' and merchant connector account id '{}' not found for the given profile",
diff --git a/crates/router/src/db/kafka_store.rs b/crates/router/src/db/kafka_store.rs
index b997aad1080..31b9ffcd7f8 100644
--- a/crates/router/src/db/kafka_store.rs
+++ b/crates/router/src/db/kafka_store.rs
@@ -2399,7 +2399,7 @@ impl RoutingAlgorithmInterface for KafkaStore {
profile_id: &str,
limit: i64,
offset: i64,
- ) -> CustomResult<Vec<storage::RoutingAlgorithmMetadata>, errors::StorageError> {
+ ) -> CustomResult<Vec<storage::RoutingProfileMetadata>, errors::StorageError> {
self.diesel_store
.list_routing_algorithm_metadata_by_profile_id(profile_id, limit, offset)
.await
diff --git a/crates/router/src/db/routing_algorithm.rs b/crates/router/src/db/routing_algorithm.rs
index b5e877b5295..ad4b3bd9192 100644
--- a/crates/router/src/db/routing_algorithm.rs
+++ b/crates/router/src/db/routing_algorithm.rs
@@ -41,7 +41,7 @@ pub trait RoutingAlgorithmInterface {
profile_id: &str,
limit: i64,
offset: i64,
- ) -> StorageResult<Vec<routing_storage::RoutingAlgorithmMetadata>>;
+ ) -> StorageResult<Vec<routing_storage::RoutingProfileMetadata>>;
async fn list_routing_algorithm_metadata_by_merchant_id(
&self,
@@ -127,7 +127,7 @@ impl RoutingAlgorithmInterface for Store {
profile_id: &str,
limit: i64,
offset: i64,
- ) -> StorageResult<Vec<routing_storage::RoutingAlgorithmMetadata>> {
+ ) -> StorageResult<Vec<routing_storage::RoutingProfileMetadata>> {
let conn = connection::pg_connection_write(self).await?;
routing_storage::RoutingAlgorithm::list_metadata_by_profile_id(
&conn, profile_id, limit, offset,
@@ -212,7 +212,7 @@ impl RoutingAlgorithmInterface for MockDb {
_profile_id: &str,
_limit: i64,
_offset: i64,
- ) -> StorageResult<Vec<routing_storage::RoutingAlgorithmMetadata>> {
+ ) -> StorageResult<Vec<routing_storage::RoutingProfileMetadata>> {
Err(errors::StorageError::MockDbError)?
}
diff --git a/crates/router/src/routes/app.rs b/crates/router/src/routes/app.rs
index 3c891d8a537..a6ce8c568b1 100644
--- a/crates/router/src/routes/app.rs
+++ b/crates/router/src/routes/app.rs
@@ -1455,7 +1455,12 @@ impl PayoutLink {
}
pub struct BusinessProfile;
-#[cfg(all(feature = "olap", feature = "v2", feature = "routing_v2"))]
+#[cfg(all(
+ feature = "olap",
+ feature = "v2",
+ feature = "routing_v2",
+ feature = "business_profile_v2"
+))]
impl BusinessProfile {
pub fn server(state: AppState) -> Scope {
web::scope("/v2/profiles")
@@ -1493,23 +1498,36 @@ impl BusinessProfile {
},
)),
)
- .service(web::resource("/deactivate_routing_algorithm").route(
- web::patch().to(|state, req, path| {
- routing::routing_unlink_config(
+ .service(
+ web::resource("/deactivate_routing_algorithm").route(web::patch().to(
+ |state, req, path| {
+ routing::routing_unlink_config(
+ state,
+ req,
+ path,
+ &TransactionType::Payment,
+ )
+ },
+ )),
+ )
+ .service(web::resource("/routing_algorithm").route(web::get().to(
+ |state, req, query_params, path| {
+ routing::routing_retrieve_linked_config(
state,
req,
+ query_params,
path,
&TransactionType::Payment,
)
- }),
- )),
+ },
+ ))),
)
}
}
#[cfg(all(
feature = "olap",
any(feature = "v1", feature = "v2"),
- not(feature = "routing_v2")
+ not(any(feature = "routing_v2", feature = "business_profile_v2"))
))]
impl BusinessProfile {
pub fn server(state: AppState) -> Scope {
diff --git a/crates/router/src/routes/routing.rs b/crates/router/src/routes/routing.rs
index 3705b0313d7..485a55baa50 100644
--- a/crates/router/src/routes/routing.rs
+++ b/crates/router/src/routes/routing.rs
@@ -4,10 +4,7 @@
//! of Routing configs.
use actix_web::{web, HttpRequest, Responder};
-use api_models::{
- enums, routing as routing_types,
- routing::{RoutingRetrieveLinkQuery, RoutingRetrieveQuery},
-};
+use api_models::{enums, routing as routing_types, routing::RoutingRetrieveQuery};
use router_env::{
tracing::{self, instrument},
Flow,
@@ -33,7 +30,7 @@ pub async fn routing_create_config(
&req,
json_payload.into_inner(),
|state, auth: auth::AuthenticationData, payload, _| {
- routing::create_routing_config(
+ routing::create_routing_algorithm_under_profile(
state,
auth.merchant_account,
auth.key_store,
@@ -115,7 +112,7 @@ pub async fn routing_link_config(
&req,
wrapper,
|state, auth: auth::AuthenticationData, wrapper, _| {
- routing::link_routing_config(
+ routing::link_routing_config_under_profile(
state,
auth.merchant_account,
auth.key_store,
@@ -152,7 +149,7 @@ pub async fn routing_retrieve_config(
&req,
algorithm_id,
|state, auth: auth::AuthenticationData, algorithm_id, _| {
- routing::retrieve_routing_config(
+ routing::retrieve_active_routing_config(
state,
auth.merchant_account,
auth.key_store,
@@ -222,7 +219,7 @@ pub async fn routing_unlink_config(
&req,
path.into_inner(),
|state, auth: auth::AuthenticationData, path, _| {
- routing::unlink_routing_config(
+ routing::unlink_routing_config_under_profile(
state,
auth.merchant_account,
auth.key_store,
@@ -535,12 +532,16 @@ pub async fn retrieve_decision_manager_config(
.await
}
-#[cfg(feature = "olap")]
+#[cfg(all(
+ feature = "olap",
+ any(feature = "v1", feature = "v2"),
+ not(any(feature = "routing_v2", feature = "business_profile_v2"))
+))]
#[instrument(skip_all)]
pub async fn routing_retrieve_linked_config(
state: web::Data<AppState>,
req: HttpRequest,
- query: web::Query<RoutingRetrieveLinkQuery>,
+ query: web::Query<routing_types::RoutingRetrieveLinkQuery>,
transaction_type: &enums::TransactionType,
) -> impl Responder {
use crate::services::authentication::AuthenticationData;
@@ -572,6 +573,54 @@ pub async fn routing_retrieve_linked_config(
.await
}
+#[cfg(all(
+ feature = "olap",
+ feature = "v2",
+ feature = "routing_v2",
+ feature = "business_profile_v2"
+))]
+#[instrument(skip_all)]
+pub async fn routing_retrieve_linked_config(
+ state: web::Data<AppState>,
+ req: HttpRequest,
+ query: web::Query<RoutingRetrieveQuery>,
+ path: web::Path<String>,
+ 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,
+ |state, auth: AuthenticationData, wrapper, _| {
+ routing::retrieve_routing_config_under_profile(
+ state,
+ auth.merchant_account,
+ auth.key_store,
+ wrapper.routing_query,
+ wrapper.profile_id,
+ transaction_type,
+ )
+ },
+ #[cfg(not(feature = "release"))]
+ auth::auth_type(
+ &auth::HeaderAuth(auth::ApiKeyAuth),
+ &auth::JWTAuth(Permission::RoutingRead),
+ req.headers(),
+ ),
+ #[cfg(feature = "release")]
+ &auth::JWTAuth(Permission::RoutingRead),
+ api_locking::LockAction::NotApplicable,
+ ))
+ .await
+}
+
#[cfg(feature = "olap")]
#[instrument(skip_all)]
pub async fn routing_retrieve_default_config_for_profiles(
diff --git a/crates/router/src/types/api/admin.rs b/crates/router/src/types/api/admin.rs
index 1217ae66bd7..56a6c4ec2b2 100644
--- a/crates/router/src/types/api/admin.rs
+++ b/crates/router/src/types/api/admin.rs
@@ -109,7 +109,10 @@ impl ForeignTryFrom<domain::MerchantAccount> for MerchantAccountResponse {
})
}
}
-
+#[cfg(all(
+ any(feature = "v1", feature = "v2"),
+ not(any(feature = "business_profile_v2", feature = "merchant_account_v2",))
+))]
impl ForeignTryFrom<domain::BusinessProfile> for BusinessProfileResponse {
type Error = error_stack::Report<errors::ParsingError>;
@@ -163,7 +166,71 @@ impl ForeignTryFrom<domain::BusinessProfile> for BusinessProfileResponse {
}
}
-#[cfg(all(feature = "v2", feature = "merchant_account_v2"))]
+#[cfg(all(
+ feature = "v2",
+ feature = "merchant_account_v2",
+ feature = "business_profile_v2"
+))]
+impl ForeignTryFrom<domain::BusinessProfile> for BusinessProfileResponse {
+ type Error = error_stack::Report<errors::ParsingError>;
+
+ fn foreign_try_from(item: domain::BusinessProfile) -> Result<Self, Self::Error> {
+ let outgoing_webhook_custom_http_headers = item
+ .outgoing_webhook_custom_http_headers
+ .map(|headers| {
+ headers
+ .into_inner()
+ .expose()
+ .parse_value::<HashMap<String, Secret<String>>>(
+ "HashMap<String, Secret<String>>",
+ )
+ })
+ .transpose()?;
+
+ Ok(Self {
+ merchant_id: item.merchant_id,
+ profile_id: item.profile_id,
+ profile_name: item.profile_name,
+ return_url: item.return_url,
+ enable_payment_response_hash: item.enable_payment_response_hash,
+ payment_response_hash_key: item.payment_response_hash_key,
+ redirect_to_merchant_with_http_post: item.redirect_to_merchant_with_http_post,
+ webhook_details: item.webhook_details.map(ForeignInto::foreign_into),
+ metadata: item.metadata,
+ // TODO: Remove routing algorithm from api models of business profile
+ routing_algorithm: todo!(),
+ intent_fulfillment_time: item.intent_fulfillment_time,
+ // TODO: Remove frm algorithm from api models of business profile
+ frm_routing_algorithm: todo!(),
+ #[cfg(feature = "payouts")]
+ // TODO: Remove payout algorithm from api models of business profile
+ payout_routing_algorithm: todo!(),
+ applepay_verified_domains: item.applepay_verified_domains,
+ payment_link_config: item.payment_link_config.map(ForeignInto::foreign_into),
+ session_expiry: item.session_expiry,
+ authentication_connector_details: item
+ .authentication_connector_details
+ .map(ForeignInto::foreign_into),
+ payout_link_config: item.payout_link_config.map(ForeignInto::foreign_into),
+ use_billing_as_payment_method_billing: item.use_billing_as_payment_method_billing,
+ extended_card_info_config: item
+ .extended_card_info_config
+ .map(|config| config.expose().parse_value("ExtendedCardInfoConfig"))
+ .transpose()?,
+ collect_shipping_details_from_wallet_connector: item
+ .collect_shipping_details_from_wallet_connector,
+ collect_billing_details_from_wallet_connector: item
+ .collect_billing_details_from_wallet_connector,
+ is_connector_agnostic_mit_enabled: item.is_connector_agnostic_mit_enabled,
+ outgoing_webhook_custom_http_headers,
+ })
+ }
+}
+#[cfg(all(
+ feature = "v2",
+ feature = "merchant_account_v2",
+ feature = "business_profile_v2"
+))]
pub async fn create_business_profile(
_state: &SessionState,
_request: BusinessProfileCreate,
@@ -174,7 +241,7 @@ pub async fn create_business_profile(
#[cfg(all(
any(feature = "v1", feature = "v2"),
- not(feature = "merchant_account_v2")
+ not(any(feature = "merchant_account_v2", feature = "business_profile_v2"))
))]
pub async fn create_business_profile(
state: &SessionState,
@@ -241,10 +308,7 @@ pub async fn create_business_profile(
.unwrap_or(merchant_account.redirect_to_merchant_with_http_post),
webhook_details: webhook_details.or(merchant_account.webhook_details),
metadata: request.metadata,
- routing_algorithm: Some(serde_json::json!({
- "algorithm_id": null,
- "timestamp": 0
- })),
+ routing_algorithm: None,
intent_fulfillment_time: request
.intent_fulfillment_time
.map(i64::from)
diff --git a/v2_migrations/2024-07-31-100300_business_profile_add_v2_columns_drop_v1_columns/down.sql b/v2_migrations/2024-07-31-100300_business_profile_add_v2_columns_drop_v1_columns/down.sql
index 5645d4c7399..3d35becdfab 100644
--- a/v2_migrations/2024-07-31-100300_business_profile_add_v2_columns_drop_v1_columns/down.sql
+++ b/v2_migrations/2024-07-31-100300_business_profile_add_v2_columns_drop_v1_columns/down.sql
@@ -3,16 +3,16 @@
-- stored in these columns.
ALTER TABLE business_profile
ADD COLUMN routing_algorithm JSON DEFAULT NULL,
- ADD COLUMN intent_fulfillment_time BIGINT DEFAULT NULL,
+ -- ADD COLUMN intent_fulfillment_time BIGINT DEFAULT NULL,
ADD COLUMN frm_routing_algorithm JSONB DEFAULT NULL,
- ADD COLUMN payout_routing_algorithm JSONB DEFAULT NULL;
+ ADD COLUMN payout_routing_algorithm JSONB DEFAULT NULL;
ALTER TABLE business_profile
DROP COLUMN routing_algorithm_id,
- DROP COLUMN order_fulfillment_time,
- DROP COLUMN order_fulfillment_time_origin,
+ -- DROP COLUMN order_fulfillment_time,
+ -- DROP COLUMN order_fulfillment_time_origin,
DROP COLUMN frm_routing_algorithm_id,
- DROP COLUMN payout_routing_algorithm_id,
- DROP COLUMN default_fallback_routing;
+ DROP COLUMN payout_routing_algorithm_id;
+ -- DROP COLUMN default_fallback_routing;
-DROP TYPE "OrderFulfillmentTimeOrigin";
+-- DROP TYPE "OrderFulfillmentTimeOrigin";
diff --git a/v2_migrations/2024-07-31-100300_business_profile_add_v2_columns_drop_v1_columns/up.sql b/v2_migrations/2024-07-31-100300_business_profile_add_v2_columns_drop_v1_columns/up.sql
index f1cff174468..2b98bef00d4 100644
--- a/v2_migrations/2024-07-31-100300_business_profile_add_v2_columns_drop_v1_columns/up.sql
+++ b/v2_migrations/2024-07-31-100300_business_profile_add_v2_columns_drop_v1_columns/up.sql
@@ -1,17 +1,17 @@
-CREATE TYPE "OrderFulfillmentTimeOrigin" AS ENUM ('create', 'confirm');
+-- CREATE TYPE "OrderFulfillmentTimeOrigin" AS ENUM ('create', 'confirm');
ALTER TABLE business_profile
ADD COLUMN routing_algorithm_id VARCHAR(64) DEFAULT NULL,
- ADD COLUMN order_fulfillment_time BIGINT DEFAULT NULL,
- ADD COLUMN order_fulfillment_time_origin "OrderFulfillmentTimeOrigin" DEFAULT NULL,
- ADD COLUMN frm_routing_algorithm_id VARCHAR(64) DEFAULT NULL,
- ADD COLUMN payout_routing_algorithm_id VARCHAR(64) DEFAULT NULL,
- ADD COLUMN default_fallback_routing JSONB DEFAULT NULL;
+ -- ADD COLUMN order_fulfillment_time BIGINT DEFAULT NULL,
+ -- ADD COLUMN order_fulfillment_time_origin "OrderFulfillmentTimeOrigin" DEFAULT NULL,
+ ADD COLUMN frm_routing_algorithm_id VARCHAR(64) DEFAULT NULL,
+ ADD COLUMN payout_routing_algorithm_id VARCHAR(64) DEFAULT NULL;
+ -- ADD COLUMN default_fallback_routing JSONB DEFAULT NULL;
-- Note: This query should not be run on higher environments as this leads to data loss.
-- The application will work fine even without these queries being run.
ALTER TABLE business_profile
DROP COLUMN routing_algorithm,
- DROP COLUMN intent_fulfillment_time,
- DROP COLUMN frm_routing_algorithm,
- DROP COLUMN payout_routing_algorithm;
+ -- DROP COLUMN intent_fulfillment_time,
+ DROP COLUMN frm_routing_algorithm,
+ DROP COLUMN payout_routing_algorithm;
|
2024-08-06T08:17:36Z
|
## Type of Change
<!-- Put an `x` in the boxes that apply -->
- [ ] Bugfix
- [ ] New feature
- [ ] Enhancement
- [x] Refactoring
- [ ] Dependency updates
- [ ] Documentation
- [ ] CI/CD
## Description
In this PR we adapt the usage of routing_algorithm_id as well as payout_routing_algorithm_id in routing and payments core for v2. Also refactored the routing_algorithm list, to list all the algorithms(history) on the basis of a single profile.
### Additional Changes
- [ ] This PR modifies the API contract
- [ ] This PR modifies the database schema
- [ ] This PR modifies application configuration/environment variables
<!--
Provide links to the files with corresponding changes.
Following are the paths where you can find config files:
1. `config`
2. `crates/router/src/configs`
3. `loadtest/config`
-->
## Motivation and Context
<!--
Why is this change required? What problem does it solve?
If it fixes an open issue, please link to the issue here.
If you don't have an issue, we'd recommend starting with one first so the PR
can focus on the implementation (unless it is an obvious bug or documentation fix
that will have little conversation).
-->
## How did you test it?
- List all the routing rules for under a profile
```
curl --location 'http://localhost:8080/v2/profile/pro_VirB3AxB3qItFTnLsuA2/routing_algorithm' \
--header 'api-key: dev_jsssWAg0XyxGK0ycPunkFjlItYNs30X1IVOr1MIF7lwrDQgBBk7npwdkZB4t7EQd'
```
## Checklist
<!-- Put an `x` in the boxes that apply -->
- [ ] I formatted the code `cargo +nightly fmt --all`
- [ ] I addressed lints thrown by `cargo clippy`
- [ ] I reviewed the submitted code
- [ ] I added unit tests for my changes where possible
|
ff430c983c56a2c4ecec13c78ccee020abd7a5d8
|
|
juspay/hyperswitch
|
juspay__hyperswitch-5548
|
Bug: [FEATURE] Add separate function for Plaid in Connector Config
Need to add separate function for plaid in connector config for wasm
|
diff --git a/crates/connector_configs/src/connector.rs b/crates/connector_configs/src/connector.rs
index ed36dbca497..6cc32fe9553 100644
--- a/crates/connector_configs/src/connector.rs
+++ b/crates/connector_configs/src/connector.rs
@@ -3,7 +3,7 @@ use std::collections::HashMap;
#[cfg(feature = "payouts")]
use api_models::enums::PayoutConnectors;
use api_models::{
- enums::{AuthenticationConnectors, Connector},
+ enums::{AuthenticationConnectors, Connector, PmAuthConnectors},
payments,
};
use serde::Deserialize;
@@ -269,6 +269,15 @@ impl ConnectorConfig {
}
}
+ pub fn get_pm_authentication_processor_config(
+ connector: PmAuthConnectors,
+ ) -> Result<Option<ConnectorTomlConfig>, String> {
+ let connector_data = Self::new()?;
+ match connector {
+ PmAuthConnectors::Plaid => Ok(connector_data.plaid),
+ }
+ }
+
pub fn get_connector_config(
connector: Connector,
) -> Result<Option<ConnectorTomlConfig>, String> {
diff --git a/crates/euclid_wasm/src/lib.rs b/crates/euclid_wasm/src/lib.rs
index eed5c38af9d..ab36031339e 100644
--- a/crates/euclid_wasm/src/lib.rs
+++ b/crates/euclid_wasm/src/lib.rs
@@ -327,6 +327,14 @@ pub fn get_authentication_connector_config(key: &str) -> JsResult {
Ok(serde_wasm_bindgen::to_value(&res)?)
}
+#[wasm_bindgen(js_name = getPMAuthenticationProcessorConfig)]
+pub fn get_pm_authentication_processor_config(key: &str) -> JsResult {
+ let key: api_model_enums::PmAuthConnectors = api_model_enums::PmAuthConnectors::from_str(key)
+ .map_err(|_| "Invalid key received".to_string())?;
+ let res = connector::ConnectorConfig::get_pm_authentication_processor_config(key)?;
+ Ok(serde_wasm_bindgen::to_value(&res)?)
+}
+
#[wasm_bindgen(js_name = getRequestPayload)]
pub fn get_request_payload(input: JsValue, response: JsValue) -> JsResult {
let input: DashboardRequestPayload = serde_wasm_bindgen::from_value(input)?;
|
2024-08-06T16:02:43Z
|
## Type of Change
<!-- Put an `x` in the boxes that apply -->
- [ ] Bugfix
- [x] New feature
- [ ] Enhancement
- [ ] Refactoring
- [ ] Dependency updates
- [ ] Documentation
- [ ] CI/CD
## Description
Refer #5548
### Additional Changes
- [ ] This PR modifies the API contract
- [ ] This PR modifies the database schema
- [x] This PR modifies application configuration/environment variables
<!--
Provide links to the files with corresponding changes.
Following are the paths where you can find config files:
1. `config`
2. `crates/router/src/configs`
3. `loadtest/config`
-->
## Motivation and Context
<!--
Why is this change required? What problem does it solve?
If it fixes an open issue, please link to the issue here.
If you don't have an issue, we'd recommend starting with one first so the PR
can focus on the implementation (unless it is an obvious bug or documentation fix
that will have little conversation).
-->
## How did you test it?
<!--
Did you write an integration/unit/API test to verify the code changes?
Or did you test this change manually (provide relevant screenshots)?
-->
## Checklist
<!-- Put an `x` in the boxes that apply -->
- [x] I formatted the code `cargo +nightly fmt --all`
- [x] I addressed lints thrown by `cargo clippy`
- [ ] I reviewed the submitted code
- [ ] I added unit tests for my changes where possible
|
76b14601c843e328d168559840d8e22f78e59d3f
|
|
juspay/hyperswitch
|
juspay__hyperswitch-5558
|
Bug: [FEATURE] return total_count in payouts filtered list API response
### Feature Description
Payouts filter API should also send a `total_count` which represents the total number of payout entries available for a given set of constraints. This API supports pagination and returns only 20 entries at a given time, `total_count` is helpful for knowing ahead of time about the total number of entries that are available.
### Possible Implementation
Write a DB query for counting all the rows for a given set of constraints, consume this query to get the total count and send back the response.
### Have you spent some time checking if this feature request has been raised before?
- [X] I checked and didn't find a similar issue
### Have you read the Contributing Guidelines?
- [X] I have read the [Contributing Guidelines](https://github.com/juspay/hyperswitch/blob/main/docs/CONTRIBUTING.md)
### Are you willing to submit a PR?
Yes, I am willing to submit a PR!
|
diff --git a/api-reference-v2/openapi_spec.json b/api-reference-v2/openapi_spec.json
index 8974f940bac..4706bc8e0dc 100644
--- a/api-reference-v2/openapi_spec.json
+++ b/api-reference-v2/openapi_spec.json
@@ -14252,7 +14252,14 @@
"type": "array",
"items": {
"$ref": "#/components/schemas/PayoutCreateResponse"
- }
+ },
+ "description": "The list of payouts response objects"
+ },
+ "total_count": {
+ "type": "integer",
+ "format": "int64",
+ "description": "The total number of available payouts for given constraints",
+ "nullable": true
}
}
},
diff --git a/crates/api_models/src/payouts.rs b/crates/api_models/src/payouts.rs
index b90b34cdff7..60c08241d17 100644
--- a/crates/api_models/src/payouts.rs
+++ b/crates/api_models/src/payouts.rs
@@ -715,8 +715,11 @@ pub struct PayoutListFilterConstraints {
pub struct PayoutListResponse {
/// The number of payouts included in the list
pub size: usize,
- // The list of payouts response objects
+ /// The list of payouts response objects
pub data: Vec<PayoutCreateResponse>,
+ /// The total number of available payouts for given constraints
+ #[serde(skip_serializing_if = "Option::is_none")]
+ pub total_count: Option<i64>,
}
#[derive(Clone, Debug, serde::Serialize, ToSchema)]
diff --git a/crates/diesel_models/src/query/payout_attempt.rs b/crates/diesel_models/src/query/payout_attempt.rs
index e415dc6735d..939336a223a 100644
--- a/crates/diesel_models/src/query/payout_attempt.rs
+++ b/crates/diesel_models/src/query/payout_attempt.rs
@@ -147,7 +147,7 @@ impl PayoutAttempt {
Vec<enums::PayoutStatus>,
Vec<enums::PayoutType>,
)> {
- let active_attempts: Vec<String> = payouts
+ let active_attempt_ids = payouts
.iter()
.map(|payout| {
format!(
@@ -156,11 +156,20 @@ impl PayoutAttempt {
payout.attempt_count.clone()
)
})
- .collect();
+ .collect::<Vec<String>>();
+
+ let active_payout_ids = payouts
+ .iter()
+ .map(|payout| payout.payout_id.clone())
+ .collect::<Vec<String>>();
let filter = <Self as HasTable>::table()
.filter(dsl::merchant_id.eq(merchant_id.to_owned()))
- .filter(dsl::payout_attempt_id.eq_any(active_attempts));
+ .filter(dsl::payout_attempt_id.eq_any(active_attempt_ids));
+
+ let payouts_filter = <Payouts as HasTable>::table()
+ .filter(payout_dsl::merchant_id.eq(merchant_id.to_owned()))
+ .filter(payout_dsl::payout_id.eq_any(active_payout_ids));
let payout_status: Vec<enums::PayoutStatus> = payouts
.iter()
@@ -181,7 +190,8 @@ impl PayoutAttempt {
.flatten()
.collect::<Vec<String>>();
- let filter_currency = <Payouts as HasTable>::table()
+ let filter_currency = payouts_filter
+ .clone()
.select(payout_dsl::destination_currency)
.distinct()
.get_results_async::<enums::Currency>(conn)
@@ -191,7 +201,8 @@ impl PayoutAttempt {
.into_iter()
.collect::<Vec<enums::Currency>>();
- let filter_payout_method = Payouts::table()
+ let filter_payout_method = payouts_filter
+ .clone()
.select(payout_dsl::payout_type)
.distinct()
.get_results_async::<Option<enums::PayoutType>>(conn)
diff --git a/crates/diesel_models/src/query/payouts.rs b/crates/diesel_models/src/query/payouts.rs
index e65062b3922..25c7bfc4f7e 100644
--- a/crates/diesel_models/src/query/payouts.rs
+++ b/crates/diesel_models/src/query/payouts.rs
@@ -1,11 +1,16 @@
-use diesel::{associations::HasTable, BoolExpressionMethods, ExpressionMethods};
-use error_stack::report;
+use async_bb8_diesel::AsyncRunQueryDsl;
+use diesel::{
+ associations::HasTable, debug_query, pg::Pg, BoolExpressionMethods, ExpressionMethods,
+ JoinOnDsl, QueryDsl,
+};
+use error_stack::{report, ResultExt};
use super::generics;
use crate::{
- errors,
+ enums, errors,
payouts::{Payouts, PayoutsNew, PayoutsUpdate, PayoutsUpdateInternal},
- schema::payouts::dsl,
+ query::generics::db_metrics,
+ schema::{payout_attempt, payouts::dsl},
PgPooledConn, StorageResult,
};
@@ -87,4 +92,43 @@ impl Payouts {
)
.await
}
+
+ pub async fn get_total_count_of_payouts(
+ conn: &PgPooledConn,
+ merchant_id: &common_utils::id_type::MerchantId,
+ active_payout_ids: &[String],
+ connector: Option<Vec<String>>,
+ currency: Option<Vec<enums::Currency>>,
+ status: Option<Vec<enums::PayoutStatus>>,
+ payout_type: Option<Vec<enums::PayoutType>>,
+ ) -> StorageResult<i64> {
+ let mut filter = <Self as HasTable>::table()
+ .inner_join(payout_attempt::table.on(payout_attempt::dsl::payout_id.eq(dsl::payout_id)))
+ .count()
+ .filter(dsl::merchant_id.eq(merchant_id.to_owned()))
+ .filter(dsl::payout_id.eq_any(active_payout_ids.to_owned()))
+ .into_boxed();
+
+ if let Some(connector) = connector {
+ filter = filter.filter(payout_attempt::dsl::connector.eq_any(connector));
+ }
+ if let Some(currency) = currency {
+ filter = filter.filter(dsl::destination_currency.eq_any(currency));
+ }
+ if let Some(status) = status {
+ filter = filter.filter(dsl::status.eq_any(status));
+ }
+ if let Some(payout_type) = payout_type {
+ filter = filter.filter(dsl::payout_type.eq_any(payout_type));
+ }
+ router_env::logger::debug!(query = %debug_query::<Pg, _>(&filter).to_string());
+
+ db_metrics::track_database_call::<<Self as HasTable>::Table, _, _>(
+ filter.get_result_async::<i64>(conn),
+ db_metrics::DatabaseOperation::Filter,
+ )
+ .await
+ .change_context(errors::DatabaseError::Others)
+ .attach_printable("Error filtering count of payouts")
+ }
}
diff --git a/crates/hyperswitch_domain_models/src/payouts/payout_attempt.rs b/crates/hyperswitch_domain_models/src/payouts/payout_attempt.rs
index adba454c798..b863382b7cd 100644
--- a/crates/hyperswitch_domain_models/src/payouts/payout_attempt.rs
+++ b/crates/hyperswitch_domain_models/src/payouts/payout_attempt.rs
@@ -41,9 +41,9 @@ pub trait PayoutAttemptInterface {
async fn get_filters_for_payouts(
&self,
- payout: &[Payouts],
- merchant_id: &id_type::MerchantId,
- storage_scheme: MerchantStorageScheme,
+ _payout: &[Payouts],
+ _merchant_id: &id_type::MerchantId,
+ _storage_scheme: MerchantStorageScheme,
) -> error_stack::Result<PayoutListFilters, errors::StorageError>;
}
diff --git a/crates/hyperswitch_domain_models/src/payouts/payouts.rs b/crates/hyperswitch_domain_models/src/payouts/payouts.rs
index 0c0fbe8ae28..834b6bb3f76 100644
--- a/crates/hyperswitch_domain_models/src/payouts/payouts.rs
+++ b/crates/hyperswitch_domain_models/src/payouts/payouts.rs
@@ -61,10 +61,29 @@ pub trait PayoutsInterface {
#[cfg(feature = "olap")]
async fn filter_payouts_by_time_range_constraints(
&self,
- merchant_id: &id_type::MerchantId,
- time_range: &api_models::payments::TimeRange,
- storage_scheme: MerchantStorageScheme,
+ _merchant_id: &id_type::MerchantId,
+ _time_range: &api_models::payments::TimeRange,
+ _storage_scheme: MerchantStorageScheme,
) -> error_stack::Result<Vec<Payouts>, errors::StorageError>;
+
+ #[cfg(feature = "olap")]
+ #[allow(clippy::too_many_arguments)]
+ async fn get_total_count_of_filtered_payouts(
+ &self,
+ _merchant_id: &id_type::MerchantId,
+ _active_payout_ids: &[String],
+ _connector: Option<Vec<api_models::enums::PayoutConnectors>>,
+ _currency: Option<Vec<storage_enums::Currency>>,
+ _status: Option<Vec<storage_enums::PayoutStatus>>,
+ _payout_method: Option<Vec<storage_enums::PayoutType>>,
+ ) -> error_stack::Result<i64, errors::StorageError>;
+
+ #[cfg(feature = "olap")]
+ async fn filter_active_payout_ids_by_constraints(
+ &self,
+ _merchant_id: &id_type::MerchantId,
+ _constraints: &PayoutFetchConstraints,
+ ) -> error_stack::Result<Vec<String>, errors::StorageError>;
}
#[derive(Clone, Debug, Eq, PartialEq)]
diff --git a/crates/router/src/core/payouts.rs b/crates/router/src/core/payouts.rs
index 07b50d3a154..aa272f7b5de 100644
--- a/crates/router/src/core/payouts.rs
+++ b/crates/router/src/core/payouts.rs
@@ -846,6 +846,7 @@ pub async fn payouts_list_core(
api::PayoutListResponse {
size: data.len(),
data,
+ total_count: None,
},
))
}
@@ -861,6 +862,7 @@ pub async fn payouts_filtered_list_core(
let limit = &filters.limit;
validator::validate_payout_list_request_for_joins(*limit)?;
let db = state.store.as_ref();
+ let constraints = filters.clone().into();
let list: Vec<(
storage::Payouts,
storage::PayoutAttempt,
@@ -868,7 +870,7 @@ pub async fn payouts_filtered_list_core(
)> = db
.filter_payouts_and_attempts(
merchant_account.get_id(),
- &filters.clone().into(),
+ &constraints,
merchant_account.storage_scheme,
)
.await
@@ -899,10 +901,35 @@ pub async fn payouts_filtered_list_core(
.map(ForeignFrom::foreign_from)
.collect();
+ let active_payout_ids = db
+ .filter_active_payout_ids_by_constraints(merchant_account.get_id(), &constraints)
+ .await
+ .change_context(errors::ApiErrorResponse::InternalServerError)
+ .attach_printable("Failed to filter active payout ids based on the constraints")?;
+
+ let total_count = db
+ .get_total_count_of_filtered_payouts(
+ merchant_account.get_id(),
+ &active_payout_ids,
+ filters.connector.clone(),
+ filters.currency.clone(),
+ filters.status.clone(),
+ filters.payout_method.clone(),
+ )
+ .await
+ .change_context(errors::ApiErrorResponse::InternalServerError)
+ .attach_printable_lazy(|| {
+ format!(
+ "Failed to fetch total count of filtered payouts for the given constraints - {:?}",
+ filters
+ )
+ })?;
+
Ok(services::ApplicationResponse::Json(
api::PayoutListResponse {
size: data.len(),
data,
+ total_count: Some(total_count),
},
))
}
diff --git a/crates/router/src/db/kafka_store.rs b/crates/router/src/db/kafka_store.rs
index 31b9ffcd7f8..de0d225d726 100644
--- a/crates/router/src/db/kafka_store.rs
+++ b/crates/router/src/db/kafka_store.rs
@@ -1909,6 +1909,39 @@ impl PayoutsInterface for KafkaStore {
.filter_payouts_by_time_range_constraints(merchant_id, time_range, storage_scheme)
.await
}
+
+ #[cfg(feature = "olap")]
+ async fn get_total_count_of_filtered_payouts(
+ &self,
+ merchant_id: &id_type::MerchantId,
+ active_payout_ids: &[String],
+ connector: Option<Vec<api_models::enums::PayoutConnectors>>,
+ currency: Option<Vec<enums::Currency>>,
+ status: Option<Vec<enums::PayoutStatus>>,
+ payout_method: Option<Vec<enums::PayoutType>>,
+ ) -> CustomResult<i64, errors::DataStorageError> {
+ self.diesel_store
+ .get_total_count_of_filtered_payouts(
+ merchant_id,
+ active_payout_ids,
+ connector,
+ currency,
+ status,
+ payout_method,
+ )
+ .await
+ }
+
+ #[cfg(feature = "olap")]
+ async fn filter_active_payout_ids_by_constraints(
+ &self,
+ merchant_id: &id_type::MerchantId,
+ constraints: &hyperswitch_domain_models::payouts::PayoutFetchConstraints,
+ ) -> CustomResult<Vec<String>, errors::DataStorageError> {
+ self.diesel_store
+ .filter_active_payout_ids_by_constraints(merchant_id, constraints)
+ .await
+ }
}
#[async_trait::async_trait]
diff --git a/crates/storage_impl/src/mock_db/payouts.rs b/crates/storage_impl/src/mock_db/payouts.rs
index 835f73c62de..c151e8acb88 100644
--- a/crates/storage_impl/src/mock_db/payouts.rs
+++ b/crates/storage_impl/src/mock_db/payouts.rs
@@ -85,4 +85,28 @@ impl PayoutsInterface for MockDb {
// TODO: Implement function for `MockDb`
Err(StorageError::MockDbError)?
}
+
+ #[cfg(feature = "olap")]
+ async fn get_total_count_of_filtered_payouts(
+ &self,
+ _merchant_id: &common_utils::id_type::MerchantId,
+ _active_payout_ids: &[String],
+ _connector: Option<Vec<api_models::enums::PayoutConnectors>>,
+ _currency: Option<Vec<storage_enums::Currency>>,
+ _status: Option<Vec<storage_enums::PayoutStatus>>,
+ _payout_method: Option<Vec<storage_enums::PayoutType>>,
+ ) -> CustomResult<i64, StorageError> {
+ // TODO: Implement function for `MockDb`
+ Err(StorageError::MockDbError)?
+ }
+
+ #[cfg(feature = "olap")]
+ async fn filter_active_payout_ids_by_constraints(
+ &self,
+ _merchant_id: &common_utils::id_type::MerchantId,
+ _constraints: &hyperswitch_domain_models::payouts::PayoutFetchConstraints,
+ ) -> CustomResult<Vec<String>, StorageError> {
+ // TODO: Implement function for `MockDb`
+ Err(StorageError::MockDbError)?
+ }
}
diff --git a/crates/storage_impl/src/payouts/payouts.rs b/crates/storage_impl/src/payouts/payouts.rs
index f449666f6e0..828355a71ea 100644
--- a/crates/storage_impl/src/payouts/payouts.rs
+++ b/crates/storage_impl/src/payouts/payouts.rs
@@ -1,5 +1,9 @@
#[cfg(feature = "olap")]
+use api_models::enums::PayoutConnectors;
+#[cfg(feature = "olap")]
use async_bb8_diesel::{AsyncConnection, AsyncRunQueryDsl};
+#[cfg(feature = "olap")]
+use common_utils::errors::ReportSwitchExt;
use common_utils::ext_traits::Encode;
#[cfg(all(
feature = "olap",
@@ -11,7 +15,7 @@ use diesel::JoinOnDsl;
use diesel::{associations::HasTable, ExpressionMethods, NullableExpressionMethods, QueryDsl};
#[cfg(feature = "olap")]
use diesel_models::{
- customers::Customer as DieselCustomer, query::generics::db_metrics,
+ customers::Customer as DieselCustomer, enums as storage_enums, query::generics::db_metrics,
schema::payouts::dsl as po_dsl,
};
use diesel_models::{
@@ -345,6 +349,39 @@ impl<T: DatabaseStore> PayoutsInterface for KVRouterStore<T> {
.filter_payouts_by_time_range_constraints(merchant_id, time_range, storage_scheme)
.await
}
+
+ #[cfg(feature = "olap")]
+ async fn get_total_count_of_filtered_payouts(
+ &self,
+ merchant_id: &common_utils::id_type::MerchantId,
+ active_payout_ids: &[String],
+ connector: Option<Vec<PayoutConnectors>>,
+ currency: Option<Vec<storage_enums::Currency>>,
+ status: Option<Vec<storage_enums::PayoutStatus>>,
+ payout_method: Option<Vec<storage_enums::PayoutType>>,
+ ) -> error_stack::Result<i64, StorageError> {
+ self.router_store
+ .get_total_count_of_filtered_payouts(
+ merchant_id,
+ active_payout_ids,
+ connector,
+ currency,
+ status,
+ payout_method,
+ )
+ .await
+ }
+
+ #[cfg(feature = "olap")]
+ async fn filter_active_payout_ids_by_constraints(
+ &self,
+ merchant_id: &common_utils::id_type::MerchantId,
+ constraints: &PayoutFetchConstraints,
+ ) -> error_stack::Result<Vec<String>, StorageError> {
+ self.router_store
+ .filter_active_payout_ids_by_constraints(merchant_id, constraints)
+ .await
+ }
}
#[async_trait::async_trait]
@@ -428,8 +465,6 @@ impl<T: DatabaseStore> PayoutsInterface for crate::RouterStore<T> {
filters: &PayoutFetchConstraints,
storage_scheme: MerchantStorageScheme,
) -> error_stack::Result<Vec<Payouts>, StorageError> {
- use common_utils::errors::ReportSwitchExt;
-
let conn = connection::pg_connection_read(self).await.switch()?;
let conn = async_bb8_diesel::Connection::as_async_conn(&conn);
@@ -492,18 +527,6 @@ impl<T: DatabaseStore> PayoutsInterface for crate::RouterStore<T> {
query = query.offset(params.offset.into());
- query = match ¶ms.currency {
- Some(currency) => {
- query.filter(po_dsl::destination_currency.eq_any(currency.clone()))
- }
- None => query,
- };
-
- query = match ¶ms.status {
- Some(status) => query.filter(po_dsl::status.eq_any(status.clone())),
- None => query,
- };
-
if let Some(currency) = ¶ms.currency {
query = query.filter(po_dsl::destination_currency.eq_any(currency.clone()));
}
@@ -549,8 +572,6 @@ impl<T: DatabaseStore> PayoutsInterface for crate::RouterStore<T> {
storage_scheme: MerchantStorageScheme,
) -> error_stack::Result<Vec<(Payouts, PayoutAttempt, Option<DieselCustomer>)>, StorageError>
{
- use common_utils::errors::ReportSwitchExt;
-
let conn = connection::pg_connection_read(self).await.switch()?;
let conn = async_bb8_diesel::Connection::as_async_conn(&conn);
let mut query = DieselPayouts::table()
@@ -558,7 +579,7 @@ impl<T: DatabaseStore> PayoutsInterface for crate::RouterStore<T> {
diesel_models::schema::payout_attempt::table
.on(poa_dsl::payout_id.eq(po_dsl::payout_id)),
)
- .inner_join(
+ .left_join(
diesel_models::schema::customers::table
.on(cust_dsl::customer_id.nullable().eq(po_dsl::customer_id)),
)
@@ -701,6 +722,122 @@ impl<T: DatabaseStore> PayoutsInterface for crate::RouterStore<T> {
self.filter_payouts_by_constraints(merchant_id, &payout_filters, storage_scheme)
.await
}
+
+ #[cfg(feature = "olap")]
+ #[instrument(skip_all)]
+ async fn get_total_count_of_filtered_payouts(
+ &self,
+ merchant_id: &common_utils::id_type::MerchantId,
+ active_payout_ids: &[String],
+ connector: Option<Vec<PayoutConnectors>>,
+ currency: Option<Vec<storage_enums::Currency>>,
+ status: Option<Vec<storage_enums::PayoutStatus>>,
+ payout_type: Option<Vec<storage_enums::PayoutType>>,
+ ) -> error_stack::Result<i64, StorageError> {
+ let conn = self
+ .db_store
+ .get_replica_pool()
+ .get()
+ .await
+ .change_context(StorageError::DatabaseConnectionError)?;
+ let connector_strings = connector.as_ref().map(|connectors| {
+ connectors
+ .iter()
+ .map(|c| c.to_string())
+ .collect::<Vec<String>>()
+ });
+ DieselPayouts::get_total_count_of_payouts(
+ &conn,
+ merchant_id,
+ active_payout_ids,
+ connector_strings,
+ currency,
+ status,
+ payout_type,
+ )
+ .await
+ .map_err(|er| {
+ let new_err = diesel_error_to_data_error(er.current_context());
+ er.change_context(new_err)
+ })
+ }
+
+ #[cfg(feature = "olap")]
+ #[instrument(skip_all)]
+ async fn filter_active_payout_ids_by_constraints(
+ &self,
+ merchant_id: &common_utils::id_type::MerchantId,
+ constraints: &PayoutFetchConstraints,
+ ) -> error_stack::Result<Vec<String>, StorageError> {
+ let conn = connection::pg_connection_read(self).await.switch()?;
+ let conn = async_bb8_diesel::Connection::as_async_conn(&conn);
+ let mut query = DieselPayouts::table()
+ .inner_join(
+ diesel_models::schema::payout_attempt::table
+ .on(poa_dsl::payout_id.eq(po_dsl::payout_id)),
+ )
+ .left_join(
+ diesel_models::schema::customers::table
+ .on(cust_dsl::customer_id.nullable().eq(po_dsl::customer_id)),
+ )
+ .select(po_dsl::payout_id)
+ .filter(po_dsl::merchant_id.eq(merchant_id.to_owned()))
+ .order(po_dsl::created_at.desc())
+ .into_boxed();
+
+ query = match constraints {
+ PayoutFetchConstraints::Single { payout_id } => {
+ query.filter(po_dsl::payout_id.eq(payout_id.to_owned()))
+ }
+ PayoutFetchConstraints::List(params) => {
+ if let Some(customer_id) = ¶ms.customer_id {
+ query = query.filter(po_dsl::customer_id.eq(customer_id.clone()));
+ }
+ if let Some(profile_id) = ¶ms.profile_id {
+ query = query.filter(po_dsl::profile_id.eq(profile_id.clone()));
+ }
+
+ query = match params.starting_at {
+ Some(starting_at) => query.filter(po_dsl::created_at.ge(starting_at)),
+ None => query,
+ };
+
+ query = match params.ending_at {
+ Some(ending_at) => query.filter(po_dsl::created_at.le(ending_at)),
+ None => query,
+ };
+
+ query = match ¶ms.currency {
+ Some(currency) => {
+ query.filter(po_dsl::destination_currency.eq_any(currency.clone()))
+ }
+ None => query,
+ };
+
+ query = match ¶ms.status {
+ Some(status) => query.filter(po_dsl::status.eq_any(status.clone())),
+ None => query,
+ };
+
+ query
+ }
+ };
+
+ logger::debug!(filter = %diesel::debug_query::<diesel::pg::Pg,_>(&query).to_string());
+
+ db_metrics::track_database_call::<<DieselPayouts as HasTable>::Table, _, _>(
+ query.get_results_async::<String>(conn),
+ db_metrics::DatabaseOperation::Filter,
+ )
+ .await
+ .map_err(|er| {
+ StorageError::DatabaseError(
+ error_stack::report!(diesel_models::errors::DatabaseError::from(er))
+ .attach_printable("Error filtering payout records"),
+ )
+ .into()
+ })
+ }
}
impl DataModelExt for Payouts {
|
2024-08-06T09:59:34Z
|
## Type of Change
<!-- Put an `x` in the boxes that apply -->
- [ ] Bugfix
- [ ] New feature
- [x] Enhancement
- [x] Refactoring
- [ ] Dependency updates
- [ ] Documentation
- [ ] CI/CD
## Description
This PR refactors the payouts filtered list's API response to include `total_count` which specifies the total number of payout entries available for the given constraints.
### Additional Changes
- [x] This PR modifies the API contract
- [ ] This PR modifies the database schema
- [ ] This PR modifies application configuration/environment variables
<!--
Provide links to the files with corresponding changes.
Following are the paths where you can find config files:
1. `config`
2. `crates/router/src/configs`
3. `loadtest/config`
-->
## How did you test it?
1. Create payouts (create multiple for listing based on different constraints)
<details>
<summary>2. Filter payouts</summary>
curl --location 'http://localhost:8080/payouts/list' \
--header 'Content-Type: application/json' \
--header 'api-key: dev_cp78v8fT2C03KkEClI9aBMrqKF6N0SBLyUjasXtUQMbLTasfR2LJwjg0LlNHY060' \
--data '{}'

</details>
## Checklist
<!-- Put an `x` in the boxes that apply -->
- [x] I formatted the code `cargo +nightly fmt --all`
- [x] I addressed lints thrown by `cargo clippy`
- [x] I reviewed the submitted code
- [ ] I added unit tests for my changes where possible
|
ed13ecac04f82b5c69b11636c1e355e7e17c60fd
|
|
juspay/hyperswitch
|
juspay__hyperswitch-5559
|
Bug: [FEATURE] add localisation support for any HTML template served through HyperSwitch
### Feature Description
Specifically for payout links
The terminal status pages for payout links are served from backend with basic HTML / JS / CSS templates. The language used in these resources is English which is hardcoded. There needs to be a locale support for handling localisation of payout links.
### Possible Implementation
Provisioning of locales
- make use of `rust-i18n` for maintaining locales in the server
- make use of `t!` macro for reading the locales at runtime
Consumption in payout links
- Consume locale during payout creation and store the payout link's URL with a hardcoded locale as a query parameter
- Fetch locale during render request and pass to the request handler
- Inject the string data dynamically into HTML / JS resources based on the locale
- Inject locale in SDK for SDK localisation
### Have you spent some time checking if this feature request has been raised before?
- [X] I checked and didn't find a similar issue
### Have you read the Contributing Guidelines?
- [X] I have read the [Contributing Guidelines](https://github.com/juspay/hyperswitch/blob/main/docs/CONTRIBUTING.md)
### Are you willing to submit a PR?
Yes, I am willing to submit a PR!
|
diff --git a/.typos.toml b/.typos.toml
index 82fb84ecf38..2f68e039cde 100644
--- a/.typos.toml
+++ b/.typos.toml
@@ -62,5 +62,20 @@ extend-exclude = [
"openapi/open_api_spec.yaml", # no longer updated
"crates/router/src/utils/user/blocker_emails.txt", # this file contains various email domains
"CHANGELOG.md", # This file contains all the commits
+ "crates/router/locales/ar.yml", # locales
+ "crates/router/locales/ca.yml", # locales
+ "crates/router/locales/de.yml", # locales
+ "crates/router/locales/es.yml", # locales
+ "crates/router/locales/fr-BE.yml", # locales
+ "crates/router/locales/fr.yml", # locales
+ "crates/router/locales/he.yml", # locales
+ "crates/router/locales/it.yml", # locales
+ "crates/router/locales/ja.yml", # locales
+ "crates/router/locales/nl.yml", # locales
+ "crates/router/locales/pl.yml", # locales
+ "crates/router/locales/pt.yml", # locales
+ "crates/router/locales/ru.yml", # locales
+ "crates/router/locales/sv.yml", # locales
+ "crates/router/locales/zh.yml", # locales
"crates/router/src/core/payment_link/locale.js" # this file contains converision of static strings in various languages
]
diff --git a/Cargo.lock b/Cargo.lock
index 9d37e75077f..c0ff88bfcf6 100644
--- a/Cargo.lock
+++ b/Cargo.lock
@@ -1488,6 +1488,12 @@ version = "0.4.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "23ce669cd6c8588f79e15cf450314f9638f967fc5770ff1c7c1deb0925ea7cfa"
+[[package]]
+name = "base62"
+version = "2.0.2"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "f879ef8fc74665ed7f0e6127cb106315888fc2744f68e14b74f83edbb2a08992"
+
[[package]]
name = "base64"
version = "0.13.1"
@@ -4321,6 +4327,12 @@ dependencies = [
"vcpkg",
]
+[[package]]
+name = "libyml"
+version = "0.0.4"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "64804cc6a5042d4f05379909ba25b503ec04e2c082151d62122d5dcaa274b961"
+
[[package]]
name = "libz-sys"
version = "1.1.16"
@@ -4383,9 +4395,9 @@ dependencies = [
[[package]]
name = "log"
-version = "0.4.21"
+version = "0.4.22"
source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "90ed8c1e510134f979dbc4f070f87d4313098b704861a105fe34231c70a3901c"
+checksum = "a7a70ba024b9dc04c27ea2f0c0548feb474ec5c54bba33a7f72f873a39d07b24"
[[package]]
name = "lru-cache"
@@ -4474,9 +4486,9 @@ checksum = "490cc448043f947bae3cbee9c203358d62dbee0db12107a74be5c30ccfd09771"
[[package]]
name = "memchr"
-version = "2.7.2"
+version = "2.7.4"
source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "6c8640c5d730cb13ebd907d8d04b52f55ac9a2eec55b440c8892f40d56c76c1d"
+checksum = "78ca9ab1a0babb1e7d5695e3530886289c18cf2f87ec19a575a0abdce112e3a3"
[[package]]
name = "memoffset"
@@ -4693,6 +4705,15 @@ dependencies = [
"minimal-lexical",
]
+[[package]]
+name = "normpath"
+version = "1.1.1"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "ec60c60a693226186f5d6edf073232bfb6464ed97eb22cf3b01c1e8198fd97f5"
+dependencies = [
+ "windows-sys 0.48.0",
+]
+
[[package]]
name = "nu-ansi-term"
version = "0.46.0"
@@ -5323,7 +5344,7 @@ version = "0.11.2"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "90fcb95eef784c2ac79119d1dd819e162b5da872ce6f3c3abe1e8ca1c082f72b"
dependencies = [
- "siphasher",
+ "siphasher 0.3.11",
]
[[package]]
@@ -6126,6 +6147,7 @@ dependencies = [
"router_derive",
"router_env",
"roxmltree",
+ "rust-i18n",
"rust_decimal",
"rustc-hash",
"rustls 0.22.4",
@@ -6229,6 +6251,57 @@ dependencies = [
"zeroize",
]
+[[package]]
+name = "rust-i18n"
+version = "3.1.1"
+source = "git+https://github.com/kashif-m/rust-i18n?rev=f2d8096aaaff7a87a847c35a5394c269f75e077a#f2d8096aaaff7a87a847c35a5394c269f75e077a"
+dependencies = [
+ "globwalk",
+ "once_cell",
+ "regex",
+ "rust-i18n-macro",
+ "rust-i18n-support",
+ "smallvec 1.13.2",
+]
+
+[[package]]
+name = "rust-i18n-macro"
+version = "3.1.1"
+source = "git+https://github.com/kashif-m/rust-i18n?rev=f2d8096aaaff7a87a847c35a5394c269f75e077a#f2d8096aaaff7a87a847c35a5394c269f75e077a"
+dependencies = [
+ "glob",
+ "once_cell",
+ "proc-macro2",
+ "quote",
+ "rust-i18n-support",
+ "serde",
+ "serde_json",
+ "serde_yml",
+ "syn 2.0.57",
+]
+
+[[package]]
+name = "rust-i18n-support"
+version = "3.1.1"
+source = "git+https://github.com/kashif-m/rust-i18n?rev=f2d8096aaaff7a87a847c35a5394c269f75e077a#f2d8096aaaff7a87a847c35a5394c269f75e077a"
+dependencies = [
+ "arc-swap",
+ "base62",
+ "globwalk",
+ "itertools 0.11.0",
+ "lazy_static",
+ "normpath",
+ "once_cell",
+ "proc-macro2",
+ "regex",
+ "serde",
+ "serde_json",
+ "serde_yml",
+ "siphasher 1.0.1",
+ "toml 0.7.8",
+ "triomphe",
+]
+
[[package]]
name = "rust-ini"
version = "0.19.0"
@@ -6465,9 +6538,9 @@ dependencies = [
[[package]]
name = "ryu"
-version = "1.0.17"
+version = "1.0.18"
source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "e86697c916019a8588c99b5fac3cead74ec0b4b819707a682fd4d23fa0ce1ba1"
+checksum = "f3cb5ba0dc43242ce17de99c180e96db90b235b8a9fdc9543c96d2209116bd9f"
[[package]]
name = "same-file"
@@ -6607,9 +6680,9 @@ checksum = "388a1df253eca08550bef6c72392cfe7c30914bf41df5269b68cbd6ff8f570a3"
[[package]]
name = "serde"
-version = "1.0.197"
+version = "1.0.205"
source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "3fb1c873e1b9b056a4dc4c0c198b24c3ffa059243875552b2bd0933b1aee4ce2"
+checksum = "e33aedb1a7135da52b7c21791455563facbbcc43d0f0f66165b42c21b3dfb150"
dependencies = [
"serde_derive",
]
@@ -6648,9 +6721,9 @@ dependencies = [
[[package]]
name = "serde_derive"
-version = "1.0.197"
+version = "1.0.205"
source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "7eb0b34b42edc17f6b7cac84a52a1c5f0e1bb2227e997ca9011ea3dd34e8610b"
+checksum = "692d6f5ac90220161d6774db30c662202721e64aed9058d2c394f451261420c1"
dependencies = [
"proc-macro2",
"quote",
@@ -6659,12 +6732,13 @@ dependencies = [
[[package]]
name = "serde_json"
-version = "1.0.115"
+version = "1.0.122"
source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "12dc5c46daa8e9fdf4f5e71b6cf9a53f2487da0e86e55808e2d35539666497dd"
+checksum = "784b6203951c57ff748476b126ccb5e8e2959a5c19e5c617ab1956be3dbc68da"
dependencies = [
"indexmap 2.3.0",
"itoa",
+ "memchr",
"ryu",
"serde",
]
@@ -6761,6 +6835,23 @@ dependencies = [
"syn 2.0.57",
]
+[[package]]
+name = "serde_yml"
+version = "0.0.11"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "48e76bab63c3fd98d27c17f9cbce177f64a91f5e69ac04cafe04e1bb25d1dc3c"
+dependencies = [
+ "indexmap 2.3.0",
+ "itoa",
+ "libyml",
+ "log",
+ "memchr",
+ "ryu",
+ "serde",
+ "serde_json",
+ "tempfile",
+]
+
[[package]]
name = "serial_test"
version = "3.0.0"
@@ -6888,6 +6979,12 @@ version = "0.3.11"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "38b58827f4464d87d377d175e90bf58eb00fd8716ff0a62f80356b5e61555d0d"
+[[package]]
+name = "siphasher"
+version = "1.0.1"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "56199f7ddabf13fe5074ce809e7d3f42b42ae711800501b5b16ea82ad029c39d"
+
[[package]]
name = "skeptic"
version = "0.13.7"
@@ -7189,6 +7286,12 @@ dependencies = [
"urlencoding",
]
+[[package]]
+name = "stable_deref_trait"
+version = "1.2.0"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "a8f112729512f8e442d81f95a8a7ddf2b7c6b8a1a6f509a95864142b30cab2d3"
+
[[package]]
name = "storage_impl"
version = "0.1.0"
@@ -8231,6 +8334,11 @@ name = "triomphe"
version = "0.1.11"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "859eb650cfee7434994602c3a68b25d77ad9e68c8a6cd491616ef86661382eb3"
+dependencies = [
+ "arc-swap",
+ "serde",
+ "stable_deref_trait",
+]
[[package]]
name = "try-lock"
diff --git a/crates/api_models/src/payouts.rs b/crates/api_models/src/payouts.rs
index 3333fb6f546..b90b34cdff7 100644
--- a/crates/api_models/src/payouts.rs
+++ b/crates/api_models/src/payouts.rs
@@ -764,6 +764,7 @@ pub struct PayoutLinkDetails {
pub enabled_payment_methods: Vec<link_utils::EnabledPaymentMethod>,
pub amount: common_utils::types::StringMajorUnit,
pub currency: common_enums::Currency,
+ pub locale: String,
}
#[derive(Clone, Debug, serde::Serialize)]
diff --git a/crates/common_utils/src/consts.rs b/crates/common_utils/src/consts.rs
index a331a05f6fa..fd155963968 100644
--- a/crates/common_utils/src/consts.rs
+++ b/crates/common_utils/src/consts.rs
@@ -127,3 +127,6 @@ pub const WILDCARD_DOMAIN_REGEX: &str = r"^((\*|https?)?://)?((\*\.|[A-Za-z0-9][
/// Maximum allowed length for MerchantName
pub const MAX_ALLOWED_MERCHANT_NAME_LENGTH: usize = 64;
+
+/// Default locale
+pub const DEFAULT_LOCALE: &str = "en";
diff --git a/crates/hyperswitch_domain_models/src/api.rs b/crates/hyperswitch_domain_models/src/api.rs
index b013d2b7902..d8a4f998e1b 100644
--- a/crates/hyperswitch_domain_models/src/api.rs
+++ b/crates/hyperswitch_domain_models/src/api.rs
@@ -64,6 +64,7 @@ pub struct PaymentLinkStatusData {
pub struct GenericLinks {
pub allowed_domains: HashSet<String>,
pub data: GenericLinksData,
+ pub locale: String,
}
#[derive(Debug, Eq, PartialEq)]
diff --git a/crates/router/Cargo.toml b/crates/router/Cargo.toml
index 3e0470cc08d..8040979abbf 100644
--- a/crates/router/Cargo.toml
+++ b/crates/router/Cargo.toml
@@ -97,6 +97,7 @@ reqwest = { version = "0.11.27", features = ["json", "native-tls", "__rustls", "
ring = "0.17.8"
roxmltree = "0.19.0"
rust_decimal = { version = "1.35.0", features = ["serde-with-float", "serde-with-str"] }
+rust-i18n = { git = "https://github.com/kashif-m/rust-i18n", rev = "f2d8096aaaff7a87a847c35a5394c269f75e077a" }
rustc-hash = "1.1.0"
rustls = "0.22"
rustls-pemfile = "2"
@@ -161,7 +162,6 @@ time = { version = "0.3.35", features = ["macros"] }
tokio = "1.37.0"
wiremock = "0.6.0"
-
# First party dev-dependencies
test_utils = { version = "0.1.0", path = "../test_utils" }
diff --git a/crates/router/locales/ar.yml b/crates/router/locales/ar.yml
new file mode 100644
index 00000000000..5cc89daa47a
--- /dev/null
+++ b/crates/router/locales/ar.yml
@@ -0,0 +1,42 @@
+_version: 1
+
+payout_link:
+ initiate:
+ not_allowed: "لا يُسمح لك بمشاهدة هذا المحتوى"
+ title: "روابط الدفع"
+ status:
+ title: "حالة الدفع"
+ info:
+ ref_id: "معرف المرجع"
+ error_code: "رمز الخطأ"
+ error_message: "رسالة الخطأ"
+ message:
+ failed: "فشل في معالجة الدفع الخاص بك. يرجى التحقق مع مزود الخدمة للحصول على مزيد من التفاصيل."
+ processing: "يجب معالجة الدفع الخاص بك خلال 2-3 أيام عمل."
+ success: "تم تنفيذ الدفع إلى طريقة الدفع المختارة."
+ redirection_text:
+ redirecting: "جارٍ إعادة التوجيه..."
+ redirecting_in: "إعادة التوجيه خلال"
+ seconds: "ثوانٍ..."
+ text:
+ failed: "فشل الدفع"
+ processing: "الدفع قيد المعالجة"
+ success: "الدفع ناجح"
+
+time:
+ am: "صباحا"
+ pm: "مساء"
+
+months:
+ january: "يناير"
+ february: "فبراير"
+ march: "مارس"
+ april: "أبريل"
+ may: "مايو"
+ june: "يونيو"
+ july: "يوليو"
+ august: "أغسطس"
+ september: "سبتمبر"
+ october: "أكتوبر"
+ november: "نوفمبر"
+ december: "ديسمبر"
diff --git a/crates/router/locales/ca.yml b/crates/router/locales/ca.yml
new file mode 100644
index 00000000000..df4d40bb204
--- /dev/null
+++ b/crates/router/locales/ca.yml
@@ -0,0 +1,42 @@
+_version: 1
+
+payout_link:
+ initiate:
+ not_allowed: "No tens permís per veure aquest contingut"
+ title: "Enllaços de Pagament"
+ status:
+ title: "Estat del Pagament"
+ info:
+ ref_id: "ID de Referència"
+ error_code: "Codi d'Error"
+ error_message: "Missatge d'Error"
+ message:
+ failed: "No s'ha pogut processar el teu pagament. Si us plau, comprova-ho amb el teu proveïdor per obtenir més detalls."
+ processing: "El teu pagament hauria de ser processat en 2-3 dies hàbils."
+ success: "El teu pagament s'ha realitzat al mètode de pagament seleccionat."
+ redirection_text:
+ redirecting: "Redirigint..."
+ redirecting_in: "Redirigint en"
+ seconds: "segons..."
+ text:
+ failed: "Falla en el Pagament"
+ processing: "Pagament en Procés"
+ success: "Pagament Exitos"
+
+time:
+ am: "AM"
+ pm: "PM"
+
+months:
+ january: "Gener"
+ february: "Febrer"
+ march: "Març"
+ april: "Abril"
+ may: "Maig"
+ june: "Juny"
+ july: "Juliol"
+ august: "Agost"
+ september: "Setembre"
+ october: "Octubre"
+ november: "Novembre"
+ december: "Desembre"
diff --git a/crates/router/locales/de.yml b/crates/router/locales/de.yml
new file mode 100644
index 00000000000..4a2ac4c4ea4
--- /dev/null
+++ b/crates/router/locales/de.yml
@@ -0,0 +1,42 @@
+_version: 1
+
+payout_link:
+ initiate:
+ not_allowed: "Sie dürfen diesen Inhalt nicht anzeigen"
+ title: "Auszahlungslinks"
+ status:
+ title: "Auszahlungsstatus"
+ info:
+ ref_id: "Referenz-ID"
+ error_code: "Fehlercode"
+ error_message: "Fehlermeldung"
+ message:
+ failed: "Die Auszahlung konnte nicht verarbeitet werden. Bitte überprüfen Sie weitere Details bei Ihrem Anbieter."
+ processing: "Ihre Auszahlung sollte innerhalb von 2-3 Werktagen verarbeitet werden."
+ success: "Ihre Auszahlung wurde auf die ausgewählte Zahlungsmethode vorgenommen."
+ redirection_text:
+ redirecting: "Weiterleitung..."
+ redirecting_in: "Weiterleitung in"
+ seconds: "Sekunden..."
+ text:
+ failed: "Auszahlung fehlgeschlagen"
+ processing: "Auszahlung wird bearbeitet"
+ success: "Auszahlung erfolgreich"
+
+time:
+ am: "AM"
+ pm: "PM"
+
+months:
+ january: "Januar"
+ february: "Februar"
+ march: "März"
+ april: "April"
+ may: "Mai"
+ june: "Juni"
+ july: "Juli"
+ august: "August"
+ september: "September"
+ october: "Oktober"
+ november: "November"
+ december: "Dezember"
diff --git a/crates/router/locales/en-GB.yml b/crates/router/locales/en-GB.yml
new file mode 100644
index 00000000000..5d0cdca4f0a
--- /dev/null
+++ b/crates/router/locales/en-GB.yml
@@ -0,0 +1,42 @@
+_version: 1
+
+payout_link:
+ initiate:
+ not_allowed: "You are not allowed to view this content"
+ title: "Payout Links"
+ status:
+ title: "Payout Status"
+ info:
+ ref_id: "Ref Id"
+ error_code: "Error Code"
+ error_message: "Error Message"
+ message:
+ failed: "Failed to process your payout. Please check with your provider for more details."
+ processing: "Your payout should be processed within 2-3 business days."
+ success: "Your payout was made to selected payment method."
+ redirection_text:
+ redirecting: "Redirecting..."
+ redirecting_in: "Redirecting in"
+ seconds: "seconds..."
+ text:
+ failed: "Payout Failed"
+ processing: "Payout Processing"
+ success: "Payout Successful"
+
+time:
+ am: "AM"
+ pm: "PM"
+
+months:
+ january: "January"
+ february: "February"
+ march: "March"
+ april: "April"
+ may: "May"
+ june: "June"
+ july: "July"
+ august: "August"
+ september: "September"
+ october: "October"
+ november: "November"
+ december: "December"
diff --git a/crates/router/locales/en.yml b/crates/router/locales/en.yml
new file mode 100644
index 00000000000..c85be7ccf46
--- /dev/null
+++ b/crates/router/locales/en.yml
@@ -0,0 +1,42 @@
+_version: 1
+
+payout_link:
+ initiate:
+ not_allowed: "You are not allowed to view this content"
+ title: "Payout Links"
+ status:
+ title: "Payout Status"
+ info:
+ ref_id: "Ref Id"
+ error_code: "Error Code"
+ error_message: "Error Message"
+ message:
+ failed: "Failed to process your payout. Please check with your provider for more details."
+ processing: "Your payout should be processed within 2-3 business days."
+ success: "Your payout was made to selected payment method."
+ redirection_text:
+ redirecting: "Redirecting ..."
+ redirecting_in: "Redirecting in"
+ seconds: "seconds ..."
+ text:
+ failed: "Payout Failed"
+ processing: "Payout Processing"
+ success: "Payout Successful"
+
+time:
+ am: "AM"
+ pm: "PM"
+
+months:
+ january: "January"
+ february: "February"
+ march: "March"
+ april: "April"
+ may: "May"
+ june: "June"
+ july: "July"
+ august: "August"
+ september: "September"
+ october: "October"
+ november: "November"
+ december: "December"
\ No newline at end of file
diff --git a/crates/router/locales/es.yml b/crates/router/locales/es.yml
new file mode 100644
index 00000000000..ebe296d067b
--- /dev/null
+++ b/crates/router/locales/es.yml
@@ -0,0 +1,42 @@
+_version: 1
+
+payout_link:
+ initiate:
+ not_allowed: "No tienes permiso para ver este contenido"
+ title: "Enlaces de Pago"
+ status:
+ title: "Estado del Pago"
+ info:
+ ref_id: "ID de Referencia"
+ error_code: "Código de Error"
+ error_message: "Mensaje de Error"
+ message:
+ failed: "No se pudo procesar tu pago. Consulta con tu proveedor para más detalles."
+ processing: "Tu pago debería ser procesado en 2-3 días hábiles."
+ success: "Tu pago se realizó al método de pago seleccionado."
+ redirection_text:
+ redirecting: "Redirigiendo..."
+ redirecting_in: "Redirigiendo en"
+ seconds: "segundos..."
+ text:
+ failed: "Fallo en el Pago"
+ processing: "Pago en Proceso"
+ success: "Pago Exitoso"
+
+time:
+ am: "AM"
+ pm: "PM"
+
+months:
+ january: "Enero"
+ february: "Febrero"
+ march: "Marzo"
+ april: "Abril"
+ may: "Mayo"
+ june: "Junio"
+ july: "Julio"
+ august: "Agosto"
+ september: "Septiembre"
+ october: "Octubre"
+ november: "Noviembre"
+ december: "Diciembre"
diff --git a/crates/router/locales/fr-BE.yml b/crates/router/locales/fr-BE.yml
new file mode 100644
index 00000000000..5f5116ea92d
--- /dev/null
+++ b/crates/router/locales/fr-BE.yml
@@ -0,0 +1,42 @@
+_version: 1
+
+payout_link:
+ initiate:
+ not_allowed: "Vous n'êtes pas autorisé à voir ce contenu"
+ title: "Liens de paiement"
+ status:
+ title: "Statut du paiement"
+ info:
+ ref_id: "ID de référence"
+ error_code: "Code d'erreur"
+ error_message: "Message d'erreur"
+ message:
+ failed: "Échec du traitement de votre paiement. Veuillez vérifier auprès de votre fournisseur pour plus de détails."
+ processing: "Votre paiement devrait être traité dans les 2 à 3 jours ouvrables."
+ success: "Votre paiement a été effectué sur le mode de paiement sélectionné."
+ redirection_text:
+ redirecting: "Redirection..."
+ redirecting_in: "Redirection dans"
+ seconds: "secondes..."
+ text:
+ failed: "Échec du paiement"
+ processing: "Paiement en cours"
+ success: "Paiement réussi"
+
+time:
+ am: "AM"
+ pm: "PM"
+
+months:
+ january: "Janvier"
+ february: "Février"
+ march: "Mars"
+ april: "Avril"
+ may: "Mai"
+ june: "Juin"
+ july: "Juillet"
+ august: "Août"
+ september: "Septembre"
+ october: "Octobre"
+ november: "Novembre"
+ december: "Décembre"
diff --git a/crates/router/locales/fr.yml b/crates/router/locales/fr.yml
new file mode 100644
index 00000000000..d12dc361d4c
--- /dev/null
+++ b/crates/router/locales/fr.yml
@@ -0,0 +1,42 @@
+_version: 1
+
+payout_link:
+ initiate:
+ not_allowed: "Vous n'êtes pas autorisé à voir ce contenu"
+ title: "Liens de Paiement"
+ status:
+ title: "Statut de Paiement"
+ info:
+ ref_id: "Id de Réf"
+ error_code: "Code d'Erreur"
+ error_message: "Message d'Erreur"
+ message:
+ failed: "Échec du traitement de votre paiement. Veuillez vérifier auprès de votre fournisseur pour plus de détails."
+ processing: "Votre paiement devrait être traité dans les 2 à 3 jours ouvrables."
+ success: "Votre paiement a été effectué sur le mode de paiement sélectionné."
+ redirection_text:
+ redirecting: "Redirection ..."
+ redirecting_in: "Redirection dans"
+ seconds: "secondes ..."
+ text:
+ failed: "Échec du Paiement"
+ processing: "Traitement du Paiement"
+ success: "Paiement Réussi"
+
+time:
+ am: "AM"
+ pm: "PM"
+
+months:
+ january: "Janvier"
+ february: "Février"
+ march: "Mars"
+ april: "Avril"
+ may: "Mai"
+ june: "Juin"
+ july: "Juillet"
+ august: "Août"
+ september: "Septembre"
+ october: "Octobre"
+ november: "Novembre"
+ december: "Décembre"
diff --git a/crates/router/locales/he.yml b/crates/router/locales/he.yml
new file mode 100644
index 00000000000..dbb3da209cf
--- /dev/null
+++ b/crates/router/locales/he.yml
@@ -0,0 +1,42 @@
+_version: 1
+
+payout_link:
+ initiate:
+ not_allowed: "אינך מורשה לצפות בתוכן זה"
+ title: "קישורי תשלום"
+ status:
+ title: "סטטוס תשלום"
+ info:
+ ref_id: "מספר הפניה"
+ error_code: "קוד שגיאה"
+ error_message: "הודעת שגיאה"
+ message:
+ failed: "נכשל בעיבוד התשלום שלך. אנא בדוק עם הספק שלך למידע נוסף."
+ processing: "התשלום שלך צריך להיות מעובד בתוך 2-3 ימי עסקים."
+ success: "התשלום שלך בוצע לשיטת התשלום שנבחרה."
+ redirection_text:
+ redirecting: "מופנה..."
+ redirecting_in: "מופנה בעוד"
+ seconds: "שניות..."
+ text:
+ failed: "תשלום נכשל"
+ processing: "תשלום בתהליך"
+ success: "תשלום הצליח"
+
+time:
+ am: "בבוקר"
+ pm: "בערב"
+
+months:
+ january: "ינואר"
+ february: "פברואר"
+ march: "מרץ"
+ april: "אפריל"
+ may: "מאי"
+ june: "יוני"
+ july: "יולי"
+ august: "אוגוסט"
+ september: "ספטמבר"
+ october: "אוקטובר"
+ november: "נובמבר"
+ december: "דצמבר"
diff --git a/crates/router/locales/it.yml b/crates/router/locales/it.yml
new file mode 100644
index 00000000000..21f36a9af51
--- /dev/null
+++ b/crates/router/locales/it.yml
@@ -0,0 +1,42 @@
+_version: 1
+
+payout_link:
+ initiate:
+ not_allowed: "Non sei autorizzato a visualizzare questo contenuto"
+ title: "Link di Pagamento"
+ status:
+ title: "Stato del Pagamento"
+ info:
+ ref_id: "ID di Riferimento"
+ error_code: "Codice di Errore"
+ error_message: "Messaggio di Errore"
+ message:
+ failed: "Impossibile elaborare il tuo pagamento. Contatta il tuo fornitore per ulteriori dettagli."
+ processing: "Il tuo pagamento dovrebbe essere elaborato entro 2-3 giorni lavorativi."
+ success: "Il tuo pagamento è stato effettuato al metodo di pagamento selezionato."
+ redirection_text:
+ redirecting: "Reindirizzamento..."
+ redirecting_in: "Reindirizzamento tra"
+ seconds: "secondi..."
+ text:
+ failed: "Pagamento Fallito"
+ processing: "Pagamento in Corso"
+ success: "Pagamento Riuscito"
+
+time:
+ am: "AM"
+ pm: "PM"
+
+months:
+ january: "Gennaio"
+ february: "Febbraio"
+ march: "Marzo"
+ april: "Aprile"
+ may: "Maggio"
+ june: "Giugno"
+ july: "Luglio"
+ august: "Agosto"
+ september: "Settembre"
+ october: "Ottobre"
+ november: "Novembre"
+ december: "Dicembre"
diff --git a/crates/router/locales/ja.yml b/crates/router/locales/ja.yml
new file mode 100644
index 00000000000..4691374297b
--- /dev/null
+++ b/crates/router/locales/ja.yml
@@ -0,0 +1,42 @@
+_version: 1
+
+payout_link:
+ initiate:
+ not_allowed: "このコンテンツを見ることはできません"
+ title: "支払いリンク"
+ status:
+ title: "支払いステータス"
+ info:
+ ref_id: "参照ID"
+ error_code: "エラーコード"
+ error_message: "エラーメッセージ"
+ message:
+ failed: "支払いの処理に失敗しました。詳細については提供者に確認してください。"
+ processing: "支払いは2〜3営業日以内に処理される予定です。"
+ success: "支払いが選択した支払い方法に対して行われました。"
+ redirection_text:
+ redirecting: "リダイレクト中..."
+ redirecting_in: "リダイレクトまで"
+ seconds: "秒..."
+ text:
+ failed: "支払い失敗"
+ processing: "支払い処理中"
+ success: "支払い成功"
+
+time:
+ am: "AM"
+ pm: "PM"
+
+months:
+ january: "1月"
+ february: "2月"
+ march: "3月"
+ april: "4月"
+ may: "5月"
+ june: "6月"
+ july: "7月"
+ august: "8月"
+ september: "9月"
+ october: "10月"
+ november: "11月"
+ december: "12月"
diff --git a/crates/router/locales/nl.yml b/crates/router/locales/nl.yml
new file mode 100644
index 00000000000..1cf808d3935
--- /dev/null
+++ b/crates/router/locales/nl.yml
@@ -0,0 +1,42 @@
+_version: 1
+
+payout_link:
+ initiate:
+ not_allowed: "Je bent niet toegestaan om deze inhoud te bekijken"
+ title: "Betalingslinks"
+ status:
+ title: "Betalingsstatus"
+ info:
+ ref_id: "Referentie-ID"
+ error_code: "Foutcode"
+ error_message: "Foutmelding"
+ message:
+ failed: "Het is niet gelukt om je betaling te verwerken. Controleer bij je aanbieder voor meer details."
+ processing: "Je betaling moet binnen 2-3 werkdagen worden verwerkt."
+ success: "Je betaling is uitgevoerd naar de geselecteerde betaalmethode."
+ redirection_text:
+ redirecting: "Doorverwijzen..."
+ redirecting_in: "Doorverwijzen in"
+ seconds: "seconden..."
+ text:
+ failed: "Betaling Mislukt"
+ processing: "Betaling in Behandeling"
+ success: "Betaling Succesvol"
+
+time:
+ am: "AM"
+ pm: "PM"
+
+months:
+ january: "Januari"
+ february: "Februari"
+ march: "Maart"
+ april: "April"
+ may: "Mei"
+ june: "Juni"
+ july: "Juli"
+ august: "Augustus"
+ september: "September"
+ october: "Oktober"
+ november: "November"
+ december: "December"
diff --git a/crates/router/locales/pl.yml b/crates/router/locales/pl.yml
new file mode 100644
index 00000000000..71faae35945
--- /dev/null
+++ b/crates/router/locales/pl.yml
@@ -0,0 +1,42 @@
+_version: 1
+
+payout_link:
+ initiate:
+ not_allowed: "Nie masz uprawnień do wyświetlania tej treści"
+ title: "Linki do wypłat"
+ status:
+ title: "Status wypłaty"
+ info:
+ ref_id: "ID referencyjny"
+ error_code: "Kod błędu"
+ error_message: "Komunikat o błędzie"
+ message:
+ failed: "Nie udało się przetworzyć Twojej wypłaty. Skontaktuj się z dostawcą w celu uzyskania szczegółowych informacji."
+ processing: "Twoja wypłata powinna zostać przetworzona w ciągu 2-3 dni roboczych."
+ success: "Twoja wypłata została zrealizowana metodą płatności, którą wybrałeś."
+ redirection_text:
+ redirecting: "Przekierowywanie..."
+ redirecting_in: "Przekierowywanie za"
+ seconds: "sekund..."
+ text:
+ failed: "Wypłata Nieudana"
+ processing: "Wypłata w Trakcie"
+ success: "Wypłata Udała się"
+
+time:
+ am: "AM"
+ pm: "PM"
+
+months:
+ january: "Styczeń"
+ february: "Luty"
+ march: "Marzec"
+ april: "Kwiecień"
+ may: "Maj"
+ june: "Czerwiec"
+ july: "Lipiec"
+ august: "Sierpień"
+ september: "Wrzesień"
+ october: "Październik"
+ november: "Listopad"
+ december: "Grudzień"
diff --git a/crates/router/locales/pt.yml b/crates/router/locales/pt.yml
new file mode 100644
index 00000000000..8a419c2df21
--- /dev/null
+++ b/crates/router/locales/pt.yml
@@ -0,0 +1,42 @@
+_version: 1
+
+payout_link:
+ initiate:
+ not_allowed: "Você não tem permissão para visualizar este conteúdo"
+ title: "Links de Pagamento"
+ status:
+ title: "Status do Pagamento"
+ info:
+ ref_id: "ID de Referência"
+ error_code: "Código de Erro"
+ error_message: "Mensagem de Erro"
+ message:
+ failed: "Falha ao processar seu pagamento. Verifique com seu provedor para mais detalhes."
+ processing: "Seu pagamento deve ser processado em 2-3 dias úteis."
+ success: "Seu pagamento foi realizado no método de pagamento selecionado."
+ redirection_text:
+ redirecting: "Redirecionando..."
+ redirecting_in: "Redirecionando em"
+ seconds: "segundos..."
+ text:
+ failed: "Falha no Pagamento"
+ processing: "Pagamento em Processamento"
+ success: "Pagamento Bem-Sucedido"
+
+time:
+ am: "AM"
+ pm: "PM"
+
+months:
+ january: "Janeiro"
+ february: "Fevereiro"
+ march: "Março"
+ april: "Abril"
+ may: "Maio"
+ june: "Junho"
+ july: "Julho"
+ august: "Agosto"
+ september: "Setembro"
+ october: "Outubro"
+ november: "Novembro"
+ december: "Dezembro"
diff --git a/crates/router/locales/ru.yml b/crates/router/locales/ru.yml
new file mode 100644
index 00000000000..8257ee67025
--- /dev/null
+++ b/crates/router/locales/ru.yml
@@ -0,0 +1,42 @@
+_version: 1
+
+payout_link:
+ initiate:
+ not_allowed: "Вам не разрешено просматривать этот контент"
+ title: "Ссылки на выплаты"
+ status:
+ title: "Статус выплаты"
+ info:
+ ref_id: "ID ссылки"
+ error_code: "Код ошибки"
+ error_message: "Сообщение об ошибке"
+ message:
+ failed: "Не удалось обработать вашу выплату. Пожалуйста, проверьте у вашего поставщика более подробную информацию."
+ processing: "Ваша выплата должна быть обработана в течение 2-3 рабочих дней."
+ success: "Ваша выплата была произведена на выбранный метод оплаты."
+ redirection_text:
+ redirecting: "Перенаправление..."
+ redirecting_in: "Перенаправление через"
+ seconds: "секунд..."
+ text:
+ failed: "Выплата не удалась"
+ processing: "Выплата в процессе"
+ success: "Выплата успешна"
+
+time:
+ am: "AM"
+ pm: "PM"
+
+months:
+ january: "Январь"
+ february: "Февраль"
+ march: "Март"
+ april: "Апрель"
+ may: "Май"
+ june: "Июнь"
+ july: "Июль"
+ august: "Август"
+ september: "Сентябрь"
+ october: "Октябрь"
+ november: "Ноябрь"
+ december: "Декабрь"
diff --git a/crates/router/locales/sv.yml b/crates/router/locales/sv.yml
new file mode 100644
index 00000000000..8c053a2b096
--- /dev/null
+++ b/crates/router/locales/sv.yml
@@ -0,0 +1,42 @@
+_version: 1
+
+payout_link:
+ initiate:
+ not_allowed: "Du har inte tillåtelse att visa detta innehåll"
+ title: "Utbetalningslänkar"
+ status:
+ title: "Utbetalningsstatus"
+ info:
+ ref_id: "Referens-ID"
+ error_code: "Felkod"
+ error_message: "Felmeddelande"
+ message:
+ failed: "Det gick inte att behandla din utbetalning. Kontrollera med din leverantör för mer information."
+ processing: "Din utbetalning bör behandlas inom 2-3 arbetsdagar."
+ success: "Din utbetalning har genomförts till vald betalningsmetod."
+ redirection_text:
+ redirecting: "Omdirigerar..."
+ redirecting_in: "Omdirigerar om"
+ seconds: "sekunder..."
+ text:
+ failed: "Utbetalning Misslyckades"
+ processing: "Utbetalning Under Behandling"
+ success: "Utbetalning Lyckad"
+
+time:
+ am: "AM"
+ pm: "PM"
+
+months:
+ january: "Januari"
+ february: "Februari"
+ march: "Mars"
+ april: "April"
+ may: "Maj"
+ june: "Juni"
+ july: "Juli"
+ august: "Augusti"
+ september: "September"
+ october: "Oktober"
+ november: "November"
+ december: "December"
diff --git a/crates/router/locales/zh.yml b/crates/router/locales/zh.yml
new file mode 100644
index 00000000000..ce7cd3d3f95
--- /dev/null
+++ b/crates/router/locales/zh.yml
@@ -0,0 +1,42 @@
+_version: 1
+
+payout_link:
+ initiate:
+ not_allowed: "您没有权限查看此内容"
+ title: "支付链接"
+ status:
+ title: "支付状态"
+ info:
+ ref_id: "参考ID"
+ error_code: "错误代码"
+ error_message: "错误信息"
+ message:
+ failed: "处理您的支付时失败。请与您的服务提供商确认更多详细信息。"
+ processing: "您的支付应在2-3个工作日内处理完毕。"
+ success: "您的支付已成功完成,使用了选定的支付方式。"
+ redirection_text:
+ redirecting: "正在重定向..."
+ redirecting_in: "重定向中"
+ seconds: "秒..."
+ text:
+ failed: "支付失败"
+ processing: "支付处理中"
+ success: "支付成功"
+
+time:
+ am: "AM"
+ pm: "PM"
+
+months:
+ january: "一月"
+ february: "二月"
+ march: "三月"
+ april: "四月"
+ may: "五月"
+ june: "六月"
+ july: "七月"
+ august: "八月"
+ september: "九月"
+ october: "十月"
+ november: "十一月"
+ december: "十二月"
diff --git a/crates/router/src/compatibility/wrap.rs b/crates/router/src/compatibility/wrap.rs
index ec43259ad2f..2c1dea5f6db 100644
--- a/crates/router/src/compatibility/wrap.rs
+++ b/crates/router/src/compatibility/wrap.rs
@@ -142,6 +142,7 @@ where
let link_type = (boxed_generic_link_data).data.to_string();
match services::generic_link_response::build_generic_link_html(
boxed_generic_link_data.data,
+ boxed_generic_link_data.locale,
) {
Ok(rendered_html) => api::http_response_html_data(rendered_html, None),
Err(_) => {
diff --git a/crates/router/src/core/generic_link/payout_link/initiate/index.html b/crates/router/src/core/generic_link/payout_link/initiate/index.html
index 1857e497d3f..fe574c37c3c 100644
--- a/crates/router/src/core/generic_link/payout_link/initiate/index.html
+++ b/crates/router/src/core/generic_link/payout_link/initiate/index.html
@@ -3,7 +3,7 @@
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
- <title>Payout Links</title>
+ <title>{{ i18n_payout_link_title }}</title>
</head>
{{ css_style_tag }}
<body>
diff --git a/crates/router/src/core/generic_link/payout_link/initiate/script.js b/crates/router/src/core/generic_link/payout_link/initiate/script.js
index 731f3f76d0a..2327bfba13c 100644
--- a/crates/router/src/core/generic_link/payout_link/initiate/script.js
+++ b/crates/router/src/core/generic_link/payout_link/initiate/script.js
@@ -14,7 +14,7 @@ try {
// Remove the script from DOM incase it's not iframed
if (!isFramed) {
function initializePayoutSDK() {
- var errMsg = "You are not allowed to view this content.";
+ var errMsg = "{{i18n_not_allowed}}";
var contentElement = document.getElementById("payout-link");
if (contentElement instanceof HTMLDivElement) {
contentElement.innerHTML = errMsg;
@@ -34,25 +34,25 @@ if (!isFramed) {
**/
function formatDate(date) {
var months = [
- "January",
- "February",
- "March",
- "April",
- "May",
- "June",
- "July",
- "August",
- "September",
- "October",
- "November",
- "December",
+ "{{i18n_january}}",
+ "{{i18n_february}}",
+ "{{i18n_march}}",
+ "{{i18n_april}}",
+ "{{i18n_may}}",
+ "{{i18n_june}}",
+ "{{i18n_july}}",
+ "{{i18n_august}}",
+ "{{i18n_september}}",
+ "{{i18n_october}}",
+ "{{i18n_november}}",
+ "{{i18n_december}}",
];
var hours = date.getHours();
var minutes = date.getMinutes();
// @ts-ignore
minutes = minutes < 10 ? "0" + minutes : minutes;
- var suffix = hours > 11 ? "PM" : "AM";
+ var suffix = hours > 11 ? "{{i18n_pm}}" : "{{i18n_am}}";
hours = hours % 12;
hours = hours ? hours : 12;
var day = date.getDate();
@@ -127,6 +127,7 @@ if (!isFramed) {
// @ts-ignore
var payoutDetails = window.__PAYOUT_DETAILS;
var clientSecret = payoutDetails.client_secret;
+ var locale = payoutDetails.locale;
var publishableKey = payoutDetails.publishable_key;
var appearance = {
variables: {
@@ -143,6 +144,7 @@ if (!isFramed) {
widgets = hyper.widgets({
appearance: appearance,
clientSecret: clientSecret,
+ locale: locale,
});
// Create payment method collect widget
diff --git a/crates/router/src/core/generic_link/payout_link/status/index.html b/crates/router/src/core/generic_link/payout_link/status/index.html
index f0fb564f64b..4a4f0260563 100644
--- a/crates/router/src/core/generic_link/payout_link/status/index.html
+++ b/crates/router/src/core/generic_link/payout_link/status/index.html
@@ -3,7 +3,7 @@
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
- <title>Payout Status</title>
+ <title>{{ i18n_payout_link_status_title }}</title>
{{ css_style_tag }}
</head>
<body>
diff --git a/crates/router/src/core/generic_link/payout_link/status/script.js b/crates/router/src/core/generic_link/payout_link/status/script.js
index 829006a4311..42b57903593 100644
--- a/crates/router/src/core/generic_link/payout_link/status/script.js
+++ b/crates/router/src/core/generic_link/payout_link/status/script.js
@@ -69,8 +69,8 @@ function renderStatusDetails(payoutDetails) {
var statusInfo = {
statusImageSrc:
"https://live.hyperswitch.io/payment-link-assets/success.png",
- statusText: "Payout Successful",
- statusMessage: "Your payout was made to selected payment method.",
+ statusText: "{{i18n_success_text}}",
+ statusMessage: "{{i18n_success_message}}",
};
switch (status) {
case "success":
@@ -80,9 +80,8 @@ function renderStatusDetails(payoutDetails) {
case "pending":
statusInfo.statusImageSrc =
"https://live.hyperswitch.io/payment-link-assets/pending.png";
- statusInfo.statusText = "Payout Processing";
- statusInfo.statusMessage =
- "Your payout should be processed within 2-3 business days.";
+ statusInfo.statusText = "{{i18n_pending_text}}";
+ statusInfo.statusMessage = "{{i18n_pending_message}}";
break;
case "failed":
case "cancelled":
@@ -96,9 +95,8 @@ function renderStatusDetails(payoutDetails) {
default:
statusInfo.statusImageSrc =
"https://live.hyperswitch.io/payment-link-assets/failed.png";
- statusInfo.statusText = "Payout Failed";
- statusInfo.statusMessage =
- "Failed to process your payout. Please check with your provider for more details.";
+ statusInfo.statusText = "{{i18n_failed_text}}";
+ statusInfo.statusMessage = "{{i18n_failed_message}}";
break;
}
@@ -120,13 +118,13 @@ function renderStatusDetails(payoutDetails) {
}
var resourceInfo = {
- "Ref Id": payoutDetails.payout_id,
+ "{{i18n_ref_id_text}}": payoutDetails.payout_id,
};
if (typeof payoutDetails.error_code === "string") {
- resourceInfo["Error Code"] = payoutDetails.error_code;
+ resourceInfo["{{i18n_error_code_text}}"] = payoutDetails.error_code;
}
if (typeof payoutDetails.error_message === "string") {
- resourceInfo["Error Message"] = payoutDetails.error_message;
+ resourceInfo["{{i18n_error_message}}"] = payoutDetails.error_message;
}
var resourceNode = document.createElement("div");
resourceNode.id = "resource-info-container";
@@ -166,8 +164,10 @@ function redirectToEndUrl(returnUrl) {
var secondsLeft = timeout - j++;
var innerText =
secondsLeft === 0
- ? "Redirecting ..."
- : "Redirecting in " + secondsLeft + " seconds ...";
+ ? "{{i18n_redirecting_text}}"
+ : "{{i18n_redirecting_in_text}} " +
+ secondsLeft +
+ " {{i18n_seconds_text}} ...";
if (statusRedirectTextNode instanceof HTMLDivElement) {
statusRedirectTextNode.innerText = innerText;
}
diff --git a/crates/router/src/core/payment_link.rs b/crates/router/src/core/payment_link.rs
index 643b69511c7..df87637f4e4 100644
--- a/crates/router/src/core/payment_link.rs
+++ b/crates/router/src/core/payment_link.rs
@@ -7,8 +7,9 @@ use api_models::{
use common_utils::{
consts::{
DEFAULT_ALLOWED_DOMAINS, DEFAULT_BACKGROUND_COLOR, DEFAULT_DISPLAY_SDK_ONLY,
- DEFAULT_ENABLE_SAVED_PAYMENT_METHOD, DEFAULT_MERCHANT_LOGO, DEFAULT_PRODUCT_IMG,
- DEFAULT_SDK_LAYOUT, DEFAULT_SESSION_EXPIRY, DEFAULT_TRANSACTION_DETAILS,
+ DEFAULT_ENABLE_SAVED_PAYMENT_METHOD, DEFAULT_LOCALE, DEFAULT_MERCHANT_LOGO,
+ DEFAULT_PRODUCT_IMG, DEFAULT_SDK_LAYOUT, DEFAULT_SESSION_EXPIRY,
+ DEFAULT_TRANSACTION_DETAILS,
},
ext_traits::{OptionExt, ValueExt},
types::{AmountConvertor, MinorUnit, StringMajorUnitForCore},
@@ -342,6 +343,7 @@ pub async fn initiate_secure_payment_link_flow(
let link_data = GenericLinks {
allowed_domains,
data: GenericLinksData::SecurePaymentLink(payment_link_data),
+ locale: DEFAULT_LOCALE.to_string(),
};
logger::info!(
"payment link data, for building secure payment link {:?}",
diff --git a/crates/router/src/core/payment_methods.rs b/crates/router/src/core/payment_methods.rs
index a33fe5bb06a..977727d9115 100644
--- a/crates/router/src/core/payment_methods.rs
+++ b/crates/router/src/core/payment_methods.rs
@@ -12,7 +12,7 @@ pub use api_models::enums::Connector;
use api_models::payment_methods;
#[cfg(feature = "payouts")]
pub use api_models::{enums::PayoutConnectors, payouts as payout_types};
-use common_utils::{ext_traits::Encode, id_type::CustomerId};
+use common_utils::{consts::DEFAULT_LOCALE, ext_traits::Encode, id_type::CustomerId};
use diesel_models::{
enums, GenericLinkNew, PaymentMethodCollectLink, PaymentMethodCollectLinkData,
};
@@ -251,6 +251,7 @@ pub async fn render_pm_collect_link(
GenericLinks {
allowed_domains: HashSet::from([]),
data: GenericLinksData::ExpiredLink(expired_link_data),
+ locale: DEFAULT_LOCALE.to_string(),
},
)))
@@ -312,8 +313,8 @@ pub async fn render_pm_collect_link(
Ok(services::ApplicationResponse::GenericLinkForm(Box::new(
GenericLinks {
allowed_domains: HashSet::from([]),
-
data: GenericLinksData::PaymentMethodCollect(generic_form_data),
+ locale: DEFAULT_LOCALE.to_string(),
},
)))
}
@@ -357,8 +358,8 @@ pub async fn render_pm_collect_link(
Ok(services::ApplicationResponse::GenericLinkForm(Box::new(
GenericLinks {
allowed_domains: HashSet::from([]),
-
data: GenericLinksData::PaymentMethodCollectStatus(generic_status_data),
+ locale: DEFAULT_LOCALE.to_string(),
},
)))
}
diff --git a/crates/router/src/core/payout_link.rs b/crates/router/src/core/payout_link.rs
index da34a82a854..1b9445f180e 100644
--- a/crates/router/src/core/payout_link.rs
+++ b/crates/router/src/core/payout_link.rs
@@ -30,6 +30,7 @@ pub async fn initiate_payout_link(
key_store: domain::MerchantKeyStore,
req: payouts::PayoutLinkInitiateRequest,
request_headers: &header::HeaderMap,
+ locale: String,
) -> RouterResponse<services::GenericLinkFormData> {
let db: &dyn StorageInterface = &*state.store;
let merchant_id = merchant_account.get_id();
@@ -108,6 +109,7 @@ pub async fn initiate_payout_link(
GenericLinks {
allowed_domains: (link_data.allowed_domains),
data: GenericLinksData::ExpiredLink(expired_link_data),
+ locale,
},
)))
}
@@ -187,6 +189,7 @@ pub async fn initiate_payout_link(
enabled_payment_methods,
amount,
currency: payout.destination_currency,
+ locale: locale.clone(),
};
let serialized_css_content = String::new();
@@ -209,6 +212,7 @@ pub async fn initiate_payout_link(
GenericLinks {
allowed_domains: (link_data.allowed_domains),
data: GenericLinksData::PayoutLink(generic_form_data),
+ locale,
},
)))
}
@@ -251,6 +255,7 @@ pub async fn initiate_payout_link(
GenericLinks {
allowed_domains: (link_data.allowed_domains),
data: GenericLinksData::PayoutLinkStatus(generic_status_data),
+ locale,
},
)))
}
diff --git a/crates/router/src/core/payouts.rs b/crates/router/src/core/payouts.rs
index 2debb492ada..07b50d3a154 100644
--- a/crates/router/src/core/payouts.rs
+++ b/crates/router/src/core/payouts.rs
@@ -300,6 +300,7 @@ pub async fn payouts_create_core(
merchant_account: domain::MerchantAccount,
key_store: domain::MerchantKeyStore,
req: payouts::PayoutCreateRequest,
+ locale: &String,
) -> RouterResponse<payouts::PayoutCreateResponse> {
// Validate create request
let (payout_id, payout_method_data, profile_id, customer) =
@@ -314,6 +315,7 @@ pub async fn payouts_create_core(
&payout_id,
&profile_id,
payout_method_data.as_ref(),
+ locale,
customer.as_ref(),
)
.await?;
@@ -2206,6 +2208,7 @@ pub async fn payout_create_db_entries(
payout_id: &String,
profile_id: &String,
stored_payout_method_data: Option<&payouts::PayoutMethodData>,
+ locale: &String,
customer: Option<&domain::Customer>,
) -> RouterResult<PayoutData> {
let db = &*state.store;
@@ -2227,6 +2230,7 @@ pub async fn payout_create_db_entries(
merchant_id,
req,
payout_id,
+ locale,
)
.await?,
),
@@ -2552,6 +2556,7 @@ pub async fn create_payout_link(
merchant_id: &common_utils::id_type::MerchantId,
req: &payouts::PayoutCreateRequest,
payout_id: &String,
+ locale: &String,
) -> RouterResult<PayoutLink> {
let payout_link_config_req = req.payout_link_config.to_owned();
@@ -2595,8 +2600,9 @@ pub async fn create_payout_link(
.as_ref()
.map_or(default_config.expiry, |expiry| *expiry);
let url = format!(
- "{base_url}/payout_link/{}/{payout_id}",
- merchant_id.get_string_repr()
+ "{base_url}/payout_link/{}/{payout_id}?locale={}",
+ merchant_id.get_string_repr(),
+ locale
);
let link = url::Url::parse(&url)
.change_context(errors::ApiErrorResponse::InternalServerError)
diff --git a/crates/router/src/lib.rs b/crates/router/src/lib.rs
index 9691a536626..9f419831026 100644
--- a/crates/router/src/lib.rs
+++ b/crates/router/src/lib.rs
@@ -11,6 +11,7 @@ pub mod core;
pub mod cors;
pub mod db;
pub mod env;
+pub mod locale;
pub(crate) mod macros;
pub mod routes;
@@ -44,6 +45,9 @@ use crate::{configs::settings, core::errors};
#[global_allocator]
static ALLOC: mimalloc::MiMalloc = mimalloc::MiMalloc;
+// Import translate fn in root
+use crate::locale::{_rust_i18n_t, _rust_i18n_try_translate};
+
/// Header Constants
pub mod headers {
pub const ACCEPT: &str = "Accept";
diff --git a/crates/router/src/locale.rs b/crates/router/src/locale.rs
new file mode 100644
index 00000000000..94961434508
--- /dev/null
+++ b/crates/router/src/locale.rs
@@ -0,0 +1,3 @@
+use rust_i18n::i18n;
+
+i18n!("locales", fallback = "en");
diff --git a/crates/router/src/routes.rs b/crates/router/src/routes.rs
index 304a0cde0ba..561f96ab71a 100644
--- a/crates/router/src/routes.rs
+++ b/crates/router/src/routes.rs
@@ -28,6 +28,7 @@ pub mod metrics;
pub mod payment_link;
pub mod payment_methods;
pub mod payments;
+#[cfg(feature = "payouts")]
pub mod payout_link;
#[cfg(feature = "payouts")]
pub mod payouts;
diff --git a/crates/router/src/routes/payout_link.rs b/crates/router/src/routes/payout_link.rs
index 7bac4c5519c..87157435721 100644
--- a/crates/router/src/routes/payout_link.rs
+++ b/crates/router/src/routes/payout_link.rs
@@ -1,17 +1,17 @@
-#[cfg(feature = "payouts")]
use actix_web::{web, Responder};
-#[cfg(feature = "payouts")]
use api_models::payouts::PayoutLinkInitiateRequest;
-#[cfg(feature = "payouts")]
+use common_utils::consts::DEFAULT_LOCALE;
use router_env::Flow;
-#[cfg(feature = "payouts")]
use crate::{
core::{api_locking, payout_link::*},
- services::{api, authentication as auth},
+ headers::ACCEPT_LANGUAGE,
+ services::{
+ api,
+ authentication::{self as auth, get_header_value_by_key},
+ },
AppState,
};
-#[cfg(feature = "payouts")]
pub async fn render_payout_link(
state: web::Data<AppState>,
req: actix_web::HttpRequest,
@@ -24,13 +24,25 @@ pub async fn render_payout_link(
payout_id,
};
let headers = req.headers();
+ let locale = get_header_value_by_key(ACCEPT_LANGUAGE.into(), headers)
+ .ok()
+ .flatten()
+ .map(|val| val.to_string())
+ .unwrap_or(DEFAULT_LOCALE.to_string());
Box::pin(api::server_wrap(
flow,
state,
&req,
payload.clone(),
|state, auth, req, _| {
- initiate_payout_link(state, auth.merchant_account, auth.key_store, req, headers)
+ initiate_payout_link(
+ state,
+ auth.merchant_account,
+ auth.key_store,
+ req,
+ headers,
+ locale.clone(),
+ )
},
&auth::MerchantIdAuth(merchant_id),
api_locking::LockAction::NotApplicable,
diff --git a/crates/router/src/routes/payouts.rs b/crates/router/src/routes/payouts.rs
index 3c3d0f0a16b..40c2e36cc58 100644
--- a/crates/router/src/routes/payouts.rs
+++ b/crates/router/src/routes/payouts.rs
@@ -2,6 +2,7 @@ use actix_web::{
body::{BoxBody, MessageBody},
web, HttpRequest, HttpResponse, Responder,
};
+use common_utils::consts;
use router_env::{instrument, tracing, Flow};
use super::app::AppState;
@@ -9,7 +10,12 @@ use super::app::AppState;
use crate::types::api::payments as payment_types;
use crate::{
core::{api_locking, payouts::*},
- services::{api, authentication as auth, authorization::permissions::Permission},
+ headers::ACCEPT_LANGUAGE,
+ services::{
+ api,
+ authentication::{self as auth, get_header_value_by_key},
+ authorization::permissions::Permission,
+ },
types::api::payouts as payout_types,
};
@@ -21,13 +27,18 @@ pub async fn payouts_create(
json_payload: web::Json<payout_types::PayoutCreateRequest>,
) -> HttpResponse {
let flow = Flow::PayoutsCreate;
+ let locale = get_header_value_by_key(ACCEPT_LANGUAGE.into(), req.headers())
+ .ok()
+ .flatten()
+ .map(|val| val.to_string())
+ .unwrap_or(consts::DEFAULT_LOCALE.to_string());
Box::pin(api::server_wrap(
flow,
state,
&req,
json_payload.into_inner(),
|state, auth, req, _| {
- payouts_create_core(state, auth.merchant_account, auth.key_store, req)
+ payouts_create_core(state, auth.merchant_account, auth.key_store, req, &locale)
},
&auth::HeaderAuth(auth::ApiKeyAuth),
api_locking::LockAction::NotApplicable,
diff --git a/crates/router/src/services/api.rs b/crates/router/src/services/api.rs
index c715594e8d5..b2571e66231 100644
--- a/crates/router/src/services/api.rs
+++ b/crates/router/src/services/api.rs
@@ -982,7 +982,10 @@ where
Ok(ApplicationResponse::GenericLinkForm(boxed_generic_link_data)) => {
let link_type = boxed_generic_link_data.data.to_string();
- match build_generic_link_html(boxed_generic_link_data.data) {
+ match build_generic_link_html(
+ boxed_generic_link_data.data,
+ boxed_generic_link_data.locale,
+ ) {
Ok(rendered_html) => {
let headers = if !boxed_generic_link_data.allowed_domains.is_empty() {
let domains_str = boxed_generic_link_data
diff --git a/crates/router/src/services/api/generic_link_response.rs b/crates/router/src/services/api/generic_link_response.rs
index f180e3d3f33..c47539eb8db 100644
--- a/crates/router/src/services/api/generic_link_response.rs
+++ b/crates/router/src/services/api/generic_link_response.rs
@@ -7,9 +7,11 @@ use tera::{Context, Tera};
use super::build_secure_payment_link_html;
use crate::core::errors;
+pub mod context;
pub fn build_generic_link_html(
boxed_generic_link_data: GenericLinksData,
+ locale: String,
) -> CustomResult<String, errors::ApiErrorResponse> {
match boxed_generic_link_data {
GenericLinksData::ExpiredLink(link_data) => build_generic_expired_link_html(&link_data),
@@ -20,10 +22,12 @@ pub fn build_generic_link_html(
GenericLinksData::PaymentMethodCollectStatus(pm_collect_data) => {
build_pm_collect_link_status_html(&pm_collect_data)
}
- GenericLinksData::PayoutLink(payout_link_data) => build_payout_link_html(&payout_link_data),
+ GenericLinksData::PayoutLink(payout_link_data) => {
+ build_payout_link_html(&payout_link_data, locale.as_str())
+ }
GenericLinksData::PayoutLinkStatus(pm_collect_data) => {
- build_payout_link_status_html(&pm_collect_data)
+ build_payout_link_status_html(&pm_collect_data, locale.as_str())
}
GenericLinksData::SecurePaymentLink(payment_link_data) => {
build_secure_payment_link_html(payment_link_data)
@@ -52,7 +56,6 @@ pub fn build_generic_expired_link_html(
fn build_html_template(
link_data: &GenericLinkFormData,
document: &'static str,
- script: &'static str,
styles: &'static str,
) -> CustomResult<(Tera, Context), errors::ApiErrorResponse> {
let mut tera: Tera = Tera::default();
@@ -65,42 +68,43 @@ fn build_html_template(
let _ = tera.add_raw_template("document_styles", &final_css);
context.insert("color_scheme", &link_data.css_data);
- // Insert dynamic context in JS
- let js_dynamic_context = "{{ script_data }}";
- let js_template = script.to_string();
- let final_js = format!("{}\n{}", js_dynamic_context, js_template);
- let _ = tera.add_raw_template("document_scripts", &final_js);
- context.insert("script_data", &link_data.js_data);
-
let css_style_tag = tera
.render("document_styles", &context)
.map(|css| format!("<style>{}</style>", css))
.change_context(errors::ApiErrorResponse::InternalServerError)
.attach_printable("Failed to render CSS template")?;
- let js_script_tag = tera
- .render("document_scripts", &context)
- .map(|js| format!("<script>{}</script>", js))
- .change_context(errors::ApiErrorResponse::InternalServerError)
- .attach_printable("Failed to render JS template")?;
-
// Insert HTML context
let html_template = document.to_string();
let _ = tera.add_raw_template("html_template", &html_template);
context.insert("css_style_tag", &css_style_tag);
- context.insert("js_script_tag", &js_script_tag);
Ok((tera, context))
}
pub fn build_payout_link_html(
link_data: &GenericLinkFormData,
+ locale: &str,
) -> CustomResult<String, errors::ApiErrorResponse> {
let document = include_str!("../../core/generic_link/payout_link/initiate/index.html");
- let script = include_str!("../../core/generic_link/payout_link/initiate/script.js");
let styles = include_str!("../../core/generic_link/payout_link/initiate/styles.css");
- let (tera, mut context) = build_html_template(link_data, document, script, styles)
+ let (mut tera, mut context) = build_html_template(link_data, document, styles)
.attach_printable("Failed to build context for payout link's HTML template")?;
+
+ // Insert dynamic context in JS
+ let script = include_str!("../../core/generic_link/payout_link/initiate/script.js");
+ let js_template = script.to_string();
+ let js_dynamic_context = "{{ script_data }}";
+ let final_js = format!("{}\n{}", js_dynamic_context, js_template);
+ let _ = tera.add_raw_template("document_scripts", &final_js);
+ context.insert("script_data", &link_data.js_data);
+ context::insert_locales_in_context_for_payout_link(&mut context, locale);
+ let js_script_tag = tera
+ .render("document_scripts", &context)
+ .map(|js| format!("<script>{}</script>", js))
+ .change_context(errors::ApiErrorResponse::InternalServerError)
+ .attach_printable("Failed to render JS template")?;
+ context.insert("js_script_tag", &js_script_tag);
context.insert(
"hyper_sdk_loader_script_tag",
&format!(
@@ -109,6 +113,7 @@ pub fn build_payout_link_html(
),
);
+ // Render HTML template
tera.render("html_template", &context)
.change_context(errors::ApiErrorResponse::InternalServerError)
.attach_printable("Failed to render payout link's HTML template")
@@ -119,12 +124,25 @@ pub fn build_pm_collect_link_html(
) -> CustomResult<String, errors::ApiErrorResponse> {
let document =
include_str!("../../core/generic_link/payment_method_collect/initiate/index.html");
- let script = include_str!("../../core/generic_link/payment_method_collect/initiate/script.js");
let styles = include_str!("../../core/generic_link/payment_method_collect/initiate/styles.css");
- let (tera, mut context) = build_html_template(link_data, document, script, styles)
+ let (mut tera, mut context) = build_html_template(link_data, document, styles)
.attach_printable(
"Failed to build context for payment method collect link's HTML template",
)?;
+
+ // Insert dynamic context in JS
+ let script = include_str!("../../core/generic_link/payment_method_collect/initiate/script.js");
+ let js_template = script.to_string();
+ let js_dynamic_context = "{{ script_data }}";
+ let final_js = format!("{}\n{}", js_dynamic_context, js_template);
+ let _ = tera.add_raw_template("document_scripts", &final_js);
+ context.insert("script_data", &link_data.js_data);
+ let js_script_tag = tera
+ .render("document_scripts", &context)
+ .map(|js| format!("<script>{}</script>", js))
+ .change_context(errors::ApiErrorResponse::InternalServerError)
+ .attach_printable("Failed to render JS template")?;
+ context.insert("js_script_tag", &js_script_tag);
context.insert(
"hyper_sdk_loader_script_tag",
&format!(
@@ -133,6 +151,7 @@ pub fn build_pm_collect_link_html(
),
);
+ // Render HTML template
tera.render("html_template", &context)
.change_context(errors::ApiErrorResponse::InternalServerError)
.attach_printable("Failed to render payment method collect link's HTML template")
@@ -140,6 +159,7 @@ pub fn build_pm_collect_link_html(
pub fn build_payout_link_status_html(
link_data: &GenericLinkStatusData,
+ locale: &str,
) -> CustomResult<String, errors::ApiErrorResponse> {
let mut tera = Tera::default();
let mut context = Context::new();
@@ -159,13 +179,13 @@ pub fn build_payout_link_status_html(
.attach_printable("Failed to render payout link status CSS template")?;
// Insert dynamic context in JS
- let js_dynamic_context = "{{ collect_link_status_context }}";
+ let js_dynamic_context = "{{ script_data }}";
let js_template =
include_str!("../../core/generic_link/payout_link/status/script.js").to_string();
let final_js = format!("{}\n{}", js_dynamic_context, js_template);
let _ = tera.add_raw_template("payout_link_status_script", &final_js);
- context.insert("collect_link_status_context", &link_data.js_data);
-
+ context.insert("script_data", &link_data.js_data);
+ context::insert_locales_in_context_for_payout_link_status(&mut context, locale);
let js_script_tag = tera
.render("payout_link_status_script", &context)
.map(|js| format!("<script>{}</script>", js))
diff --git a/crates/router/src/services/api/generic_link_response/context.rs b/crates/router/src/services/api/generic_link_response/context.rs
new file mode 100644
index 00000000000..1ea45bd1083
--- /dev/null
+++ b/crates/router/src/services/api/generic_link_response/context.rs
@@ -0,0 +1,80 @@
+use rust_i18n::t;
+use tera::Context;
+
+pub fn insert_locales_in_context_for_payout_link(context: &mut Context, locale: &str) {
+ let i18n_payout_link_title = t!("payout_link.initiate.title", locale = locale);
+ let i18n_january = t!("months.january", locale = locale);
+ let i18n_february = t!("months.february", locale = locale);
+ let i18n_march = t!("months.march", locale = locale);
+ let i18n_april = t!("months.april", locale = locale);
+ let i18n_may = t!("months.may", locale = locale);
+ let i18n_june = t!("months.june", locale = locale);
+ let i18n_july = t!("months.july", locale = locale);
+ let i18n_august = t!("months.august", locale = locale);
+ let i18n_september = t!("months.september", locale = locale);
+ let i18n_october = t!("months.october", locale = locale);
+ let i18n_november = t!("months.november", locale = locale);
+ let i18n_december = t!("months.december", locale = locale);
+ let i18n_not_allowed = t!("payout_link.initiate.not_allowed", locale = locale);
+ let i18n_am = t!("time.am", locale = locale);
+ let i18n_pm = t!("time.pm", locale = locale);
+
+ context.insert("i18n_payout_link_title", &i18n_payout_link_title);
+ context.insert("i18n_january", &i18n_january);
+ context.insert("i18n_february", &i18n_february);
+ context.insert("i18n_march", &i18n_march);
+ context.insert("i18n_april", &i18n_april);
+ context.insert("i18n_may", &i18n_may);
+ context.insert("i18n_june", &i18n_june);
+ context.insert("i18n_july", &i18n_july);
+ context.insert("i18n_august", &i18n_august);
+ context.insert("i18n_september", &i18n_september);
+ context.insert("i18n_october", &i18n_october);
+ context.insert("i18n_november", &i18n_november);
+ context.insert("i18n_december", &i18n_december);
+ context.insert("i18n_not_allowed", &i18n_not_allowed);
+ context.insert("i18n_am", &i18n_am);
+ context.insert("i18n_pm", &i18n_pm);
+}
+
+pub fn insert_locales_in_context_for_payout_link_status(context: &mut Context, locale: &str) {
+ let i18n_payout_link_status_title = t!("payout_link.status.title", locale = locale);
+ let i18n_success_text = t!("payout_link.status.text.success", locale = locale);
+ let i18n_success_message = t!("payout_link.status.message.success", locale = locale);
+ let i18n_pending_text = t!("payout_link.status.text.pending", locale = locale);
+ let i18n_pending_message = t!("payout_link.status.message.pending", locale = locale);
+ let i18n_failed_text = t!("payout_link.status.text.failed", locale = locale);
+ let i18n_failed_message = t!("payout_link.status.message.failed", locale = locale);
+ let i18n_ref_id_text = t!("payout_link.status.info.ref_id", locale = locale);
+ let i18n_error_code_text = t!("payout_link.status.info.error_code", locale = locale);
+ let i18n_error_message = t!("payout_link.status.info.error_message", locale = locale);
+ let i18n_redirecting_text = t!(
+ "payout_link.status.redirection_text.redirecting",
+ locale = locale
+ );
+ let i18n_redirecting_in_text = t!(
+ "payout_link.status.redirection_text.redirecting_in",
+ locale = locale
+ );
+ let i18n_seconds_text = t!(
+ "payout_link.status.redirection_text.seconds",
+ locale = locale
+ );
+
+ context.insert(
+ "i18n_payout_link_status_title",
+ &i18n_payout_link_status_title,
+ );
+ context.insert("i18n_success_text", &i18n_success_text);
+ context.insert("i18n_success_message", &i18n_success_message);
+ context.insert("i18n_pending_text", &i18n_pending_text);
+ context.insert("i18n_pending_message", &i18n_pending_message);
+ context.insert("i18n_failed_text", &i18n_failed_text);
+ context.insert("i18n_failed_message", &i18n_failed_message);
+ context.insert("i18n_ref_id_text", &i18n_ref_id_text);
+ context.insert("i18n_error_code_text", &i18n_error_code_text);
+ context.insert("i18n_error_message", &i18n_error_message);
+ context.insert("i18n_redirecting_text", &i18n_redirecting_text);
+ context.insert("i18n_redirecting_in_text", &i18n_redirecting_in_text);
+ context.insert("i18n_seconds_text", &i18n_seconds_text);
+}
|
2024-08-07T09:24:07Z
|
## Type of Change
<!-- Put an `x` in the boxes that apply -->
- [ ] Bugfix
- [x] New feature
- [ ] Enhancement
- [ ] Refactoring
- [ ] Dependency updates
- [ ] Documentation
- [ ] CI/CD
## Description
Described in #5559
This uses a forked version of `rust-i18n` which handles string index slicing
original - https://github.com/longbridgeapp/rust-i18n
forked - https://github.com/kashif-m/rust-i18n/commits/v3.1.1-safe
### Additional Changes
- [ ] This PR modifies the API contract
- [ ] This PR modifies the database schema
- [ ] This PR modifies application configuration/environment variables
<!--
Provide links to the files with corresponding changes.
Following are the paths where you can find config files:
1. `config`
2. `crates/router/src/configs`
3. `loadtest/config`
-->
## How did you test it?
<details>
<summary>
1. Create a payout link (without passing any locale in create request)
</summary>
```curl
curl --location 'http://localhost:8080/payouts/create' \
--header 'Content-Type: application/json' \
--header 'api-key: dev_cp78v8fT2C03KkEClI9aBMrqKF6N0SBLyUjasXtUQMbLTasfR2LJwjg0LlNHY060' \
--data '{
"amount": 1,
"currency": "EUR",
"customer_id": "cus_05845u0qSuOENDnHLqTl",
"description": "Its my first payout request",
"billing": {
"address": {
"city": "Hoogeveen",
"country": "NL",
"line1": "Raadhuisplein",
"line2": "92",
"zip": "7901 BW",
"state": "FL",
"first_name": "John",
"last_name": "Doe"
},
"phone": {
"number": "0650242319",
"country_code": "+31"
}
},
"entity_type": "Individual",
"confirm": false,
"auto_fulfill": true,
"session_expiry": 1000000,
"priority": "instant",
"profile_id": "pro_Qr3Tm0ncxuiKXvdt6u2H",
"payout_link": true,
"payout_link_config": {
"theme": "#0066ff",
"logo": "https://hyperswitch.io/favicon.ico",
"merchant_name": "HyperSwitch Inc."
}
}'
```


</details>
<details>
<summary>2. Create a payout link (pass locale in create request)</summary>
```curl
curl --location 'http://localhost:8080/payouts/create' \
--header 'Accept-Language: fr' \
--header 'Content-Type: application/json' \
--header 'api-key: dev_cp78v8fT2C03KkEClI9aBMrqKF6N0SBLyUjasXtUQMbLTasfR2LJwjg0LlNHY060' \
--data '{
"amount": 1,
"currency": "EUR",
"customer_id": "cus_05845u0qSuOENDnHLqTl",
"description": "Its my first payout request",
"billing": {
"address": {
"city": "Hoogeveen",
"country": "NL",
"line1": "Raadhuisplein",
"line2": "92",
"zip": "7901 BW",
"state": "FL",
"first_name": "John",
"last_name": "Doe"
},
"phone": {
"number": "0650242319",
"country_code": "+31"
}
},
"entity_type": "Individual",
"confirm": false,
"auto_fulfill": true,
"session_expiry": 1000000,
"priority": "instant",
"profile_id": "pro_Qr3Tm0ncxuiKXvdt6u2H",
"payout_link": true,
"payout_link_config": {
"theme": "#0066ff",
"logo": "https://hyperswitch.io/favicon.ico",
"merchant_name": "HyperSwitch Inc."
}
}'
```

*fr*

*zh*

</details>
## Checklist
<!-- Put an `x` in the boxes that apply -->
- [x] I formatted the code `cargo +nightly fmt --all`
- [x] I addressed lints thrown by `cargo clippy`
- [ ] I reviewed the submitted code
- [ ] I added unit tests for my changes where possible
|
942e63d9cd607913d4ef7d5a01493a1615a783c1
|
|
juspay/hyperswitch
|
juspay__hyperswitch-5565
|
Bug: Implement API models for Payment methods v2
Need to implement API models for v2 of Payment Methods
|
diff --git a/api-reference-v2/openapi_spec.json b/api-reference-v2/openapi_spec.json
index 757beea4b65..0505dd498e3 100644
--- a/api-reference-v2/openapi_spec.json
+++ b/api-reference-v2/openapi_spec.json
@@ -10283,17 +10283,6 @@
}
}
},
- {
- "type": "object",
- "required": [
- "paypal"
- ],
- "properties": {
- "paypal": {
- "type": "object"
- }
- }
- },
{
"type": "object",
"required": [
diff --git a/crates/api_models/src/payment_methods.rs b/crates/api_models/src/payment_methods.rs
index c90031dc077..de94d4f5872 100644
--- a/crates/api_models/src/payment_methods.rs
+++ b/crates/api_models/src/payment_methods.rs
@@ -1,4 +1,6 @@
use std::collections::{HashMap, HashSet};
+#[cfg(all(feature = "v2", feature = "payment_methods_v2"))]
+use std::str::FromStr;
use cards::CardNumber;
use common_utils::{
@@ -20,6 +22,10 @@ use crate::{
payments::{self, BankCodeResponse},
};
+#[cfg(all(
+ any(feature = "v1", feature = "v2"),
+ not(feature = "payment_methods_v2")
+))]
#[derive(Debug, serde::Deserialize, serde::Serialize, Clone, ToSchema)]
#[serde(deny_unknown_fields)]
pub struct PaymentMethodCreate {
@@ -96,6 +102,66 @@ pub struct PaymentMethodCreate {
pub network_transaction_id: Option<String>,
}
+#[cfg(all(feature = "v2", feature = "payment_methods_v2"))]
+#[derive(Debug, serde::Deserialize, serde::Serialize, Clone, ToSchema)]
+#[serde(deny_unknown_fields)]
+pub struct PaymentMethodCreate {
+ /// The type of payment method use for the payment.
+ #[schema(value_type = PaymentMethod,example = "card")]
+ pub payment_method: api_enums::PaymentMethod,
+
+ /// This is a sub-category of payment method.
+ #[schema(value_type = PaymentMethodType,example = "credit")]
+ pub payment_method_type: api_enums::PaymentMethodType,
+
+ /// You can specify up to 50 keys, with key names up to 40 characters long and values up to 500 characters long. Metadata is useful for storing additional, structured information on an object.
+ #[schema(value_type = Option<Object>,example = json!({ "city": "NY", "unit": "245" }))]
+ pub metadata: Option<pii::SecretSerdeValue>,
+
+ /// The unique identifier of the customer.
+ #[schema(value_type = String, max_length = 64, min_length = 1, example = "cus_y3oqhf46pyzuxjbcn2giaqnb44")]
+ pub customer_id: id_type::CustomerId,
+
+ /// Payment method data to be passed
+ pub payment_method_data: PaymentMethodCreateData,
+
+ /// The billing details of the payment method
+ #[schema(value_type = Option<Address>)]
+ pub billing: Option<payments::Address>,
+}
+
+#[cfg(all(feature = "v2", feature = "payment_methods_v2"))]
+#[derive(Debug, serde::Deserialize, serde::Serialize, Clone, ToSchema)]
+#[serde(deny_unknown_fields)]
+pub struct PaymentMethodIntentCreate {
+ /// You can specify up to 50 keys, with key names up to 40 characters long and values up to 500 characters long. Metadata is useful for storing additional, structured information on an object.
+ #[schema(value_type = Option<Object>,example = json!({ "city": "NY", "unit": "245" }))]
+ pub metadata: Option<pii::SecretSerdeValue>,
+
+ /// The billing details of the payment method
+ #[schema(value_type = Option<Address>)]
+ pub billing: Option<payments::Address>,
+
+ /// The unique identifier of the customer.
+ #[schema(value_type = String, max_length = 64, min_length = 1, example = "cus_y3oqhf46pyzuxjbcn2giaqnb44")]
+ pub customer_id: id_type::CustomerId,
+}
+
+#[cfg(all(feature = "v2", feature = "payment_methods_v2"))]
+#[derive(Debug, serde::Deserialize, serde::Serialize, Clone, ToSchema)]
+#[serde(deny_unknown_fields)]
+pub struct PaymentMethodIntentConfirm {
+ /// For SDK based calls, client_secret would be required
+ pub client_secret: String,
+
+ /// The unique identifier of the customer.
+ #[schema(value_type = Option<String>, max_length = 64, min_length = 1, example = "cus_y3oqhf46pyzuxjbcn2giaqnb44")]
+ pub customer_id: Option<id_type::CustomerId>,
+
+ /// Payment method data to be passed
+ pub payment_method_data: PaymentMethodCreateData,
+}
+
#[derive(Debug, serde::Deserialize, serde::Serialize, Clone)]
/// This struct is only used by and internal api to migrate payment method
pub struct PaymentMethodMigrate {
@@ -159,6 +225,10 @@ pub struct PaymentsMandateReferenceRecord {
pub original_payment_authorized_currency: Option<common_enums::Currency>,
}
+#[cfg(all(
+ any(feature = "v1", feature = "v2"),
+ not(feature = "payment_methods_v2")
+))]
impl PaymentMethodCreate {
pub fn get_payment_method_create_from_payment_method_migrate(
card_number: CardNumber,
@@ -202,6 +272,20 @@ impl PaymentMethodCreate {
}
}
+#[cfg(all(feature = "v2", feature = "payment_methods_v2"))]
+impl PaymentMethodCreate {
+ pub fn get_payment_method_create_from_payment_method_migrate(
+ _card_number: CardNumber,
+ _payment_method_migrate: &PaymentMethodMigrate,
+ ) -> Self {
+ todo!()
+ }
+}
+
+#[cfg(all(
+ any(feature = "v1", feature = "v2"),
+ not(feature = "payment_methods_v2")
+))]
#[derive(Debug, serde::Deserialize, serde::Serialize, Clone, ToSchema)]
#[serde(deny_unknown_fields)]
pub struct PaymentMethodUpdate {
@@ -218,15 +302,58 @@ pub struct PaymentMethodUpdate {
pub client_secret: Option<String>,
}
+#[cfg(all(feature = "v2", feature = "payment_methods_v2"))]
+#[derive(Debug, serde::Deserialize, serde::Serialize, Clone, ToSchema)]
+#[serde(deny_unknown_fields)]
+pub struct PaymentMethodUpdate {
+ /// payment method data to be passed
+ pub payment_method_data: Option<PaymentMethodUpdateData>,
+
+ /// This is a 15 minute expiry token which shall be used from the client to authenticate and perform sessions from the SDK
+ #[schema(max_length = 30, min_length = 30, example = "secret_k2uj3he2893eiu2d")]
+ pub client_secret: Option<String>,
+}
+
+#[cfg(all(feature = "v2", feature = "payment_methods_v2"))]
+#[derive(Debug, serde::Deserialize, serde::Serialize, Clone, ToSchema)]
+#[serde(deny_unknown_fields)]
+#[serde(rename_all = "snake_case")]
+#[serde(rename = "payment_method_data")]
+pub enum PaymentMethodUpdateData {
+ Card(CardDetailUpdate),
+}
+
+#[cfg(all(feature = "v2", feature = "payment_methods_v2"))]
#[derive(Debug, serde::Deserialize, serde::Serialize, Clone, ToSchema)]
#[serde(deny_unknown_fields)]
#[serde(rename_all = "snake_case")]
#[serde(rename = "payment_method_data")]
+pub enum PaymentMethodCreateData {
+ Card(CardDetail),
+ #[cfg(feature = "payouts")]
+ #[schema(value_type = Bank)]
+ BankTransfer(payouts::Bank),
+ #[cfg(feature = "payouts")]
+ #[schema(value_type = Wallet)]
+ Wallet(payouts::Wallet),
+}
+#[cfg(all(
+ any(feature = "v1", feature = "v2"),
+ not(feature = "payment_methods_v2")
+))]
+#[derive(Debug, serde::Deserialize, serde::Serialize, Clone, ToSchema)]
+#[serde(deny_unknown_fields)]
+#[serde(rename_all = "snake_case")]
+#[serde(rename = "payment_method_data")]
pub enum PaymentMethodCreateData {
Card(CardDetail),
}
+#[cfg(all(
+ any(feature = "v1", feature = "v2"),
+ not(feature = "payment_methods_v2")
+))]
#[derive(Debug, serde::Deserialize, serde::Serialize, Clone, ToSchema)]
#[serde(deny_unknown_fields)]
pub struct CardDetail {
@@ -264,6 +391,54 @@ pub struct CardDetail {
pub card_type: Option<String>,
}
+#[cfg(all(feature = "v2", feature = "payment_methods_v2"))]
+#[derive(
+ Debug, serde::Deserialize, serde::Serialize, Clone, ToSchema, strum::EnumString, strum::Display,
+)]
+#[serde(rename_all = "snake_case")]
+pub enum CardType {
+ Credit,
+ Debit,
+}
+
+#[cfg(all(feature = "v2", feature = "payment_methods_v2"))]
+#[derive(Debug, serde::Deserialize, serde::Serialize, Clone, ToSchema)]
+#[serde(deny_unknown_fields)]
+pub struct CardDetail {
+ /// Card Number
+ #[schema(value_type = String,example = "4111111145551142")]
+ pub card_number: CardNumber,
+
+ /// Card Expiry Month
+ #[schema(value_type = String,example = "10")]
+ pub card_exp_month: masking::Secret<String>,
+
+ /// Card Expiry Year
+ #[schema(value_type = String,example = "25")]
+ pub card_exp_year: masking::Secret<String>,
+
+ /// Card Holder Name
+ #[schema(value_type = String,example = "John Doe")]
+ pub card_holder_name: Option<masking::Secret<String>>,
+
+ /// Card Holder's Nick Name
+ #[schema(value_type = Option<String>,example = "John Doe")]
+ pub nick_name: Option<masking::Secret<String>>,
+
+ /// Card Issuing Country
+ pub card_issuing_country: Option<api_enums::CountryAlpha2>,
+
+ /// Card's Network
+ #[schema(value_type = Option<CardNetwork>)]
+ pub card_network: Option<api_enums::CardNetwork>,
+
+ /// Issuer Bank for Card
+ pub card_issuer: Option<String>,
+
+ /// Card Type
+ pub card_type: Option<CardType>,
+}
+
#[derive(Debug, serde::Deserialize, serde::Serialize, Clone, ToSchema)]
#[serde(deny_unknown_fields)]
pub struct MigrateCardDetail {
@@ -301,6 +476,10 @@ pub struct MigrateCardDetail {
pub card_type: Option<String>,
}
+#[cfg(all(
+ any(feature = "v1", feature = "v2"),
+ not(feature = "payment_methods_v2")
+))]
#[derive(Debug, serde::Deserialize, serde::Serialize, Clone, ToSchema)]
#[serde(deny_unknown_fields)]
pub struct CardDetailUpdate {
@@ -321,6 +500,10 @@ pub struct CardDetailUpdate {
pub nick_name: Option<masking::Secret<String>>,
}
+#[cfg(all(
+ any(feature = "v1", feature = "v2"),
+ not(feature = "payment_methods_v2")
+))]
impl CardDetailUpdate {
pub fn apply(&self, card_data_from_locker: Card) -> CardDetail {
CardDetail {
@@ -349,6 +532,58 @@ impl CardDetailUpdate {
}
}
+#[cfg(all(feature = "v2", feature = "payment_methods_v2"))]
+#[derive(Debug, serde::Deserialize, serde::Serialize, Clone, ToSchema)]
+#[serde(deny_unknown_fields)]
+pub struct CardDetailUpdate {
+ /// Card Holder Name
+ #[schema(value_type = String,example = "John Doe")]
+ pub card_holder_name: Option<masking::Secret<String>>,
+
+ /// Card Holder's Nick Name
+ #[schema(value_type = Option<String>,example = "John Doe")]
+ pub nick_name: Option<masking::Secret<String>>,
+}
+
+#[cfg(all(feature = "v2", feature = "payment_methods_v2"))]
+impl CardDetailUpdate {
+ pub fn apply(&self, card_data_from_locker: Card) -> CardDetail {
+ CardDetail {
+ card_number: card_data_from_locker.card_number,
+ card_exp_month: card_data_from_locker.card_exp_month,
+ card_exp_year: card_data_from_locker.card_exp_year,
+ card_holder_name: self
+ .card_holder_name
+ .clone()
+ .or(card_data_from_locker.name_on_card),
+ nick_name: self
+ .nick_name
+ .clone()
+ .or(card_data_from_locker.nick_name.map(masking::Secret::new)),
+ card_issuing_country: None,
+ card_network: None,
+ card_issuer: None,
+ card_type: None,
+ }
+ }
+}
+
+#[cfg(all(feature = "v2", feature = "payment_methods_v2"))]
+#[derive(Debug, serde::Deserialize, serde::Serialize, Clone, ToSchema)]
+#[serde(deny_unknown_fields)]
+#[serde(rename_all = "snake_case")]
+#[serde(rename = "payment_method_data")]
+pub enum PaymentMethodResponseData {
+ Card(CardDetailFromLocker),
+ #[cfg(feature = "payouts")]
+ #[schema(value_type = Bank)]
+ Bank(payouts::Bank),
+}
+
+#[cfg(all(
+ any(feature = "v1", feature = "v2"),
+ not(feature = "payment_methods_v2")
+))]
#[derive(Debug, serde::Deserialize, serde::Serialize, ToSchema)]
pub struct PaymentMethodResponse {
/// Unique identifier for a merchant
@@ -410,6 +645,52 @@ pub struct PaymentMethodResponse {
pub client_secret: Option<String>,
}
+#[cfg(all(feature = "v2", feature = "payment_methods_v2"))]
+#[derive(Debug, serde::Deserialize, serde::Serialize, ToSchema, Clone)]
+pub struct PaymentMethodResponse {
+ /// Unique identifier for a merchant
+ #[schema(example = "merchant_1671528864")]
+ pub merchant_id: id_type::MerchantId,
+
+ /// The unique identifier of the customer.
+ #[schema(value_type = Option<String>, max_length = 64, min_length = 1, example = "cus_y3oqhf46pyzuxjbcn2giaqnb44")]
+ pub customer_id: id_type::CustomerId,
+
+ /// The unique identifier of the Payment method
+ #[schema(example = "card_rGK4Vi5iSW70MY7J2mIg")]
+ pub payment_method_id: String,
+
+ /// The type of payment method use for the payment.
+ #[schema(value_type = PaymentMethod, example = "card")]
+ pub payment_method: Option<api_enums::PaymentMethod>,
+
+ /// This is a sub-category of payment method.
+ #[schema(value_type = Option<PaymentMethodType>, example = "credit")]
+ pub payment_method_type: Option<api_enums::PaymentMethodType>,
+
+ /// Indicates whether the payment method is eligible for recurring payments
+ #[schema(example = true)]
+ pub recurring_enabled: bool,
+
+ /// You can specify up to 50 keys, with key names up to 40 characters long and values up to 500 characters long. Metadata is useful for storing additional, structured information on an object.
+ #[schema(value_type = Option<Object>, example = json!({ "city": "NY", "unit": "245" }))]
+ pub metadata: Option<pii::SecretSerdeValue>,
+
+ /// A timestamp (ISO 8601 code) that determines when the customer was created
+ #[schema(value_type = Option<PrimitiveDateTime>, example = "2023-01-18T11:04:09.922Z")]
+ #[serde(default, with = "common_utils::custom_serde::iso8601::option")]
+ pub created: Option<time::PrimitiveDateTime>,
+
+ #[schema(value_type = Option<PrimitiveDateTime>, example = "2024-02-24T11:04:09.922Z")]
+ #[serde(default, with = "common_utils::custom_serde::iso8601::option")]
+ pub last_used_at: Option<time::PrimitiveDateTime>,
+
+ /// For Client based calls
+ pub client_secret: Option<String>,
+
+ pub payment_method_data: Option<PaymentMethodResponseData>,
+}
+
#[derive(Clone, Debug, Eq, PartialEq, serde::Deserialize, serde::Serialize)]
pub enum PaymentMethodsData {
Card(CardDetailsPaymentMethod),
@@ -469,12 +750,53 @@ pub struct Card {
pub card_exp_year: masking::Secret<String>,
pub card_brand: Option<String>,
pub card_isin: Option<String>,
- pub nick_name: Option<String>,
+ pub nick_name: Option<String>,
+}
+
+#[cfg(all(
+ any(feature = "v1", feature = "v2"),
+ not(feature = "payment_methods_v2")
+))]
+#[derive(Debug, serde::Deserialize, serde::Serialize, Clone, ToSchema)]
+pub struct CardDetailFromLocker {
+ pub scheme: Option<String>,
+ pub issuer_country: Option<String>,
+ pub last4_digits: Option<String>,
+ #[serde(skip)]
+ #[schema(value_type=Option<String>)]
+ pub card_number: Option<CardNumber>,
+
+ #[schema(value_type=Option<String>)]
+ pub expiry_month: Option<masking::Secret<String>>,
+
+ #[schema(value_type=Option<String>)]
+ pub expiry_year: Option<masking::Secret<String>>,
+
+ #[schema(value_type=Option<String>)]
+ pub card_token: Option<masking::Secret<String>>,
+
+ #[schema(value_type=Option<String>)]
+ pub card_holder_name: Option<masking::Secret<String>>,
+
+ #[schema(value_type=Option<String>)]
+ pub card_fingerprint: Option<masking::Secret<String>>,
+
+ #[schema(value_type=Option<String>)]
+ pub nick_name: Option<masking::Secret<String>>,
+
+ #[schema(value_type = Option<CardNetwork>)]
+ pub card_network: Option<api_enums::CardNetwork>,
+
+ pub card_isin: Option<String>,
+ pub card_issuer: Option<String>,
+ pub card_type: Option<String>,
+ pub saved_to_locker: bool,
}
+
+#[cfg(all(feature = "v2", feature = "payment_methods_v2"))]
#[derive(Debug, serde::Deserialize, serde::Serialize, Clone, ToSchema)]
pub struct CardDetailFromLocker {
- pub scheme: Option<String>,
- pub issuer_country: Option<String>,
+ pub issuer_country: Option<api_enums::CountryAlpha2>,
pub last4_digits: Option<String>,
#[serde(skip)]
#[schema(value_type=Option<String>)]
@@ -486,9 +808,6 @@ pub struct CardDetailFromLocker {
#[schema(value_type=Option<String>)]
pub expiry_year: Option<masking::Secret<String>>,
- #[schema(value_type=Option<String>)]
- pub card_token: Option<masking::Secret<String>>,
-
#[schema(value_type=Option<String>)]
pub card_holder_name: Option<masking::Secret<String>>,
@@ -511,6 +830,10 @@ fn saved_in_locker_default() -> bool {
true
}
+#[cfg(all(
+ any(feature = "v1", feature = "v2"),
+ not(feature = "payment_methods_v2")
+))]
impl From<CardDetailFromLocker> for payments::AdditionalCardInfo {
fn from(item: CardDetailFromLocker) -> Self {
Self {
@@ -533,6 +856,33 @@ impl From<CardDetailFromLocker> for payments::AdditionalCardInfo {
}
}
+#[cfg(all(feature = "v2", feature = "payment_methods_v2"))]
+impl From<CardDetailFromLocker> for payments::AdditionalCardInfo {
+ fn from(item: CardDetailFromLocker) -> Self {
+ Self {
+ card_issuer: item.card_issuer,
+ card_network: item.card_network,
+ card_type: item.card_type,
+ card_issuing_country: item.issuer_country.map(|country| country.to_string()),
+ bank_code: None,
+ last4: item.last4_digits,
+ card_isin: item.card_isin,
+ card_extended_bin: item
+ .card_number
+ .map(|card_number| card_number.get_extended_card_bin()),
+ card_exp_month: item.expiry_month,
+ card_exp_year: item.expiry_year,
+ card_holder_name: item.card_holder_name,
+ payment_checks: None,
+ authentication_data: None,
+ }
+ }
+}
+
+#[cfg(all(
+ any(feature = "v1", feature = "v2"),
+ not(feature = "payment_methods_v2")
+))]
impl From<CardDetailsPaymentMethod> for CardDetailFromLocker {
fn from(item: CardDetailsPaymentMethod) -> Self {
Self {
@@ -555,6 +905,37 @@ impl From<CardDetailsPaymentMethod> for CardDetailFromLocker {
}
}
+#[cfg(all(feature = "v2", feature = "payment_methods_v2"))]
+impl From<CardDetailsPaymentMethod> for CardDetailFromLocker {
+ fn from(item: CardDetailsPaymentMethod) -> Self {
+ Self {
+ issuer_country: item
+ .issuer_country
+ .as_ref()
+ .map(|c| api_enums::CountryAlpha2::from_str(c))
+ .transpose()
+ .ok()
+ .flatten(),
+ last4_digits: item.last4_digits,
+ card_number: None,
+ expiry_month: item.expiry_month,
+ expiry_year: item.expiry_year,
+ card_holder_name: item.card_holder_name,
+ card_fingerprint: None,
+ nick_name: item.nick_name,
+ card_isin: item.card_isin,
+ card_issuer: item.card_issuer,
+ card_network: item.card_network,
+ card_type: item.card_type,
+ saved_to_locker: item.saved_to_locker,
+ }
+ }
+}
+
+#[cfg(all(
+ any(feature = "v1", feature = "v2"),
+ not(feature = "payment_methods_v2")
+))]
impl From<CardDetailFromLocker> for CardDetailsPaymentMethod {
fn from(item: CardDetailFromLocker) -> Self {
Self {
@@ -573,6 +954,25 @@ impl From<CardDetailFromLocker> for CardDetailsPaymentMethod {
}
}
+#[cfg(all(feature = "v2", feature = "payment_methods_v2"))]
+impl From<CardDetailFromLocker> for CardDetailsPaymentMethod {
+ fn from(item: CardDetailFromLocker) -> Self {
+ Self {
+ issuer_country: item.issuer_country.map(|country| country.to_string()),
+ last4_digits: item.last4_digits,
+ expiry_month: item.expiry_month,
+ expiry_year: item.expiry_year,
+ nick_name: item.nick_name,
+ card_holder_name: item.card_holder_name,
+ card_isin: item.card_isin,
+ card_issuer: item.card_issuer,
+ card_network: item.card_network,
+ card_type: item.card_type,
+ saved_to_locker: item.saved_to_locker,
+ }
+ }
+}
+
#[derive(Debug, Clone, serde::Serialize, serde::Deserialize, ToSchema, PartialEq, Eq)]
pub struct PaymentExperienceTypes {
/// The payment experience enabled
@@ -783,6 +1183,10 @@ pub struct RequestPaymentMethodTypes {
pub installment_payment_enabled: bool,
}
+#[cfg(all(
+ any(feature = "v1", feature = "v2"),
+ not(feature = "payment_methods_v2")
+))]
//List Payment Method
#[derive(Debug, Clone, serde::Serialize, Default, ToSchema)]
#[serde(deny_unknown_fields)]
@@ -820,6 +1224,10 @@ pub struct PaymentMethodListRequest {
pub limit: Option<i64>,
}
+#[cfg(all(
+ any(feature = "v1", feature = "v2"),
+ not(feature = "payment_methods_v2")
+))]
impl<'de> serde::Deserialize<'de> for PaymentMethodListRequest {
fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
where
@@ -901,6 +1309,115 @@ impl<'de> serde::Deserialize<'de> for PaymentMethodListRequest {
}
}
+#[cfg(all(feature = "v2", feature = "payment_methods_v2"))]
+//List Payment Method
+#[derive(Debug, Clone, serde::Serialize, Default, ToSchema)]
+#[serde(deny_unknown_fields)]
+pub struct PaymentMethodListRequest {
+ /// This is a 15 minute expiry token which shall be used from the client to authenticate and perform sessions from the SDK
+ #[schema(max_length = 30, min_length = 30, example = "secret_k2uj3he2893eiu2d")]
+ pub client_secret: Option<String>,
+
+ /// The two-letter ISO currency code
+ #[schema(value_type = Option<Vec<CountryAlpha2>>, example = json!(["US", "UK", "IN"]))]
+ pub accepted_countries: Option<Vec<api_enums::CountryAlpha2>>,
+
+ /// Filter by amount
+ #[schema(example = 60)]
+ pub amount: Option<MinorUnit>,
+
+ /// The three-letter ISO currency code
+ #[schema(value_type = Option<Vec<Currency>>,example = json!(["USD", "EUR"]))]
+ pub accepted_currencies: Option<Vec<api_enums::Currency>>,
+
+ /// Indicates whether the payment method is eligible for recurring payments
+ #[schema(example = true)]
+ pub recurring_enabled: Option<bool>,
+
+ /// Indicates whether the payment method is eligible for card netwotks
+ #[schema(value_type = Option<Vec<CardNetwork>>, example = json!(["visa", "mastercard"]))]
+ pub card_networks: Option<Vec<api_enums::CardNetwork>>,
+
+ /// Indicates the limit of last used payment methods
+ #[schema(example = 1)]
+ pub limit: Option<i64>,
+}
+
+#[cfg(all(feature = "v2", feature = "payment_methods_v2"))]
+impl<'de> serde::Deserialize<'de> for PaymentMethodListRequest {
+ fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
+ where
+ D: serde::Deserializer<'de>,
+ {
+ struct FieldVisitor;
+
+ impl<'de> de::Visitor<'de> for FieldVisitor {
+ type Value = PaymentMethodListRequest;
+
+ fn expecting(&self, formatter: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
+ formatter.write_str("Failed while deserializing as map")
+ }
+
+ fn visit_map<A>(self, mut map: A) -> Result<Self::Value, A::Error>
+ where
+ A: de::MapAccess<'de>,
+ {
+ let mut output = PaymentMethodListRequest::default();
+
+ while let Some(key) = map.next_key()? {
+ match key {
+ "client_secret" => {
+ set_or_reject_duplicate(
+ &mut output.client_secret,
+ "client_secret",
+ map.next_value()?,
+ )?;
+ }
+ "accepted_countries" => match output.accepted_countries.as_mut() {
+ Some(inner) => inner.push(map.next_value()?),
+ None => {
+ output.accepted_countries = Some(vec![map.next_value()?]);
+ }
+ },
+ "amount" => {
+ set_or_reject_duplicate(
+ &mut output.amount,
+ "amount",
+ map.next_value()?,
+ )?;
+ }
+ "accepted_currencies" => match output.accepted_currencies.as_mut() {
+ Some(inner) => inner.push(map.next_value()?),
+ None => {
+ output.accepted_currencies = Some(vec![map.next_value()?]);
+ }
+ },
+ "recurring_enabled" => {
+ set_or_reject_duplicate(
+ &mut output.recurring_enabled,
+ "recurring_enabled",
+ map.next_value()?,
+ )?;
+ }
+ "card_network" => match output.card_networks.as_mut() {
+ Some(inner) => inner.push(map.next_value()?),
+ None => output.card_networks = Some(vec![map.next_value()?]),
+ },
+ "limit" => {
+ set_or_reject_duplicate(&mut output.limit, "limit", map.next_value()?)?;
+ }
+ _ => {}
+ }
+ }
+
+ Ok(output)
+ }
+ }
+
+ deserializer.deserialize_identifier(FieldVisitor)
+ }
+}
+
// Try to set the provided value to the data otherwise throw an error
fn set_or_reject_duplicate<T, E: de::Error>(
data: &mut Option<T>,
@@ -1015,6 +1532,10 @@ pub struct CustomerPaymentMethodsListResponse {
pub is_guest_customer: Option<bool>,
}
+#[cfg(all(
+ any(feature = "v2", feature = "v1"),
+ not(feature = "payment_methods_v2")
+))]
#[derive(Debug, serde::Serialize, ToSchema)]
pub struct PaymentMethodDeleteResponse {
/// The unique identifier of the Payment method
@@ -1025,6 +1546,14 @@ pub struct PaymentMethodDeleteResponse {
#[schema(example = true)]
pub deleted: bool,
}
+
+#[cfg(all(feature = "v2", feature = "payment_methods_v2"))]
+#[derive(Debug, serde::Serialize, ToSchema)]
+pub struct PaymentMethodDeleteResponse {
+ /// The unique identifier of the Payment method
+ #[schema(example = "card_rGK4Vi5iSW70MY7J2mIg")]
+ pub payment_method_id: String,
+}
#[derive(Debug, serde::Serialize, ToSchema)]
pub struct CustomerDefaultPaymentMethodResponse {
/// The unique identifier of the Payment method
@@ -1063,26 +1592,10 @@ pub struct CustomerPaymentMethod {
#[schema(value_type = Option<PaymentMethodType>,example = "credit_card")]
pub payment_method_type: Option<api_enums::PaymentMethodType>,
- /// The name of the bank/ provider issuing the payment method to the end user
- #[schema(example = "Citibank")]
- pub payment_method_issuer: Option<String>,
-
- /// A standard code representing the issuer of payment method
- #[schema(value_type = Option<PaymentMethodIssuerCode>,example = "jp_applepay")]
- pub payment_method_issuer_code: Option<api_enums::PaymentMethodIssuerCode>,
-
/// Indicates whether the payment method is eligible for recurring payments
#[schema(example = true)]
pub recurring_enabled: bool,
- /// Indicates whether the payment method is eligible for installment payments
- #[schema(example = true)]
- pub installment_payment_enabled: bool,
-
- /// Type of payment experience enabled with the connector
- #[schema(value_type = Option<Vec<PaymentExperience>>,example = json!(["redirect_to_url"]))]
- pub payment_experience: Option<Vec<api_enums::PaymentExperience>>,
-
/// PaymentMethod Data from locker
pub payment_method_data: Option<PaymentMethodListData>,
@@ -1112,7 +1625,7 @@ pub struct CustomerPaymentMethod {
pub last_used_at: Option<time::PrimitiveDateTime>,
/// Indicates if the payment method has been set to default or not
#[schema(example = true)]
- pub default_payment_method_set: bool,
+ pub is_default: bool,
/// The billing details of the payment method
#[schema(value_type = Option<Address>)]
@@ -1501,6 +2014,10 @@ pub enum MigrationStatus {
type PaymentMethodMigrationResponseType =
(Result<PaymentMethodResponse, String>, PaymentMethodRecord);
+#[cfg(all(
+ any(feature = "v2", feature = "v1"),
+ not(feature = "payment_methods_v2")
+))]
impl From<PaymentMethodMigrationResponseType> for PaymentMethodMigrationResponse {
fn from((response, record): PaymentMethodMigrationResponseType) -> Self {
match response {
@@ -1526,6 +2043,32 @@ impl From<PaymentMethodMigrationResponseType> for PaymentMethodMigrationResponse
}
}
+#[cfg(all(feature = "v2", feature = "payment_methods_v2"))]
+impl From<PaymentMethodMigrationResponseType> for PaymentMethodMigrationResponse {
+ fn from((response, record): PaymentMethodMigrationResponseType) -> Self {
+ match response {
+ Ok(res) => Self {
+ payment_method_id: Some(res.payment_method_id),
+ payment_method: res.payment_method,
+ payment_method_type: res.payment_method_type,
+ customer_id: Some(res.customer_id),
+ migration_status: MigrationStatus::Success,
+ migration_error: None,
+ card_number_masked: Some(record.card_number_masked),
+ line_number: record.line_number,
+ },
+ Err(e) => Self {
+ customer_id: Some(record.customer_id),
+ migration_status: MigrationStatus::Failed,
+ migration_error: Some(e),
+ card_number_masked: Some(record.card_number_masked),
+ line_number: record.line_number,
+ ..Self::default()
+ },
+ }
+ }
+}
+
impl From<PaymentMethodRecord> for PaymentMethodMigrate {
fn from(record: PaymentMethodRecord) -> Self {
let mut mandate_reference = HashMap::new();
diff --git a/crates/router/src/compatibility/stripe/customers.rs b/crates/router/src/compatibility/stripe/customers.rs
index 330610a9a36..7cecf49496b 100644
--- a/crates/router/src/compatibility/stripe/customers.rs
+++ b/crates/router/src/compatibility/stripe/customers.rs
@@ -17,7 +17,11 @@ use crate::{
types::api::{customers as customer_types, payment_methods},
};
-#[cfg(all(any(feature = "v1", feature = "v2"), not(feature = "customer_v2")))]
+#[cfg(all(
+ any(feature = "v1", feature = "v2"),
+ not(feature = "customer_v2"),
+ not(feature = "payment_methods_v2")
+))]
#[instrument(skip_all, fields(flow = ?Flow::CustomersCreate))]
pub async fn customer_create(
state: web::Data<routes::AppState>,
@@ -59,7 +63,11 @@ pub async fn customer_create(
.await
}
-#[cfg(all(any(feature = "v1", feature = "v2"), not(feature = "customer_v2")))]
+#[cfg(all(
+ any(feature = "v1", feature = "v2"),
+ not(feature = "customer_v2"),
+ not(feature = "payment_methods_v2")
+))]
#[instrument(skip_all, fields(flow = ?Flow::CustomersRetrieve))]
pub async fn customer_retrieve(
state: web::Data<routes::AppState>,
@@ -93,7 +101,11 @@ pub async fn customer_retrieve(
.await
}
-#[cfg(all(any(feature = "v1", feature = "v2"), not(feature = "customer_v2")))]
+#[cfg(all(
+ any(feature = "v1", feature = "v2"),
+ not(feature = "customer_v2"),
+ not(feature = "payment_methods_v2")
+))]
#[instrument(skip_all, fields(flow = ?Flow::CustomersUpdate))]
pub async fn customer_update(
state: web::Data<routes::AppState>,
@@ -145,7 +157,11 @@ pub async fn customer_update(
.await
}
-#[cfg(all(any(feature = "v1", feature = "v2"), not(feature = "customer_v2")))]
+#[cfg(all(
+ any(feature = "v1", feature = "v2"),
+ not(feature = "customer_v2"),
+ not(feature = "payment_methods_v2")
+))]
#[instrument(skip_all, fields(flow = ?Flow::CustomersDelete))]
pub async fn customer_delete(
state: web::Data<routes::AppState>,
@@ -179,7 +195,11 @@ pub async fn customer_delete(
.await
}
-#[cfg(all(any(feature = "v1", feature = "v2"), not(feature = "customer_v2")))]
+#[cfg(all(
+ any(feature = "v1", feature = "v2"),
+ not(feature = "customer_v2"),
+ not(feature = "payment_methods_v2")
+))]
#[instrument(skip_all, fields(flow = ?Flow::CustomerPaymentMethodsList))]
pub async fn list_customer_payment_method_api(
state: web::Data<routes::AppState>,
diff --git a/crates/router/src/compatibility/stripe/customers/types.rs b/crates/router/src/compatibility/stripe/customers/types.rs
index 9f5c546a18e..2b62d8f5dac 100644
--- a/crates/router/src/compatibility/stripe/customers/types.rs
+++ b/crates/router/src/compatibility/stripe/customers/types.rs
@@ -1,6 +1,11 @@
use std::{convert::From, default::Default};
-use api_models::{payment_methods as api_types, payments};
+#[cfg(all(
+ any(feature = "v1", feature = "v2"),
+ not(feature = "payment_methods_v2")
+))]
+use api_models::payment_methods as api_types;
+use api_models::payments;
#[cfg(all(any(feature = "v1", feature = "v2"), not(feature = "customer_v2")))]
use common_utils::{crypto::Encryptable, date_time};
use common_utils::{
@@ -209,6 +214,10 @@ pub struct CardDetails {
pub fingerprint: Option<masking::Secret<String>>,
}
+#[cfg(all(
+ any(feature = "v1", feature = "v2"),
+ not(feature = "payment_methods_v2")
+))]
impl From<api::CustomerPaymentMethodsListResponse> for CustomerPaymentMethodListResponse {
fn from(item: api::CustomerPaymentMethodsListResponse) -> Self {
let customer_payment_methods = item.customer_payment_methods;
@@ -223,27 +232,15 @@ impl From<api::CustomerPaymentMethodsListResponse> for CustomerPaymentMethodList
}
}
-// Check this in review
+#[cfg(all(
+ any(feature = "v1", feature = "v2"),
+ not(feature = "payment_methods_v2")
+))]
impl From<api_types::CustomerPaymentMethod> for PaymentMethodData {
fn from(item: api_types::CustomerPaymentMethod) -> Self {
- #[cfg(all(
- any(feature = "v1", feature = "v2"),
- not(feature = "payment_methods_v2")
- ))]
let card = item.card.map(From::from);
- #[cfg(all(feature = "v2", feature = "payment_methods_v2"))]
- let card = match item.payment_method_data {
- Some(api_types::PaymentMethodListData::Card(card)) => Some(CardDetails::from(card)),
- _ => None,
- };
Self {
- #[cfg(all(
- any(feature = "v1", feature = "v2"),
- not(feature = "payment_methods_v2")
- ))]
id: Some(item.payment_token),
- #[cfg(all(feature = "v2", feature = "payment_methods_v2"))]
- id: item.payment_token,
object: "payment_method",
card,
created: item.created,
@@ -251,6 +248,10 @@ impl From<api_types::CustomerPaymentMethod> for PaymentMethodData {
}
}
+#[cfg(all(
+ any(feature = "v1", feature = "v2"),
+ not(feature = "payment_methods_v2")
+))]
impl From<api_types::CardDetailFromLocker> for CardDetails {
fn from(item: api_types::CardDetailFromLocker) -> Self {
Self {
diff --git a/crates/router/src/core/locker_migration.rs b/crates/router/src/core/locker_migration.rs
index 9e633f224c0..14a27c9ecff 100644
--- a/crates/router/src/core/locker_migration.rs
+++ b/crates/router/src/core/locker_migration.rs
@@ -1,6 +1,16 @@
-use api_models::{enums as api_enums, locker_migration::MigrateCardResponse};
+#[cfg(all(
+ any(feature = "v1", feature = "v2"),
+ not(feature = "payment_methods_v2")
+))]
+use api_models::enums as api_enums;
+use api_models::locker_migration::MigrateCardResponse;
use common_utils::{errors::CustomResult, id_type};
-use diesel_models::{enums as storage_enums, PaymentMethod};
+#[cfg(all(
+ any(feature = "v1", feature = "v2"),
+ not(feature = "payment_methods_v2")
+))]
+use diesel_models::enums as storage_enums;
+use diesel_models::PaymentMethod;
#[cfg(all(any(feature = "v1", feature = "v2"), not(feature = "customer_v2")))]
use error_stack::FutureExt;
use error_stack::ResultExt;
@@ -9,13 +19,22 @@ use futures::TryFutureExt;
#[cfg(all(any(feature = "v1", feature = "v2"), not(feature = "customer_v2")))]
use super::errors::StorageErrorExt;
+#[cfg(all(
+ any(feature = "v1", feature = "v2"),
+ not(feature = "payment_methods_v2")
+))]
use super::payment_methods::cards;
-use crate::{
- errors,
- routes::SessionState,
- services::{self, logger},
- types::{api, domain},
-};
+#[cfg(all(
+ any(feature = "v1", feature = "v2"),
+ not(feature = "payment_methods_v2")
+))]
+use crate::services::logger;
+#[cfg(all(
+ any(feature = "v1", feature = "v2"),
+ not(feature = "payment_methods_v2")
+))]
+use crate::types::api;
+use crate::{errors, routes::SessionState, services, types::domain};
#[cfg(all(feature = "v2", feature = "customer_v2"))]
pub async fn rust_locker_migration(
@@ -89,6 +108,10 @@ pub async fn rust_locker_migration(
))
}
+#[cfg(all(
+ any(feature = "v1", feature = "v2"),
+ not(feature = "payment_methods_v2")
+))]
pub async fn call_to_locker(
state: &SessionState,
payment_methods: Vec<PaymentMethod>,
@@ -185,3 +208,14 @@ pub async fn call_to_locker(
Ok(cards_moved)
}
+
+#[cfg(all(feature = "v2", feature = "payment_methods_v2"))]
+pub async fn call_to_locker(
+ _state: &SessionState,
+ _payment_methods: Vec<PaymentMethod>,
+ _customer_id: &id_type::CustomerId,
+ _merchant_id: &id_type::MerchantId,
+ _merchant_account: &domain::MerchantAccount,
+) -> CustomResult<usize, errors::ApiErrorResponse> {
+ todo!()
+}
diff --git a/crates/router/src/core/payment_methods.rs b/crates/router/src/core/payment_methods.rs
index 14fad68c171..cadeee51dc4 100644
--- a/crates/router/src/core/payment_methods.rs
+++ b/crates/router/src/core/payment_methods.rs
@@ -9,13 +9,19 @@ pub mod vault;
use std::borrow::Cow;
#[cfg(all(any(feature = "v1", feature = "v2"), not(feature = "customer_v2")))]
use std::collections::HashSet;
+#[cfg(all(feature = "v2", feature = "payment_methods_v2"))]
+use std::str::FromStr;
+#[cfg(all(feature = "v2", feature = "payment_methods_v2"))]
+pub use api_models::enums as api_enums;
pub use api_models::enums::Connector;
use api_models::payment_methods;
#[cfg(feature = "payouts")]
pub use api_models::{enums::PayoutConnectors, payouts as payout_types};
#[cfg(all(any(feature = "v1", feature = "v2"), not(feature = "customer_v2")))]
use common_utils::ext_traits::Encode;
+#[cfg(all(feature = "v2", feature = "payment_methods_v2"))]
+use common_utils::ext_traits::OptionExt;
use common_utils::{consts::DEFAULT_LOCALE, id_type::CustomerId};
use diesel_models::{
enums, GenericLinkNew, PaymentMethodCollectLink, PaymentMethodCollectLinkData,
@@ -38,7 +44,10 @@ use crate::{
},
routes::{app::StorageInterface, SessionState},
services,
- types::{domain, storage},
+ types::{
+ domain,
+ storage::{self, enums as storage_enums},
+ },
};
const PAYMENT_METHOD_STATUS_UPDATE_TASK: &str = "PAYMENT_METHOD_STATUS_UPDATE";
@@ -579,3 +588,164 @@ pub async fn retrieve_payment_method_with_token(
};
Ok(token)
}
+
+#[cfg(all(feature = "v2", feature = "payment_methods_v2"))]
+#[instrument(skip_all)]
+pub(crate) async fn get_payment_method_create_request(
+ payment_method_data: Option<&domain::PaymentMethodData>,
+ payment_method: Option<storage_enums::PaymentMethod>,
+ payment_method_type: Option<storage_enums::PaymentMethodType>,
+ customer_id: &Option<CustomerId>,
+ billing_name: Option<masking::Secret<String>>,
+) -> RouterResult<payment_methods::PaymentMethodCreate> {
+ match payment_method_data {
+ Some(pm_data) => match payment_method {
+ Some(payment_method) => match pm_data {
+ domain::PaymentMethodData::Card(card) => {
+ let card_detail = payment_methods::CardDetail {
+ card_number: card.card_number.clone(),
+ card_exp_month: card.card_exp_month.clone(),
+ card_exp_year: card.card_exp_year.clone(),
+ card_holder_name: billing_name,
+ nick_name: card.nick_name.clone(),
+ card_issuing_country: card
+ .card_issuing_country
+ .as_ref()
+ .map(|c| api_enums::CountryAlpha2::from_str(c))
+ .transpose()
+ .ok()
+ .flatten(),
+ card_network: card.card_network.clone(),
+ card_issuer: card.card_issuer.clone(),
+ card_type: card
+ .card_type
+ .as_ref()
+ .map(|c| payment_methods::CardType::from_str(c))
+ .transpose()
+ .ok()
+ .flatten(),
+ };
+ let payment_method_request = payment_methods::PaymentMethodCreate {
+ payment_method: payment_method,
+ payment_method_type: payment_method_type
+ .get_required_value("Payment_method_type")
+ .change_context(errors::ApiErrorResponse::MissingRequiredField {
+ field_name: "payment_method_data",
+ })?,
+ metadata: None,
+ customer_id: customer_id
+ .clone()
+ .get_required_value("customer_id")
+ .change_context(errors::ApiErrorResponse::MissingRequiredField {
+ field_name: "customer_id",
+ })?,
+ payment_method_data: payment_methods::PaymentMethodCreateData::Card(
+ card_detail,
+ ),
+ billing: None,
+ };
+ Ok(payment_method_request)
+ }
+ _ => Err(report!(errors::ApiErrorResponse::MissingRequiredField {
+ field_name: "payment_method_data"
+ })
+ .attach_printable("Payment method data is incorrect")),
+ },
+ None => Err(report!(errors::ApiErrorResponse::MissingRequiredField {
+ field_name: "payment_method_type"
+ })
+ .attach_printable("PaymentMethodType Required")),
+ },
+ None => Err(report!(errors::ApiErrorResponse::MissingRequiredField {
+ field_name: "payment_method_data"
+ })
+ .attach_printable("PaymentMethodData required Or Card is already saved")),
+ }
+}
+
+#[cfg(all(
+ any(feature = "v1", feature = "v2"),
+ not(feature = "payment_methods_v2")
+))]
+#[instrument(skip_all)]
+pub(crate) async fn get_payment_method_create_request(
+ payment_method_data: Option<&domain::PaymentMethodData>,
+ payment_method: Option<storage_enums::PaymentMethod>,
+ payment_method_type: Option<storage_enums::PaymentMethodType>,
+ customer_id: &Option<CustomerId>,
+ billing_name: Option<masking::Secret<String>>,
+) -> RouterResult<payment_methods::PaymentMethodCreate> {
+ match payment_method_data {
+ Some(pm_data) => match payment_method {
+ Some(payment_method) => match pm_data {
+ domain::PaymentMethodData::Card(card) => {
+ let card_detail = payment_methods::CardDetail {
+ card_number: card.card_number.clone(),
+ card_exp_month: card.card_exp_month.clone(),
+ card_exp_year: card.card_exp_year.clone(),
+ card_holder_name: billing_name,
+ nick_name: card.nick_name.clone(),
+ card_issuing_country: card.card_issuing_country.clone(),
+ card_network: card.card_network.clone(),
+ card_issuer: card.card_issuer.clone(),
+ card_type: card.card_type.clone(),
+ };
+ let payment_method_request = payment_methods::PaymentMethodCreate {
+ payment_method: Some(payment_method),
+ payment_method_type,
+ payment_method_issuer: card.card_issuer.clone(),
+ payment_method_issuer_code: None,
+ #[cfg(feature = "payouts")]
+ bank_transfer: None,
+ #[cfg(feature = "payouts")]
+ wallet: None,
+ card: Some(card_detail),
+ metadata: None,
+ customer_id: customer_id.clone(),
+ card_network: card
+ .card_network
+ .as_ref()
+ .map(|card_network| card_network.to_string()),
+ client_secret: None,
+ payment_method_data: None,
+ billing: None,
+ connector_mandate_details: None,
+ network_transaction_id: None,
+ };
+ Ok(payment_method_request)
+ }
+ _ => {
+ let payment_method_request = payment_methods::PaymentMethodCreate {
+ payment_method: Some(payment_method),
+ payment_method_type,
+ payment_method_issuer: None,
+ payment_method_issuer_code: None,
+ #[cfg(feature = "payouts")]
+ bank_transfer: None,
+ #[cfg(feature = "payouts")]
+ wallet: None,
+ card: None,
+ metadata: None,
+ customer_id: customer_id.clone(),
+ card_network: None,
+ client_secret: None,
+ payment_method_data: None,
+ billing: None,
+ connector_mandate_details: None,
+ network_transaction_id: None,
+ };
+
+ Ok(payment_method_request)
+ }
+ },
+ None => Err(report!(errors::ApiErrorResponse::MissingRequiredField {
+ field_name: "payment_method_type"
+ })
+ .attach_printable("PaymentMethodType Required")),
+ },
+ None => Err(report!(errors::ApiErrorResponse::MissingRequiredField {
+ field_name: "payment_method_data"
+ })
+ .attach_printable("PaymentMethodData required Or Card is already saved")),
+ }
+}
diff --git a/crates/router/src/core/payment_methods/cards.rs b/crates/router/src/core/payment_methods/cards.rs
index f305a0100aa..274ef3c0966 100644
--- a/crates/router/src/core/payment_methods/cards.rs
+++ b/crates/router/src/core/payment_methods/cards.rs
@@ -4,8 +4,12 @@ use std::{
str::FromStr,
};
+#[cfg(all(
+ any(feature = "v1", feature = "v2"),
+ not(feature = "payment_methods_v2")
+))]
+use api_models::admin::PaymentMethodsEnabled;
use api_models::{
- admin::PaymentMethodsEnabled,
enums as api_enums,
payment_methods::{
BankAccountTokenData, Card, CardDetailUpdate, CardDetailsPaymentMethod, CardNetworkTypes,
@@ -33,13 +37,19 @@ use common_utils::{
};
use diesel_models::payment_method;
use error_stack::{report, ResultExt};
-use euclid::{
- dssa::graph::{AnalysisContext, CgraphExt},
- frontend::dir,
-};
+#[cfg(all(
+ any(feature = "v1", feature = "v2"),
+ not(feature = "payment_methods_v2")
+))]
+use euclid::dssa::graph::{AnalysisContext, CgraphExt};
+use euclid::frontend::dir;
use hyperswitch_constraint_graph as cgraph;
#[cfg(all(any(feature = "v1", feature = "v2"), not(feature = "customer_v2")))]
use hyperswitch_domain_models::customer::CustomerUpdate;
+#[cfg(all(
+ any(feature = "v1", feature = "v2"),
+ not(feature = "payment_methods_v2")
+))]
use kgraph_utils::transformers::IntoDirValue;
use masking::Secret;
use router_env::{instrument, metrics::add_attributes, tracing};
@@ -66,11 +76,7 @@ use crate::{
},
core::{
errors::{self, StorageErrorExt},
- payment_methods::{
- add_payment_method_status_update_task, transformers as payment_methods,
- utils::{get_merchant_pm_filter_graph, make_pm_graph, refresh_pm_filters_cache},
- vault,
- },
+ payment_methods::{transformers as payment_methods, vault},
payments::{
helpers,
routing::{self, SessionFlowRoutingInput},
@@ -85,36 +91,27 @@ use crate::{
api::{self, routing as routing_types, PaymentMethodCreateExt},
domain::{self, BusinessProfile},
storage::{self, enums, PaymentMethodListContext, PaymentTokenData},
- transformers::{ForeignFrom, ForeignTryFrom},
+ transformers::ForeignTryFrom,
},
utils::{ConnectorResponseExt, OptionExt},
};
+#[cfg(all(
+ any(feature = "v1", feature = "v2"),
+ not(feature = "payment_methods_v2")
+))]
+use crate::{
+ core::payment_methods::{
+ add_payment_method_status_update_task,
+ utils::{get_merchant_pm_filter_graph, make_pm_graph, refresh_pm_filters_cache},
+ },
+ types::transformers::ForeignFrom,
+};
-#[cfg(all(feature = "v2", feature = "customer_v2"))]
-#[instrument(skip_all)]
-#[allow(clippy::too_many_arguments)]
-pub async fn create_payment_method(
- state: &routes::SessionState,
- req: &api::PaymentMethodCreate,
- customer_id: &id_type::CustomerId,
- payment_method_id: &str,
- locker_id: Option<String>,
- merchant_id: &id_type::MerchantId,
- pm_metadata: Option<serde_json::Value>,
- customer_acceptance: Option<serde_json::Value>,
- payment_method_data: Option<Encryption>,
- key_store: &domain::MerchantKeyStore,
- connector_mandate_details: Option<serde_json::Value>,
- status: Option<enums::PaymentMethodStatus>,
- network_transaction_id: Option<String>,
- storage_scheme: MerchantStorageScheme,
- payment_method_billing_address: Option<Encryption>,
- card_scheme: Option<String>,
-) -> errors::CustomResult<storage::PaymentMethod, errors::ApiErrorResponse> {
- todo!()
-}
-
-#[cfg(all(any(feature = "v1", feature = "v2"), not(feature = "customer_v2")))]
+#[cfg(all(
+ any(feature = "v1", feature = "v2"),
+ not(feature = "payment_methods_v2"),
+ not(feature = "customer_v2")
+))]
#[instrument(skip_all)]
#[allow(clippy::too_many_arguments)]
pub async fn create_payment_method(
@@ -209,6 +206,38 @@ pub async fn create_payment_method(
Ok(response)
}
+#[cfg(all(
+ feature = "v2",
+ feature = "payment_methods_v2",
+ feature = "customer_v2"
+))]
+#[instrument(skip_all)]
+#[allow(clippy::too_many_arguments)]
+pub async fn create_payment_method(
+ _state: &routes::SessionState,
+ _req: &api::PaymentMethodCreate,
+ _customer_id: &id_type::CustomerId,
+ _payment_method_id: &str,
+ _locker_id: Option<String>,
+ _merchant_id: &id_type::MerchantId,
+ _pm_metadata: Option<serde_json::Value>,
+ _customer_acceptance: Option<serde_json::Value>,
+ _payment_method_data: Option<Encryption>,
+ _key_store: &domain::MerchantKeyStore,
+ _connector_mandate_details: Option<serde_json::Value>,
+ _status: Option<enums::PaymentMethodStatus>,
+ _network_transaction_id: Option<String>,
+ _storage_scheme: MerchantStorageScheme,
+ _payment_method_billing_address: Option<Encryption>,
+ _card_scheme: Option<String>,
+) -> errors::CustomResult<storage::PaymentMethod, errors::ApiErrorResponse> {
+ todo!()
+}
+
+#[cfg(all(
+ any(feature = "v1", feature = "v2"),
+ not(feature = "payment_methods_v2")
+))]
pub fn store_default_payment_method(
req: &api::PaymentMethodCreate,
customer_id: &id_type::CustomerId,
@@ -238,6 +267,23 @@ pub fn store_default_payment_method(
(payment_method_response, None)
}
+
+#[cfg(all(feature = "v2", feature = "payment_methods_v2"))]
+pub fn store_default_payment_method(
+ _req: &api::PaymentMethodCreate,
+ _customer_id: &id_type::CustomerId,
+ _merchant_id: &id_type::MerchantId,
+) -> (
+ api::PaymentMethodResponse,
+ Option<payment_methods::DataDuplicationCheck>,
+) {
+ todo!()
+}
+
+#[cfg(all(
+ any(feature = "v1", feature = "v2"),
+ not(feature = "payment_methods_v2")
+))]
#[instrument(skip_all)]
pub async fn get_or_insert_payment_method(
state: &routes::SessionState,
@@ -308,6 +354,23 @@ pub async fn get_or_insert_payment_method(
}
}
+#[cfg(all(feature = "v2", feature = "payment_methods_v2"))]
+#[instrument(skip_all)]
+pub async fn get_or_insert_payment_method(
+ _state: &routes::SessionState,
+ _req: api::PaymentMethodCreate,
+ _resp: &mut api::PaymentMethodResponse,
+ _merchant_account: &domain::MerchantAccount,
+ _customer_id: &id_type::CustomerId,
+ _key_store: &domain::MerchantKeyStore,
+) -> errors::RouterResult<diesel_models::PaymentMethod> {
+ todo!()
+}
+
+#[cfg(all(
+ any(feature = "v1", feature = "v2"),
+ not(feature = "payment_methods_v2")
+))]
pub async fn migrate_payment_method(
state: routes::SessionState,
req: api::PaymentMethodMigrate,
@@ -373,6 +436,17 @@ pub async fn migrate_payment_method(
}
}
+#[cfg(all(feature = "v2", feature = "payment_methods_v2"))]
+pub async fn migrate_payment_method(
+ _state: routes::SessionState,
+ _req: api::PaymentMethodMigrate,
+ _merchant_id: &id_type::MerchantId,
+ _merchant_account: &domain::MerchantAccount,
+ _key_store: &domain::MerchantKeyStore,
+) -> errors::RouterResponse<api::PaymentMethodResponse> {
+ todo!()
+}
+
pub async fn populate_bin_details_for_masked_card(
card_details: &api_models::payment_methods::MigrateCardDetail,
db: &dyn db::StorageInterface,
@@ -409,6 +483,10 @@ pub async fn populate_bin_details_for_masked_card(
Ok(card_bin_details)
}
+#[cfg(all(
+ any(feature = "v1", feature = "v2"),
+ not(feature = "payment_methods_v2")
+))]
impl
ForeignTryFrom<(
&api_models::payment_methods::MigrateCardDetail,
@@ -483,19 +561,91 @@ impl
}
}
-#[cfg(all(feature = "v2", feature = "customer_v2"))]
-pub async fn skip_locker_call_and_migrate_payment_method(
- _state: routes::SessionState,
- _req: &api::PaymentMethodMigrate,
- _merchant_id: id_type::MerchantId,
- _key_store: &domain::MerchantKeyStore,
- _merchant_account: &domain::MerchantAccount,
- _card: api_models::payment_methods::CardDetailFromLocker,
-) -> errors::RouterResponse<api::PaymentMethodResponse> {
- todo!()
+#[cfg(all(feature = "v2", feature = "payment_methods_v2"))]
+impl
+ ForeignTryFrom<(
+ &api_models::payment_methods::MigrateCardDetail,
+ Option<diesel_models::CardInfo>,
+ )> for api_models::payment_methods::CardDetailFromLocker
+{
+ type Error = error_stack::Report<errors::ApiErrorResponse>;
+ fn foreign_try_from(
+ (card_details, card_info): (
+ &api_models::payment_methods::MigrateCardDetail,
+ Option<diesel_models::CardInfo>,
+ ),
+ ) -> Result<Self, Self::Error> {
+ let (card_isin, last4_digits) =
+ get_card_bin_and_last4_digits_for_masked_card(card_details.card_number.peek())
+ .change_context(errors::ApiErrorResponse::InvalidRequestData {
+ message: "Invalid card number".to_string(),
+ })?;
+ if let Some(card_bin_info) = card_info {
+ Ok(Self {
+ last4_digits: Some(last4_digits.clone()),
+ issuer_country: card_details
+ .card_issuing_country
+ .as_ref()
+ .map(|c| api_enums::CountryAlpha2::from_str(c))
+ .transpose()
+ .ok()
+ .flatten()
+ .or(card_bin_info
+ .card_issuing_country
+ .as_ref()
+ .map(|c| api_enums::CountryAlpha2::from_str(c))
+ .transpose()
+ .ok()
+ .flatten()),
+ card_number: None,
+ expiry_month: Some(card_details.card_exp_month.clone()),
+ expiry_year: Some(card_details.card_exp_year.clone()),
+ card_fingerprint: None,
+ card_holder_name: card_details.card_holder_name.clone(),
+ nick_name: card_details.nick_name.clone(),
+ card_isin: Some(card_isin.clone()),
+ card_issuer: card_details
+ .card_issuer
+ .clone()
+ .or(card_bin_info.card_issuer),
+ card_network: card_details
+ .card_network
+ .clone()
+ .or(card_bin_info.card_network),
+ card_type: card_details.card_type.clone().or(card_bin_info.card_type),
+ saved_to_locker: false,
+ })
+ } else {
+ Ok(Self {
+ last4_digits: Some(last4_digits.clone()),
+ issuer_country: card_details
+ .card_issuing_country
+ .as_ref()
+ .map(|c| api_enums::CountryAlpha2::from_str(c))
+ .transpose()
+ .ok()
+ .flatten(),
+ card_number: None,
+ expiry_month: Some(card_details.card_exp_month.clone()),
+ expiry_year: Some(card_details.card_exp_year.clone()),
+ card_fingerprint: None,
+ card_holder_name: card_details.card_holder_name.clone(),
+ nick_name: card_details.nick_name.clone(),
+ card_isin: Some(card_isin.clone()),
+ card_issuer: card_details.card_issuer.clone(),
+ card_network: card_details.card_network.clone(),
+ card_type: card_details.card_type.clone(),
+ saved_to_locker: false,
+ })
+ }
+ }
}
-#[cfg(all(any(feature = "v1", feature = "v2"), not(feature = "customer_v2")))]
+#[cfg(all(
+ any(feature = "v1", feature = "v2"),
+ not(feature = "payment_methods_v2"),
+ not(feature = "customer_v2")
+))]
pub async fn skip_locker_call_and_migrate_payment_method(
state: routes::SessionState,
req: &api::PaymentMethodMigrate,
@@ -613,6 +763,23 @@ pub async fn skip_locker_call_and_migrate_payment_method(
))
}
+// need to discuss regarding the migration APIs for v2
+#[cfg(all(
+ feature = "v2",
+ feature = "payment_methods_v2",
+ feature = "customer_v2"
+))]
+pub async fn skip_locker_call_and_migrate_payment_method(
+ _state: routes::SessionState,
+ _req: &api::PaymentMethodMigrate,
+ _merchant_id: id_type::MerchantId,
+ _key_store: &domain::MerchantKeyStore,
+ _merchant_account: &domain::MerchantAccount,
+ _card: api_models::payment_methods::CardDetailFromLocker,
+) -> errors::RouterResponse<api::PaymentMethodResponse> {
+ todo!()
+}
+
pub fn get_card_bin_and_last4_digits_for_masked_card(
masked_card_number: &str,
) -> Result<(String, String), cards::CardNumberValidationErr> {
@@ -633,6 +800,10 @@ pub fn get_card_bin_and_last4_digits_for_masked_card(
Ok((card_isin, last4_digits))
}
+#[cfg(all(
+ any(feature = "v1", feature = "v2"),
+ not(feature = "payment_methods_v2")
+))]
#[instrument(skip_all)]
pub async fn get_client_secret_or_add_payment_method(
state: &routes::SessionState,
@@ -710,6 +881,17 @@ pub async fn get_client_secret_or_add_payment_method(
}
}
+#[cfg(all(feature = "v2", feature = "payment_methods_v2"))]
+#[instrument(skip_all)]
+pub async fn get_client_secret_or_add_payment_method(
+ _state: &routes::SessionState,
+ _req: api::PaymentMethodCreate,
+ _merchant_account: &domain::MerchantAccount,
+ _key_store: &domain::MerchantKeyStore,
+) -> errors::RouterResponse<api::PaymentMethodResponse> {
+ todo!()
+}
+
#[instrument(skip_all)]
pub fn authenticate_pm_client_secret_and_check_expiry(
req_client_secret: &String,
@@ -738,19 +920,11 @@ pub fn authenticate_pm_client_secret_and_check_expiry(
}
}
-#[cfg(all(feature = "v2", feature = "customer_v2"))]
-#[instrument(skip_all)]
-pub async fn add_payment_method_data(
- _state: routes::SessionState,
- _req: api::PaymentMethodCreate,
- _merchant_account: domain::MerchantAccount,
- _key_store: domain::MerchantKeyStore,
- _pm_id: String,
-) -> errors::RouterResponse<api::PaymentMethodResponse> {
- todo!()
-}
-
-#[cfg(all(any(feature = "v1", feature = "v2"), not(feature = "customer_v2")))]
+#[cfg(all(
+ any(feature = "v1", feature = "v2"),
+ not(feature = "payment_methods_v2"),
+ not(feature = "customer_v2")
+))]
#[instrument(skip_all)]
pub async fn add_payment_method_data(
state: routes::SessionState,
@@ -940,6 +1114,10 @@ pub async fn add_payment_method_data(
}
}
+#[cfg(all(
+ any(feature = "v1", feature = "v2"),
+ not(feature = "payment_methods_v2")
+))]
#[instrument(skip_all)]
pub async fn add_payment_method(
state: &routes::SessionState,
@@ -1187,6 +1365,21 @@ pub async fn add_payment_method(
Ok(services::ApplicationResponse::Json(resp))
}
+#[cfg(all(feature = "v2", feature = "payment_methods_v2"))]
+#[instrument(skip_all)]
+pub async fn add_payment_method(
+ _state: &routes::SessionState,
+ _req: api::PaymentMethodCreate,
+ _merchant_account: &domain::MerchantAccount,
+ _key_store: &domain::MerchantKeyStore,
+) -> errors::RouterResponse<api::PaymentMethodResponse> {
+ todo!()
+}
+
+#[cfg(all(
+ any(feature = "v1", feature = "v2"),
+ not(feature = "payment_methods_v2")
+))]
#[allow(clippy::too_many_arguments)]
pub async fn insert_payment_method(
state: &routes::SessionState,
@@ -1240,6 +1433,63 @@ pub async fn insert_payment_method(
.await
}
+#[cfg(all(feature = "v2", feature = "payment_methods_v2"))]
+#[allow(clippy::too_many_arguments)]
+pub async fn insert_payment_method(
+ state: &routes::SessionState,
+ resp: &api::PaymentMethodResponse,
+ req: &api::PaymentMethodCreate,
+ key_store: &domain::MerchantKeyStore,
+ merchant_id: &id_type::MerchantId,
+ customer_id: &id_type::CustomerId,
+ pm_metadata: Option<serde_json::Value>,
+ customer_acceptance: Option<serde_json::Value>,
+ locker_id: Option<String>,
+ connector_mandate_details: Option<serde_json::Value>,
+ network_transaction_id: Option<String>,
+ storage_scheme: MerchantStorageScheme,
+ payment_method_billing_address: Option<Encryption>,
+) -> errors::RouterResult<diesel_models::PaymentMethod> {
+ let pm_card_details = match &resp.payment_method_data {
+ Some(api::PaymentMethodResponseData::Card(card_data)) => Some(PaymentMethodsData::Card(
+ CardDetailsPaymentMethod::from(card_data.clone()),
+ )),
+ _ => None,
+ };
+
+ let pm_data_encrypted: Option<Encryptable<Secret<serde_json::Value>>> = pm_card_details
+ .clone()
+ .async_map(|pm_card| create_encrypted_data(state, key_store, pm_card))
+ .await
+ .transpose()
+ .change_context(errors::ApiErrorResponse::InternalServerError)
+ .attach_printable("Unable to encrypt payment method data")?;
+
+ create_payment_method(
+ state,
+ req,
+ customer_id,
+ &resp.payment_method_id,
+ locker_id,
+ merchant_id,
+ pm_metadata,
+ customer_acceptance,
+ pm_data_encrypted.map(Into::into),
+ key_store,
+ connector_mandate_details,
+ None,
+ network_transaction_id,
+ storage_scheme,
+ payment_method_billing_address,
+ None,
+ )
+ .await
+}
+
+#[cfg(all(
+ any(feature = "v1", feature = "v2"),
+ not(feature = "payment_methods_v2")
+))]
#[instrument(skip_all)]
pub async fn update_customer_payment_method(
state: routes::SessionState,
@@ -1460,6 +1710,22 @@ pub async fn update_customer_payment_method(
}
}
+#[cfg(all(feature = "v2", feature = "payment_methods_v2"))]
+#[instrument(skip_all)]
+pub async fn update_customer_payment_method(
+ _state: routes::SessionState,
+ _merchant_account: domain::MerchantAccount,
+ _req: api::PaymentMethodUpdate,
+ _payment_method_id: &str,
+ _key_store: domain::MerchantKeyStore,
+) -> errors::RouterResponse<api::PaymentMethodResponse> {
+ todo!()
+}
+
+#[cfg(all(
+ any(feature = "v1", feature = "v2"),
+ not(feature = "payment_methods_v2")
+))]
pub fn validate_payment_method_update(
card_updation_obj: CardDetailUpdate,
existing_card_data: api::CardDetailFromLocker,
@@ -1510,6 +1776,14 @@ pub fn validate_payment_method_update(
})
}
+#[cfg(all(feature = "v2", feature = "payment_methods_v2"))]
+pub fn validate_payment_method_update(
+ _card_updation_obj: CardDetailUpdate,
+ _existing_card_data: api::CardDetailFromLocker,
+) -> bool {
+ todo!()
+}
+
// Wrapper function to switch lockers
#[cfg(feature = "payouts")]
@@ -3497,6 +3771,10 @@ pub async fn call_surcharge_decision_management_for_saved_card(
Ok(())
}
+#[cfg(all(
+ any(feature = "v1", feature = "v2"),
+ not(feature = "payment_methods_v2")
+))]
#[allow(clippy::too_many_arguments)]
pub async fn filter_payment_methods(
graph: &cgraph::ConstraintGraph<dir::DirValue>,
@@ -3685,6 +3963,25 @@ pub async fn filter_payment_methods(
Ok(())
}
+// v2 type for PaymentMethodListRequest will not have the installment_payment_enabled field,
+// need to re-evaluate filter logic
+#[cfg(all(feature = "v2", feature = "payment_methods_v2"))]
+#[allow(clippy::too_many_arguments)]
+pub async fn filter_payment_methods(
+ _graph: &cgraph::ConstraintGraph<dir::DirValue>,
+ _mca_id: String,
+ _payment_methods: &[Secret<serde_json::Value>],
+ _req: &mut api::PaymentMethodListRequest,
+ _resp: &mut Vec<ResponsePaymentMethodIntermediate>,
+ _payment_intent: Option<&storage::PaymentIntent>,
+ _payment_attempt: Option<&storage::PaymentAttempt>,
+ _address: Option<&domain::Address>,
+ _connector: String,
+ _saved_payment_methods: &settings::EligiblePaymentMethods,
+) -> errors::CustomResult<(), errors::ApiErrorResponse> {
+ todo!()
+}
+
fn filter_amount_based(
payment_method: &RequestPaymentMethodTypes,
amount: Option<MinorUnit>,
@@ -4585,20 +4882,16 @@ async fn generate_saved_pm_response(
customer_id: pm.customer_id,
payment_method,
payment_method_type: pm.payment_method_type,
- payment_method_issuer: pm.payment_method_issuer,
payment_method_data: pmd,
metadata: pm.metadata,
- payment_method_issuer_code: pm.payment_method_issuer_code,
recurring_enabled: mca_enabled,
- installment_payment_enabled: false,
- payment_experience: Some(vec![api_models::enums::PaymentExperience::RedirectToUrl]),
created: Some(pm.created_at),
bank: bank_details,
surcharge_details: None,
requires_cvv: requires_cvv
&& !(off_session_payment_flag && pm.connector_mandate_details.is_some()),
last_used_at: Some(pm.last_used_at),
- default_payment_method_set: customer.default_payment_method_id.is_some()
+ is_default: customer.default_payment_method_id.is_some()
&& customer.default_payment_method_id == Some(pm.payment_method_id),
billing: payment_method_billing,
};
@@ -4688,6 +4981,10 @@ where
.attach_printable("unable to parse generic data value")
}
+#[cfg(all(
+ any(feature = "v2", feature = "v1"),
+ not(feature = "payment_methods_v2")
+))]
pub async fn get_card_details_with_locker_fallback(
pm: &payment_method::PaymentMethod,
state: &routes::SessionState,
@@ -4726,6 +5023,48 @@ pub async fn get_card_details_with_locker_fallback(
})
}
+#[cfg(all(feature = "v2", feature = "payment_methods_v2"))]
+pub async fn get_card_details_with_locker_fallback(
+ pm: &payment_method::PaymentMethod,
+ state: &routes::SessionState,
+ key_store: &domain::MerchantKeyStore,
+) -> errors::RouterResult<Option<api::CardDetailFromLocker>> {
+ let key = key_store.key.get_inner().peek();
+ let identifier = Identifier::Merchant(key_store.merchant_id.clone());
+ let card_decrypted = domain::types::crypto_operation::<serde_json::Value, masking::WithType>(
+ &state.into(),
+ type_name!(payment_method::PaymentMethod),
+ domain::types::CryptoOperation::DecryptOptional(pm.payment_method_data.clone()),
+ identifier,
+ key,
+ )
+ .await
+ .and_then(|val| val.try_into_optionaloperation())
+ .change_context(errors::StorageError::DecryptionError)
+ .attach_printable("unable to decrypt card details")
+ .ok()
+ .flatten()
+ .map(|x| x.into_inner().expose())
+ .and_then(|v| serde_json::from_value::<PaymentMethodsData>(v).ok())
+ .and_then(|pmd| match pmd {
+ PaymentMethodsData::Card(crd) => Some(api::CardDetailFromLocker::from(crd)),
+ _ => None,
+ });
+
+ Ok(if let Some(crd) = card_decrypted {
+ Some(crd)
+ } else {
+ logger::debug!(
+ "Getting card details from locker as it is not found in payment methods table"
+ );
+ Some(get_card_details_from_locker(state, pm).await?)
+ })
+}
+
+#[cfg(all(
+ any(feature = "v2", feature = "v1"),
+ not(feature = "payment_methods_v2")
+))]
pub async fn get_card_details_without_locker_fallback(
pm: &payment_method::PaymentMethod,
state: &routes::SessionState,
@@ -4764,6 +5103,43 @@ pub async fn get_card_details_without_locker_fallback(
})
}
+#[cfg(all(feature = "v2", feature = "payment_methods_v2"))]
+pub async fn get_card_details_without_locker_fallback(
+ pm: &payment_method::PaymentMethod,
+ state: &routes::SessionState,
+ key_store: &domain::MerchantKeyStore,
+) -> errors::RouterResult<api::CardDetailFromLocker> {
+ let key = key_store.key.get_inner().peek();
+ let identifier = Identifier::Merchant(key_store.merchant_id.clone());
+ let card_decrypted = domain::types::crypto_operation::<serde_json::Value, masking::WithType>(
+ &state.into(),
+ type_name!(payment_method::PaymentMethod),
+ domain::types::CryptoOperation::DecryptOptional(pm.payment_method_data.clone()),
+ identifier,
+ key,
+ )
+ .await
+ .and_then(|val| val.try_into_optionaloperation())
+ .change_context(errors::StorageError::DecryptionError)
+ .attach_printable("unable to decrypt card details")
+ .ok()
+ .flatten()
+ .map(|x| x.into_inner().expose())
+ .and_then(|v| serde_json::from_value::<PaymentMethodsData>(v).ok())
+ .and_then(|pmd| match pmd {
+ PaymentMethodsData::Card(crd) => Some(api::CardDetailFromLocker::from(crd)),
+ _ => None,
+ });
+ Ok(if let Some(crd) = card_decrypted {
+ crd
+ } else {
+ logger::debug!(
+ "Getting card details from locker as it is not found in payment methods table"
+ );
+ get_card_details_from_locker(state, pm).await?
+ })
+}
+
pub async fn get_card_details_from_locker(
state: &routes::SessionState,
pm: &storage::PaymentMethod,
@@ -5160,6 +5536,10 @@ impl TempLockerCardSupport {
}
}
+#[cfg(all(
+ any(feature = "v2", feature = "v1"),
+ not(feature = "payment_methods_v2")
+))]
#[instrument(skip_all)]
pub async fn retrieve_payment_method(
state: routes::SessionState,
@@ -5215,6 +5595,62 @@ pub async fn retrieve_payment_method(
))
}
+#[cfg(all(feature = "v2", feature = "payment_methods_v2"))]
+#[instrument(skip_all)]
+pub async fn retrieve_payment_method(
+ state: routes::SessionState,
+ pm: api::PaymentMethodId,
+ key_store: domain::MerchantKeyStore,
+ merchant_account: domain::MerchantAccount,
+) -> errors::RouterResponse<api::PaymentMethodResponse> {
+ let db = state.store.as_ref();
+ let pm = db
+ .find_payment_method(&pm.payment_method_id, merchant_account.storage_scheme)
+ .await
+ .to_not_found_response(errors::ApiErrorResponse::PaymentMethodNotFound)?;
+
+ let card = if pm.payment_method == Some(enums::PaymentMethod::Card) {
+ let card_detail = if state.conf.locker.locker_enabled {
+ let card = get_card_from_locker(
+ &state,
+ &pm.customer_id,
+ &pm.merchant_id,
+ pm.locker_id.as_ref().unwrap_or(&pm.payment_method_id),
+ )
+ .await
+ .change_context(errors::ApiErrorResponse::InternalServerError)
+ .attach_printable("Error getting card from card vault")?;
+ payment_methods::get_card_detail(&pm, card)
+ .change_context(errors::ApiErrorResponse::InternalServerError)
+ .attach_printable("Failed while getting card details from locker")?
+ } else {
+ get_card_details_without_locker_fallback(&pm, &state, &key_store).await?
+ };
+ Some(card_detail)
+ } else {
+ None
+ };
+ Ok(services::ApplicationResponse::Json(
+ api::PaymentMethodResponse {
+ merchant_id: pm.merchant_id,
+ customer_id: pm.customer_id,
+ payment_method_id: pm.payment_method_id,
+ payment_method: pm.payment_method,
+ payment_method_type: pm.payment_method_type,
+ metadata: pm.metadata,
+ created: Some(pm.created_at),
+ recurring_enabled: false,
+ payment_method_data: card.clone().map(api::PaymentMethodResponseData::Card),
+ last_used_at: Some(pm.last_used_at),
+ client_secret: pm.client_secret,
+ },
+ ))
+}
+
+#[cfg(all(
+ any(feature = "v2", feature = "v1"),
+ not(feature = "payment_methods_v2")
+))]
#[instrument(skip_all)]
#[cfg(all(feature = "v2", feature = "customer_v2"))]
pub async fn delete_payment_method(
@@ -5306,6 +5742,17 @@ pub async fn delete_payment_method(
))
}
+#[cfg(all(feature = "v2", feature = "payment_methods_v2"))]
+#[instrument(skip_all)]
+pub async fn delete_payment_method(
+ _state: routes::SessionState,
+ _merchant_account: domain::MerchantAccount,
+ _pm_id: api::PaymentMethodId,
+ _key_store: domain::MerchantKeyStore,
+) -> errors::RouterResponse<api::PaymentMethodDeleteResponse> {
+ todo!()
+}
+
pub async fn create_encrypted_data<T>(
state: &routes::SessionState,
key_store: &domain::MerchantKeyStore,
diff --git a/crates/router/src/core/payment_methods/surcharge_decision_configs.rs b/crates/router/src/core/payment_methods/surcharge_decision_configs.rs
index 23f79848dee..477f025c785 100644
--- a/crates/router/src/core/payment_methods/surcharge_decision_configs.rs
+++ b/crates/router/src/core/payment_methods/surcharge_decision_configs.rs
@@ -403,20 +403,12 @@ pub async fn perform_surcharge_decision_management_for_saved_cards(
backend_input.payment_method.payment_method_type =
customer_payment_method.payment_method_type;
- let card_network = match &customer_payment_method.payment_method_data {
- Some(api_models::payment_methods::PaymentMethodListData::Card(card)) => card
- .scheme
- .as_ref()
- .map(|scheme| {
- scheme
- .clone()
- .parse_enum("CardNetwork")
- .change_context(ConfigError::DslExecutionError)
- })
- .transpose()?,
+ let card_network = match customer_payment_method.payment_method_data.as_ref() {
+ Some(api_models::payment_methods::PaymentMethodListData::Card(card)) => {
+ card.card_network.clone()
+ }
_ => None,
};
-
backend_input.payment_method.card_network = card_network;
let surcharge_details = surcharge_source
diff --git a/crates/router/src/core/payment_methods/transformers.rs b/crates/router/src/core/payment_methods/transformers.rs
index 9ca2bffc88c..ed4f2d9d15f 100644
--- a/crates/router/src/core/payment_methods/transformers.rs
+++ b/crates/router/src/core/payment_methods/transformers.rs
@@ -1,3 +1,6 @@
+#[cfg(all(feature = "v2", feature = "payment_methods_v2"))]
+use std::str::FromStr;
+
use api_models::{enums as api_enums, payment_methods::Card};
use common_utils::{
ext_traits::{Encode, StringExt},
@@ -312,7 +315,11 @@ pub async fn mk_add_locker_request_hs(
Ok(request)
}
-#[cfg(feature = "payouts")]
+#[cfg(all(
+ any(feature = "v1", feature = "v2"),
+ not(feature = "payment_methods_v2"),
+ feature = "payouts"
+))]
pub fn mk_add_bank_response_hs(
bank: api::BankPayout,
bank_reference: String,
@@ -337,6 +344,20 @@ pub fn mk_add_bank_response_hs(
}
}
+#[cfg(all(feature = "v2", feature = "payment_methods_v2", feature = "payouts"))]
+pub fn mk_add_bank_response_hs(
+ _bank: api::BankPayout,
+ _bank_reference: String,
+ _req: api::PaymentMethodCreate,
+ _merchant_id: &id_type::MerchantId,
+) -> api::PaymentMethodResponse {
+ todo!()
+}
+
+#[cfg(all(
+ any(feature = "v1", feature = "v2"),
+ not(feature = "payment_methods_v2")
+))]
pub fn mk_add_card_response_hs(
card: api::CardDetail,
card_reference: String,
@@ -386,6 +407,16 @@ pub fn mk_add_card_response_hs(
}
}
+#[cfg(all(feature = "v2", feature = "payment_methods_v2"))]
+pub fn mk_add_card_response_hs(
+ _card: api::CardDetail,
+ _card_reference: String,
+ _req: api::PaymentMethodCreate,
+ _merchant_id: &id_type::MerchantId,
+) -> api::PaymentMethodResponse {
+ todo!()
+}
+
pub async fn mk_get_card_request_hs(
jwekey: &settings::Jwekey,
locker: &settings::Locker,
@@ -502,6 +533,10 @@ pub fn mk_delete_card_response(
})
}
+#[cfg(all(
+ any(feature = "v1", feature = "v2"),
+ not(feature = "payment_methods_v2")
+))]
pub fn get_card_detail(
pm: &storage::PaymentMethod,
response: Card,
@@ -530,6 +565,39 @@ pub fn get_card_detail(
Ok(card_detail)
}
+#[cfg(all(feature = "v2", feature = "payment_methods_v2"))]
+pub fn get_card_detail(
+ pm: &storage::PaymentMethod,
+ response: Card,
+) -> CustomResult<api::CardDetailFromLocker, errors::VaultError> {
+ let card_number = response.card_number;
+ let last4_digits = card_number.clone().get_last4();
+ //fetch form card bin
+
+ let card_detail = api::CardDetailFromLocker {
+ issuer_country: pm
+ .issuer_country
+ .as_ref()
+ .map(|c| api_enums::CountryAlpha2::from_str(c))
+ .transpose()
+ .ok()
+ .flatten(),
+ last4_digits: Some(last4_digits),
+ card_number: Some(card_number),
+ expiry_month: Some(response.card_exp_month),
+ expiry_year: Some(response.card_exp_year),
+ card_fingerprint: None,
+ card_holder_name: response.name_on_card,
+ nick_name: response.nick_name.map(Secret::new),
+ card_isin: None,
+ card_issuer: None,
+ card_network: None,
+ card_type: None,
+ saved_to_locker: true,
+ };
+ Ok(card_detail)
+}
+
//------------------------------------------------TokenizeService------------------------------------------------
pub fn mk_crud_locker_request(
locker: &settings::Locker,
diff --git a/crates/router/src/core/payments/helpers.rs b/crates/router/src/core/payments/helpers.rs
index 3715adefed4..a1b65fa2682 100644
--- a/crates/router/src/core/payments/helpers.rs
+++ b/crates/router/src/core/payments/helpers.rs
@@ -1354,89 +1354,6 @@ where
Box::new(PaymentResponse)
}
-#[instrument(skip_all)]
-pub(crate) async fn get_payment_method_create_request(
- payment_method_data: Option<&domain::PaymentMethodData>,
- payment_method: Option<storage_enums::PaymentMethod>,
- payment_method_type: Option<storage_enums::PaymentMethodType>,
- customer_id: &Option<id_type::CustomerId>,
- billing_name: Option<masking::Secret<String>>,
-) -> RouterResult<api::PaymentMethodCreate> {
- match payment_method_data {
- Some(pm_data) => match payment_method {
- Some(payment_method) => match pm_data {
- domain::PaymentMethodData::Card(card) => {
- let card_detail = api::CardDetail {
- card_number: card.card_number.clone(),
- card_exp_month: card.card_exp_month.clone(),
- card_exp_year: card.card_exp_year.clone(),
- card_holder_name: billing_name,
- nick_name: card.nick_name.clone(),
- card_issuing_country: card.card_issuing_country.clone(),
- card_network: card.card_network.clone(),
- card_issuer: card.card_issuer.clone(),
- card_type: card.card_type.clone(),
- };
- let payment_method_request = api::PaymentMethodCreate {
- payment_method: Some(payment_method),
- payment_method_type,
- payment_method_issuer: card.card_issuer.clone(),
- payment_method_issuer_code: None,
- #[cfg(feature = "payouts")]
- bank_transfer: None,
- #[cfg(feature = "payouts")]
- wallet: None,
- card: Some(card_detail),
- metadata: None,
- customer_id: customer_id.clone(),
- card_network: card
- .card_network
- .as_ref()
- .map(|card_network| card_network.to_string()),
- client_secret: None,
- payment_method_data: None,
- billing: None,
- connector_mandate_details: None,
- network_transaction_id: None,
- };
- Ok(payment_method_request)
- }
- _ => {
- let payment_method_request = api::PaymentMethodCreate {
- payment_method: Some(payment_method),
- payment_method_type,
- payment_method_issuer: None,
- payment_method_issuer_code: None,
- #[cfg(feature = "payouts")]
- bank_transfer: None,
- #[cfg(feature = "payouts")]
- wallet: None,
- card: None,
- metadata: None,
- customer_id: customer_id.clone(),
- card_network: None,
- client_secret: None,
- payment_method_data: None,
- billing: None,
- connector_mandate_details: None,
- network_transaction_id: None,
- };
-
- Ok(payment_method_request)
- }
- },
- None => Err(report!(errors::ApiErrorResponse::MissingRequiredField {
- field_name: "payment_method_type"
- })
- .attach_printable("PaymentMethodType Required")),
- },
- None => Err(report!(errors::ApiErrorResponse::MissingRequiredField {
- field_name: "payment_method_data"
- })
- .attach_printable("PaymentMethodData required Or Card is already saved")),
- }
-}
-
#[cfg(all(feature = "v2", feature = "customer_v2"))]
pub async fn get_customer_from_details<F: Clone>(
_state: &SessionState,
@@ -4081,6 +3998,10 @@ pub async fn get_additional_payment_data(
}
}
+#[cfg(all(
+ any(feature = "v1", feature = "v2"),
+ not(feature = "payment_methods_v2")
+))]
pub async fn populate_bin_details_for_payment_method_create(
card_details: api_models::payment_methods::CardDetail,
db: &dyn StorageInterface,
@@ -4138,6 +4059,14 @@ pub async fn populate_bin_details_for_payment_method_create(
}
}
+#[cfg(all(feature = "v2", feature = "payment_methods_v2"))]
+pub async fn populate_bin_details_for_payment_method_create(
+ _card_details: api_models::payment_methods::CardDetail,
+ _db: &dyn StorageInterface,
+) -> api_models::payment_methods::CardDetail {
+ todo!()
+}
+
pub fn validate_customer_access(
payment_intent: &PaymentIntent,
auth_flow: services::AuthFlow,
diff --git a/crates/router/src/core/payments/tokenization.rs b/crates/router/src/core/payments/tokenization.rs
index e9ebeafafd9..f26ed588a01 100644
--- a/crates/router/src/core/payments/tokenization.rs
+++ b/crates/router/src/core/payments/tokenization.rs
@@ -1,5 +1,9 @@
use std::collections::HashMap;
+#[cfg(all(
+ any(feature = "v1", feature = "v2"),
+ not(feature = "payment_methods_v2")
+))]
use api_models::payment_methods::PaymentMethodsData;
use common_enums::PaymentMethod;
use common_utils::{
@@ -54,6 +58,10 @@ impl<F, Req: Clone> From<&types::RouterData<F, Req, types::PaymentsResponseData>
}
}
+#[cfg(all(
+ any(feature = "v1", feature = "v2"),
+ not(feature = "payment_methods_v2")
+))]
#[instrument(skip_all)]
#[allow(clippy::too_many_arguments)]
pub async fn save_payment_method<FData>(
@@ -180,14 +188,15 @@ where
.attach_printable("Unable to serialize customer acceptance to value")?;
let pm_id = if customer_acceptance.is_some() {
- let payment_method_create_request = helpers::get_payment_method_create_request(
- Some(&save_payment_method_data.request.get_payment_method_data()),
- Some(save_payment_method_data.payment_method),
- payment_method_type,
- &customer_id.clone(),
- billing_name,
- )
- .await?;
+ let payment_method_create_request =
+ payment_methods::get_payment_method_create_request(
+ Some(&save_payment_method_data.request.get_payment_method_data()),
+ Some(save_payment_method_data.payment_method),
+ payment_method_type,
+ &customer_id.clone(),
+ billing_name,
+ )
+ .await?;
let customer_id = customer_id.to_owned().get_required_value("customer_id")?;
let merchant_id = merchant_account.get_id();
let (mut resp, duplication_check) = if !state.conf.locker.locker_enabled {
@@ -641,6 +650,35 @@ where
}
}
+// check in review
+#[cfg(all(feature = "v2", feature = "payment_methods_v2"))]
+#[instrument(skip_all)]
+#[allow(clippy::too_many_arguments)]
+pub async fn save_payment_method<FData>(
+ _state: &SessionState,
+ _connector_name: String,
+ _merchant_connector_id: Option<String>,
+ _save_payment_method_data: SavePaymentMethodData<FData>,
+ _customer_id: Option<id_type::CustomerId>,
+ _merchant_account: &domain::MerchantAccount,
+ _payment_method_type: Option<storage_enums::PaymentMethodType>,
+ _key_store: &domain::MerchantKeyStore,
+ _amount: Option<i64>,
+ _currency: Option<storage_enums::Currency>,
+ _billing_name: Option<Secret<String>>,
+ _payment_method_billing_address: Option<&api::Address>,
+ _business_profile: &domain::BusinessProfile,
+) -> RouterResult<(Option<String>, Option<common_enums::PaymentMethodStatus>)>
+where
+ FData: mandate::MandateBehaviour + Clone,
+{
+ todo!()
+}
+
+#[cfg(all(
+ any(feature = "v1", feature = "v2"),
+ not(feature = "payment_methods_v2")
+))]
async fn skip_saving_card_in_locker(
merchant_account: &domain::MerchantAccount,
payment_method_request: api::PaymentMethodCreate,
@@ -729,6 +767,21 @@ async fn skip_saving_card_in_locker(
}
}
+#[cfg(all(feature = "v2", feature = "payment_methods_v2"))]
+async fn skip_saving_card_in_locker(
+ merchant_account: &domain::MerchantAccount,
+ payment_method_request: api::PaymentMethodCreate,
+) -> RouterResult<(
+ api_models::payment_methods::PaymentMethodResponse,
+ Option<payment_methods::transformers::DataDuplicationCheck>,
+)> {
+ todo!()
+}
+
+#[cfg(all(
+ any(feature = "v1", feature = "v2"),
+ not(feature = "payment_methods_v2")
+))]
pub async fn save_in_locker(
state: &SessionState,
merchant_account: &domain::MerchantAccount,
@@ -779,6 +832,18 @@ pub async fn save_in_locker(
}
}
+#[cfg(all(feature = "v2", feature = "payment_methods_v2"))]
+pub async fn save_in_locker(
+ _state: &SessionState,
+ _merchant_account: &domain::MerchantAccount,
+ _payment_method_request: api::PaymentMethodCreate,
+) -> RouterResult<(
+ api_models::payment_methods::PaymentMethodResponse,
+ Option<payment_methods::transformers::DataDuplicationCheck>,
+)> {
+ todo!()
+}
+
pub fn create_payment_method_metadata(
metadata: Option<&pii::SecretSerdeValue>,
connector_token: Option<(String, String)>,
diff --git a/crates/router/src/core/payouts/helpers.rs b/crates/router/src/core/payouts/helpers.rs
index 4f9e3f9529e..2cfeb9691d0 100644
--- a/crates/router/src/core/payouts/helpers.rs
+++ b/crates/router/src/core/payouts/helpers.rs
@@ -193,6 +193,10 @@ pub async fn make_payout_method_data<'a>(
}
}
+#[cfg(all(
+ any(feature = "v1", feature = "v2"),
+ not(feature = "payment_methods_v2")
+))]
pub async fn save_payout_data_to_locker(
state: &SessionState,
payout_data: &mut PayoutData,
@@ -605,6 +609,18 @@ pub async fn save_payout_data_to_locker(
Ok(())
}
+#[cfg(all(feature = "v2", feature = "payment_methods_v2"))]
+pub async fn save_payout_data_to_locker(
+ _state: &SessionState,
+ _payout_data: &mut PayoutData,
+ _customer_id: &id_type::CustomerId,
+ _payout_method_data: &api::PayoutMethodData,
+ _merchant_account: &domain::MerchantAccount,
+ _key_store: &domain::MerchantKeyStore,
+) -> RouterResult<()> {
+ todo!()
+}
+
#[cfg(all(feature = "v2", feature = "customer_v2"))]
pub(super) async fn get_or_create_customer_details(
_state: &SessionState,
diff --git a/crates/router/src/routes/payment_methods.rs b/crates/router/src/routes/payment_methods.rs
index 36f70957207..b3c7f5cc59b 100644
--- a/crates/router/src/routes/payment_methods.rs
+++ b/crates/router/src/routes/payment_methods.rs
@@ -168,6 +168,10 @@ pub async fn migrate_payment_methods(
.await
}
+#[cfg(all(
+ any(feature = "v1", feature = "v2"),
+ not(feature = "payment_methods_v2")
+))]
#[instrument(skip_all, fields(flow = ?Flow::PaymentMethodSave))]
pub async fn save_payment_method_api(
state: web::Data<AppState>,
@@ -712,14 +716,14 @@ mod tests {
use super::*;
- #[test]
- fn test_custom_list_deserialization() {
- let dummy_data = "amount=120&recurring_enabled=true&installment_payment_enabled=true";
- let de_query: web::Query<PaymentMethodListRequest> =
- web::Query::from_query(dummy_data).unwrap();
- let de_struct = de_query.into_inner();
- assert_eq!(de_struct.installment_payment_enabled, Some(true))
- }
+ // #[test]
+ // fn test_custom_list_deserialization() {
+ // let dummy_data = "amount=120&recurring_enabled=true&installment_payment_enabled=true";
+ // let de_query: web::Query<PaymentMethodListRequest> =
+ // web::Query::from_query(dummy_data).unwrap();
+ // let de_struct = de_query.into_inner();
+ // assert_eq!(de_struct.installment_payment_enabled, Some(true))
+ // }
#[test]
fn test_custom_list_deserialization_multi_amount() {
diff --git a/crates/router/src/services/authentication.rs b/crates/router/src/services/authentication.rs
index 4ac2c02c94c..9ab2e2e3b07 100644
--- a/crates/router/src/services/authentication.rs
+++ b/crates/router/src/services/authentication.rs
@@ -1,10 +1,14 @@
use actix_web::http::header::HeaderMap;
+#[cfg(all(
+ any(feature = "v2", feature = "v1"),
+ not(feature = "payment_methods_v2")
+))]
+use api_models::payment_methods::PaymentMethodCreate;
+#[cfg(all(feature = "v2", feature = "payment_methods_v2"))]
+use api_models::payment_methods::PaymentMethodIntentConfirm;
#[cfg(feature = "payouts")]
use api_models::payouts;
-use api_models::{
- payment_methods::{PaymentMethodCreate, PaymentMethodListRequest},
- payments,
-};
+use api_models::{payment_methods::PaymentMethodListRequest, payments};
use async_trait::async_trait;
use common_enums::TokenPurpose;
use common_utils::{date_time, id_type};
@@ -1366,12 +1370,23 @@ impl ClientSecretFetch for PaymentMethodListRequest {
}
}
+#[cfg(all(
+ any(feature = "v2", feature = "v1"),
+ not(feature = "payment_methods_v2")
+))]
impl ClientSecretFetch for PaymentMethodCreate {
fn get_client_secret(&self) -> Option<&String> {
self.client_secret.as_ref()
}
}
+#[cfg(all(feature = "v2", feature = "payment_methods_v2"))]
+impl ClientSecretFetch for PaymentMethodIntentConfirm {
+ fn get_client_secret(&self) -> Option<&String> {
+ Some(&self.client_secret)
+ }
+}
+
impl ClientSecretFetch for api_models::cards_info::CardsInfoRequest {
fn get_client_secret(&self) -> Option<&String> {
self.client_secret.as_ref()
diff --git a/crates/router/src/types/api/mandates.rs b/crates/router/src/types/api/mandates.rs
index 686f7f3ce49..bf8f00526e9 100644
--- a/crates/router/src/types/api/mandates.rs
+++ b/crates/router/src/types/api/mandates.rs
@@ -108,6 +108,10 @@ impl MandateResponseExt for MandateResponse {
}
}
+#[cfg(all(
+ any(feature = "v1", feature = "v2"),
+ not(feature = "payment_methods_v2")
+))]
impl From<api::payment_methods::CardDetailFromLocker> for MandateCardDetails {
fn from(card_details_from_locker: api::payment_methods::CardDetailFromLocker) -> Self {
mandates::MandateCardDetails {
@@ -128,3 +132,30 @@ impl From<api::payment_methods::CardDetailFromLocker> for MandateCardDetails {
.into()
}
}
+
+#[cfg(all(feature = "v2", feature = "payment_methods_v2"))]
+impl From<api::payment_methods::CardDetailFromLocker> for MandateCardDetails {
+ fn from(card_details_from_locker: api::payment_methods::CardDetailFromLocker) -> Self {
+ mandates::MandateCardDetails {
+ last4_digits: card_details_from_locker.last4_digits,
+ card_exp_month: card_details_from_locker.expiry_month.clone(),
+ card_exp_year: card_details_from_locker.expiry_year.clone(),
+ card_holder_name: card_details_from_locker.card_holder_name,
+ card_token: None,
+ scheme: None,
+ issuer_country: card_details_from_locker
+ .issuer_country
+ .map(|country| country.to_string()),
+ card_fingerprint: card_details_from_locker.card_fingerprint,
+ card_isin: card_details_from_locker.card_isin,
+ card_issuer: card_details_from_locker.card_issuer,
+ card_network: card_details_from_locker.card_network,
+ card_type: card_details_from_locker
+ .card_type
+ .as_ref()
+ .map(|c| c.to_string()),
+ nick_name: card_details_from_locker.nick_name,
+ }
+ .into()
+ }
+}
diff --git a/crates/router/src/types/api/payment_methods.rs b/crates/router/src/types/api/payment_methods.rs
index 062a2fdf630..f4d1492fb44 100644
--- a/crates/router/src/types/api/payment_methods.rs
+++ b/crates/router/src/types/api/payment_methods.rs
@@ -1,14 +1,15 @@
#[cfg(all(feature = "v2", feature = "payment_methods_v2"))]
pub use api_models::payment_methods::{
- CardDetail, CardDetailFromLocker, CardDetailsPaymentMethod, CustomerPaymentMethod,
+ CardDetail, CardDetailFromLocker, CardDetailsPaymentMethod, CardType, CustomerPaymentMethod,
CustomerPaymentMethodsListResponse, DefaultPaymentMethod, DeleteTokenizeByTokenRequest,
GetTokenizePayloadRequest, GetTokenizePayloadResponse, ListCountriesCurrenciesRequest,
PaymentMethodCollectLinkRenderRequest, PaymentMethodCollectLinkRequest, PaymentMethodCreate,
- PaymentMethodCreateData, PaymentMethodDeleteResponse, PaymentMethodId, PaymentMethodList,
+ PaymentMethodCreateData, PaymentMethodDeleteResponse, PaymentMethodId,
+ PaymentMethodIntentConfirm, PaymentMethodIntentCreate, PaymentMethodList,
PaymentMethodListData, PaymentMethodListRequest, PaymentMethodListResponse,
- PaymentMethodMigrate, PaymentMethodResponse, PaymentMethodUpdate, PaymentMethodsData,
- TokenizePayloadEncrypted, TokenizePayloadRequest, TokenizedCardValue1, TokenizedCardValue2,
- TokenizedWalletValue1, TokenizedWalletValue2,
+ PaymentMethodMigrate, PaymentMethodResponse, PaymentMethodResponseData, PaymentMethodUpdate,
+ PaymentMethodsData, TokenizePayloadEncrypted, TokenizePayloadRequest, TokenizedCardValue1,
+ TokenizedCardValue2, TokenizedWalletValue1, TokenizedWalletValue2,
};
#[cfg(all(
any(feature = "v2", feature = "v1"),
@@ -37,6 +38,10 @@ pub(crate) trait PaymentMethodCreateExt {
}
// convert self.payment_method_type to payment_method and compare it against self.payment_method
+#[cfg(all(
+ any(feature = "v2", feature = "v1"),
+ not(feature = "payment_methods_v2")
+))]
impl PaymentMethodCreateExt for PaymentMethodCreate {
fn validate(&self) -> RouterResult<()> {
if let Some(pm) = self.payment_method {
@@ -52,3 +57,19 @@ impl PaymentMethodCreateExt for PaymentMethodCreate {
Ok(())
}
}
+
+#[cfg(all(feature = "v2", feature = "payment_methods_v2"))]
+impl PaymentMethodCreateExt for PaymentMethodCreate {
+ fn validate(&self) -> RouterResult<()> {
+ if !validate_payment_method_type_against_payment_method(
+ self.payment_method,
+ self.payment_method_type,
+ ) {
+ return Err(report!(errors::ApiErrorResponse::InvalidRequestData {
+ message: "Invalid 'payment_method_type' provided".to_string()
+ })
+ .attach_printable("Invalid payment method type"));
+ }
+ Ok(())
+ }
+}
diff --git a/crates/router/src/types/transformers.rs b/crates/router/src/types/transformers.rs
index 67af63b154e..2cc95281f03 100644
--- a/crates/router/src/types/transformers.rs
+++ b/crates/router/src/types/transformers.rs
@@ -81,6 +81,10 @@ impl ForeignFrom<api_models::refunds::RefundType> for storage_enums::RefundType
}
}
+#[cfg(all(
+ any(feature = "v1", feature = "v2"),
+ not(feature = "payment_methods_v2")
+))]
impl
ForeignFrom<(
Option<payment_methods::CardDetailFromLocker>,
@@ -113,6 +117,36 @@ impl
}
}
+#[cfg(all(feature = "v2", feature = "payment_methods_v2"))]
+impl
+ ForeignFrom<(
+ Option<payment_methods::CardDetailFromLocker>,
+ diesel_models::PaymentMethod,
+ )> for payment_methods::PaymentMethodResponse
+{
+ fn foreign_from(
+ (card_details, item): (
+ Option<payment_methods::CardDetailFromLocker>,
+ diesel_models::PaymentMethod,
+ ),
+ ) -> Self {
+ Self {
+ merchant_id: item.merchant_id,
+ customer_id: item.customer_id,
+ payment_method_id: item.payment_method_id,
+ payment_method: item.payment_method,
+ payment_method_type: item.payment_method_type,
+ payment_method_data: card_details
+ .map(|card| payment_methods::PaymentMethodResponseData::Card(card.clone())),
+ recurring_enabled: false,
+ metadata: item.metadata,
+ created: Some(item.created_at),
+ last_used_at: None,
+ client_secret: item.client_secret,
+ }
+ }
+}
+
impl ForeignFrom<storage_enums::AttemptStatus> for storage_enums::IntentStatus {
fn foreign_from(s: storage_enums::AttemptStatus) -> Self {
match s {
diff --git a/scripts/ci-checks-v2.sh b/scripts/ci-checks-v2.sh
index bebfce27e73..151e5a382d0 100755
--- a/scripts/ci-checks-v2.sh
+++ b/scripts/ci-checks-v2.sh
@@ -7,7 +7,7 @@ diesel_models
hyperswitch_domain_models
storage_impl'
-v2_feature_set='v2,merchant_account_v2,payment_v2,customer_v2,routing_v2,business_profile_v2'
+v2_feature_set='v2,merchant_account_v2,payment_v2,customer_v2,routing_v2,business_profile_v2,payment_methods_v2'
packages_checked=()
packages_skipped=()
@@ -38,7 +38,7 @@ if [[ "${GITHUB_EVENT_NAME:-}" == 'pull_request' ]]; then
# A package must be checked if it has been modified
if grep --quiet --extended-regexp "^crates/${package_name}" <<< "${files_modified}"; then
if [[ "${package_name}" == "storage_impl" ]]; then
- all_commands+=("cargo hack clippy --features 'v2,payment_v2,customer_v2' -p storage_impl")
+ all_commands+=("cargo hack clippy --features 'v2,payment_v2,customer_v2,payment_methods_v2' -p storage_impl")
else
valid_features="$(features_to_run "$package_name")"
all_commands+=("cargo hack clippy --feature-powerset --depth 2 --ignore-unknown-features --at-least-one-of 'v2 ' --include-features '${valid_features}' --package '${package_name}'")
|
2024-08-07T19:00:31Z
|
## Type of Change
<!-- Put an `x` in the boxes that apply -->
- [ ] Bugfix
- [x] New feature
- [ ] Enhancement
- [ ] Refactoring
- [ ] Dependency updates
- [ ] Documentation
- [ ] CI/CD
## Description
<!-- Describe your changes in detail -->
API models for payment methods v2
- Implemented types for API v2
- Have left a todo! macro for functions where v2 implementation is unclear
### Additional Changes
- [ ] This PR modifies the API contract
- [ ] This PR modifies the database schema
- [ ] This PR modifies application configuration/environment variables
<!--
Provide links to the files with corresponding changes.
Following are the paths where you can find config files:
1. `config`
2. `crates/router/src/configs`
3. `loadtest/config`
-->
## Motivation and Context
<!--
Why is this change required? What problem does it solve?
If it fixes an open issue, please link to the issue here.
If you don't have an issue, we'd recommend starting with one first so the PR
can focus on the implementation (unless it is an obvious bug or documentation fix
that will have little conversation).
-->
## How did you test it?
<!--
Did you write an integration/unit/API test to verify the code changes?
Or did you test this change manually (provide relevant screenshots)?
-->
Logic can't be tested as of now as this PR is only concerned with API model change
## Checklist
<!-- Put an `x` in the boxes that apply -->
- [x] I formatted the code `cargo +nightly fmt --all`
- [ ] I addressed lints thrown by `cargo clippy`
- [ ] I reviewed the submitted code
- [ ] I added unit tests for my changes where possible
|
36cc0ccbe69dc8f43c4cdd6daaea5e07beea8514
|
|
juspay/hyperswitch
|
juspay__hyperswitch-5543
|
Bug: feat(user_roles): Start inserting V2 user_roles in DB
Currently we only have V1 user_roles data. These roles are at merchant level.
To start supporting profile level dashboard, we should start inserting V2 user_roles which will have profile context as well.
|
diff --git a/crates/diesel_models/src/query/user_role.rs b/crates/diesel_models/src/query/user_role.rs
index 85f866f2fc2..fde146408a9 100644
--- a/crates/diesel_models/src/query/user_role.rs
+++ b/crates/diesel_models/src/query/user_role.rs
@@ -5,6 +5,7 @@ use diesel::{
BoolExpressionMethods, ExpressionMethods, QueryDsl,
};
use error_stack::{report, ResultExt};
+use router_env::logger;
use crate::{
enums::UserRoleVersion, errors, query::generics, schema::user_roles::dsl, user_role::*,
@@ -18,6 +19,21 @@ impl UserRoleNew {
}
impl UserRole {
+ pub async fn insert_multiple_user_roles(
+ conn: &PgPooledConn,
+ user_roles: Vec<UserRoleNew>,
+ ) -> StorageResult<Vec<Self>> {
+ let query = diesel::insert_into(<Self>::table()).values(user_roles);
+
+ logger::debug!(query = %debug_query::<Pg,_>(&query).to_string());
+
+ query
+ .get_results_async(conn)
+ .await
+ .change_context(errors::DatabaseError::Others)
+ .attach_printable("Error while inserting user_roles")
+ }
+
pub async fn find_by_user_id(
conn: &PgPooledConn,
user_id: String,
diff --git a/crates/router/src/core/user.rs b/crates/router/src/core/user.rs
index 17ebd00a994..ace8c3babc6 100644
--- a/crates/router/src/core/user.rs
+++ b/crates/router/src/core/user.rs
@@ -1,4 +1,7 @@
-use std::collections::{HashMap, HashSet};
+use std::{
+ collections::{HashMap, HashSet},
+ ops::Not,
+};
use api_models::{
payments::RedirectionResponse,
@@ -13,7 +16,6 @@ use diesel_models::{
organization::OrganizationBridge,
user as storage_user,
user_authentication_method::{UserAuthenticationMethodNew, UserAuthenticationMethodUpdate},
- user_role::UserRoleNew,
};
use error_stack::{report, ResultExt};
#[cfg(feature = "email")]
@@ -60,10 +62,11 @@ pub async fn signup_with_merchant_id(
.await?;
let user_role = new_user
- .insert_user_role_in_db(
+ .insert_org_level_user_role_in_db(
state.clone(),
common_utils::consts::ROLE_ID_ORGANIZATION_ADMIN.to_string(),
UserStatus::Active,
+ None,
)
.await?;
@@ -132,10 +135,11 @@ pub async fn signup(
.insert_user_and_merchant_in_db(state.clone())
.await?;
let user_role = new_user
- .insert_user_role_in_db(
+ .insert_org_level_user_role_in_db(
state.clone(),
common_utils::consts::ROLE_ID_ORGANIZATION_ADMIN.to_string(),
UserStatus::Active,
+ None,
)
.await?;
utils::user_role::set_role_permissions_in_cache_by_user_role(&state, &user_role).await;
@@ -163,10 +167,11 @@ pub async fn signup_token_only_flow(
.insert_user_and_merchant_in_db(state.clone())
.await?;
let user_role = new_user
- .insert_user_role_in_db(
+ .insert_org_level_user_role_in_db(
state.clone(),
common_utils::consts::ROLE_ID_ORGANIZATION_ADMIN.to_string(),
UserStatus::Active,
+ None,
)
.await?;
@@ -314,10 +319,11 @@ pub async fn connect_account(
.insert_user_and_merchant_in_db(state.clone())
.await?;
let user_role = new_user
- .insert_user_role_in_db(
+ .insert_org_level_user_role_in_db(
state.clone(),
common_utils::consts::ROLE_ID_ORGANIZATION_ADMIN.to_string(),
UserStatus::Active,
+ None,
)
.await?;
@@ -773,37 +779,60 @@ async fn handle_existing_user_invitation(
auth_id: &Option<String>,
) -> UserResult<InviteMultipleUserResponse> {
let now = common_utils::date_time::now();
- state
+
+ if state
.store
- .insert_user_role(UserRoleNew {
- user_id: invitee_user_from_db.get_user_id().to_owned(),
- merchant_id: Some(user_from_token.merchant_id.clone()),
- role_id: request.role_id.clone(),
- org_id: Some(user_from_token.org_id.clone()),
- status: {
- if cfg!(feature = "email") {
- UserStatus::InvitationSent
- } else {
- UserStatus::Active
- }
- },
- created_by: user_from_token.user_id.clone(),
- last_modified_by: user_from_token.user_id.clone(),
- created_at: now,
- last_modified: now,
- profile_id: None,
- entity_id: None,
- entity_type: None,
- version: UserRoleVersion::V1,
- })
+ .find_user_role_by_user_id_and_lineage(
+ invitee_user_from_db.get_user_id(),
+ &user_from_token.org_id,
+ &user_from_token.merchant_id,
+ user_from_token.profile_id.as_ref(),
+ UserRoleVersion::V1,
+ )
.await
- .map_err(|e| {
- if e.current_context().is_db_unique_violation() {
- e.change_context(UserErrors::UserExists)
+ .is_err_and(|err| err.current_context().is_db_not_found())
+ .not()
+ {
+ return Err(UserErrors::UserExists.into());
+ }
+
+ if state
+ .store
+ .find_user_role_by_user_id_and_lineage(
+ invitee_user_from_db.get_user_id(),
+ &user_from_token.org_id,
+ &user_from_token.merchant_id,
+ user_from_token.profile_id.as_ref(),
+ UserRoleVersion::V2,
+ )
+ .await
+ .is_err_and(|err| err.current_context().is_db_not_found())
+ .not()
+ {
+ return Err(UserErrors::UserExists.into());
+ }
+
+ let user_role = domain::NewUserRole {
+ user_id: invitee_user_from_db.get_user_id().to_owned(),
+ role_id: request.role_id.clone(),
+ status: {
+ if cfg!(feature = "email") {
+ UserStatus::InvitationSent
} else {
- e.change_context(UserErrors::InternalServerError)
+ UserStatus::Active
}
- })?;
+ },
+ created_by: user_from_token.user_id.clone(),
+ last_modified_by: user_from_token.user_id.clone(),
+ created_at: now,
+ last_modified: now,
+ entity: domain::MerchantLevel {
+ org_id: user_from_token.org_id.clone(),
+ merchant_id: user_from_token.merchant_id.clone(),
+ },
+ }
+ .insert_in_v1_and_v2(state)
+ .await?;
let is_email_sent;
#[cfg(feature = "email")]
@@ -865,31 +894,22 @@ async fn handle_new_user_invitation(
};
let now = common_utils::date_time::now();
- state
- .store
- .insert_user_role(UserRoleNew {
- user_id: new_user.get_user_id().to_owned(),
- merchant_id: Some(user_from_token.merchant_id.clone()),
- role_id: request.role_id.clone(),
- org_id: Some(user_from_token.org_id.clone()),
- status: invitation_status,
- created_by: user_from_token.user_id.clone(),
- last_modified_by: user_from_token.user_id.clone(),
- created_at: now,
- last_modified: now,
- profile_id: None,
- entity_id: None,
- entity_type: None,
- version: UserRoleVersion::V1,
- })
- .await
- .map_err(|e| {
- if e.current_context().is_db_unique_violation() {
- e.change_context(UserErrors::UserExists)
- } else {
- e.change_context(UserErrors::InternalServerError)
- }
- })?;
+
+ let user_role = domain::NewUserRole {
+ user_id: new_user.get_user_id().to_owned(),
+ role_id: request.role_id.clone(),
+ status: invitation_status,
+ created_by: user_from_token.user_id.clone(),
+ last_modified_by: user_from_token.user_id.clone(),
+ created_at: now,
+ last_modified: now,
+ entity: domain::MerchantLevel {
+ merchant_id: user_from_token.merchant_id.clone(),
+ org_id: user_from_token.org_id.clone(),
+ },
+ }
+ .insert_in_v1_and_v2(state)
+ .await?;
let is_email_sent;
// TODO: Adding this to avoid clippy lints, remove this once the token only flow is being used
@@ -1289,7 +1309,7 @@ pub async fn create_internal_user(
}
})?;
- let new_user = domain::NewUser::try_from((request, internal_merchant.organization_id))?;
+ let new_user = domain::NewUser::try_from((request, internal_merchant.organization_id.clone()))?;
let mut store_user: storage_user::UserNew = new_user.clone().try_into()?;
store_user.set_is_verified(true);
@@ -1308,12 +1328,16 @@ pub async fn create_internal_user(
.map(domain::user::UserFromStorage::from)?;
new_user
- .insert_user_role_in_db(
- state,
+ .get_no_level_user_role(
common_utils::consts::ROLE_ID_INTERNAL_VIEW_ONLY_USER.to_string(),
UserStatus::Active,
)
- .await?;
+ .add_entity(domain::InternalLevel {
+ org_id: internal_merchant.organization_id,
+ })
+ .insert_in_v1_and_v2(&state)
+ .await
+ .change_context(UserErrors::InternalServerError)?;
Ok(ApplicationResponse::StatusOk)
}
@@ -1448,10 +1472,11 @@ pub async fn create_merchant_account(
.await?;
let role_insertion_res = new_user
- .insert_user_role_in_db(
+ .insert_org_level_user_role_in_db(
state.clone(),
common_utils::consts::ROLE_ID_ORGANIZATION_ADMIN.to_string(),
UserStatus::Active,
+ Some(UserRoleVersion::V1),
)
.await;
if let Err(e) = role_insertion_res {
diff --git a/crates/router/src/db/kafka_store.rs b/crates/router/src/db/kafka_store.rs
index 0d8b753463b..3a7a2c44f31 100644
--- a/crates/router/src/db/kafka_store.rs
+++ b/crates/router/src/db/kafka_store.rs
@@ -35,7 +35,7 @@ use super::{
user::{sample_data::BatchSampleDataInterface, UserInterface},
user_authentication_method::UserAuthenticationMethodInterface,
user_key_store::UserKeyStoreInterface,
- user_role::{ListUserRolesByOrgIdPayload, UserRoleInterface},
+ user_role::{InsertUserRolePayload, ListUserRolesByOrgIdPayload, UserRoleInterface},
};
#[cfg(feature = "payouts")]
use crate::services::kafka::payout::KafkaPayout;
@@ -2766,8 +2766,8 @@ impl RedisConnInterface for KafkaStore {
impl UserRoleInterface for KafkaStore {
async fn insert_user_role(
&self,
- user_role: user_storage::UserRoleNew,
- ) -> CustomResult<user_storage::UserRole, errors::StorageError> {
+ user_role: InsertUserRolePayload,
+ ) -> CustomResult<Vec<user_storage::UserRole>, errors::StorageError> {
self.diesel_store.insert_user_role(user_role).await
}
diff --git a/crates/router/src/db/user_role.rs b/crates/router/src/db/user_role.rs
index 8d07f53e12d..57090632725 100644
--- a/crates/router/src/db/user_role.rs
+++ b/crates/router/src/db/user_role.rs
@@ -10,12 +10,35 @@ use crate::{
services::Store,
};
+pub enum InsertUserRolePayload {
+ OnlyV1(storage::UserRoleNew),
+ OnlyV2(storage::UserRoleNew),
+ V1AndV2(Box<[storage::UserRoleNew; 2]>),
+}
+
+impl InsertUserRolePayload {
+ fn convert_to_vec(self) -> Vec<storage::UserRoleNew> {
+ match self {
+ Self::OnlyV1(user_role) | Self::OnlyV2(user_role) => vec![user_role],
+ Self::V1AndV2(user_roles) => user_roles.to_vec(),
+ }
+ }
+}
+
+pub struct ListUserRolesByOrgIdPayload<'a> {
+ pub user_id: Option<&'a String>,
+ pub org_id: &'a id_type::OrganizationId,
+ pub merchant_id: Option<&'a id_type::MerchantId>,
+ pub profile_id: Option<&'a id_type::ProfileId>,
+ pub version: Option<enums::UserRoleVersion>,
+}
+
#[async_trait::async_trait]
pub trait UserRoleInterface {
async fn insert_user_role(
&self,
- user_role: storage::UserRoleNew,
- ) -> CustomResult<storage::UserRole, errors::StorageError>;
+ user_role: InsertUserRolePayload,
+ ) -> CustomResult<Vec<storage::UserRole>, errors::StorageError>;
async fn find_user_role_by_user_id(
&self,
@@ -86,24 +109,16 @@ pub trait UserRoleInterface {
) -> CustomResult<Vec<storage::UserRole>, errors::StorageError>;
}
-pub struct ListUserRolesByOrgIdPayload<'a> {
- pub user_id: Option<&'a String>,
- pub org_id: &'a id_type::OrganizationId,
- pub merchant_id: Option<&'a id_type::MerchantId>,
- pub profile_id: Option<&'a id_type::ProfileId>,
- pub version: Option<enums::UserRoleVersion>,
-}
-
#[async_trait::async_trait]
impl UserRoleInterface for Store {
#[instrument(skip_all)]
async fn insert_user_role(
&self,
- user_role: storage::UserRoleNew,
- ) -> CustomResult<storage::UserRole, errors::StorageError> {
+ user_role: InsertUserRolePayload,
+ ) -> CustomResult<Vec<storage::UserRole>, errors::StorageError> {
let conn = connection::pg_connection_write(self).await?;
- user_role
- .insert(&conn)
+
+ storage::UserRole::insert_multiple_user_roles(&conn, user_role.convert_to_vec())
.await
.map_err(|error| report!(errors::StorageError::from(error)))
}
@@ -138,7 +153,6 @@ impl UserRoleInterface for Store {
.map_err(|error| report!(errors::StorageError::from(error)))
}
- #[instrument(skip_all)]
async fn list_user_roles_by_user_id_and_version(
&self,
user_id: &str,
@@ -275,37 +289,44 @@ impl UserRoleInterface for Store {
impl UserRoleInterface for MockDb {
async fn insert_user_role(
&self,
- user_role: storage::UserRoleNew,
- ) -> CustomResult<storage::UserRole, errors::StorageError> {
- let mut user_roles = self.user_roles.lock().await;
- if user_roles
- .iter()
- .any(|user_role_inner| user_role_inner.user_id == user_role.user_id)
- {
- Err(errors::StorageError::DuplicateValue {
- entity: "user_id",
- key: None,
- })?
- }
- let user_role = storage::UserRole {
- id: i32::try_from(user_roles.len())
- .change_context(errors::StorageError::MockDbError)?,
- user_id: user_role.user_id,
- merchant_id: user_role.merchant_id,
- role_id: user_role.role_id,
- status: user_role.status,
- created_by: user_role.created_by,
- created_at: user_role.created_at,
- last_modified: user_role.last_modified,
- last_modified_by: user_role.last_modified_by,
- org_id: user_role.org_id,
- profile_id: None,
- entity_id: None,
- entity_type: None,
- version: enums::UserRoleVersion::V1,
- };
- user_roles.push(user_role.clone());
- Ok(user_role)
+ user_role: InsertUserRolePayload,
+ ) -> CustomResult<Vec<storage::UserRole>, errors::StorageError> {
+ let mut db_user_roles = self.user_roles.lock().await;
+
+ user_role
+ .convert_to_vec()
+ .into_iter()
+ .map(|user_role| {
+ if db_user_roles
+ .iter()
+ .any(|user_role_inner| user_role_inner.user_id == user_role.user_id)
+ {
+ Err(errors::StorageError::DuplicateValue {
+ entity: "user_id",
+ key: None,
+ })?
+ }
+ let user_role = storage::UserRole {
+ id: i32::try_from(db_user_roles.len())
+ .change_context(errors::StorageError::MockDbError)?,
+ user_id: user_role.user_id,
+ merchant_id: user_role.merchant_id,
+ role_id: user_role.role_id,
+ status: user_role.status,
+ created_by: user_role.created_by,
+ created_at: user_role.created_at,
+ last_modified: user_role.last_modified,
+ last_modified_by: user_role.last_modified_by,
+ org_id: user_role.org_id,
+ profile_id: None,
+ entity_id: None,
+ entity_type: None,
+ version: enums::UserRoleVersion::V1,
+ };
+ db_user_roles.push(user_role.clone());
+ Ok(user_role)
+ })
+ .collect::<Result<Vec<_>, _>>()
}
async fn find_user_role_by_user_id(
diff --git a/crates/router/src/types/domain/user.rs b/crates/router/src/types/domain/user.rs
index b252e618536..42cb71458d5 100644
--- a/crates/router/src/types/domain/user.rs
+++ b/crates/router/src/types/domain/user.rs
@@ -3,7 +3,7 @@ use std::{collections::HashSet, ops, str::FromStr};
use api_models::{
admin as admin_api, organization as api_org, user as user_api, user_role as user_role_api,
};
-use common_enums::TokenPurpose;
+use common_enums::{EntityType, TokenPurpose};
use common_utils::{
crypto::Encryptable, errors::CustomResult, id_type, new_type::MerchantName, pii, type_name,
types::keymanager::Identifier,
@@ -19,6 +19,7 @@ use masking::{ExposeInterface, PeekInterface, Secret};
use once_cell::sync::Lazy;
use rand::distributions::{Alphanumeric, DistString};
use router_env::env;
+use time::PrimitiveDateTime;
use unicode_segmentation::UnicodeSegmentation;
#[cfg(feature = "keymanager_create")]
use {base64::Engine, common_utils::types::keymanager::EncryptionTransferRequest};
@@ -29,9 +30,13 @@ use crate::{
admin,
errors::{self, UserErrors, UserResult},
},
- db::GlobalStorageInterface,
+ db::{user_role::InsertUserRolePayload, GlobalStorageInterface},
routes::SessionState,
- services::{self, authentication as auth, authentication::UserFromToken, authorization::info},
+ services::{
+ self,
+ authentication::{self as auth, UserFromToken},
+ authorization::info,
+ },
types::transformers::ForeignFrom,
utils::{self, user::password},
};
@@ -638,38 +643,51 @@ impl NewUser {
created_user
}
- pub async fn insert_user_role_in_db(
+ pub fn get_no_level_user_role(
self,
- state: SessionState,
role_id: String,
user_status: UserStatus,
- ) -> UserResult<UserRole> {
+ ) -> NewUserRole<NoLevel> {
let now = common_utils::date_time::now();
let user_id = self.get_user_id();
- state
- .store
- .insert_user_role(UserRoleNew {
- merchant_id: Some(self.get_new_merchant().get_merchant_id()),
- status: user_status,
- created_by: user_id.clone(),
- last_modified_by: user_id.clone(),
- user_id,
- role_id,
- created_at: now,
- last_modified: now,
- org_id: Some(
- self.get_new_merchant()
- .get_new_organization()
- .get_organization_id(),
- ),
- profile_id: None,
- entity_id: None,
- entity_type: None,
- version: UserRoleVersion::V1,
- })
- .await
- .change_context(UserErrors::InternalServerError)
+ NewUserRole {
+ status: user_status,
+ created_by: user_id.clone(),
+ last_modified_by: user_id.clone(),
+ user_id,
+ role_id,
+ created_at: now,
+ last_modified: now,
+ entity: NoLevel,
+ }
+ }
+
+ pub async fn insert_org_level_user_role_in_db(
+ self,
+ state: SessionState,
+ role_id: String,
+ user_status: UserStatus,
+ version: Option<UserRoleVersion>,
+ ) -> UserResult<UserRole> {
+ let org_id = self
+ .get_new_merchant()
+ .get_new_organization()
+ .get_organization_id();
+ let merchant_id = self.get_new_merchant().get_merchant_id();
+
+ let org_user_role = self
+ .get_no_level_user_role(role_id, user_status)
+ .add_entity(OrganizationLevel {
+ org_id,
+ merchant_id,
+ });
+
+ match version {
+ Some(UserRoleVersion::V1) => org_user_role.insert_in_v1(&state).await,
+ Some(UserRoleVersion::V2) => org_user_role.insert_in_v2(&state).await,
+ None => org_user_role.insert_in_v1_and_v2(&state).await,
+ }
}
}
@@ -1282,3 +1300,252 @@ impl RecoveryCodes {
self.0
}
}
+
+// This is for easier construction
+#[derive(Clone)]
+pub struct NoLevel;
+
+#[derive(Clone)]
+pub struct OrganizationLevel {
+ pub org_id: id_type::OrganizationId,
+ // Keeping this to allow insertion of org_admins in V1
+ pub merchant_id: id_type::MerchantId,
+}
+
+#[derive(Clone)]
+pub struct MerchantLevel {
+ pub org_id: id_type::OrganizationId,
+ pub merchant_id: id_type::MerchantId,
+}
+
+#[derive(Clone)]
+pub struct ProfileLevel {
+ pub org_id: id_type::OrganizationId,
+ pub merchant_id: id_type::MerchantId,
+ pub profile_id: id_type::ProfileId,
+}
+
+#[derive(Clone)]
+pub struct InternalLevel {
+ pub org_id: id_type::OrganizationId,
+}
+
+#[derive(Clone)]
+pub struct NewUserRole<E: Clone> {
+ pub user_id: String,
+ pub role_id: String,
+ pub status: UserStatus,
+ pub created_by: String,
+ pub last_modified_by: String,
+ pub created_at: PrimitiveDateTime,
+ pub last_modified: PrimitiveDateTime,
+ pub entity: E,
+}
+
+impl NewUserRole<NoLevel> {
+ pub fn add_entity<T>(self, entity: T) -> NewUserRole<T>
+ where
+ T: Clone,
+ {
+ NewUserRole {
+ entity,
+ user_id: self.user_id,
+ role_id: self.role_id,
+ status: self.status,
+ created_by: self.created_by,
+ last_modified_by: self.last_modified_by,
+ created_at: self.created_at,
+ last_modified: self.last_modified,
+ }
+ }
+}
+
+pub struct EntityInfo {
+ org_id: id_type::OrganizationId,
+ merchant_id: Option<id_type::MerchantId>,
+ profile_id: Option<id_type::ProfileId>,
+ entity_id: String,
+ entity_type: EntityType,
+}
+
+impl<E> NewUserRole<E>
+where
+ E: Clone,
+{
+ fn convert_to_new_v1_role(
+ self,
+ org_id: id_type::OrganizationId,
+ merchant_id: id_type::MerchantId,
+ ) -> UserRoleNew {
+ UserRoleNew {
+ user_id: self.user_id,
+ role_id: self.role_id,
+ status: self.status,
+ created_by: self.created_by,
+ last_modified_by: self.last_modified_by,
+ created_at: self.created_at,
+ last_modified: self.last_modified,
+ org_id: Some(org_id),
+ merchant_id: Some(merchant_id),
+ profile_id: None,
+ entity_id: None,
+ entity_type: None,
+ version: UserRoleVersion::V1,
+ }
+ }
+
+ fn convert_to_new_v2_role(self, entity: EntityInfo) -> UserRoleNew {
+ UserRoleNew {
+ user_id: self.user_id,
+ role_id: self.role_id,
+ status: self.status,
+ created_by: self.created_by,
+ last_modified_by: self.last_modified_by,
+ created_at: self.created_at,
+ last_modified: self.last_modified,
+ org_id: Some(entity.org_id),
+ merchant_id: entity.merchant_id,
+ profile_id: entity.profile_id,
+ entity_id: Some(entity.entity_id),
+ entity_type: Some(entity.entity_type),
+ version: UserRoleVersion::V2,
+ }
+ }
+
+ async fn insert_v1_and_v2_in_db_and_get_v1(
+ state: &SessionState,
+ v1_role: UserRoleNew,
+ v2_role: UserRoleNew,
+ ) -> UserResult<UserRole> {
+ let inserted_roles = state
+ .store
+ .insert_user_role(InsertUserRolePayload::V1AndV2(Box::new([v1_role, v2_role])))
+ .await
+ .change_context(UserErrors::InternalServerError)?;
+
+ // Returning v1 role so other code which was not migrated doesn't break
+ inserted_roles
+ .into_iter()
+ .find(|role| role.version == UserRoleVersion::V1)
+ .ok_or(report!(UserErrors::InternalServerError))
+ }
+}
+
+impl NewUserRole<OrganizationLevel> {
+ pub async fn insert_in_v1(self, state: &SessionState) -> UserResult<UserRole> {
+ let entity = self.entity.clone();
+
+ let new_v1_role = self
+ .clone()
+ .convert_to_new_v1_role(entity.org_id.clone(), entity.merchant_id.clone());
+
+ state
+ .store
+ .insert_user_role(InsertUserRolePayload::OnlyV1(new_v1_role))
+ .await
+ .change_context(UserErrors::InternalServerError)?
+ .pop()
+ .ok_or(report!(UserErrors::InternalServerError))
+ }
+
+ pub async fn insert_in_v2(self, state: &SessionState) -> UserResult<UserRole> {
+ let entity = self.entity.clone();
+
+ let new_v2_role = self.convert_to_new_v2_role(EntityInfo {
+ org_id: entity.org_id.clone(),
+ merchant_id: None,
+ profile_id: None,
+ entity_id: entity.org_id.get_string_repr().to_owned(),
+ entity_type: EntityType::Organization,
+ });
+ state
+ .store
+ .insert_user_role(InsertUserRolePayload::OnlyV2(new_v2_role))
+ .await
+ .change_context(UserErrors::InternalServerError)?
+ .pop()
+ .ok_or(report!(UserErrors::InternalServerError))
+ }
+
+ pub async fn insert_in_v1_and_v2(self, state: &SessionState) -> UserResult<UserRole> {
+ let entity = self.entity.clone();
+
+ let new_v1_role = self
+ .clone()
+ .convert_to_new_v1_role(entity.org_id.clone(), entity.merchant_id.clone());
+
+ let new_v2_role = self.clone().convert_to_new_v2_role(EntityInfo {
+ org_id: entity.org_id.clone(),
+ merchant_id: None,
+ profile_id: None,
+ entity_id: entity.org_id.get_string_repr().to_owned(),
+ entity_type: EntityType::Organization,
+ });
+
+ Self::insert_v1_and_v2_in_db_and_get_v1(state, new_v1_role, new_v2_role).await
+ }
+}
+
+impl NewUserRole<MerchantLevel> {
+ pub async fn insert_in_v1_and_v2(self, state: &SessionState) -> UserResult<UserRole> {
+ let entity = self.entity.clone();
+
+ let new_v1_role = self
+ .clone()
+ .convert_to_new_v1_role(entity.org_id.clone(), entity.merchant_id.clone());
+
+ let new_v2_role = self.clone().convert_to_new_v2_role(EntityInfo {
+ org_id: entity.org_id.clone(),
+ merchant_id: Some(entity.merchant_id.clone()),
+ profile_id: None,
+ entity_id: entity.merchant_id.get_string_repr().to_owned(),
+ entity_type: EntityType::Merchant,
+ });
+
+ Self::insert_v1_and_v2_in_db_and_get_v1(state, new_v1_role, new_v2_role).await
+ }
+}
+
+impl NewUserRole<InternalLevel> {
+ pub async fn insert_in_v1_and_v2(self, state: &SessionState) -> UserResult<UserRole> {
+ let entity = self.entity.clone();
+ let internal_merchant_id = id_type::MerchantId::get_internal_user_merchant_id(
+ consts::user_role::INTERNAL_USER_MERCHANT_ID,
+ );
+
+ let new_v1_role = self
+ .clone()
+ .convert_to_new_v1_role(entity.org_id.clone(), internal_merchant_id.clone());
+
+ let new_v2_role = self.convert_to_new_v2_role(EntityInfo {
+ org_id: entity.org_id.clone(),
+ merchant_id: Some(internal_merchant_id.clone()),
+ profile_id: None,
+ entity_id: internal_merchant_id.get_string_repr().to_owned(),
+ entity_type: EntityType::Internal,
+ });
+
+ Self::insert_v1_and_v2_in_db_and_get_v1(state, new_v1_role, new_v2_role).await
+ }
+}
+
+impl NewUserRole<ProfileLevel> {
+ pub async fn insert_in_v2(self, state: &SessionState) -> UserResult<UserRole> {
+ let entity = self.entity.clone();
+
+ let new_v2_role = self.convert_to_new_v2_role(EntityInfo {
+ org_id: entity.org_id.clone(),
+ merchant_id: Some(entity.merchant_id.clone()),
+ profile_id: Some(entity.profile_id.clone()),
+ entity_id: entity.profile_id.get_string_repr().to_owned(),
+ entity_type: EntityType::Profile,
+ });
+ state
+ .store
+ .insert_user_role(InsertUserRolePayload::OnlyV2(new_v2_role))
+ .await
+ .change_context(UserErrors::InternalServerError)?
+ .pop()
+ .ok_or(report!(UserErrors::InternalServerError))
+ }
+}
diff --git a/migrations/2024-08-06-103905_drop_user_id_merchant_id_unique_in_user_roles/down.sql b/migrations/2024-08-06-103905_drop_user_id_merchant_id_unique_in_user_roles/down.sql
new file mode 100644
index 00000000000..3a210e27da9
--- /dev/null
+++ b/migrations/2024-08-06-103905_drop_user_id_merchant_id_unique_in_user_roles/down.sql
@@ -0,0 +1,2 @@
+-- This file should undo anything in `up.sql`
+ALTER TABLE user_roles ADD CONSTRAINT user_merchant_unique UNIQUE (user_id, merchant_id);
diff --git a/migrations/2024-08-06-103905_drop_user_id_merchant_id_unique_in_user_roles/up.sql b/migrations/2024-08-06-103905_drop_user_id_merchant_id_unique_in_user_roles/up.sql
new file mode 100644
index 00000000000..33c04e8dbde
--- /dev/null
+++ b/migrations/2024-08-06-103905_drop_user_id_merchant_id_unique_in_user_roles/up.sql
@@ -0,0 +1,2 @@
+-- Your SQL goes here
+ALTER TABLE user_roles DROP CONSTRAINT user_merchant_unique;
|
2024-08-13T09:41:59Z
|
## Type of Change
<!-- Put an `x` in the boxes that apply -->
- [ ] Bugfix
- [x] New feature
- [ ] Enhancement
- [ ] Refactoring
- [ ] Dependency updates
- [ ] Documentation
- [ ] CI/CD
## Description
<!-- Describe your changes in detail -->
- From this PR, we will start inserting V2 user_roles.
### Additional Changes
- [ ] This PR modifies the API contract
- [x] This PR modifies the database schema
- [ ] This PR modifies application configuration/environment variables
<!--
Provide links to the files with corresponding changes.
Following are the paths where you can find config files:
1. `config`
2. `crates/router/src/configs`
3. `loadtest/config`
-->
## Motivation and Context
<!--
Why is this change required? What problem does it solve?
If it fixes an open issue, please link to the issue here.
If you don't have an issue, we'd recommend starting with one first so the PR
can focus on the implementation (unless it is an obvious bug or documentation fix
that will have little conversation).
-->
Closes #5543.
## How did you test it?
<!--
Did you write an integration/unit/API test to verify the code changes?
Or did you test this change manually (provide relevant screenshots)?
-->
All the following APIs will insert both V1 and V2 roles in DB.
```curl
curl --location 'https://integ-api.hyperswitch.io/user/signup' \
--header 'Content-Type: application/json' \
--data-raw '{
"email": "new email",
"password": "password"
}'
```
```curl
curl --location 'https://integ-api.hyperswitch.io/user/signup?token_only=true' \
--header 'Content-Type: application/json' \
--data '{
"email": "new email",
"password": "password"
}'
```
```
curl --location 'https://integ-api.hyperswitch.io/user/connect_account' \
--header 'Content-Type: application/json' \
--data-raw '{
"email": "new email"
}'
```
```
curl --location 'https://integ-api.hyperswitch.io/user/internal_signup' \
--header 'api-key: test_admin' \
--header 'Content-Type: application/json' \
--data '{
"name" : "name",
"email" : "new email",
"password": "password"
}'
```
```
curl --location 'https://integ-api.hyperswitch.io/user/user/invite_multiple' \
--header 'Content-Type: application/json' \
--data-raw '[
{
"email": "email",
"name": "name",
"role_id": "merchant_view_only"
},
{
"email": "email 2",
"name": "name",
"role_id": "merchant_admin"
}
]'
```
This will only insert V1 role in DB.
```
curl --location 'https://integ-api.hyperswitch.io/user/create_merchant' \
--header 'Content-Type: application/json' \
--header 'Authorization: ••••••' \
--data '{
"company_name": "Juspay"
}'
```
## Checklist
<!-- Put an `x` in the boxes that apply -->
- [x] I formatted the code `cargo +nightly fmt --all`
- [x] I addressed lints thrown by `cargo clippy`
- [x] I reviewed the submitted code
- [ ] I added unit tests for my changes where possible
|
c85b4a3a273ea211084ed26b1eb77f0731ac35ca
|
|
juspay/hyperswitch
|
juspay__hyperswitch-5526
|
Bug: [BUG] Fix status mapping for Plaid
### Feature Description
The current status mapping for Plaid is incorrect.
We need to fix the few of the status in the status mapping from Plaid status to Attempt status
### Possible Implementation
Will fix accordingly
### Have you spent some time checking if this feature request has been raised before?
- [X] I checked and didn't find a similar issue
### Have you read the Contributing Guidelines?
- [X] I have read the [Contributing Guidelines](https://github.com/juspay/hyperswitch/blob/main/docs/CONTRIBUTING.md)
### Are you willing to submit a PR?
Yes, I am willing to submit a PR!
|
diff --git a/crates/router/src/connector/plaid/transformers.rs b/crates/router/src/connector/plaid/transformers.rs
index 545ea271c43..cf9c91afd0c 100644
--- a/crates/router/src/connector/plaid/transformers.rs
+++ b/crates/router/src/connector/plaid/transformers.rs
@@ -233,16 +233,16 @@ impl From<PlaidPaymentStatus> for enums::AttemptStatus {
fn from(item: PlaidPaymentStatus) -> Self {
match item {
PlaidPaymentStatus::PaymentStatusAuthorising => Self::Authorizing,
- PlaidPaymentStatus::PaymentStatusBlocked => Self::AuthorizationFailed,
+ PlaidPaymentStatus::PaymentStatusBlocked
+ | PlaidPaymentStatus::PaymentStatusInsufficientFunds
+ | PlaidPaymentStatus::PaymentStatusRejected => Self::AuthorizationFailed,
PlaidPaymentStatus::PaymentStatusCancelled => Self::Voided,
PlaidPaymentStatus::PaymentStatusEstablished => Self::Authorized,
- PlaidPaymentStatus::PaymentStatusExecuted => Self::Authorized,
+ PlaidPaymentStatus::PaymentStatusExecuted
+ | PlaidPaymentStatus::PaymentStatusSettled
+ | PlaidPaymentStatus::PaymentStatusInitiated => Self::Charged,
PlaidPaymentStatus::PaymentStatusFailed => Self::Failure,
- PlaidPaymentStatus::PaymentStatusInitiated => Self::AuthenticationPending,
PlaidPaymentStatus::PaymentStatusInputNeeded => Self::AuthenticationPending,
- PlaidPaymentStatus::PaymentStatusInsufficientFunds => Self::AuthorizationFailed,
- PlaidPaymentStatus::PaymentStatusRejected => Self::AuthorizationFailed,
- PlaidPaymentStatus::PaymentStatusSettled => Self::Charged,
}
}
}
|
2024-08-05T11:58:05Z
|
## Type of Change
<!-- Put an `x` in the boxes that apply -->
- [x] Bugfix
- [ ] New feature
- [ ] Enhancement
- [ ] Refactoring
- [ ] Dependency updates
- [ ] Documentation
- [ ] CI/CD
## Description
<!-- Describe your changes in detail -->
There was a need to fix the status mapping for Plaid as the previous mapping was incorrect.
### Additional Changes
- [ ] This PR modifies the API contract
- [ ] This PR modifies the database schema
- [ ] This PR modifies application configuration/environment variables
<!--
Provide links to the files with corresponding changes.
Following are the paths where you can find config files:
1. `config`
2. `crates/router/src/configs`
3. `loadtest/config`
-->
## Motivation and Context
<!--
Why is this change required? What problem does it solve?
If it fixes an open issue, please link to the issue here.
If you don't have an issue, we'd recommend starting with one first so the PR
can focus on the implementation (unless it is an obvious bug or documentation fix
that will have little conversation).
-->
## How did you test it?
<!--
Did you write an integration/unit/API test to verify the code changes?
Or did you test this change manually (provide relevant screenshots)?
-->
Payment sync -
```
curl --location --request GET 'https://sandbox.hyperswitch.io/payments/pay_IKnoLdEMCFdurH4Ps1Zl?force_sync=true' \
--header 'Accept: application/json' \
--header 'api-key: some key'
```
During payments sync, we used to get `status` as `requires_capture` for Open banking PIS flow, which is wrong
```
{
"payment_id": "pay_iwAee7HK6dpcvgROftP2",
"merchant_id": "merchant_1722345123",
"status": "requires_capture",
"amount": 2999,
"net_amount": 2999,
"amount_capturable": 2999,
"amount_received": null,
"connector": "plaid",
"client_secret": "pay_iwAee7HK6dpcvgROftP2_secret_6chxX9TLDDz4CGYoLoBG",
"created": "2024-08-05T07:25:10.346Z",
"currency": "EUR",
"customer_id": "hyperswitch_sdk_demo_id",
"customer": {
"id": "hyperswitch_sdk_demo_id",
"name": null,
"email": "hyperswitch_sdk_demo_id@gmail.com",
"phone": null,
"phone_country_code": null
},
"description": "Hello this is description",
"refunds": null,
"disputes": null,
"mandate_id": null,
"mandate_data": null,
"setup_future_usage": null,
"off_session": null,
"capture_on": null,
"capture_method": "automatic",
"payment_method": null,
"payment_method_data": null,
"payment_token": null,
"shipping": {
"address": {
"city": "San Fransico",
"country": "GB",
"line1": "1467",
"line2": "Harrison Street",
"line3": "Harrison Street",
"zip": "94122",
"state": "California",
"first_name": "joseph",
"last_name": "Doe"
},
"phone": {
"number": "8056594427",
"country_code": "+91"
},
"email": null
},
"billing": {
"address": {
"city": "San Fransico",
"country": "GB",
"line1": "1467",
"line2": "Harrison Street",
"line3": "Harrison Street",
"zip": "94122",
"state": "California",
"first_name": "joseph",
"last_name": "Doe"
},
"phone": {
"number": "8056594427",
"country_code": "+91"
},
"email": null
},
"order_details": [
{
"brand": null,
"amount": 2999,
"category": null,
"quantity": 1,
"product_id": null,
"product_name": "Apple iPhone 15",
"product_type": null,
"sub_category": null,
"product_img_link": null,
"requires_shipping": null
}
],
"email": "hyperswitch_sdk_demo_id@gmail.com",
"name": null,
"phone": null,
"return_url": "http://localhost:9060/",
"authentication_type": "three_ds",
"statement_descriptor_name": null,
"statement_descriptor_suffix": null,
"next_action": null,
"cancellation_reason": null,
"error_code": null,
"error_message": null,
"unified_code": null,
"unified_message": null,
"payment_experience": null,
"payment_method_type": "open_banking_pis",
"connector_label": null,
"business_country": null,
"business_label": null,
"business_sub_label": null,
"allowed_payment_method_types": null,
"ephemeral_key": null,
"manual_retry_allowed": false,
"connector_transaction_id": "payment-id-sandbox-da16858f-7096-4162-b6a8-2f3b1a06eb24",
"frm_message": null,
"metadata": {
"udf1": "value1",
"login_date": "2019-09-10T10:11:12Z",
"new_customer": "true"
},
"connector_metadata": null,
"feature_metadata": null,
"reference_id": "payment-id-sandbox-da16858f-7096-4162-b6a8-2f3b1a06eb24",
"payment_link": null,
"profile_id": "pro_RKQntIzzPm28JaWdlSe6",
"surcharge_details": null,
"attempt_count": 1,
"merchant_decision": null,
"merchant_connector_id": "mca_EqOrIDNZEPknqvKnEO7H",
"incremental_authorization_allowed": null,
"authorization_count": null,
"incremental_authorizations": null,
"external_authentication_details": null,
"external_3ds_authentication_attempted": false,
"expires_on": "2024-08-05T07:40:10.346Z",
"fingerprint": null,
"browser_info": {
"language": "en-GB",
"time_zone": -330,
"ip_address": "103.159.11.202",
"user_agent": "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/127.0.0.0 Safari/537.36",
"color_depth": 24,
"java_enabled": true,
"screen_width": 2560,
"accept_header": "text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,image/apng,*/*;q=0.8",
"screen_height": 1440,
"java_script_enabled": true
},
"payment_method_id": null,
"payment_method_status": null,
"updated": "2024-08-05T07:32:25.029Z",
"charges": null,
"frm_metadata": null,
"merchant_order_reference_id": null
}
```
With this fix the ideal response would have `status` as `succeeded` this -
```
{
"payment_id": "pay_iwAee7HK6dpcvgROftP2",
"merchant_id": "merchant_1722345123",
"status": "succeeded",
"amount": 2999,
"net_amount": 2999,
"amount_capturable": 2999,
"amount_received": null,
"connector": "plaid",
"client_secret": "pay_iwAee7HK6dpcvgROftP2_secret_6chxX9TLDDz4CGYoLoBG",
"created": "2024-08-05T07:25:10.346Z",
"currency": "EUR",
"customer_id": "hyperswitch_sdk_demo_id",
"customer": {
"id": "hyperswitch_sdk_demo_id",
"name": null,
"email": "hyperswitch_sdk_demo_id@gmail.com",
"phone": null,
"phone_country_code": null
},
"description": "Hello this is description",
"refunds": null,
"disputes": null,
"mandate_id": null,
"mandate_data": null,
"setup_future_usage": null,
"off_session": null,
"capture_on": null,
"capture_method": "automatic",
"payment_method": null,
"payment_method_data": null,
"payment_token": null,
"shipping": {
"address": {
"city": "San Fransico",
"country": "GB",
"line1": "1467",
"line2": "Harrison Street",
"line3": "Harrison Street",
"zip": "94122",
"state": "California",
"first_name": "joseph",
"last_name": "Doe"
},
"phone": {
"number": "8056594427",
"country_code": "+91"
},
"email": null
},
"billing": {
"address": {
"city": "San Fransico",
"country": "GB",
"line1": "1467",
"line2": "Harrison Street",
"line3": "Harrison Street",
"zip": "94122",
"state": "California",
"first_name": "joseph",
"last_name": "Doe"
},
"phone": {
"number": "8056594427",
"country_code": "+91"
},
"email": null
},
"order_details": [
{
"brand": null,
"amount": 2999,
"category": null,
"quantity": 1,
"product_id": null,
"product_name": "Apple iPhone 15",
"product_type": null,
"sub_category": null,
"product_img_link": null,
"requires_shipping": null
}
],
"email": "hyperswitch_sdk_demo_id@gmail.com",
"name": null,
"phone": null,
"return_url": "http://localhost:9060/",
"authentication_type": "three_ds",
"statement_descriptor_name": null,
"statement_descriptor_suffix": null,
"next_action": null,
"cancellation_reason": null,
"error_code": null,
"error_message": null,
"unified_code": null,
"unified_message": null,
"payment_experience": null,
"payment_method_type": "open_banking_pis",
"connector_label": null,
"business_country": null,
"business_label": null,
"business_sub_label": null,
"allowed_payment_method_types": null,
"ephemeral_key": null,
"manual_retry_allowed": false,
"connector_transaction_id": "payment-id-sandbox-da16858f-7096-4162-b6a8-2f3b1a06eb24",
"frm_message": null,
"metadata": {
"udf1": "value1",
"login_date": "2019-09-10T10:11:12Z",
"new_customer": "true"
},
"connector_metadata": null,
"feature_metadata": null,
"reference_id": "payment-id-sandbox-da16858f-7096-4162-b6a8-2f3b1a06eb24",
"payment_link": null,
"profile_id": "pro_RKQntIzzPm28JaWdlSe6",
"surcharge_details": null,
"attempt_count": 1,
"merchant_decision": null,
"merchant_connector_id": "mca_EqOrIDNZEPknqvKnEO7H",
"incremental_authorization_allowed": null,
"authorization_count": null,
"incremental_authorizations": null,
"external_authentication_details": null,
"external_3ds_authentication_attempted": false,
"expires_on": "2024-08-05T07:40:10.346Z",
"fingerprint": null,
"browser_info": {
"language": "en-GB",
"time_zone": -330,
"ip_address": "103.159.11.202",
"user_agent": "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/127.0.0.0 Safari/537.36",
"color_depth": 24,
"java_enabled": true,
"screen_width": 2560,
"accept_header": "text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,image/apng,*/*;q=0.8",
"screen_height": 1440,
"java_script_enabled": true
},
"payment_method_id": null,
"payment_method_status": null,
"updated": "2024-08-05T07:32:25.029Z",
"charges": null,
"frm_metadata": null,
"merchant_order_reference_id": null
}
```
## Checklist
<!-- Put an `x` in the boxes that apply -->
- [x] I formatted the code `cargo +nightly fmt --all`
- [x] I addressed lints thrown by `cargo clippy`
- [ ] I reviewed the submitted code
- [ ] I added unit tests for my changes where possible
|
a3e01bb4ae5893f639f3846ccb73adcca6b25ee0
|
|
juspay/hyperswitch
|
juspay__hyperswitch-5537
|
Bug: feat(users): Role info api with parent tags
|
diff --git a/crates/api_models/src/user_role.rs b/crates/api_models/src/user_role.rs
index 02e40e2fe1a..5319c81385a 100644
--- a/crates/api_models/src/user_role.rs
+++ b/crates/api_models/src/user_role.rs
@@ -38,6 +38,19 @@ pub enum Permission {
GenerateReport,
}
+#[derive(Clone, Debug, serde::Serialize, PartialEq, Eq, Hash)]
+pub enum ParentGroup {
+ Operations,
+ Connectors,
+ Workflows,
+ Analytics,
+ Users,
+ #[serde(rename = "MerchantAccess")]
+ Merchant,
+ #[serde(rename = "OrganizationAccess")]
+ Organization,
+}
+
#[derive(Debug, serde::Serialize)]
pub enum PermissionModule {
Payments,
@@ -63,6 +76,7 @@ pub struct AuthorizationInfoResponse(pub Vec<AuthorizationInfo>);
pub enum AuthorizationInfo {
Module(ModuleInfo),
Group(GroupInfo),
+ GroupWithTag(ParentInfo),
}
#[derive(Debug, serde::Serialize)]
@@ -79,6 +93,13 @@ pub struct GroupInfo {
pub permissions: Vec<PermissionInfo>,
}
+#[derive(Debug, serde::Serialize, Clone)]
+pub struct ParentInfo {
+ pub name: ParentGroup,
+ pub description: &'static str,
+ pub groups: Vec<PermissionGroup>,
+}
+
#[derive(Debug, serde::Serialize)]
pub struct PermissionInfo {
pub enum_name: Permission,
diff --git a/crates/router/src/core/user_role.rs b/crates/router/src/core/user_role.rs
index f2fddd61bb6..d9ee8f21805 100644
--- a/crates/router/src/core/user_role.rs
+++ b/crates/router/src/core/user_role.rs
@@ -1,9 +1,12 @@
+use std::collections::HashMap;
+
use api_models::{user as user_api, user_role as user_role_api};
use diesel_models::{
enums::{UserRoleVersion, UserStatus},
user_role::UserRoleUpdate,
};
use error_stack::{report, ResultExt};
+use once_cell::sync::Lazy;
use router_env::logger;
use crate::{
@@ -18,8 +21,9 @@ use crate::{
types::domain,
utils,
};
-
pub mod role;
+use common_enums::PermissionGroup;
+use strum::IntoEnumIterator;
// TODO: To be deprecated once groups are stable
pub async fn get_authorization_info_with_modules(
@@ -47,6 +51,38 @@ pub async fn get_authorization_info_with_groups(
),
))
}
+pub async fn get_authorization_info_with_group_tag(
+) -> UserResponse<user_role_api::AuthorizationInfoResponse> {
+ static GROUPS_WITH_PARENT_TAGS: Lazy<Vec<user_role_api::ParentInfo>> = Lazy::new(|| {
+ PermissionGroup::iter()
+ .map(|value| (info::get_parent_name(value), value))
+ .fold(
+ HashMap::new(),
+ |mut acc: HashMap<user_role_api::ParentGroup, Vec<PermissionGroup>>,
+ (key, value)| {
+ acc.entry(key).or_default().push(value);
+ acc
+ },
+ )
+ .into_iter()
+ .map(|(name, value)| user_role_api::ParentInfo {
+ name: name.clone(),
+ description: info::get_parent_group_description(name),
+ groups: value,
+ })
+ .collect()
+ });
+
+ Ok(ApplicationResponse::Json(
+ user_role_api::AuthorizationInfoResponse(
+ GROUPS_WITH_PARENT_TAGS
+ .iter()
+ .cloned()
+ .map(user_role_api::AuthorizationInfo::GroupWithTag)
+ .collect(),
+ ),
+ ))
+}
pub async fn update_user_role(
state: SessionState,
diff --git a/crates/router/src/routes/app.rs b/crates/router/src/routes/app.rs
index 2bb1a5eee8e..37b3f7cbd03 100644
--- a/crates/router/src/routes/app.rs
+++ b/crates/router/src/routes/app.rs
@@ -1609,6 +1609,7 @@ impl User {
.route(web::get().to(list_merchants_for_user)),
)
.service(web::resource("/permission_info").route(web::get().to(get_authorization_info)))
+ .service(web::resource("/module/list").route(web::get().to(get_role_information)))
.service(web::resource("/update").route(web::post().to(update_user_account_details)))
.service(
web::resource("/data")
diff --git a/crates/router/src/routes/lock_utils.rs b/crates/router/src/routes/lock_utils.rs
index 9f073853d88..a0e8ed2f8b7 100644
--- a/crates/router/src/routes/lock_utils.rs
+++ b/crates/router/src/routes/lock_utils.rs
@@ -250,6 +250,7 @@ impl From<Flow> for ApiIdentifier {
| Flow::GetRoleFromToken
| Flow::UpdateUserRole
| Flow::GetAuthorizationInfo
+ | Flow::GetRolesInfo
| Flow::AcceptInvitation
| Flow::MerchantSelect
| Flow::DeleteUserRole
diff --git a/crates/router/src/routes/user_role.rs b/crates/router/src/routes/user_role.rs
index 4239f2d3814..bce0e6da147 100644
--- a/crates/router/src/routes/user_role.rs
+++ b/crates/router/src/routes/user_role.rs
@@ -268,3 +268,23 @@ pub async fn delete_user_role(
))
.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::UsersRead),
+ api_locking::LockAction::NotApplicable,
+ ))
+ .await
+}
diff --git a/crates/router/src/services/authorization/info.rs b/crates/router/src/services/authorization/info.rs
index 371087cc303..ca5a6689395 100644
--- a/crates/router/src/services/authorization/info.rs
+++ b/crates/router/src/services/authorization/info.rs
@@ -1,4 +1,4 @@
-use api_models::user_role::{GroupInfo, PermissionInfo};
+use api_models::user_role::{GroupInfo, ParentGroup, PermissionInfo};
use common_enums::PermissionGroup;
use strum::{EnumIter, IntoEnumIterator};
@@ -217,3 +217,33 @@ fn get_group_description(group: PermissionGroup) -> &'static str {
PermissionGroup::OrganizationManage => "Manage organization level tasks like create new Merchant accounts, Organization level roles, etc",
}
}
+
+pub fn get_parent_name(group: PermissionGroup) -> ParentGroup {
+ match group {
+ PermissionGroup::OperationsView | PermissionGroup::OperationsManage => {
+ ParentGroup::Operations
+ }
+ PermissionGroup::ConnectorsView | PermissionGroup::ConnectorsManage => {
+ ParentGroup::Connectors
+ }
+ PermissionGroup::WorkflowsView | PermissionGroup::WorkflowsManage => ParentGroup::Workflows,
+ PermissionGroup::AnalyticsView => ParentGroup::Analytics,
+ PermissionGroup::UsersView | PermissionGroup::UsersManage => ParentGroup::Users,
+ PermissionGroup::MerchantDetailsView | PermissionGroup::MerchantDetailsManage => {
+ ParentGroup::Merchant
+ }
+ PermissionGroup::OrganizationManage => ParentGroup::Organization,
+ }
+}
+
+pub fn get_parent_group_description(group: ParentGroup) -> &'static str {
+ match group {
+ ParentGroup::Operations => "Payments, Refunds, Payouts, Mandates, Disputes and Customers",
+ ParentGroup::Connectors => "Create, modify and delete connectors like Payment Processors, Payout Processors and Fraud & Risk Manager",
+ ParentGroup::Workflows => "Create, modify and delete Routing, 3DS Decision Manager, Surcharge Decision Manager",
+ ParentGroup::Analytics => "View Analytics",
+ ParentGroup::Users => "Manage and invite Users to the Team",
+ ParentGroup::Merchant => "Create, modify and delete Merchant Details like api keys, webhooks, etc",
+ ParentGroup::Organization =>"Manage organization level tasks like create new Merchant accounts, Organization level roles, etc",
+ }
+}
diff --git a/crates/router_env/src/logger/types.rs b/crates/router_env/src/logger/types.rs
index f1d2e5d8dcc..8142aa437ed 100644
--- a/crates/router_env/src/logger/types.rs
+++ b/crates/router_env/src/logger/types.rs
@@ -354,6 +354,8 @@ pub enum Flow {
SwitchMerchant,
/// Get permission info
GetAuthorizationInfo,
+ /// Get Roles info
+ GetRolesInfo,
/// List roles
ListRoles,
/// Get role
|
2024-08-06T09:55:25Z
|
## Type of Change
<!-- Put an `x` in the boxes that apply -->
- [ ] Bugfix
- [X] New feature
- [ ] Enhancement
- [ ] Refactoring
- [ ] Dependency updates
- [ ] Documentation
- [ ] CI/CD
## Description
<!-- Describe your changes in detail -->
The permission_info API previously returned permission groups, each with its own description. With this update, permission groups are now organized under parent groups, and descriptions are tied to the parent group instead of individual groups. Additionally, permissions for each group have been removed, as the dashboard no longer utilizes that data.
Older structure :
```
[
{
"group": "operations_view",
"description": "View Payments, Refunds, Payouts, Mandates, Disputes and Customers",
"permissions": [
{
"enum_name": "PaymentRead",
"description": "View all payments"
},
{
"enum_name": "RefundRead",
"description": "View all refunds"
},
{
"enum_name": "MandateRead",
"description": "View mandates"
},
{
"enum_name": "DisputeRead",
"description": "View disputes"
},
{
"enum_name": "CustomerRead",
"description": "View customers"
},
{
"enum_name": "GenerateReport",
"description": "Generate reports for payments, refunds and disputes"
},
{
"enum_name": "PayoutRead",
"description": "View all payouts"
},
{
"enum_name": "MerchantAccountRead",
"description": "View merchant account details"
}
]
},
{
"group": "operations_manage",
"description": "Create, modify and delete Payments, Refunds, Payouts, Mandates, Disputes and Customers",
"permissions": [
{
"enum_name": "PaymentWrite",
"description": "Create payment, download payments data"
},
{
"enum_name": "RefundWrite",
"description": "Create refund, download refunds data"
},
{
"enum_name": "MandateWrite",
"description": "Create and update mandates"
},
{
"enum_name": "DisputeWrite",
"description": "Create and update disputes"
},
{
"enum_name": "CustomerWrite",
"description": "Create, update and delete customers"
},
{
"enum_name": "PayoutWrite",
"description": "Create payout, download payout data"
},
{
"enum_name": "MerchantAccountRead",
"description": "View merchant account details"
}
]
},
]
```
New structure :
```
{
"name": "Operations",
"description": "Payments, Refunds, Payouts, Mandates, Disputes and Customers",
"groups": [
"operations_view",
"operations_manage"
]
}
```
### Additional Changes
- [X] This PR modifies the API contract
- [ ] This PR modifies the database schema
- [ ] This PR modifies application configuration/environment variables
<!--
Provide links to the files with corresponding changes.
Following are the paths where you can find config files:
1. `config`
2. `crates/router/src/configs`
3. `loadtest/config`
-->
## Motivation and Context
<!--
Why is this change required? What problem does it solve?
If it fixes an open issue, please link to the issue here.
If you don't have an issue, we'd recommend starting with one first so the PR
can focus on the implementation (unless it is an obvious bug or documentation fix
that will have little conversation).
-->
This will close the issue
## How did you test it?
<!--
Did you write an integration/unit/API test to verify the code changes?
Or did you test this change manually (provide relevant screenshots)?
-->
Request :
```
curl --location 'http://localhost:8080/user/module/list' \
--header 'Authorization: Bearer token '
```
Response :
```
[
{
"name": "Users",
"description": "Manage and invite Users to the Team",
"groups": [
"users_view",
"users_manage"
]
},
{
"name": "MerchantAccess",
"description": "Create, modify and delete Merchant Details like api keys, webhooks, etc",
"groups": [
"merchant_details_view",
"merchant_details_manage"
]
},
{
"name": "OrganizationAccess",
"description": "Manage organization level tasks like create new Merchant accounts, Organization level roles, etc",
"groups": [
"organization_manage"
]
},
{
"name": "Analytics",
"description": "View Analytics",
"groups": [
"analytics_view"
]
},
{
"name": "Connectors",
"description": "Create, modify and delete connectors like Payment Processors, Payout Processors and Fraud & Risk Manager",
"groups": [
"connectors_view",
"connectors_manage"
]
},
{
"name": "Operations",
"description": "Payments, Refunds, Payouts, Mandates, Disputes and Customers",
"groups": [
"operations_view",
"operations_manage"
]
},
{
"name": "Workflows",
"description": "Create, modify and delete Routing, 3DS Decision Manager, Surcharge Decision Manager",
"groups": [
"workflows_view",
"workflows_manage"
]
}
]
```
## Checklist
<!-- Put an `x` in the boxes that apply -->
- [X] I formatted the code `cargo +nightly fmt --all`
- [X] I addressed lints thrown by `cargo clippy`
- [ ] I reviewed the submitted code
- [ ] I added unit tests for my changes where possible
|
72b61310523403113b469e6e6a9a89806849bb1e
|
|
juspay/hyperswitch
|
juspay__hyperswitch-5521
|
Bug: [REFACTOR] Refactor deactivating and retrieve apis for routing v2
### Feature Description
Refactor deactivating and retrieve apis for routing v2
### Possible Implementation
Refactor deactivating and retrieve apis for routing v2
### Have you spent some time checking if this feature request has been raised before?
- [X] I checked and didn't find a similar issue
### Have you read the Contributing Guidelines?
- [X] I have read the [Contributing Guidelines](https://github.com/juspay/hyperswitch/blob/main/docs/CONTRIBUTING.md)
### Are you willing to submit a PR?
Yes, I am willing to submit a PR!
|
diff --git a/crates/api_models/src/routing.rs b/crates/api_models/src/routing.rs
index 265d0451117..aca7bfaebe3 100644
--- a/crates/api_models/src/routing.rs
+++ b/crates/api_models/src/routing.rs
@@ -30,7 +30,16 @@ impl ConnectorSelection {
}
}
}
+#[cfg(all(feature = "v2", feature = "routing_v2"))]
+#[derive(Debug, Clone, serde::Serialize, serde::Deserialize, ToSchema)]
+pub struct RoutingConfigRequest {
+ pub name: String,
+ pub description: String,
+ pub algorithm: RoutingAlgorithm,
+ pub profile_id: String,
+}
+#[cfg(all(any(feature = "v1", feature = "v2"), not(feature = "routing_v2")))]
#[derive(Debug, Clone, serde::Serialize, serde::Deserialize, ToSchema)]
pub struct RoutingConfigRequest {
pub name: Option<String>,
diff --git a/crates/router/src/core/routing.rs b/crates/router/src/core/routing.rs
index 2451156e874..cb7cf344e89 100644
--- a/crates/router/src/core/routing.rs
+++ b/crates/router/src/core/routing.rs
@@ -1,15 +1,12 @@
pub mod helpers;
pub mod transformers;
+#[cfg(all(feature = "v2", feature = "routing_v2"))]
+use api_models::routing::RoutingConfigRequest;
use api_models::{
enums,
- routing::{
- self as routing_types, RoutingAlgorithmId, RoutingRetrieveLinkQuery, RoutingRetrieveQuery,
- },
+ routing::{self as routing_types, RoutingRetrieveLinkQuery, RoutingRetrieveQuery},
};
-#[cfg(all(feature = "v2", feature = "routing_v2"))]
-use diesel_models::routing_algorithm::RoutingAlgorithm;
-#[cfg(all(any(feature = "v1", feature = "v2"), not(feature = "routing_v2")))]
use diesel_models::routing_algorithm::RoutingAlgorithm;
use error_stack::ResultExt;
#[cfg(all(feature = "v2", feature = "routing_v2"))]
@@ -19,11 +16,8 @@ use rustc_hash::FxHashSet;
use super::payments;
#[cfg(feature = "payouts")]
use super::payouts;
-#[cfg(all(any(feature = "v1", feature = "v2"), not(feature = "routing_v2")))]
-use crate::consts;
-#[cfg(all(feature = "v2", feature = "routing_v2"))]
-use crate::{consts, core::errors::RouterResult, db::StorageInterface};
use crate::{
+ consts,
core::{
errors::{self, RouterResponse, StorageErrorExt},
metrics, utils as core_utils,
@@ -36,6 +30,8 @@ use crate::{
},
utils::{self, OptionExt, ValueExt},
};
+#[cfg(all(feature = "v2", feature = "routing_v2"))]
+use crate::{core::errors::RouterResult, db::StorageInterface};
pub enum TransactionData<'a, F>
where
F: Clone,
@@ -51,10 +47,8 @@ struct RoutingAlgorithmUpdate(RoutingAlgorithm);
#[cfg(all(feature = "v2", feature = "routing_v2"))]
impl RoutingAlgorithmUpdate {
pub fn create_new_routing_algorithm(
- algorithm: routing_types::RoutingAlgorithm,
+ request: &RoutingConfigRequest,
merchant_id: &common_utils::id_type::MerchantId,
- name: String,
- description: String,
profile_id: String,
transaction_type: &enums::TransactionType,
) -> Self {
@@ -67,10 +61,10 @@ impl RoutingAlgorithmUpdate {
algorithm_id,
profile_id,
merchant_id: merchant_id.clone(),
- name,
- description: Some(description),
- kind: algorithm.get_kind().foreign_into(),
- algorithm_data: serde_json::json!(algorithm),
+ name: request.name.clone(),
+ description: Some(request.description.clone()),
+ kind: request.algorithm.get_kind().foreign_into(),
+ algorithm_data: serde_json::json!(request.algorithm),
created_at: timestamp,
modified_at: timestamp,
algorithm_for: transaction_type.to_owned(),
@@ -150,36 +144,15 @@ pub async fn create_routing_config(
state: SessionState,
merchant_account: domain::MerchantAccount,
key_store: domain::MerchantKeyStore,
- request: routing_types::RoutingConfigRequest,
+ request: RoutingConfigRequest,
transaction_type: &enums::TransactionType,
) -> RouterResponse<routing_types::RoutingDictionaryRecord> {
metrics::ROUTING_CREATE_REQUEST_RECEIVED.add(&metrics::CONTEXT, 1, &[]);
let db = &*state.store;
- let name = request
- .name
- .get_required_value("name")
- .change_context(errors::ApiErrorResponse::MissingRequiredField { field_name: "name" })
- .attach_printable("Name of config not given")?;
-
- let description = request
- .description
- .get_required_value("description")
- .change_context(errors::ApiErrorResponse::MissingRequiredField {
- field_name: "description",
- })
- .attach_printable("Description of config not given")?;
-
- let algorithm = request
- .algorithm
- .get_required_value("algorithm")
- .change_context(errors::ApiErrorResponse::MissingRequiredField {
- field_name: "algorithm",
- })
- .attach_printable("Algorithm of config not given")?;
let business_profile = core_utils::validate_and_get_business_profile(
db,
- request.profile_id.as_ref(),
+ Some(&request.profile_id),
merchant_account.get_id(),
)
.await?
@@ -205,16 +178,14 @@ pub async fn create_routing_config(
let algorithm_helper = helpers::RoutingAlgorithmHelpers {
name_mca_id_set,
name_set,
- routing_algorithm: &algorithm,
+ routing_algorithm: &request.algorithm,
};
algorithm_helper.validate_connectors_in_routing_config()?;
let algo = RoutingAlgorithmUpdate::create_new_routing_algorithm(
- algorithm,
+ &request,
merchant_account.get_id(),
- name,
- description,
business_profile.profile_id,
transaction_type,
);
@@ -327,11 +298,13 @@ pub async fn link_routing_config(
let routing_algorithm =
RoutingAlgorithmUpdate::fetch_routing_algo(merchant_account.get_id(), &algorithm_id, db)
.await?;
+
utils::when(routing_algorithm.0.profile_id != profile_id, || {
Err(errors::ApiErrorResponse::PreconditionFailed {
message: "Profile Id is invalid for the routing config".to_string(),
})
})?;
+
let business_profile = core_utils::validate_and_get_business_profile(
db,
Some(&profile_id),
@@ -348,6 +321,7 @@ pub async fn link_routing_config(
.unwrap_or_default();
routing_algorithm.update_routing_ref_with_algorithm_id(transaction_type, &mut routing_ref)?;
+
// TODO move to business profile
helpers::update_business_profile_active_algorithm_ref(
db,
@@ -432,10 +406,41 @@ pub async fn link_routing_config(
))
}
+#[cfg(all(feature = "v2", feature = "routing_v2"))]
+pub async fn retrieve_routing_config(
+ state: SessionState,
+ merchant_account: domain::MerchantAccount,
+ algorithm_id: routing_types::RoutingAlgorithmId,
+) -> RouterResponse<routing_types::MerchantRoutingAlgorithm> {
+ metrics::ROUTING_RETRIEVE_CONFIG.add(&metrics::CONTEXT, 1, &[]);
+ let db = state.store.as_ref();
+
+ let routing_algorithm =
+ RoutingAlgorithmUpdate::fetch_routing_algo(merchant_account.get_id(), &algorithm_id.0, db)
+ .await?;
+ // TODO: Move to domain types of Business Profile
+ core_utils::validate_and_get_business_profile(
+ db,
+ Some(&routing_algorithm.0.profile_id),
+ merchant_account.get_id(),
+ )
+ .await?
+ .get_required_value("BusinessProfile")
+ .change_context(errors::ApiErrorResponse::ResourceIdNotFound)?;
+
+ let response = routing_types::MerchantRoutingAlgorithm::foreign_try_from(routing_algorithm.0)
+ .change_context(errors::ApiErrorResponse::InternalServerError)
+ .attach_printable("unable to parse routing algorithm")?;
+
+ metrics::ROUTING_RETRIEVE_CONFIG_SUCCESS_RESPONSE.add(&metrics::CONTEXT, 1, &[]);
+ Ok(service_api::ApplicationResponse::Json(response))
+}
+
+#[cfg(all(any(feature = "v1", feature = "v2"), not(feature = "routing_v2")))]
pub async fn retrieve_routing_config(
state: SessionState,
merchant_account: domain::MerchantAccount,
- algorithm_id: RoutingAlgorithmId,
+ algorithm_id: routing_types::RoutingAlgorithmId,
) -> RouterResponse<routing_types::MerchantRoutingAlgorithm> {
metrics::ROUTING_RETRIEVE_CONFIG.add(&metrics::CONTEXT, 1, &[]);
let db = state.store.as_ref();
@@ -465,6 +470,70 @@ pub async fn retrieve_routing_config(
Ok(service_api::ApplicationResponse::Json(response))
}
+#[cfg(all(feature = "v2", feature = "routing_v2"))]
+pub async fn unlink_routing_config(
+ state: SessionState,
+ merchant_account: domain::MerchantAccount,
+ profile_id: String,
+ transaction_type: &enums::TransactionType,
+) -> RouterResponse<routing_types::RoutingDictionaryRecord> {
+ metrics::ROUTING_UNLINK_CONFIG.add(&metrics::CONTEXT, 1, &[]);
+ let db = state.store.as_ref();
+
+ let business_profile = core_utils::validate_and_get_business_profile(
+ db,
+ Some(&profile_id),
+ merchant_account.get_id(),
+ )
+ .await?
+ .get_required_value("BusinessProfile")?;
+
+ let routing_algo_ref = routing_types::RoutingAlgorithmRef::parse_routing_algorithm(
+ match transaction_type {
+ enums::TransactionType::Payment => business_profile.routing_algorithm.clone(),
+ #[cfg(feature = "payouts")]
+ enums::TransactionType::Payout => business_profile.payout_routing_algorithm.clone(),
+ }
+ .map(Secret::new),
+ )
+ .change_context(errors::ApiErrorResponse::InternalServerError)
+ .attach_printable("unable to deserialize routing algorithm ref from merchant account")?
+ .unwrap_or_default();
+
+ if let Some(algorithm_id) = routing_algo_ref.algorithm_id {
+ let timestamp = common_utils::date_time::now_unix_timestamp();
+ let routing_algorithm: routing_types::RoutingAlgorithmRef =
+ routing_types::RoutingAlgorithmRef {
+ algorithm_id: None,
+ timestamp,
+ config_algo_id: routing_algo_ref.config_algo_id.clone(),
+ surcharge_config_algo_id: routing_algo_ref.surcharge_config_algo_id,
+ };
+ let record = RoutingAlgorithmUpdate::fetch_routing_algo(
+ merchant_account.get_id(),
+ &algorithm_id,
+ db,
+ )
+ .await?;
+ let response = record.0.foreign_into();
+ helpers::update_business_profile_active_algorithm_ref(
+ db,
+ business_profile,
+ routing_algorithm,
+ transaction_type,
+ )
+ .await?;
+
+ metrics::ROUTING_UNLINK_CONFIG_SUCCESS_RESPONSE.add(&metrics::CONTEXT, 1, &[]);
+ Ok(service_api::ApplicationResponse::Json(response))
+ } else {
+ Err(errors::ApiErrorResponse::PreconditionFailed {
+ message: "Algorithm is already inactive".to_string(),
+ })?
+ }
+}
+
+#[cfg(all(any(feature = "v1", feature = "v2"), not(feature = "routing_v2")))]
pub async fn unlink_routing_config(
state: SessionState,
merchant_account: domain::MerchantAccount,
diff --git a/crates/router/src/routes/app.rs b/crates/router/src/routes/app.rs
index 708fcbbf406..928289c3e56 100644
--- a/crates/router/src/routes/app.rs
+++ b/crates/router/src/routes/app.rs
@@ -1454,18 +1454,16 @@ impl BusinessProfile {
},
)),
)
- .service(
- web::resource("/deactivate_routing_algorithm").route(web::post().to(
- |state, req, path| {
- routing::routing_unlink_config(
- state,
- req,
- path,
- &TransactionType::Payment,
- )
- },
- )),
- ),
+ .service(web::resource("/deactivate_routing_algorithm").route(
+ web::patch().to(|state, req, path| {
+ routing::routing_unlink_config(
+ state,
+ req,
+ path,
+ &TransactionType::Payment,
+ )
+ }),
+ )),
)
}
}
diff --git a/crates/router/src/routes/routing.rs b/crates/router/src/routes/routing.rs
index b4e180cf718..8e375898377 100644
--- a/crates/router/src/routes/routing.rs
+++ b/crates/router/src/routes/routing.rs
@@ -200,7 +200,41 @@ pub async fn list_routing_configs(
.await
}
-#[cfg(feature = "olap")]
+#[cfg(all(feature = "olap", feature = "v2", feature = "routing_v2"))]
+#[instrument(skip_all)]
+pub async fn routing_unlink_config(
+ state: web::Data<AppState>,
+ req: HttpRequest,
+ path: web::Path<String>,
+ transaction_type: &enums::TransactionType,
+) -> impl Responder {
+ let flow = Flow::RoutingUnlinkConfig;
+ Box::pin(oss_api::server_wrap(
+ flow,
+ state,
+ &req,
+ path.into_inner(),
+ |state, auth: auth::AuthenticationData, path, _| {
+ routing::unlink_routing_config(state, auth.merchant_account, path, transaction_type)
+ },
+ #[cfg(not(feature = "release"))]
+ auth::auth_type(
+ &auth::ApiKeyAuth,
+ &auth::JWTAuth(Permission::RoutingWrite),
+ req.headers(),
+ ),
+ #[cfg(feature = "release")]
+ &auth::JWTAuth(Permission::RoutingWrite),
+ api_locking::LockAction::NotApplicable,
+ ))
+ .await
+}
+
+#[cfg(all(
+ feature = "olap",
+ any(feature = "v1", feature = "v2"),
+ not(feature = "routing_v2")
+))]
#[instrument(skip_all)]
pub async fn routing_unlink_config(
state: web::Data<AppState>,
|
2024-07-30T11:24:12Z
|
## Type of Change
<!-- Put an `x` in the boxes that apply -->
- [ ] Bugfix
- [ ] New feature
- [ ] Enhancement
- [x] Refactoring
- [ ] Dependency updates
- [ ] Documentation
- [ ] CI/CD
## Description
Refactor api v2 routes for deactivating and retrieving the routing config
### Additional Changes
- [ ] This PR modifies the API contract
- [ ] This PR modifies the database schema
- [ ] This PR modifies application configuration/environment variables
<!--
Provide links to the files with corresponding changes.
Following are the paths where you can find config files:
1. `config`
2. `crates/router/src/configs`
3. `loadtest/config`
-->
## Motivation and Context
<!--
Why is this change required? What problem does it solve?
If it fixes an open issue, please link to the issue here.
If you don't have an issue, we'd recommend starting with one first so the PR
can focus on the implementation (unless it is an obvious bug or documentation fix
that will have little conversation).
-->
## How did you test it?
- To deactivate the routing config
```
curl --location --request PATCH 'http://localhost:8080/v2/profiles/pro_VirB3AxB3qItFTnLsuA2/deactivate_routing_algorithm' \
--header 'Content-Type: application/json' \
--header 'api-key: dev_CMjrHy1A62kEwdzCDoLWRBta6xBZalgupmamFfdKfJdMjklfCil5S1wqAZ0F4Jw5' \
--data '
'
```
- To retrieve the routing config
```
curl --location 'http://localhost:8080/v2/routing_algorithm/routing_merchant_1722847196_EiushCG51H' \
--header 'api-key: dev_CMjrHy1A62kEwdzCDoLWRBta6xBZalgupmamFfdKfJdMjklfCil5S1wqAZ0F4Jw5'
```
## Checklist
<!-- Put an `x` in the boxes that apply -->
- [ ] I formatted the code `cargo +nightly fmt --all`
- [ ] I addressed lints thrown by `cargo clippy`
- [ ] I reviewed the submitted code
- [ ] I added unit tests for my changes where possible
|
a3ad0d92d71f654b3843bff550322f665d26223f
|
|
juspay/hyperswitch
|
juspay__hyperswitch-5504
|
Bug: [TRACKER] This issue tracks all the issues related to payment links
### Bug Description
1. open payment links are listing saved payment methods
### Expected Behavior
1. open payment links should not list saved payment methods
### Have you spent some time checking if this bug has been raised before?
- [X] I checked and didn't find a similar issue
### Have you read the Contributing Guidelines?
- [X] I have read the [Contributing Guidelines](https://github.com/juspay/hyperswitch/blob/main/docs/CONTRIBUTING.md)
### Are you willing to submit a PR?
Yes, I am willing to submit a PR!
|
diff --git a/crates/router/src/core/payment_link/payment_link_initiate/payment_link_initiator.js b/crates/router/src/core/payment_link/payment_link_initiate/payment_link_initiator.js
index 6269b3546af..71f0875f42e 100644
--- a/crates/router/src/core/payment_link/payment_link_initiate/payment_link_initiator.js
+++ b/crates/router/src/core/payment_link/payment_link_initiate/payment_link_initiator.js
@@ -41,6 +41,7 @@ function initializeSDK() {
var unifiedCheckoutOptions = {
displaySavedPaymentMethodsCheckbox: false,
+ displaySavedPaymentMethods: false,
layout: {
type: type, //accordion , tabs, spaced accordion
spacedAccordionItems: paymentDetails.sdk_layout === "spaced_accordion",
|
2024-08-01T07:14:07Z
|
## Type of Change
<!-- Put an `x` in the boxes that apply -->
- [x] Bugfix
- [ ] New feature
- [ ] Enhancement
- [ ] Refactoring
- [ ] Dependency updates
- [ ] Documentation
- [ ] CI/CD
## Description
This PR adds an argument to be sent to the SDK for open payment links. This field controls the listing of SPMs for a given customer. Default value is `true` in SDK, needs to be sent as `false` explicitly during SDK integration
### Additional Changes
- [ ] This PR modifies the API contract
- [ ] This PR modifies the database schema
- [ ] This PR modifies application configuration/environment variables
<!--
Provide links to the files with corresponding changes.
Following are the paths where you can find config files:
1. `config`
2. `crates/router/src/configs`
3. `loadtest/config`
-->
## Motivation and Context
<!--
Why is this change required? What problem does it solve?
If it fixes an open issue, please link to the issue here.
If you don't have an issue, we'd recommend starting with one first so the PR
can focus on the implementation (unless it is an obvious bug or documentation fix
that will have little conversation).
-->
Bug fixes; open link is not behaving as expected
## How did you test it?
<details>
<summary>1. Create non 3DS open payment link with an existing customer</summary>
curl --location 'https://sandbox.hyperswitch.io/payments' \
--header 'Content-Type: application/json' \
--header 'Accept: application/json' \
--header 'api-key: API_KEY' \
--data-raw '{
"customer_id": "cus_05845u0qSuOENDnHLqTl",
"amount": 100,
"currency": "USD",
"payment_link": true,
"authentication_type": "no_three_ds",
"connector": [
"stripe"
],
"billing": {
"address": {
"line1": "1467",
"line2": "Harrison Street",
"line3": "Harrison Street",
"city": "San Fransico",
"state": "CA",
"zip": "94122",
"country": "US",
"first_name": "John",
"last_name": "Doe"
},
"phone": {
"number": "8056594427",
"country_code": "+91"
}
},
"email": "john.doe@example.com",
"session_expiry": 1000000,
"return_url": "https://google.com",
"payment_link_config": {
"theme": "#14356f",
"logo": "https://hyperswitch.io/favicon.ico",
"seller_name": "HyperSwitch Inc."
}
}'
</details>
SPMs should not be displayed in the payment link
## Checklist
<!-- Put an `x` in the boxes that apply -->
- [x] I formatted the code `cargo +nightly fmt --all`
- [x] I addressed lints thrown by `cargo clippy`
- [x] I reviewed the submitted code
- [ ] I added unit tests for my changes where possible
|
93f557bacb9bf8e77e3b7b1b0521f0566793305b
|
|
juspay/hyperswitch
|
juspay__hyperswitch-5540
|
Bug: feat: support profile level delete in V1 - V2
Add support to delete user role
- Support profile level delete along with merchant level delete.
- In v1v2 version, delete from both V1 and V2
|
diff --git a/crates/common_enums/src/enums.rs b/crates/common_enums/src/enums.rs
index 015bf2d6c68..b81fb6e04e8 100644
--- a/crates/common_enums/src/enums.rs
+++ b/crates/common_enums/src/enums.rs
@@ -3085,6 +3085,8 @@ pub enum ApiVersion {
Debug,
Eq,
PartialEq,
+ Ord,
+ PartialOrd,
serde::Deserialize,
serde::Serialize,
strum::Display,
@@ -3095,10 +3097,10 @@ pub enum ApiVersion {
#[strum(serialize_all = "snake_case")]
#[serde(rename_all = "snake_case")]
pub enum EntityType {
- Internal,
- Organization,
- Merchant,
- Profile,
+ Internal = 3,
+ Organization = 2,
+ Merchant = 1,
+ Profile = 0,
}
#[derive(Clone, Debug, serde::Serialize)]
diff --git a/crates/diesel_models/src/query/user_role.rs b/crates/diesel_models/src/query/user_role.rs
index 2f2923db000..b84ea63de1d 100644
--- a/crates/diesel_models/src/query/user_role.rs
+++ b/crates/diesel_models/src/query/user_role.rs
@@ -82,22 +82,6 @@ impl UserRole {
.await
}
- pub async fn delete_by_user_id_merchant_id(
- conn: &PgPooledConn,
- user_id: String,
- merchant_id: id_type::MerchantId,
- version: UserRoleVersion,
- ) -> StorageResult<Self> {
- generics::generic_delete_one_with_result::<<Self as HasTable>::Table, _, _>(
- conn,
- dsl::user_id
- .eq(user_id)
- .and(dsl::merchant_id.eq(merchant_id))
- .and(dsl::version.eq(version)),
- )
- .await
- }
-
pub async fn list_by_user_id(
conn: &PgPooledConn,
user_id: String,
@@ -129,4 +113,71 @@ impl UserRole {
)
.await
}
+
+ pub async fn find_by_user_id_org_id_merchant_id_profile_id(
+ conn: &PgPooledConn,
+ user_id: String,
+ org_id: id_type::OrganizationId,
+ merchant_id: id_type::MerchantId,
+ profile_id: Option<String>,
+ version: UserRoleVersion,
+ ) -> StorageResult<Self> {
+ // Checking in user roles, for a user in token hierarchy, only one of the relation will be true, either org level, merchant level or profile level
+ // (org_id = ? && merchant_id = null && profile_id = null) || (org_id = ? && merchant_id = ? && profile_id = null) || (org_id = ? && merchant_id = ? && profile_id = ?)
+ let check_lineage = dsl::org_id
+ .eq(org_id.clone())
+ .and(dsl::merchant_id.is_null().and(dsl::profile_id.is_null()))
+ .or(dsl::org_id.eq(org_id.clone()).and(
+ dsl::merchant_id
+ .eq(merchant_id.clone())
+ .and(dsl::profile_id.is_null()),
+ ))
+ .or(dsl::org_id.eq(org_id).and(
+ dsl::merchant_id
+ .eq(merchant_id)
+ //TODO: In case of None, profile_id = NULL its unexpected behaviour, after V1 profile id will not be option
+ .and(dsl::profile_id.eq(profile_id)),
+ ));
+
+ let predicate = dsl::user_id
+ .eq(user_id)
+ .and(check_lineage)
+ .and(dsl::version.eq(version));
+
+ generics::generic_find_one::<<Self as HasTable>::Table, _, _>(conn, predicate).await
+ }
+
+ pub async fn delete_by_user_id_org_id_merchant_id_profile_id(
+ conn: &PgPooledConn,
+ user_id: String,
+ org_id: id_type::OrganizationId,
+ merchant_id: id_type::MerchantId,
+ profile_id: Option<String>,
+ version: UserRoleVersion,
+ ) -> StorageResult<Self> {
+ // Checking in user roles, for a user in token hierarchy, only one of the relation will be true, either org level, merchant level or profile level
+ // (org_id = ? && merchant_id = null && profile_id = null) || (org_id = ? && merchant_id = ? && profile_id = null) || (org_id = ? && merchant_id = ? && profile_id = ?)
+ let check_lineage = dsl::org_id
+ .eq(org_id.clone())
+ .and(dsl::merchant_id.is_null().and(dsl::profile_id.is_null()))
+ .or(dsl::org_id.eq(org_id.clone()).and(
+ dsl::merchant_id
+ .eq(merchant_id.clone())
+ .and(dsl::profile_id.is_null()),
+ ))
+ .or(dsl::org_id.eq(org_id).and(
+ dsl::merchant_id
+ .eq(merchant_id)
+ //TODO: In case of None, profile_id = NULL its unexpected behaviour, after V1 profile id will not be option
+ .and(dsl::profile_id.eq(profile_id)),
+ ));
+
+ let predicate = dsl::user_id
+ .eq(user_id)
+ .and(check_lineage)
+ .and(dsl::version.eq(version));
+
+ generics::generic_delete_one_with_result::<<Self as HasTable>::Table, _, _>(conn, predicate)
+ .await
+ }
}
diff --git a/crates/router/src/core/user_role.rs b/crates/router/src/core/user_role.rs
index b5c7f6db016..f2fddd61bb6 100644
--- a/crates/router/src/core/user_role.rs
+++ b/crates/router/src/core/user_role.rs
@@ -342,68 +342,169 @@ pub async fn delete_user_role(
.attach_printable("User deleting himself");
}
- let user_roles = state
+ let deletion_requestor_role_info = roles::RoleInfo::from_role_id(
+ &state,
+ &user_from_token.role_id,
+ &user_from_token.merchant_id,
+ &user_from_token.org_id,
+ )
+ .await
+ .change_context(UserErrors::InternalServerError)?;
+
+ let mut user_role_deleted_flag = false;
+
+ // Find in V2
+ let user_role_v2 = match state
.store
- .list_user_roles_by_user_id(user_from_db.get_user_id(), UserRoleVersion::V1)
+ .find_user_role_by_user_id_and_lineage(
+ user_from_db.get_user_id(),
+ &user_from_token.org_id,
+ &user_from_token.merchant_id,
+ user_from_token.profile_id.as_ref(),
+ UserRoleVersion::V2,
+ )
+ .await
+ {
+ Ok(user_role) => Some(user_role),
+ Err(e) => {
+ if e.current_context().is_db_not_found() {
+ None
+ } else {
+ return Err(UserErrors::InternalServerError.into());
+ }
+ }
+ };
+
+ if let Some(role_to_be_deleted) = user_role_v2 {
+ let target_role_info = roles::RoleInfo::from_role_id(
+ &state,
+ &role_to_be_deleted.role_id,
+ &user_from_token.merchant_id,
+ &user_from_token.org_id,
+ )
.await
.change_context(UserErrors::InternalServerError)?;
- for user_role in user_roles.iter() {
- let Some(merchant_id) = user_role.merchant_id.as_ref() else {
- return Err(report!(UserErrors::InternalServerError))
- .attach_printable("merchant_id not found for user_role");
- };
+ if !target_role_info.is_deletable() {
+ return Err(report!(UserErrors::InvalidDeleteOperation)).attach_printable(format!(
+ "Invalid operation, role_id = {} is not deletable",
+ role_to_be_deleted.role_id
+ ));
+ }
- if merchant_id == &user_from_token.merchant_id {
- let role_info = roles::RoleInfo::from_role_id(
- &state,
- &user_role.role_id,
- &user_from_token.merchant_id,
+ if deletion_requestor_role_info.get_entity_type() < target_role_info.get_entity_type() {
+ return Err(report!(UserErrors::InvalidDeleteOperation)).attach_printable(format!(
+ "Invalid operation, deletion requestor = {} cannot delete target = {}",
+ deletion_requestor_role_info.get_entity_type(),
+ target_role_info.get_entity_type()
+ ));
+ }
+
+ user_role_deleted_flag = true;
+ state
+ .store
+ .delete_user_role_by_user_id_and_lineage(
+ user_from_db.get_user_id(),
&user_from_token.org_id,
+ &user_from_token.merchant_id,
+ user_from_token.profile_id.as_ref(),
+ UserRoleVersion::V2,
)
.await
- .change_context(UserErrors::InternalServerError)?;
- if !role_info.is_deletable() {
- return Err(report!(UserErrors::InvalidDeleteOperation))
- .attach_printable(format!("role_id = {} is not deletable", user_role.role_id));
+ .change_context(UserErrors::InternalServerError)
+ .attach_printable("Error while deleting user role")?;
+ }
+
+ // Find in V1
+ let user_role_v1 = match state
+ .store
+ .find_user_role_by_user_id_and_lineage(
+ user_from_db.get_user_id(),
+ &user_from_token.org_id,
+ &user_from_token.merchant_id,
+ user_from_token.profile_id.as_ref(),
+ UserRoleVersion::V1,
+ )
+ .await
+ {
+ Ok(user_role) => Some(user_role),
+ Err(e) => {
+ if e.current_context().is_db_not_found() {
+ None
+ } else {
+ return Err(UserErrors::InternalServerError.into());
}
- } else {
- return Err(report!(UserErrors::InvalidDeleteOperation))
- .attach_printable("User is not associated with the merchant");
}
- }
+ };
+
+ if let Some(role_to_be_deleted) = user_role_v1 {
+ let target_role_info = roles::RoleInfo::from_role_id(
+ &state,
+ &role_to_be_deleted.role_id,
+ &user_from_token.merchant_id,
+ &user_from_token.org_id,
+ )
+ .await
+ .change_context(UserErrors::InternalServerError)?;
+
+ if !target_role_info.is_deletable() {
+ return Err(report!(UserErrors::InvalidDeleteOperation)).attach_printable(format!(
+ "Invalid operation, role_id = {} is not deletable",
+ role_to_be_deleted.role_id
+ ));
+ }
- let deleted_user_role = if user_roles.len() > 1 {
+ if deletion_requestor_role_info.get_entity_type() < target_role_info.get_entity_type() {
+ return Err(report!(UserErrors::InvalidDeleteOperation)).attach_printable(format!(
+ "Invalid operation, deletion requestor = {} cannot delete target = {}",
+ deletion_requestor_role_info.get_entity_type(),
+ target_role_info.get_entity_type()
+ ));
+ }
+
+ user_role_deleted_flag = true;
state
.store
- .delete_user_role_by_user_id_merchant_id(
+ .delete_user_role_by_user_id_and_lineage(
user_from_db.get_user_id(),
+ &user_from_token.org_id,
&user_from_token.merchant_id,
+ user_from_token.profile_id.as_ref(),
UserRoleVersion::V1,
)
.await
.change_context(UserErrors::InternalServerError)
- .attach_printable("Error while deleting user role")?
- } else {
+ .attach_printable("Error while deleting user role")?;
+ }
+
+ if !user_role_deleted_flag {
+ return Err(report!(UserErrors::InvalidDeleteOperation))
+ .attach_printable("User is not associated with the merchant");
+ }
+
+ // Check if user has any more role associations
+ let user_roles_v2 = state
+ .store
+ .list_user_roles_by_user_id(user_from_db.get_user_id(), UserRoleVersion::V2)
+ .await
+ .change_context(UserErrors::InternalServerError)?;
+
+ let user_roles_v1 = state
+ .store
+ .list_user_roles_by_user_id(user_from_db.get_user_id(), UserRoleVersion::V1)
+ .await
+ .change_context(UserErrors::InternalServerError)?;
+
+ // If user has no more role associated with him then deleting user
+ if user_roles_v2.is_empty() && user_roles_v1.is_empty() {
state
.global_store
.delete_user_by_user_id(user_from_db.get_user_id())
.await
.change_context(UserErrors::InternalServerError)
.attach_printable("Error while deleting user entry")?;
+ }
- state
- .store
- .delete_user_role_by_user_id_merchant_id(
- user_from_db.get_user_id(),
- &user_from_token.merchant_id,
- UserRoleVersion::V1,
- )
- .await
- .change_context(UserErrors::InternalServerError)
- .attach_printable("Error while deleting user role")?
- };
-
- auth::blacklist::insert_user_in_blacklist(&state, &deleted_user_role.user_id).await?;
+ auth::blacklist::insert_user_in_blacklist(&state, user_from_db.get_user_id()).await?;
Ok(ApplicationResponse::StatusOk)
}
diff --git a/crates/router/src/db/kafka_store.rs b/crates/router/src/db/kafka_store.rs
index 31b9ffcd7f8..183722590c3 100644
--- a/crates/router/src/db/kafka_store.rs
+++ b/crates/router/src/db/kafka_store.rs
@@ -2645,24 +2645,51 @@ impl UserRoleInterface for KafkaStore {
.await
}
- async fn delete_user_role_by_user_id_merchant_id(
+ async fn list_user_roles_by_user_id(
+ &self,
+ user_id: &str,
+ version: enums::UserRoleVersion,
+ ) -> CustomResult<Vec<user_storage::UserRole>, errors::StorageError> {
+ self.diesel_store
+ .list_user_roles_by_user_id(user_id, version)
+ .await
+ }
+
+ async fn find_user_role_by_user_id_and_lineage(
&self,
user_id: &str,
+ org_id: &id_type::OrganizationId,
merchant_id: &id_type::MerchantId,
+ profile_id: Option<&String>,
version: enums::UserRoleVersion,
- ) -> CustomResult<user_storage::UserRole, errors::StorageError> {
+ ) -> CustomResult<storage::UserRole, errors::StorageError> {
self.diesel_store
- .delete_user_role_by_user_id_merchant_id(user_id, merchant_id, version)
+ .find_user_role_by_user_id_and_lineage(
+ user_id,
+ org_id,
+ merchant_id,
+ profile_id,
+ version,
+ )
.await
}
- async fn list_user_roles_by_user_id(
+ async fn delete_user_role_by_user_id_and_lineage(
&self,
user_id: &str,
+ org_id: &id_type::OrganizationId,
+ merchant_id: &id_type::MerchantId,
+ profile_id: Option<&String>,
version: enums::UserRoleVersion,
- ) -> CustomResult<Vec<user_storage::UserRole>, errors::StorageError> {
+ ) -> CustomResult<storage::UserRole, errors::StorageError> {
self.diesel_store
- .list_user_roles_by_user_id(user_id, version)
+ .delete_user_role_by_user_id_and_lineage(
+ user_id,
+ org_id,
+ merchant_id,
+ profile_id,
+ version,
+ )
.await
}
diff --git a/crates/router/src/db/user_role.rs b/crates/router/src/db/user_role.rs
index 203860728c0..05f37d0ee72 100644
--- a/crates/router/src/db/user_role.rs
+++ b/crates/router/src/db/user_role.rs
@@ -49,24 +49,35 @@ pub trait UserRoleInterface {
version: enums::UserRoleVersion,
) -> CustomResult<Vec<storage::UserRole>, errors::StorageError>;
- async fn delete_user_role_by_user_id_merchant_id(
+ async fn list_user_roles_by_user_id(
&self,
user_id: &str,
+ version: enums::UserRoleVersion,
+ ) -> CustomResult<Vec<storage::UserRole>, errors::StorageError>;
+
+ async fn list_user_roles_by_merchant_id(
+ &self,
merchant_id: &id_type::MerchantId,
version: enums::UserRoleVersion,
- ) -> CustomResult<storage::UserRole, errors::StorageError>;
+ ) -> CustomResult<Vec<storage::UserRole>, errors::StorageError>;
- async fn list_user_roles_by_user_id(
+ async fn find_user_role_by_user_id_and_lineage(
&self,
user_id: &str,
+ org_id: &id_type::OrganizationId,
+ merchant_id: &id_type::MerchantId,
+ profile_id: Option<&String>,
version: enums::UserRoleVersion,
- ) -> CustomResult<Vec<storage::UserRole>, errors::StorageError>;
+ ) -> CustomResult<storage::UserRole, errors::StorageError>;
- async fn list_user_roles_by_merchant_id(
+ async fn delete_user_role_by_user_id_and_lineage(
&self,
+ user_id: &str,
+ org_id: &id_type::OrganizationId,
merchant_id: &id_type::MerchantId,
+ profile_id: Option<&String>,
version: enums::UserRoleVersion,
- ) -> CustomResult<Vec<storage::UserRole>, errors::StorageError>;
+ ) -> CustomResult<storage::UserRole, errors::StorageError>;
async fn transfer_org_ownership_between_users(
&self,
@@ -161,25 +172,6 @@ impl UserRoleInterface for Store {
.map_err(|error| report!(errors::StorageError::from(error)))
}
- #[instrument(skip_all)]
- async fn delete_user_role_by_user_id_merchant_id(
- &self,
- user_id: &str,
- merchant_id: &id_type::MerchantId,
- version: enums::UserRoleVersion,
- ) -> CustomResult<storage::UserRole, errors::StorageError> {
- let conn = connection::pg_connection_write(self).await?;
-
- storage::UserRole::delete_by_user_id_merchant_id(
- &conn,
- user_id.to_owned(),
- merchant_id.to_owned(),
- version,
- )
- .await
- .map_err(|error| report!(errors::StorageError::from(error)))
- }
-
#[instrument(skip_all)]
async fn list_user_roles_by_user_id(
&self,
@@ -204,6 +196,50 @@ impl UserRoleInterface for Store {
.map_err(|error| report!(errors::StorageError::from(error)))
}
+ #[instrument(skip_all)]
+ async fn find_user_role_by_user_id_and_lineage(
+ &self,
+ user_id: &str,
+ org_id: &id_type::OrganizationId,
+ merchant_id: &id_type::MerchantId,
+ profile_id: Option<&String>,
+ version: enums::UserRoleVersion,
+ ) -> CustomResult<storage::UserRole, errors::StorageError> {
+ let conn = connection::pg_connection_write(self).await?;
+ storage::UserRole::find_by_user_id_org_id_merchant_id_profile_id(
+ &conn,
+ user_id.to_owned(),
+ org_id.to_owned(),
+ merchant_id.to_owned(),
+ profile_id.cloned(),
+ version,
+ )
+ .await
+ .map_err(|error| report!(errors::StorageError::from(error)))
+ }
+
+ #[instrument(skip_all)]
+ async fn delete_user_role_by_user_id_and_lineage(
+ &self,
+ user_id: &str,
+ org_id: &id_type::OrganizationId,
+ merchant_id: &id_type::MerchantId,
+ profile_id: Option<&String>,
+ version: enums::UserRoleVersion,
+ ) -> CustomResult<storage::UserRole, errors::StorageError> {
+ let conn = connection::pg_connection_write(self).await?;
+ storage::UserRole::delete_by_user_id_org_id_merchant_id_profile_id(
+ &conn,
+ user_id.to_owned(),
+ org_id.to_owned(),
+ merchant_id.to_owned(),
+ profile_id.cloned(),
+ version,
+ )
+ .await
+ .map_err(|error| report!(errors::StorageError::from(error)))
+ }
+
#[instrument(skip_all)]
async fn transfer_org_ownership_between_users(
&self,
@@ -565,32 +601,6 @@ impl UserRoleInterface for MockDb {
Ok(())
}
- async fn delete_user_role_by_user_id_merchant_id(
- &self,
- user_id: &str,
- merchant_id: &id_type::MerchantId,
- version: enums::UserRoleVersion,
- ) -> CustomResult<storage::UserRole, errors::StorageError> {
- let mut user_roles = self.user_roles.lock().await;
-
- let index = user_roles.iter().position(|role| {
- role.user_id == user_id
- && role.version == version
- && match role.merchant_id {
- Some(ref mid) => mid == merchant_id,
- None => false,
- }
- });
-
- match index {
- Some(idx) => Ok(user_roles.remove(idx)),
- None => Err(errors::StorageError::ValueNotFound(
- "Cannot find user role to delete".to_string(),
- )
- .into()),
- }
- }
-
async fn list_user_roles_by_user_id(
&self,
user_id: &str,
@@ -634,4 +644,83 @@ impl UserRoleInterface for MockDb {
Ok(filtered_roles)
}
+
+ async fn find_user_role_by_user_id_and_lineage(
+ &self,
+ user_id: &str,
+ org_id: &id_type::OrganizationId,
+ merchant_id: &id_type::MerchantId,
+ profile_id: Option<&String>,
+ version: enums::UserRoleVersion,
+ ) -> CustomResult<storage::UserRole, errors::StorageError> {
+ let user_roles = self.user_roles.lock().await;
+
+ for user_role in user_roles.iter() {
+ let org_level_check = user_role.org_id.as_ref() == Some(org_id)
+ && user_role.merchant_id.is_none()
+ && user_role.profile_id.is_none();
+
+ let merchant_level_check = user_role.org_id.as_ref() == Some(org_id)
+ && user_role.merchant_id.as_ref() == Some(merchant_id)
+ && user_role.profile_id.is_none();
+
+ let profile_level_check = user_role.org_id.as_ref() == Some(org_id)
+ && user_role.merchant_id.as_ref() == Some(merchant_id)
+ && user_role.profile_id.as_ref() == profile_id;
+
+ // Check if any condition matches and the version matches
+ if user_role.user_id == user_id
+ && (org_level_check || merchant_level_check || profile_level_check)
+ && user_role.version == version
+ {
+ return Ok(user_role.clone());
+ }
+ }
+
+ Err(errors::StorageError::ValueNotFound(format!(
+ "No user role available for user_id = {} in the current token hierarchy",
+ user_id
+ ))
+ .into())
+ }
+
+ async fn delete_user_role_by_user_id_and_lineage(
+ &self,
+ user_id: &str,
+ org_id: &id_type::OrganizationId,
+ merchant_id: &id_type::MerchantId,
+ profile_id: Option<&String>,
+ version: enums::UserRoleVersion,
+ ) -> CustomResult<storage::UserRole, errors::StorageError> {
+ let mut user_roles = self.user_roles.lock().await;
+
+ // Find the position of the user role to delete
+ let index = user_roles.iter().position(|role| {
+ let org_level_check = role.org_id.as_ref() == Some(org_id)
+ && role.merchant_id.is_none()
+ && role.profile_id.is_none();
+
+ let merchant_level_check = role.org_id.as_ref() == Some(org_id)
+ && role.merchant_id.as_ref() == Some(merchant_id)
+ && role.profile_id.is_none();
+
+ let profile_level_check = role.org_id.as_ref() == Some(org_id)
+ && role.merchant_id.as_ref() == Some(merchant_id)
+ && role.profile_id.as_ref() == profile_id;
+
+ // Check if the user role matches the conditions and the version matches
+ role.user_id == user_id
+ && (org_level_check || merchant_level_check || profile_level_check)
+ && role.version == version
+ });
+
+ // Remove and return the user role if found
+ match index {
+ Some(idx) => Ok(user_roles.remove(idx)),
+ None => Err(errors::StorageError::ValueNotFound(
+ "Cannot find user role to delete".to_string(),
+ )
+ .into()),
+ }
+ }
}
|
2024-08-06T11:03:04Z
|
## Type of Change
<!-- Put an `x` in the boxes that apply -->
- [ ] Bugfix
- [x] New feature
- [ ] Enhancement
- [x] Refactoring
- [ ] Dependency updates
- [ ] Documentation
- [ ] CI/CD
## Description
- Add support to delete profile level users
- Delete is backward compatible
- Delete to support both V1 and V2 operations accordingly
### Additional Changes
- [ ] This PR modifies the API contract
- [ ] This PR modifies the database schema
- [ ] This PR modifies application configuration/environment variables
<!--
Provide links to the files with corresponding changes.
Following are the paths where you can find config files:
1. `config`
2. `crates/router/src/configs`
3. `loadtest/config`
-->
## Motivation and Context
Closes [#5540](https://github.com/juspay/hyperswitch/issues/5540)
## How did you test it?
Use the curl to delete user role
```
curl --location --request DELETE 'http://localhost:8080/user/user/delete' \
--header 'Authorization: Bearer JWT' \
--header 'Content-Type: application/json' \
--data-raw '{
"email": "email_to_delete"
}'
```
## Checklist
<!-- Put an `x` in the boxes that apply -->
- [x] I formatted the code `cargo +nightly fmt --all`
- [x] I addressed lints thrown by `cargo clippy`
- [x] I reviewed the submitted code
- [ ] I added unit tests for my changes where possible
|
0ab0aa1a94fe98719d51ff89d27935a30cb33721
|
|
juspay/hyperswitch
|
juspay__hyperswitch-5506
|
Bug: Docs: Adding redirect URL details
Documentation didn't have any details about the Redirect URL.
|
diff --git a/crates/api_models/src/payments.rs b/crates/api_models/src/payments.rs
index a466288b416..09fede09e5d 100644
--- a/crates/api_models/src/payments.rs
+++ b/crates/api_models/src/payments.rs
@@ -2978,7 +2978,6 @@ where
| PaymentMethodDataResponse::MandatePayment {}
| PaymentMethodDataResponse::GiftCard {}
| PaymentMethodDataResponse::PayLater(_)
- | PaymentMethodDataResponse::Paypal {}
| PaymentMethodDataResponse::RealTimePayment {}
| PaymentMethodDataResponse::Upi {}
| PaymentMethodDataResponse::Wallet {}
@@ -3005,7 +3004,6 @@ pub enum PaymentMethodDataResponse {
BankTransfer {},
Wallet {},
PayLater(Box<PaylaterResponse>),
- Paypal {},
BankRedirect {},
Crypto {},
BankDebit {},
|
2024-08-01T10:24:49Z
|
## Type of Change
<!-- Put an `x` in the boxes that apply -->
- [ ] Bugfix
- [ ] New feature
- [ ] Enhancement
- [ ] Refactoring
- [ ] Dependency updates
- [X] Documentation
- [ ] CI/CD
## Description
<!-- Describe your changes in detail -->
### Additional Changes
- [ ] This PR modifies the API contract
- [ ] This PR modifies the database schema
- [ ] This PR modifies application configuration/environment variables
<!--
Provide links to the files with corresponding changes.
Following are the paths where you can find config files:
1. `config`
2. `crates/router/src/configs`
3. `loadtest/config`
-->
## Motivation and Context
<!--
Why is this change required? What problem does it solve?
If it fixes an open issue, please link to the issue here.
If you don't have an issue, we'd recommend starting with one first so the PR
can focus on the implementation (unless it is an obvious bug or documentation fix
that will have little conversation).
-->
Closes #5506
## How did you test it?
<!--
Did you write an integration/unit/API test to verify the code changes?
Or did you test this change manually (provide relevant screenshots)?
-->
## Checklist
<!-- Put an `x` in the boxes that apply -->
- [ ] I formatted the code `cargo +nightly fmt --all`
- [ ] I addressed lints thrown by `cargo clippy`
- [ ] I reviewed the submitted code
- [ ] I added unit tests for my changes where possible
|
c036fd7f41a21eb481859671db672b0bcebdca97
|
|
juspay/hyperswitch
|
juspay__hyperswitch-5495
|
Bug: [BUG] Open payment links does not redirect to status page
### Bug Description
Open payment links does not redirect to status page after payment has completed.
### Expected Behavior
Once payment request is submitted for non 3DS txns, payment link should redirect to the status page.
### Actual Behavior
Once payment request is submitted for non 3DS txns, payment link is not redirecting to the status page.
### Context For The Bug
`redirectToStatus` fn is invoked when payment is completed
### Environment
Are you using hyperswitch hosted version? Yes/No
If yes, please provide the value of the `x-request-id` response header to help us debug your issue.
If not (or if building/running locally), please provide the following details:
1. Operating System or Linux distribution:
2. Rust version (output of `rustc --version`): ``
3. App version (output of `cargo r --features vergen -- --version`): ``
### Have you spent some time checking if this bug has been raised before?
- [X] I checked and didn't find a similar issue
### Have you read the Contributing Guidelines?
- [X] I have read the [Contributing Guidelines](https://github.com/juspay/hyperswitch/blob/main/docs/CONTRIBUTING.md)
### Are you willing to submit a PR?
Yes, I am willing to submit a PR!
|
diff --git a/crates/router/src/core/payment_link/payment_link_initiate/payment_link_initiator.js b/crates/router/src/core/payment_link/payment_link_initiate/payment_link_initiator.js
index 4d14af1577c..6269b3546af 100644
--- a/crates/router/src/core/payment_link/payment_link_initiate/payment_link_initiator.js
+++ b/crates/router/src/core/payment_link/payment_link_initiate/payment_link_initiator.js
@@ -68,15 +68,15 @@ function initializeSDK() {
setTimeout(() => {
document.body.removeChild(shimmer);
}, 500);
+}
- /**
- * Use - redirect to /payment_link/status
- */
- function redirectToStatus() {
- var arr = window.location.pathname.split("/");
- arr.splice(0, 2);
- arr.unshift("status");
- arr.unshift("payment_link");
- window.location.href = window.location.origin + "/" + arr.join("/");
- }
+/**
+ * Use - redirect to /payment_link/status
+ */
+function redirectToStatus() {
+ var arr = window.location.pathname.split("/");
+ arr.splice(0, 2);
+ arr.unshift("status");
+ arr.unshift("payment_link");
+ window.location.href = window.location.origin + "/" + arr.join("/");
}
|
2024-07-31T14:33:51Z
|
## Type of Change
<!-- Put an `x` in the boxes that apply -->
- [x] Bugfix
- [ ] New feature
- [ ] Enhancement
- [ ] Refactoring
- [ ] Dependency updates
- [ ] Documentation
- [ ] CI/CD
## Description
Described in https://github.com/juspay/hyperswitch/issues/5495
### Additional Changes
- [ ] This PR modifies the API contract
- [ ] This PR modifies the database schema
- [ ] This PR modifies application configuration/environment variables
<!--
Provide links to the files with corresponding changes.
Following are the paths where you can find config files:
1. `config`
2. `crates/router/src/configs`
3. `loadtest/config`
-->
## How did you test it?
<details>
<summary>1. Create non 3DS open payment link</summary>
curl --location 'https://sandbox.hyperswitch.io/payments' \
--header 'Content-Type: application/json' \
--header 'Accept: application/json' \
--header 'api-key: API_KEY' \
--data-raw '{
"customer_id": "cus_05845u0qSuOENDnHLqTl",
"amount": 100,
"currency": "USD",
"payment_link": true,
"authentication_type": "no_three_ds",
"connector": [
"stripe"
],
"billing": {
"address": {
"line1": "1467",
"line2": "Harrison Street",
"line3": "Harrison Street",
"city": "San Fransico",
"state": "CA",
"zip": "94122",
"country": "US",
"first_name": "John",
"last_name": "Doe"
},
"phone": {
"number": "8056594427",
"country_code": "+91"
}
},
"email": "john.doe@example.com",
"session_expiry": 1000000,
"return_url": "https://google.com",
"payment_link_config": {
"theme": "#14356f",
"logo": "https://hyperswitch.io/favicon.ico",
"seller_name": "HyperSwitch Inc."
}
}'
</details>
Complete the payment, and wait for redirection
## Checklist
<!-- Put an `x` in the boxes that apply -->
- [x] I formatted the code `cargo +nightly fmt --all`
- [x] I addressed lints thrown by `cargo clippy`
- [x] I reviewed the submitted code
- [ ] I added unit tests for my changes where possible
|
540ef071cb238a56d52d06687226aab7fd0dfe68
|
|
juspay/hyperswitch
|
juspay__hyperswitch-5510
|
Bug: [FEAT] add a wrapper for encryption and decryption
|
diff --git a/crates/common_utils/src/macros.rs b/crates/common_utils/src/macros.rs
index abd24ac8679..06554ee9b51 100644
--- a/crates/common_utils/src/macros.rs
+++ b/crates/common_utils/src/macros.rs
@@ -301,3 +301,14 @@ mod id_type {
};
}
}
+
+/// Get the type name for a type
+#[macro_export]
+macro_rules! type_name {
+ ($type:ty) => {
+ std::any::type_name::<$type>()
+ .rsplit("::")
+ .nth(1)
+ .unwrap_or_default();
+ };
+}
diff --git a/crates/hyperswitch_domain_models/src/business_profile.rs b/crates/hyperswitch_domain_models/src/business_profile.rs
index 779dcdb2fbb..08903748c01 100644
--- a/crates/hyperswitch_domain_models/src/business_profile.rs
+++ b/crates/hyperswitch_domain_models/src/business_profile.rs
@@ -5,7 +5,7 @@ use common_utils::{
date_time,
encryption::Encryption,
errors::{CustomResult, ValidationError},
- pii,
+ pii, type_name,
types::keymanager,
};
use diesel_models::business_profile::{
@@ -15,7 +15,7 @@ use diesel_models::business_profile::{
use error_stack::ResultExt;
use masking::{PeekInterface, Secret};
-use crate::type_encryption::{decrypt_optional, AsyncLift};
+use crate::type_encryption::{crypto_operation, AsyncLift, CryptoOperation};
#[cfg(all(
any(feature = "v1", feature = "v2"),
@@ -348,8 +348,16 @@ impl super::behaviour::Conversion for BusinessProfile {
.collect_billing_details_from_wallet_connector,
outgoing_webhook_custom_http_headers: item
.outgoing_webhook_custom_http_headers
- .async_lift(|inner| {
- decrypt_optional(state, inner, key_manager_identifier.clone(), key.peek())
+ .async_lift(|inner| async {
+ crypto_operation(
+ state,
+ type_name!(Self::DstType),
+ CryptoOperation::DecryptOptional(inner),
+ key_manager_identifier.clone(),
+ key.peek(),
+ )
+ .await
+ .and_then(|val| val.try_into_optionaloperation())
})
.await?,
})
@@ -725,8 +733,16 @@ impl super::behaviour::Conversion for BusinessProfile {
.collect_billing_details_from_wallet_connector,
outgoing_webhook_custom_http_headers: item
.outgoing_webhook_custom_http_headers
- .async_lift(|inner| {
- decrypt_optional(state, inner, key_manager_identifier.clone(), key.peek())
+ .async_lift(|inner| async {
+ crypto_operation(
+ state,
+ type_name!(Self::DstType),
+ CryptoOperation::DecryptOptional(inner),
+ key_manager_identifier.clone(),
+ key.peek(),
+ )
+ .await
+ .and_then(|val| val.try_into_optionaloperation())
})
.await?,
routing_algorithm_id: item.routing_algorithm_id,
diff --git a/crates/hyperswitch_domain_models/src/customer.rs b/crates/hyperswitch_domain_models/src/customer.rs
index 6b08e30d33f..42c66b74c01 100644
--- a/crates/hyperswitch_domain_models/src/customer.rs
+++ b/crates/hyperswitch_domain_models/src/customer.rs
@@ -110,17 +110,21 @@ impl super::behaviour::Conversion for Customer {
where
Self: Sized,
{
- let decrypted = types::batch_decrypt(
+ let decrypted = types::crypto_operation(
state,
- CustomerRequestWithEncryption::to_encryptable(CustomerRequestWithEncryption {
- name: item.name.clone(),
- phone: item.phone.clone(),
- email: item.email.clone(),
- }),
+ common_utils::type_name!(Self::DstType),
+ types::CryptoOperation::BatchDecrypt(CustomerRequestWithEncryption::to_encryptable(
+ CustomerRequestWithEncryption {
+ name: item.name.clone(),
+ phone: item.phone.clone(),
+ email: item.email.clone(),
+ },
+ )),
keymanager::Identifier::Merchant(item.merchant_id.clone()),
key.peek(),
)
.await
+ .and_then(|val| val.try_into_batchoperation())
.change_context(ValidationError::InvalidValue {
message: "Failed while decrypting customer data".to_string(),
})?;
@@ -206,17 +210,21 @@ impl super::behaviour::Conversion for Customer {
where
Self: Sized,
{
- let decrypted = types::batch_decrypt(
+ let decrypted = types::crypto_operation(
state,
- CustomerRequestWithEncryption::to_encryptable(CustomerRequestWithEncryption {
- name: item.name.clone(),
- phone: item.phone.clone(),
- email: item.email.clone(),
- }),
+ type_name!(Self::DstType),
+ types::CryptoOperation::BatchDecrypt(CustomerRequestWithEncryption::to_encryptable(
+ CustomerRequestWithEncryption {
+ name: item.name.clone(),
+ phone: item.phone.clone(),
+ email: item.email.clone(),
+ },
+ )),
keymanager::Identifier::Merchant(item.merchant_id.clone()),
key.peek(),
)
.await
+ .and_then(|val| val.try_into_batchoperation())
.change_context(ValidationError::InvalidValue {
message: "Failed while decrypting customer data".to_string(),
})?;
diff --git a/crates/hyperswitch_domain_models/src/merchant_account.rs b/crates/hyperswitch_domain_models/src/merchant_account.rs
index 1697b78275c..8ce0b3a5e43 100644
--- a/crates/hyperswitch_domain_models/src/merchant_account.rs
+++ b/crates/hyperswitch_domain_models/src/merchant_account.rs
@@ -4,7 +4,7 @@ use common_utils::{
encryption::Encryption,
errors::{CustomResult, ValidationError},
ext_traits::ValueExt,
- pii,
+ pii, type_name,
types::keymanager::{self},
};
use diesel_models::{
@@ -15,7 +15,7 @@ use error_stack::ResultExt;
use masking::{PeekInterface, Secret};
use router_env::logger;
-use crate::type_encryption::{decrypt_optional, AsyncLift};
+use crate::type_encryption::{crypto_operation, AsyncLift, CryptoOperation};
#[cfg(all(
any(feature = "v1", feature = "v2"),
@@ -565,14 +565,30 @@ impl super::behaviour::Conversion for MerchantAccount {
id,
merchant_name: item
.merchant_name
- .async_lift(|inner| {
- decrypt_optional(state, inner, key_manager_identifier.clone(), key.peek())
+ .async_lift(|inner| async {
+ crypto_operation(
+ state,
+ type_name!(Self::DstType),
+ CryptoOperation::DecryptOptional(inner),
+ key_manager_identifier.clone(),
+ key.peek(),
+ )
+ .await
+ .and_then(|val| val.try_into_optionaloperation())
})
.await?,
merchant_details: item
.merchant_details
- .async_lift(|inner| {
- decrypt_optional(state, inner, key_manager_identifier.clone(), key.peek())
+ .async_lift(|inner| async {
+ crypto_operation(
+ state,
+ type_name!(Self::DstType),
+ CryptoOperation::DecryptOptional(inner),
+ key_manager_identifier.clone(),
+ key.peek(),
+ )
+ .await
+ .and_then(|val| val.try_into_optionaloperation())
})
.await?,
publishable_key,
@@ -679,14 +695,30 @@ impl super::behaviour::Conversion for MerchantAccount {
redirect_to_merchant_with_http_post: item.redirect_to_merchant_with_http_post,
merchant_name: item
.merchant_name
- .async_lift(|inner| {
- decrypt_optional(state, inner, key_manager_identifier.clone(), key.peek())
+ .async_lift(|inner| async {
+ crypto_operation(
+ state,
+ type_name!(Self::DstType),
+ CryptoOperation::DecryptOptional(inner),
+ key_manager_identifier.clone(),
+ key.peek(),
+ )
+ .await
+ .and_then(|val| val.try_into_optionaloperation())
})
.await?,
merchant_details: item
.merchant_details
- .async_lift(|inner| {
- decrypt_optional(state, inner, key_manager_identifier.clone(), key.peek())
+ .async_lift(|inner| async {
+ crypto_operation(
+ state,
+ type_name!(Self::DstType),
+ CryptoOperation::DecryptOptional(inner),
+ key_manager_identifier.clone(),
+ key.peek(),
+ )
+ .await
+ .and_then(|val| val.try_into_optionaloperation())
})
.await?,
webhook_details: item.webhook_details,
diff --git a/crates/hyperswitch_domain_models/src/merchant_connector_account.rs b/crates/hyperswitch_domain_models/src/merchant_connector_account.rs
index cea595aed64..006fd5d7755 100644
--- a/crates/hyperswitch_domain_models/src/merchant_connector_account.rs
+++ b/crates/hyperswitch_domain_models/src/merchant_connector_account.rs
@@ -3,7 +3,7 @@ use common_utils::{
date_time,
encryption::Encryption,
errors::{CustomResult, ValidationError},
- pii,
+ pii, type_name,
types::keymanager::{Identifier, KeyManagerState},
};
use diesel_models::{enums, merchant_connector_account::MerchantConnectorAccountUpdateInternal};
@@ -11,7 +11,7 @@ use error_stack::ResultExt;
use masking::{PeekInterface, Secret};
use super::behaviour;
-use crate::type_encryption::{decrypt, decrypt_optional, AsyncLift};
+use crate::type_encryption::{crypto_operation, AsyncLift, CryptoOperation};
#[cfg(all(
any(feature = "v1", feature = "v2"),
@@ -185,13 +185,15 @@ impl behaviour::Conversion for MerchantConnectorAccount {
Ok(Self {
merchant_id: other.merchant_id,
connector_name: other.connector_name,
- connector_account_details: decrypt(
+ connector_account_details: crypto_operation(
state,
- other.connector_account_details,
+ type_name!(Self::DstType),
+ CryptoOperation::Decrypt(other.connector_account_details),
identifier.clone(),
key.peek(),
)
.await
+ .and_then(|val| val.try_into_operation())
.change_context(ValidationError::InvalidValue {
message: "Failed while decrypting connector account details".to_string(),
})?,
@@ -216,18 +218,35 @@ impl behaviour::Conversion for MerchantConnectorAccount {
status: other.status,
connector_wallets_details: other
.connector_wallets_details
- .async_lift(|inner| decrypt_optional(state, inner, identifier.clone(), key.peek()))
+ .async_lift(|inner| async {
+ crypto_operation(
+ state,
+ type_name!(Self::DstType),
+ CryptoOperation::DecryptOptional(inner),
+ identifier.clone(),
+ key.peek(),
+ )
+ .await
+ .and_then(|val| val.try_into_optionaloperation())
+ })
.await
.change_context(ValidationError::InvalidValue {
message: "Failed while decrypting connector wallets details".to_string(),
})?,
additional_merchant_data: if let Some(data) = other.additional_merchant_data {
Some(
- decrypt(state, data, identifier, key.peek())
- .await
- .change_context(ValidationError::InvalidValue {
- message: "Failed while decrypting additional_merchant_data".to_string(),
- })?,
+ crypto_operation(
+ state,
+ type_name!(Self::DstType),
+ CryptoOperation::Decrypt(data),
+ identifier,
+ key.peek(),
+ )
+ .await
+ .and_then(|val| val.try_into_operation())
+ .change_context(ValidationError::InvalidValue {
+ message: "Failed while decrypting additional_merchant_data".to_string(),
+ })?,
)
} else {
None
@@ -309,13 +328,15 @@ impl behaviour::Conversion for MerchantConnectorAccount {
id: other.id,
merchant_id: other.merchant_id,
connector_name: other.connector_name,
- connector_account_details: decrypt(
+ connector_account_details: crypto_operation(
state,
- other.connector_account_details,
+ type_name!(Self::DstType),
+ CryptoOperation::Decrypt(other.connector_account_details),
identifier.clone(),
key.peek(),
)
.await
+ .and_then(|val| val.try_into_operation())
.change_context(ValidationError::InvalidValue {
message: "Failed while decrypting connector account details".to_string(),
})?,
@@ -335,18 +356,35 @@ impl behaviour::Conversion for MerchantConnectorAccount {
status: other.status,
connector_wallets_details: other
.connector_wallets_details
- .async_lift(|inner| decrypt_optional(state, inner, identifier.clone(), key.peek()))
+ .async_lift(|inner| async {
+ crypto_operation(
+ state,
+ type_name!(Self::DstType),
+ CryptoOperation::DecryptOptional(inner),
+ identifier.clone(),
+ key.peek(),
+ )
+ .await
+ .and_then(|val| val.try_into_optionaloperation())
+ })
.await
.change_context(ValidationError::InvalidValue {
message: "Failed while decrypting connector wallets details".to_string(),
})?,
additional_merchant_data: if let Some(data) = other.additional_merchant_data {
Some(
- decrypt(state, data, identifier, key.peek())
- .await
- .change_context(ValidationError::InvalidValue {
- message: "Failed while decrypting additional_merchant_data".to_string(),
- })?,
+ crypto_operation(
+ state,
+ type_name!(Self::DstType),
+ CryptoOperation::Decrypt(data),
+ identifier,
+ key.peek(),
+ )
+ .await
+ .and_then(|val| val.try_into_operation())
+ .change_context(ValidationError::InvalidValue {
+ message: "Failed while decrypting additional_merchant_data".to_string(),
+ })?,
)
} else {
None
diff --git a/crates/hyperswitch_domain_models/src/merchant_key_store.rs b/crates/hyperswitch_domain_models/src/merchant_key_store.rs
index bfd75a08fa3..d24e23c5792 100644
--- a/crates/hyperswitch_domain_models/src/merchant_key_store.rs
+++ b/crates/hyperswitch_domain_models/src/merchant_key_store.rs
@@ -2,13 +2,14 @@ use common_utils::{
crypto::Encryptable,
custom_serde, date_time,
errors::{CustomResult, ValidationError},
+ type_name,
types::keymanager::{self, KeyManagerState},
};
use error_stack::ResultExt;
use masking::{PeekInterface, Secret};
use time::PrimitiveDateTime;
-use crate::type_encryption::decrypt;
+use crate::type_encryption::{crypto_operation, CryptoOperation};
#[derive(Clone, Debug, serde::Serialize)]
pub struct MerchantKeyStore {
@@ -40,12 +41,20 @@ impl super::behaviour::Conversion for MerchantKeyStore {
Self: Sized,
{
let identifier = keymanager::Identifier::Merchant(item.merchant_id.clone());
+
Ok(Self {
- key: decrypt(state, item.key, identifier, key.peek())
- .await
- .change_context(ValidationError::InvalidValue {
- message: "Failed while decrypting customer data".to_string(),
- })?,
+ key: crypto_operation(
+ state,
+ type_name!(Self::DstType),
+ CryptoOperation::Decrypt(item.key),
+ identifier,
+ key.peek(),
+ )
+ .await
+ .and_then(|val| val.try_into_operation())
+ .change_context(ValidationError::InvalidValue {
+ message: "Failed while decrypting customer data".to_string(),
+ })?,
merchant_id: item.merchant_id,
created_at: item.created_at,
})
diff --git a/crates/hyperswitch_domain_models/src/payments/payment_attempt.rs b/crates/hyperswitch_domain_models/src/payments/payment_attempt.rs
index 15c5aded500..79818d5b157 100644
--- a/crates/hyperswitch_domain_models/src/payments/payment_attempt.rs
+++ b/crates/hyperswitch_domain_models/src/payments/payment_attempt.rs
@@ -3,7 +3,7 @@ use common_enums as storage_enums;
use common_utils::{
encryption::Encryption,
errors::{CustomResult, ValidationError},
- id_type, pii,
+ id_type, pii, type_name,
types::{
keymanager::{self, KeyManagerState},
MinorUnit,
@@ -18,7 +18,7 @@ use super::PaymentIntent;
use crate::{
behaviour, errors,
mandates::{MandateDataType, MandateDetails},
- type_encryption::{decrypt_optional, AsyncLift},
+ type_encryption::{crypto_operation, AsyncLift, CryptoOperation},
ForeignIDRef, RemoteStorageObject,
};
@@ -553,8 +553,17 @@ impl behaviour::Conversion for PaymentIntent {
Self: Sized,
{
async {
- let inner_decrypt =
- |inner| decrypt_optional(state, inner, key_manager_identifier.clone(), key.peek());
+ let inner_decrypt = |inner| async {
+ crypto_operation(
+ state,
+ type_name!(Self::DstType),
+ CryptoOperation::DecryptOptional(inner),
+ key_manager_identifier.clone(),
+ key.peek(),
+ )
+ .await
+ .and_then(|val| val.try_into_optionaloperation())
+ };
Ok::<Self, error_stack::Report<common_utils::errors::CryptoError>>(Self {
payment_id: storage_model.payment_id,
merchant_id: storage_model.merchant_id,
@@ -742,8 +751,17 @@ impl behaviour::Conversion for PaymentIntent {
Self: Sized,
{
async {
- let inner_decrypt =
- |inner| decrypt_optional(state, inner, key_manager_identifier.clone(), key.peek());
+ let inner_decrypt = |inner| async {
+ crypto_operation(
+ state,
+ type_name!(Self::DstType),
+ CryptoOperation::DecryptOptional(inner),
+ key_manager_identifier.clone(),
+ key.peek(),
+ )
+ .await
+ .and_then(|val| val.try_into_optionaloperation())
+ };
Ok::<Self, error_stack::Report<common_utils::errors::CryptoError>>(Self {
payment_id: storage_model.payment_id,
merchant_id: storage_model.merchant_id,
diff --git a/crates/hyperswitch_domain_models/src/type_encryption.rs b/crates/hyperswitch_domain_models/src/type_encryption.rs
index a36969478d1..0ff37b0bc29 100644
--- a/crates/hyperswitch_domain_models/src/type_encryption.rs
+++ b/crates/hyperswitch_domain_models/src/type_encryption.rs
@@ -9,6 +9,7 @@ use common_utils::{
};
use encrypt::TypeEncryption;
use masking::Secret;
+use router_env::{instrument, tracing};
use rustc_hash::FxHashMap;
mod encrypt {
@@ -831,12 +832,12 @@ impl<U, V: Lift<U> + Lift<U, SelfWrapper<U> = V> + Send> AsyncLift<U> for V {
}
#[inline]
-pub async fn encrypt<E: Clone, S>(
+async fn encrypt<E: Clone, S>(
state: &KeyManagerState,
inner: Secret<E, S>,
identifier: Identifier,
key: &[u8],
-) -> CustomResult<crypto::Encryptable<Secret<E, S>>, errors::CryptoError>
+) -> CustomResult<crypto::Encryptable<Secret<E, S>>, CryptoError>
where
S: masking::Strategy<E>,
crypto::Encryptable<Secret<E, S>>: TypeEncryption<E, crypto::GcmAes256, S>,
@@ -851,12 +852,12 @@ where
}
#[inline]
-pub async fn batch_encrypt<E: Clone, S>(
+async fn batch_encrypt<E: Clone, S>(
state: &KeyManagerState,
inner: FxHashMap<String, Secret<E, S>>,
identifier: Identifier,
key: &[u8],
-) -> CustomResult<FxHashMap<String, crypto::Encryptable<Secret<E, S>>>, errors::CryptoError>
+) -> CustomResult<FxHashMap<String, crypto::Encryptable<Secret<E, S>>>, CryptoError>
where
S: masking::Strategy<E>,
crypto::Encryptable<Secret<E, S>>: TypeEncryption<E, crypto::GcmAes256, S>,
@@ -881,12 +882,12 @@ where
}
#[inline]
-pub async fn encrypt_optional<E: Clone, S>(
+async fn encrypt_optional<E: Clone, S>(
state: &KeyManagerState,
inner: Option<Secret<E, S>>,
identifier: Identifier,
key: &[u8],
-) -> CustomResult<Option<crypto::Encryptable<Secret<E, S>>>, errors::CryptoError>
+) -> CustomResult<Option<crypto::Encryptable<Secret<E, S>>>, CryptoError>
where
Secret<E, S>: Send,
S: masking::Strategy<E>,
@@ -899,12 +900,12 @@ where
}
#[inline]
-pub async fn decrypt_optional<T: Clone, S: masking::Strategy<T>>(
+async fn decrypt_optional<T: Clone, S: masking::Strategy<T>>(
state: &KeyManagerState,
inner: Option<Encryption>,
identifier: Identifier,
key: &[u8],
-) -> CustomResult<Option<crypto::Encryptable<Secret<T, S>>>, errors::CryptoError>
+) -> CustomResult<Option<crypto::Encryptable<Secret<T, S>>>, CryptoError>
where
crypto::Encryptable<Secret<T, S>>: TypeEncryption<T, crypto::GcmAes256, S>,
{
@@ -915,12 +916,12 @@ where
}
#[inline]
-pub async fn decrypt<T: Clone, S: masking::Strategy<T>>(
+async fn decrypt<T: Clone, S: masking::Strategy<T>>(
state: &KeyManagerState,
inner: Encryption,
identifier: Identifier,
key: &[u8],
-) -> CustomResult<crypto::Encryptable<Secret<T, S>>, errors::CryptoError>
+) -> CustomResult<crypto::Encryptable<Secret<T, S>>, CryptoError>
where
crypto::Encryptable<Secret<T, S>>: TypeEncryption<T, crypto::GcmAes256, S>,
{
@@ -934,12 +935,12 @@ where
}
#[inline]
-pub async fn batch_decrypt<E: Clone, S>(
+async fn batch_decrypt<E: Clone, S>(
state: &KeyManagerState,
inner: FxHashMap<String, Encryption>,
identifier: Identifier,
key: &[u8],
-) -> CustomResult<FxHashMap<String, crypto::Encryptable<Secret<E, S>>>, errors::CryptoError>
+) -> CustomResult<FxHashMap<String, crypto::Encryptable<Secret<E, S>>>, CryptoError>
where
S: masking::Strategy<E>,
crypto::Encryptable<Secret<E, S>>: TypeEncryption<E, crypto::GcmAes256, S>,
@@ -963,6 +964,65 @@ where
}
}
+pub enum CryptoOperation<T: Clone, S: masking::Strategy<T>> {
+ Encrypt(Secret<T, S>),
+ EncryptOptional(Option<Secret<T, S>>),
+ Decrypt(Encryption),
+ DecryptOptional(Option<Encryption>),
+ BatchEncrypt(FxHashMap<String, Secret<T, S>>),
+ BatchDecrypt(FxHashMap<String, Encryption>),
+}
+
+use errors::CryptoError;
+
+#[derive(router_derive::TryGetEnumVariant)]
+#[error(CryptoError::EncodingFailed)]
+pub enum CryptoOutput<T: Clone, S: masking::Strategy<T>> {
+ Operation(crypto::Encryptable<Secret<T, S>>),
+ OptionalOperation(Option<crypto::Encryptable<Secret<T, S>>>),
+ BatchOperation(FxHashMap<String, crypto::Encryptable<Secret<T, S>>>),
+}
+
+#[instrument(skip_all, fields(table = table_name))]
+pub async fn crypto_operation<T: Clone + Send, S: masking::Strategy<T>>(
+ state: &KeyManagerState,
+ table_name: &str,
+ operation: CryptoOperation<T, S>,
+ identifier: Identifier,
+ key: &[u8],
+) -> CustomResult<CryptoOutput<T, S>, CryptoError>
+where
+ Secret<T, S>: Send,
+ crypto::Encryptable<Secret<T, S>>: TypeEncryption<T, crypto::GcmAes256, S>,
+{
+ match operation {
+ CryptoOperation::Encrypt(data) => {
+ let data = encrypt(state, data, identifier, key).await?;
+ Ok(CryptoOutput::Operation(data))
+ }
+ CryptoOperation::EncryptOptional(data) => {
+ let data = encrypt_optional(state, data, identifier, key).await?;
+ Ok(CryptoOutput::OptionalOperation(data))
+ }
+ CryptoOperation::Decrypt(data) => {
+ let data = decrypt(state, data, identifier, key).await?;
+ Ok(CryptoOutput::Operation(data))
+ }
+ CryptoOperation::DecryptOptional(data) => {
+ let data = decrypt_optional(state, data, identifier, key).await?;
+ Ok(CryptoOutput::OptionalOperation(data))
+ }
+ CryptoOperation::BatchEncrypt(data) => {
+ let data = batch_encrypt(state, data, identifier, key).await?;
+ Ok(CryptoOutput::BatchOperation(data))
+ }
+ CryptoOperation::BatchDecrypt(data) => {
+ let data = batch_decrypt(state, data, identifier, key).await?;
+ Ok(CryptoOutput::BatchOperation(data))
+ }
+ }
+}
+
pub(crate) mod metrics {
use router_env::{counter_metric, global_meter, histogram_metric, metrics_context, once_cell};
diff --git a/crates/router/src/core/admin.rs b/crates/router/src/core/admin.rs
index 820a0a965c6..0761f2b0ad5 100644
--- a/crates/router/src/core/admin.rs
+++ b/crates/router/src/core/admin.rs
@@ -8,7 +8,7 @@ use base64::Engine;
use common_utils::{
date_time,
ext_traits::{AsyncExt, Encode, ValueExt},
- id_type, pii,
+ id_type, pii, type_name,
types::keymanager::{self as km_types, KeyManagerState},
};
use diesel_models::configs;
@@ -216,13 +216,15 @@ pub async fn create_merchant_account(
let key_store = domain::MerchantKeyStore {
merchant_id: merchant_id.clone(),
- key: domain_types::encrypt(
+ key: domain_types::crypto_operation(
key_manager_state,
- key.to_vec().into(),
+ type_name!(domain::MerchantKeyStore),
+ domain_types::CryptoOperation::Encrypt(key.to_vec().into()),
identifier.clone(),
master_key,
)
.await
+ .and_then(|val| val.try_into_operation())
.change_context(errors::ApiErrorResponse::InternalServerError)
.attach_printable("Failed to decrypt data from key store")?,
created_at: date_time::now(),
@@ -341,23 +343,29 @@ impl MerchantAccountCreateBridge for api::MerchantAccountCreate {
merchant_id: identifier.clone(),
merchant_name: self
.merchant_name
- .async_lift(|inner| {
- domain_types::encrypt_optional(
+ .async_lift(|inner| async {
+ domain_types::crypto_operation(
&key_manager_state,
- inner,
+ type_name!(domain::MerchantAccount),
+ domain_types::CryptoOperation::EncryptOptional(inner),
km_types::Identifier::Merchant(key_store.merchant_id.clone()),
key.peek(),
)
+ .await
+ .and_then(|val| val.try_into_optionaloperation())
})
.await?,
merchant_details: merchant_details
- .async_lift(|inner| {
- domain_types::encrypt_optional(
+ .async_lift(|inner| async {
+ domain_types::crypto_operation(
&key_manager_state,
- inner,
+ type_name!(domain::MerchantAccount),
+ domain_types::CryptoOperation::EncryptOptional(inner),
km_types::Identifier::Merchant(key_store.merchant_id.clone()),
key.peek(),
)
+ .await
+ .and_then(|val| val.try_into_optionaloperation())
})
.await?,
return_url: self.return_url.map(|a| a.to_string()),
@@ -646,23 +654,30 @@ impl MerchantAccountCreateBridge for api::MerchantAccountCreate {
domain::MerchantAccount::from(domain::MerchantAccountSetter {
id,
merchant_name: Some(
- domain_types::encrypt(
+ domain_types::crypto_operation(
&key_manager_state,
- self.merchant_name
- .map(|merchant_name| merchant_name.into_inner()),
+ type_name!(domain::MerchantAccount),
+ domain_types::CryptoOperation::Encrypt(
+ self.merchant_name
+ .map(|merchant_name| merchant_name.into_inner()),
+ ),
identifier.clone(),
key.peek(),
)
- .await?,
+ .await
+ .and_then(|val| val.try_into_operation())?,
),
merchant_details: merchant_details
- .async_lift(|inner| {
- domain_types::encrypt_optional(
+ .async_lift(|inner| async {
+ domain_types::crypto_operation(
&key_manager_state,
- inner,
+ type_name!(domain::MerchantAccount),
+ domain_types::CryptoOperation::EncryptOptional(inner),
identifier.clone(),
key.peek(),
)
+ .await
+ .and_then(|val| val.try_into_optionaloperation())
})
.await?,
routing_algorithm: Some(serde_json::json!({
@@ -918,25 +933,31 @@ impl MerchantAccountUpdateBridge for api::MerchantAccountUpdate {
merchant_name: self
.merchant_name
.map(Secret::new)
- .async_lift(|inner| {
- domain_types::encrypt_optional(
+ .async_lift(|inner| async {
+ domain_types::crypto_operation(
key_manager_state,
- inner,
+ type_name!(storage::MerchantAccount),
+ domain_types::CryptoOperation::EncryptOptional(inner),
identifier.clone(),
key,
)
+ .await
+ .and_then(|val| val.try_into_optionaloperation())
})
.await
.change_context(errors::ApiErrorResponse::InternalServerError)
.attach_printable("Unable to encrypt merchant name")?,
merchant_details: merchant_details
- .async_lift(|inner| {
- domain_types::encrypt_optional(
+ .async_lift(|inner| async {
+ domain_types::crypto_operation(
key_manager_state,
- inner,
+ type_name!(storage::MerchantAccount),
+ domain_types::CryptoOperation::EncryptOptional(inner),
km_types::Identifier::Merchant(key_store.merchant_id.clone()),
key,
)
+ .await
+ .and_then(|val| val.try_into_optionaloperation())
})
.await
.change_context(errors::ApiErrorResponse::InternalServerError)
@@ -2006,13 +2027,16 @@ impl MerchantConnectorAccountUpdateBridge for api_models::admin::MerchantConnect
connector_label: self.connector_label.clone(),
connector_account_details: self
.connector_account_details
- .async_lift(|inner| {
- domain_types::encrypt_optional(
+ .async_lift(|inner| async {
+ domain_types::crypto_operation(
key_manager_state,
- inner,
+ type_name!(storage::MerchantConnectorAccount),
+ domai_types::CryptoOperation::EncryptOptional(inner),
km_types::Identifier::Merchant(key_store.merchant_id.clone()),
key_store.key.get_inner().peek(),
)
+ .await
+ .and_then(|val| val.try_into_optionaloperation())
})
.await
.change_context(errors::ApiErrorResponse::InternalServerError)
@@ -2141,13 +2165,16 @@ impl MerchantConnectorAccountUpdateBridge for api_models::admin::MerchantConnect
connector_label: self.connector_label.clone(),
connector_account_details: self
.connector_account_details
- .async_lift(|inner| {
- domain_types::encrypt_optional(
+ .async_lift(|inner| async {
+ domain_types::crypto_operation(
key_manager_state,
- inner,
+ type_name!(storage::MerchantConnectorAccount),
+ domain_types::CryptoOperation::EncryptOptional(inner),
km_types::Identifier::Merchant(key_store.merchant_id.clone()),
key_store.key.get_inner().peek(),
)
+ .await
+ .and_then(|val| val.try_into_optionaloperation())
})
.await
.change_context(errors::ApiErrorResponse::InternalServerError)
@@ -2268,17 +2295,19 @@ impl MerchantConnectorAccountCreateBridge for api::MerchantConnectorCreate {
merchant_id: business_profile.merchant_id.clone(),
connector_type: self.connector_type,
connector_name: self.connector_name.to_string(),
- connector_account_details: domain_types::encrypt(
+ connector_account_details: domain_types::crypto_operation(
key_manager_state,
- self.connector_account_details.ok_or(
+ type_name!(domain::MerchantConnectorAccount),
+ domain_types::CryptoOperation::Encrypt(self.connector_account_details.ok_or(
errors::ApiErrorResponse::MissingRequiredField {
field_name: "connector_account_details",
},
- )?,
+ )?),
identifier.clone(),
key_store.key.peek(),
)
.await
+ .and_then(|val| val.try_into_operation())
.change_context(errors::ApiErrorResponse::InternalServerError)
.attach_printable("Unable to encrypt connector account details")?,
payment_methods_enabled,
@@ -2306,13 +2335,15 @@ impl MerchantConnectorAccountCreateBridge for api::MerchantConnectorCreate {
status: connector_status,
connector_wallets_details: helpers::get_encrypted_apple_pay_connector_wallets_details(state, &key_store, &self.metadata).await?,
additional_merchant_data: if let Some(mcd) = merchant_recipient_data {
- Some(domain_types::encrypt(
+ Some(domain_types::crypto_operation(
key_manager_state,
- Secret::new(mcd),
+ type_name!(domain::MerchantConnectorAccount),
+ domain_types::CryptoOperation::Encrypt(Secret::new(mcd)),
identifier,
key_store.key.peek(),
)
.await
+ .and_then(|val| val.try_into_operation())
.change_context(errors::ApiErrorResponse::InternalServerError)
.attach_printable("Unable to encrypt additional_merchant_data")?)
} else {
@@ -2434,17 +2465,19 @@ impl MerchantConnectorAccountCreateBridge for api::MerchantConnectorCreate {
connector_type: self.connector_type,
connector_name: self.connector_name.to_string(),
merchant_connector_id: utils::generate_id(consts::ID_LENGTH, "mca"),
- connector_account_details: domain_types::encrypt(
+ connector_account_details: domain_types::crypto_operation(
key_manager_state,
- self.connector_account_details.ok_or(
+ type_name!(domain::MerchantConnectorAccount),
+ domain_types::CryptoOperation::Encrypt(self.connector_account_details.ok_or(
errors::ApiErrorResponse::MissingRequiredField {
field_name: "connector_account_details",
},
- )?,
+ )?),
identifier.clone(),
key_store.key.peek(),
)
.await
+ .and_then(|val| val.try_into_operation())
.change_context(errors::ApiErrorResponse::InternalServerError)
.attach_printable("Unable to encrypt connector account details")?,
payment_methods_enabled,
@@ -2475,13 +2508,15 @@ impl MerchantConnectorAccountCreateBridge for api::MerchantConnectorCreate {
business_label: self.business_label.clone(),
business_sub_label: self.business_sub_label.clone(),
additional_merchant_data: if let Some(mcd) = merchant_recipient_data {
- Some(domain_types::encrypt(
+ Some(domain_types::crypto_operation(
key_manager_state,
- Secret::new(mcd),
+ type_name!(domain::MerchantConnectorAccount),
+ domain_types::CryptoOperation::Encrypt(Secret::new(mcd)),
identifier,
key_store.key.peek(),
)
.await
+ .and_then(|val| val.try_into_operation())
.change_context(errors::ApiErrorResponse::InternalServerError)
.attach_printable("Unable to encrypt additional_merchant_data")?)
} else {
diff --git a/crates/router/src/core/apple_pay_certificates_migration.rs b/crates/router/src/core/apple_pay_certificates_migration.rs
index 8fe61f75ca2..44be8f33bbe 100644
--- a/crates/router/src/core/apple_pay_certificates_migration.rs
+++ b/crates/router/src/core/apple_pay_certificates_migration.rs
@@ -1,5 +1,5 @@
use api_models::apple_pay_certificates_migration;
-use common_utils::{errors::CustomResult, types::keymanager::Identifier};
+use common_utils::{errors::CustomResult, type_name, types::keymanager::Identifier};
use error_stack::ResultExt;
use masking::{PeekInterface, Secret};
@@ -64,17 +64,19 @@ pub async fn apple_pay_certificates_migration(
})
.ok();
if let Some(apple_pay_metadata) = connector_apple_pay_metadata {
- let encrypted_apple_pay_metadata = domain_types::encrypt(
+ let encrypted_apple_pay_metadata = domain_types::crypto_operation(
&(&state).into(),
- Secret::new(
+ type_name!(storage::MerchantConnectorAccount),
+ domain_types::CryptoOperation::Encrypt(Secret::new(
serde_json::to_value(apple_pay_metadata)
.change_context(errors::ApiErrorResponse::InternalServerError)
.attach_printable("Failed to serialize apple pay metadata as JSON")?,
- ),
+ )),
Identifier::Merchant(merchant_id.clone()),
key_store.key.get_inner().peek(),
)
.await
+ .and_then(|val| val.try_into_operation())
.change_context(errors::ApiErrorResponse::InternalServerError)
.attach_printable("Unable to encrypt connector apple pay metadata")?;
diff --git a/crates/router/src/core/customers.rs b/crates/router/src/core/customers.rs
index 73368cba0e4..69bf4052d70 100644
--- a/crates/router/src/core/customers.rs
+++ b/crates/router/src/core/customers.rs
@@ -4,13 +4,11 @@ use common_utils::{crypto::Encryptable, ext_traits::OptionExt, types::Descriptio
use common_utils::{
errors::ReportSwitchExt,
ext_traits::AsyncExt,
- id_type,
+ id_type, type_name,
types::keymanager::{Identifier, KeyManagerState, ToEncryptable},
};
use error_stack::{report, ResultExt};
#[cfg(all(any(feature = "v1", feature = "v2"), not(feature = "customer_v2")))]
-use hyperswitch_domain_models::type_encryption::encrypt;
-#[cfg(all(any(feature = "v1", feature = "v2"), not(feature = "customer_v2")))]
use masking::{Secret, SwitchStrategy};
use router_env::{instrument, tracing};
@@ -145,17 +143,21 @@ impl CustomerCreateBridge for customers::CustomerRequest {
.encrypt_customer_address_and_set_to_db(db)
.await?;
- let encrypted_data = types::batch_encrypt(
+ let encrypted_data = types::crypto_operation(
key_manager_state,
- CustomerRequestWithEmail::to_encryptable(CustomerRequestWithEmail {
- name: self.name.clone(),
- email: self.email.clone(),
- phone: self.phone.clone(),
- }),
+ type_name!(domain::Customer),
+ types::CryptoOperation::BatchEncrypt(CustomerRequestWithEmail::to_encryptable(
+ CustomerRequestWithEmail {
+ name: self.name.clone(),
+ email: self.email.clone(),
+ phone: self.phone.clone(),
+ },
+ )),
Identifier::Merchant(key_store.merchant_id.clone()),
key,
)
.await
+ .and_then(|val| val.try_into_batchoperation())
.switch()
.attach_printable("Failed while encrypting Customer")?;
@@ -227,17 +229,21 @@ impl CustomerCreateBridge for customers::CustomerRequest {
let merchant_id = merchant_account.get_id().clone();
let key = key_store.key.get_inner().peek();
- let encrypted_data = types::batch_encrypt(
+ let encrypted_data = types::crypto_operation(
key_state,
- CustomerRequestWithEmail::to_encryptable(CustomerRequestWithEmail {
- name: Some(self.name.clone()),
- email: Some(self.email.clone()),
- phone: self.phone.clone(),
- }),
+ type_name!(domain::Customer),
+ types::CryptoOperation::BatchEncrypt(CustomerRequestWithEmail::to_encryptable(
+ CustomerRequestWithEmail {
+ name: Some(self.name.clone()),
+ email: Some(self.email.clone()),
+ phone: self.phone.clone(),
+ },
+ )),
Identifier::Merchant(key_store.merchant_id.clone()),
key,
)
.await
+ .and_then(|val| val.try_into_batchoperation())
.switch()
.attach_printable("Failed while encrypting Customer")?;
@@ -508,13 +514,15 @@ pub async fn delete_customer(
let key = key_store.key.get_inner().peek();
let identifier = Identifier::Merchant(key_store.merchant_id.clone());
- let redacted_encrypted_value: Encryptable<Secret<_>> = encrypt(
+ let redacted_encrypted_value: Encryptable<Secret<_>> = types::crypto_operation(
key_manager_state,
- REDACTED.to_string().into(),
+ type_name!(storage::Address),
+ types::CryptoOperation::Encrypt(REDACTED.to_string().into()),
identifier.clone(),
key,
)
.await
+ .and_then(|val| val.try_into_operation())
.switch()?;
let redacted_encrypted_email = Encryptable::new(
@@ -566,13 +574,15 @@ pub async fn delete_customer(
let updated_customer = storage::CustomerUpdate::Update {
name: Some(redacted_encrypted_value.clone()),
email: Some(
- encrypt(
+ types::crypto_operation(
key_manager_state,
- REDACTED.to_string().into(),
+ type_name!(storage::Customer),
+ types::CryptoOperation::Encrypt(REDACTED.to_string().into()),
identifier,
key,
)
.await
+ .and_then(|val| val.try_into_operation())
.switch()?,
),
phone: Box::new(Some(redacted_encrypted_value.clone())),
@@ -697,17 +707,21 @@ pub async fn update_customer(
None => None,
}
};
- let encrypted_data = types::batch_encrypt(
+ let encrypted_data = types::crypto_operation(
&(&state).into(),
- CustomerRequestWithEmail::to_encryptable(CustomerRequestWithEmail {
- name: update_customer.name.clone(),
- email: update_customer.email.clone(),
- phone: update_customer.phone.clone(),
- }),
+ type_name!(domain::Customer),
+ types::CryptoOperation::BatchEncrypt(CustomerRequestWithEmail::to_encryptable(
+ CustomerRequestWithEmail {
+ name: update_customer.name.clone(),
+ email: update_customer.email.clone(),
+ phone: update_customer.phone.clone(),
+ },
+ )),
Identifier::Merchant(key_store.merchant_id.clone()),
key,
)
.await
+ .and_then(|val| val.try_into_batchoperation())
.switch()?;
let encryptable_customer = CustomerRequestWithEmail::from_encryptable(encrypted_data)
.change_context(errors::CustomersErrorResponse::InternalServerError)?;
diff --git a/crates/router/src/core/payment_methods/cards.rs b/crates/router/src/core/payment_methods/cards.rs
index a7a240339ee..9f13530fbd5 100644
--- a/crates/router/src/core/payment_methods/cards.rs
+++ b/crates/router/src/core/payment_methods/cards.rs
@@ -25,7 +25,7 @@ use common_utils::{
crypto::Encryptable,
encryption::Encryption,
ext_traits::{AsyncExt, Encode, StringExt, ValueExt},
- generate_id, id_type,
+ generate_id, id_type, type_name,
types::{
keymanager::{Identifier, KeyManagerState},
MinorUnit,
@@ -76,7 +76,7 @@ use crate::{
services,
types::{
api::{self, routing as routing_types, PaymentMethodCreateExt},
- domain::{self, types::decrypt_optional},
+ domain,
storage::{self, enums, PaymentMethodListContext, PaymentTokenData},
transformers::{ForeignFrom, ForeignTryFrom},
},
@@ -1219,13 +1219,18 @@ pub async fn update_customer_payment_method(
}
// Fetch the existing payment method data from db
- let existing_card_data = decrypt_optional::<serde_json::Value, masking::WithType>(
+ let existing_card_data = domain::types::crypto_operation::<
+ serde_json::Value,
+ masking::WithType,
+ >(
&(&state).into(),
- pm.payment_method_data.clone(),
+ type_name!(payment_method::PaymentMethod),
+ domain::types::CryptoOperation::DecryptOptional(pm.payment_method_data.clone()),
Identifier::Merchant(key_store.merchant_id.clone()),
key_store.key.get_inner().peek(),
)
.await
+ .and_then(|val| val.try_into_optionaloperation())
.change_context(errors::ApiErrorResponse::InternalServerError)
.attach_printable("Failed to decrypt card details")?
.map(|x| x.into_inner().expose())
@@ -1479,13 +1484,16 @@ pub async fn add_bank_to_locker(
let secret: Secret<String> = Secret::new(v.to_string());
secret
})
- .async_lift(|inner| {
- domain::types::encrypt_optional(
+ .async_lift(|inner| async {
+ domain::types::crypto_operation(
&key_manager_state,
- inner,
+ type_name!(payment_method::PaymentMethod),
+ domain::types::CryptoOperation::EncryptOptional(inner),
Identifier::Merchant(key_store.merchant_id.clone()),
key,
)
+ .await
+ .and_then(|val| val.try_into_optionaloperation())
})
.await
}
@@ -1693,13 +1701,17 @@ pub async fn decode_and_decrypt_locker_data(
.change_context(errors::VaultError::ResponseDeserializationFailed)
.attach_printable("Failed to decode hex string into bytes")?;
// Decrypt
- decrypt_optional(
+ domain::types::crypto_operation(
&state.into(),
- Some(Encryption::new(decoded_bytes.into())),
+ type_name!(payment_method::PaymentMethod),
+ domain::types::CryptoOperation::DecryptOptional(Some(Encryption::new(
+ decoded_bytes.into(),
+ ))),
Identifier::Merchant(key_store.merchant_id.clone()),
key,
)
.await
+ .and_then(|val| val.try_into_optionaloperation())
.change_context(errors::VaultError::FetchPaymentMethodFailed)?
.map_or(
Err(report!(errors::VaultError::FetchPaymentMethodFailed)),
@@ -4505,13 +4517,15 @@ where
{
let key = key_store.key.get_inner().peek();
let identifier = Identifier::Merchant(key_store.merchant_id.clone());
- let decrypted_data = decrypt_optional::<serde_json::Value, masking::WithType>(
+ let decrypted_data = domain::types::crypto_operation::<serde_json::Value, masking::WithType>(
&state.into(),
- data,
+ type_name!(T),
+ domain::types::CryptoOperation::DecryptOptional(data),
identifier,
key,
)
.await
+ .and_then(|val| val.try_into_optionaloperation())
.change_context(errors::StorageError::DecryptionError)
.change_context(errors::ApiErrorResponse::InternalServerError)
.attach_printable("unable to decrypt data")?;
@@ -4531,13 +4545,15 @@ pub async fn get_card_details_with_locker_fallback(
) -> errors::RouterResult<Option<api::CardDetailFromLocker>> {
let key = key_store.key.get_inner().peek();
let identifier = Identifier::Merchant(key_store.merchant_id.clone());
- let card_decrypted = decrypt_optional::<serde_json::Value, masking::WithType>(
+ let card_decrypted = domain::types::crypto_operation::<serde_json::Value, masking::WithType>(
&state.into(),
- pm.payment_method_data.clone(),
+ type_name!(payment_method::PaymentMethod),
+ domain::types::CryptoOperation::DecryptOptional(pm.payment_method_data.clone()),
identifier,
key,
)
.await
+ .and_then(|val| val.try_into_optionaloperation())
.change_context(errors::StorageError::DecryptionError)
.attach_printable("unable to decrypt card details")
.ok()
@@ -4567,13 +4583,15 @@ pub async fn get_card_details_without_locker_fallback(
) -> errors::RouterResult<api::CardDetailFromLocker> {
let key = key_store.key.get_inner().peek();
let identifier = Identifier::Merchant(key_store.merchant_id.clone());
- let card_decrypted = decrypt_optional::<serde_json::Value, masking::WithType>(
+ let card_decrypted = domain::types::crypto_operation::<serde_json::Value, masking::WithType>(
&state.into(),
- pm.payment_method_data.clone(),
+ type_name!(payment_method::PaymentMethod),
+ domain::types::CryptoOperation::DecryptOptional(pm.payment_method_data.clone()),
identifier,
key,
)
.await
+ .and_then(|val| val.try_into_optionaloperation())
.change_context(errors::StorageError::DecryptionError)
.attach_printable("unable to decrypt card details")
.ok()
@@ -4642,26 +4660,29 @@ async fn get_masked_bank_details(
) -> errors::RouterResult<Option<MaskedBankDetails>> {
let key = key_store.key.get_inner().peek();
let identifier = Identifier::Merchant(key_store.merchant_id.clone());
- let payment_method_data = decrypt_optional::<serde_json::Value, masking::WithType>(
- &state.into(),
- pm.payment_method_data.clone(),
- identifier,
- key,
- )
- .await
- .change_context(errors::StorageError::DecryptionError)
- .change_context(errors::ApiErrorResponse::InternalServerError)
- .attach_printable("unable to decrypt bank details")?
- .map(|x| x.into_inner().expose())
- .map(
- |v| -> Result<PaymentMethodsData, error_stack::Report<errors::ApiErrorResponse>> {
- v.parse_value::<PaymentMethodsData>("PaymentMethodsData")
- .change_context(errors::StorageError::DeserializationFailed)
- .change_context(errors::ApiErrorResponse::InternalServerError)
- .attach_printable("Failed to deserialize Payment Method Auth config")
- },
- )
- .transpose()?;
+ let payment_method_data =
+ domain::types::crypto_operation::<serde_json::Value, masking::WithType>(
+ &state.into(),
+ type_name!(payment_method::PaymentMethod),
+ domain::types::CryptoOperation::DecryptOptional(pm.payment_method_data.clone()),
+ identifier,
+ key,
+ )
+ .await
+ .and_then(|val| val.try_into_optionaloperation())
+ .change_context(errors::StorageError::DecryptionError)
+ .change_context(errors::ApiErrorResponse::InternalServerError)
+ .attach_printable("unable to decrypt bank details")?
+ .map(|x| x.into_inner().expose())
+ .map(
+ |v| -> Result<PaymentMethodsData, error_stack::Report<errors::ApiErrorResponse>> {
+ v.parse_value::<PaymentMethodsData>("PaymentMethodsData")
+ .change_context(errors::StorageError::DeserializationFailed)
+ .change_context(errors::ApiErrorResponse::InternalServerError)
+ .attach_printable("Failed to deserialize Payment Method Auth config")
+ },
+ )
+ .transpose()?;
match payment_method_data {
Some(pmd) => match pmd {
@@ -4682,26 +4703,29 @@ async fn get_bank_account_connector_details(
) -> errors::RouterResult<Option<BankAccountTokenData>> {
let key = key_store.key.get_inner().peek();
let identifier = Identifier::Merchant(key_store.merchant_id.clone());
- let payment_method_data = decrypt_optional::<serde_json::Value, masking::WithType>(
- &state.into(),
- pm.payment_method_data.clone(),
- identifier,
- key,
- )
- .await
- .change_context(errors::StorageError::DecryptionError)
- .change_context(errors::ApiErrorResponse::InternalServerError)
- .attach_printable("unable to decrypt bank details")?
- .map(|x| x.into_inner().expose())
- .map(
- |v| -> Result<PaymentMethodsData, error_stack::Report<errors::ApiErrorResponse>> {
- v.parse_value::<PaymentMethodsData>("PaymentMethodsData")
- .change_context(errors::StorageError::DeserializationFailed)
- .change_context(errors::ApiErrorResponse::InternalServerError)
- .attach_printable("Failed to deserialize Payment Method Auth config")
- },
- )
- .transpose()?;
+ let payment_method_data =
+ domain::types::crypto_operation::<serde_json::Value, masking::WithType>(
+ &state.into(),
+ type_name!(payment_method::PaymentMethod),
+ domain::types::CryptoOperation::DecryptOptional(pm.payment_method_data.clone()),
+ identifier,
+ key,
+ )
+ .await
+ .and_then(|val| val.try_into_optionaloperation())
+ .change_context(errors::StorageError::DecryptionError)
+ .change_context(errors::ApiErrorResponse::InternalServerError)
+ .attach_printable("unable to decrypt bank details")?
+ .map(|x| x.into_inner().expose())
+ .map(
+ |v| -> Result<PaymentMethodsData, error_stack::Report<errors::ApiErrorResponse>> {
+ v.parse_value::<PaymentMethodsData>("PaymentMethodsData")
+ .change_context(errors::StorageError::DeserializationFailed)
+ .change_context(errors::ApiErrorResponse::InternalServerError)
+ .attach_printable("Failed to deserialize Payment Method Auth config")
+ },
+ )
+ .transpose()?;
match payment_method_data {
Some(pmd) => match pmd {
@@ -5125,11 +5149,17 @@ where
let secret_data = Secret::<_, masking::WithType>::new(encoded_data);
- let encrypted_data =
- domain::types::encrypt(&key_manager_state, secret_data, identifier.clone(), key)
- .await
- .change_context(errors::StorageError::EncryptionError)
- .attach_printable("Unable to encrypt data")?;
+ let encrypted_data = domain::types::crypto_operation(
+ &key_manager_state,
+ type_name!(payment_method::PaymentMethod),
+ domain::types::CryptoOperation::Encrypt(secret_data),
+ identifier.clone(),
+ key,
+ )
+ .await
+ .and_then(|val| val.try_into_operation())
+ .change_context(errors::StorageError::EncryptionError)
+ .attach_printable("Unable to encrypt data")?;
Ok(encrypted_data)
}
diff --git a/crates/router/src/core/payments/helpers.rs b/crates/router/src/core/payments/helpers.rs
index 6b39ec672e4..c3f7b25b0c9 100644
--- a/crates/router/src/core/payments/helpers.rs
+++ b/crates/router/src/core/payments/helpers.rs
@@ -11,7 +11,7 @@ use common_enums::ConnectorType;
use common_utils::{
crypto::Encryptable,
ext_traits::{AsyncExt, ByteSliceExt, Encode, ValueExt},
- fp_utils, generate_id, id_type, pii,
+ fp_utils, generate_id, id_type, pii, type_name,
types::{
keymanager::{Identifier, KeyManagerState, ToEncryptable},
MinorUnit,
@@ -166,20 +166,24 @@ pub async fn create_or_update_address_for_payment_by_request(
Ok(match address_id {
Some(id) => match req_address {
Some(address) => {
- let encrypted_data = types::batch_encrypt(
+ let encrypted_data = types::crypto_operation(
&session_state.into(),
- AddressDetailsWithPhone::to_encryptable(AddressDetailsWithPhone {
- address: address.address.clone(),
- phone_number: address
- .phone
- .as_ref()
- .and_then(|phone| phone.number.clone()),
- email: address.email.clone(),
- }),
+ type_name!(domain::Address),
+ types::CryptoOperation::BatchEncrypt(AddressDetailsWithPhone::to_encryptable(
+ AddressDetailsWithPhone {
+ address: address.address.clone(),
+ phone_number: address
+ .phone
+ .as_ref()
+ .and_then(|phone| phone.number.clone()),
+ email: address.email.clone(),
+ },
+ )),
Identifier::Merchant(merchant_key_store.merchant_id.clone()),
key,
)
.await
+ .and_then(|val| val.try_into_batchoperation())
.change_context(errors::ApiErrorResponse::InternalServerError)
.attach_printable("Failed while encrypting address")?;
let encryptable_address = AddressDetailsWithPhone::from_encryptable(encrypted_data)
@@ -353,20 +357,24 @@ pub async fn get_domain_address(
) -> CustomResult<domain::Address, common_utils::errors::CryptoError> {
async {
let address_details = &address.address.as_ref();
- let encrypted_data = types::batch_encrypt(
+ let encrypted_data = types::crypto_operation(
&session_state.into(),
- AddressDetailsWithPhone::to_encryptable(AddressDetailsWithPhone {
- address: address_details.cloned(),
- phone_number: address
- .phone
- .as_ref()
- .and_then(|phone| phone.number.clone()),
- email: address.email.clone(),
- }),
+ type_name!(domain::Address),
+ types::CryptoOperation::BatchEncrypt(AddressDetailsWithPhone::to_encryptable(
+ AddressDetailsWithPhone {
+ address: address_details.cloned(),
+ phone_number: address
+ .phone
+ .as_ref()
+ .and_then(|phone| phone.number.clone()),
+ email: address.email.clone(),
+ },
+ )),
Identifier::Merchant(merchant_id.to_owned()),
key,
)
- .await?;
+ .await
+ .and_then(|val| val.try_into_batchoperation())?;
let encryptable_address = AddressDetailsWithPhone::from_encryptable(encrypted_data)
.change_context(common_utils::errors::CryptoError::EncodingFailed)?;
Ok(domain::Address {
@@ -1645,17 +1653,21 @@ pub async fn create_customer_if_not_exist<'a, F: Clone, R>(
)
.await?;
let key = key_store.key.get_inner().peek();
- let encrypted_data = types::batch_encrypt(
+ let encrypted_data = types::crypto_operation(
key_manager_state,
- CustomerRequestWithEmail::to_encryptable(CustomerRequestWithEmail {
- name: request_customer_details.name.clone(),
- email: request_customer_details.email.clone(),
- phone: request_customer_details.phone.clone(),
- }),
+ type_name!(domain::Customer),
+ types::CryptoOperation::BatchEncrypt(CustomerRequestWithEmail::to_encryptable(
+ CustomerRequestWithEmail {
+ name: request_customer_details.name.clone(),
+ email: request_customer_details.email.clone(),
+ phone: request_customer_details.phone.clone(),
+ },
+ )),
Identifier::Merchant(key_store.merchant_id.clone()),
key,
)
.await
+ .and_then(|val| val.try_into_batchoperation())
.change_context(errors::StorageError::SerializationFailed)
.attach_printable("Failed while encrypting Customer while Update")?;
let encryptable_customer = CustomerRequestWithEmail::from_encryptable(encrypted_data)
@@ -4186,13 +4198,16 @@ pub async fn get_encrypted_apple_pay_connector_wallets_details(
.map(masking::Secret::new);
let key_manager_state: KeyManagerState = state.into();
let encrypted_connector_apple_pay_details = connector_apple_pay_details
- .async_lift(|wallets_details| {
- types::encrypt_optional(
+ .async_lift(|wallets_details| async {
+ types::crypto_operation(
&key_manager_state,
- wallets_details,
+ type_name!(domain::MerchantConnectorAccount),
+ types::CryptoOperation::EncryptOptional(wallets_details),
Identifier::Merchant(key_store.merchant_id.clone()),
key_store.key.get_inner().peek(),
)
+ .await
+ .and_then(|val| val.try_into_optionaloperation())
})
.await
.change_context(errors::ApiErrorResponse::InternalServerError)
diff --git a/crates/router/src/core/payments/operations/payment_confirm.rs b/crates/router/src/core/payments/operations/payment_confirm.rs
index 318a2e0373b..ed3e4b2c235 100644
--- a/crates/router/src/core/payments/operations/payment_confirm.rs
+++ b/crates/router/src/core/payments/operations/payment_confirm.rs
@@ -9,6 +9,7 @@ use api_models::{
use async_trait::async_trait;
use common_utils::{
ext_traits::{AsyncExt, Encode, StringExt, ValueExt},
+ type_name,
types::keymanager::Identifier,
};
use error_stack::{report, ResultExt};
@@ -39,7 +40,10 @@ use crate::{
types::{
self,
api::{self, ConnectorCallType, PaymentIdTypeExt},
- domain::{self, types::decrypt_optional},
+ domain::{
+ self,
+ types::{crypto_operation, CryptoOperation},
+ },
storage::{self, enums as storage_enums},
},
utils::{self, OptionExt},
@@ -1084,13 +1088,15 @@ impl<F: Clone> UpdateTracker<F, PaymentData<F>, api::PaymentsRequest> for Paymen
let key = key_store.key.get_inner().peek();
let card_detail_from_locker: Option<api::CardDetailFromLocker> =
- decrypt_optional::<serde_json::Value, masking::WithType>(
+ crypto_operation::<serde_json::Value, masking::WithType>(
key_manager_state,
- pm.payment_method_data.clone(),
+ type_name!(storage::PaymentMethod),
+ CryptoOperation::DecryptOptional(pm.payment_method_data.clone()),
Identifier::Merchant(key_store.merchant_id.clone()),
key,
)
.await
+ .and_then(|val| val.try_into_optionaloperation())
.change_context(errors::StorageError::DecryptionError)
.attach_printable("unable to decrypt card details")
.ok()
diff --git a/crates/router/src/core/payments/operations/payment_create.rs b/crates/router/src/core/payments/operations/payment_create.rs
index 94eddff25d4..4e45b184ed0 100644
--- a/crates/router/src/core/payments/operations/payment_create.rs
+++ b/crates/router/src/core/payments/operations/payment_create.rs
@@ -6,6 +6,7 @@ use api_models::{
use async_trait::async_trait;
use common_utils::{
ext_traits::{AsyncExt, Encode, ValueExt},
+ type_name,
types::{keymanager::Identifier, MinorUnit},
};
use diesel_models::{ephemeral_key, PaymentMethod};
@@ -13,7 +14,7 @@ use error_stack::{self, ResultExt};
use hyperswitch_domain_models::{
mandates::{MandateData, MandateDetails},
payments::{payment_attempt::PaymentAttempt, payment_intent::CustomerData},
- type_encryption::decrypt_optional,
+ type_encryption::{crypto_operation, CryptoOperation},
};
use masking::{ExposeInterface, PeekInterface, Secret};
use router_derive::PaymentOperation;
@@ -865,13 +866,15 @@ impl PaymentCreate {
additional_pm_data = payment_method_info
.as_ref()
.async_map(|pm_info| async {
- decrypt_optional::<serde_json::Value, masking::WithType>(
+ crypto_operation::<serde_json::Value, masking::WithType>(
&state.into(),
- pm_info.payment_method_data.clone(),
+ type_name!(PaymentMethod),
+ CryptoOperation::DecryptOptional(pm_info.payment_method_data.clone()),
Identifier::Merchant(key_store.merchant_id.clone()),
key_store.key.get_inner().peek(),
)
.await
+ .and_then(|val| val.try_into_optionaloperation())
.map_err(|err| logger::error!("Failed to decrypt card details: {:?}", err))
.ok()
.flatten()
diff --git a/crates/router/src/core/payouts/helpers.rs b/crates/router/src/core/payouts/helpers.rs
index c4010490c20..6b0f2026472 100644
--- a/crates/router/src/core/payouts/helpers.rs
+++ b/crates/router/src/core/payouts/helpers.rs
@@ -5,7 +5,7 @@ use common_utils::{
encryption::Encryption,
errors::CustomResult,
ext_traits::{AsyncExt, StringExt},
- fp_utils, id_type,
+ fp_utils, id_type, type_name,
types::{
keymanager::{Identifier, KeyManagerState},
MinorUnit,
@@ -15,7 +15,7 @@ use common_utils::{
use common_utils::{generate_customer_id_of_default_length, types::keymanager::ToEncryptable};
use error_stack::{report, ResultExt};
#[cfg(all(any(feature = "v1", feature = "v2"), not(feature = "customer_v2")))]
-use hyperswitch_domain_models::type_encryption::batch_encrypt;
+use hyperswitch_domain_models::type_encryption::{crypto_operation, CryptoOperation};
use masking::{PeekInterface, Secret};
use router_env::logger;
@@ -39,10 +39,7 @@ use crate::{
services,
types::{
api::{self, enums as api_enums},
- domain::{
- self,
- types::{self as domain_types, AsyncLift},
- },
+ domain::{self, types::AsyncLift},
storage,
transformers::ForeignFrom,
},
@@ -252,13 +249,16 @@ pub async fn save_payout_data_to_locker(
let secret: Secret<String> = Secret::new(v.to_string());
secret
})
- .async_lift(|inner| {
- domain_types::encrypt_optional(
+ .async_lift(|inner| async {
+ crypto_operation(
&key_manager_state,
- inner,
+ type_name!(storage::PaymentMethod),
+ CryptoOperation::EncryptOptional(inner),
Identifier::Merchant(key_store.merchant_id.clone()),
key,
)
+ .await
+ .and_then(|val| val.try_into_optionaloperation())
})
.await
}
@@ -644,17 +644,21 @@ pub async fn get_or_create_customer_details(
{
Some(customer) => Ok(Some(customer)),
None => {
- let encrypted_data = batch_encrypt(
+ let encrypted_data = crypto_operation(
&state.into(),
- CustomerRequestWithEmail::to_encryptable(CustomerRequestWithEmail {
- name: customer_details.name.clone(),
- email: customer_details.email.clone(),
- phone: customer_details.phone.clone(),
- }),
+ type_name!(domain::Customer),
+ CryptoOperation::BatchEncrypt(CustomerRequestWithEmail::to_encryptable(
+ CustomerRequestWithEmail {
+ name: customer_details.name.clone(),
+ email: customer_details.email.clone(),
+ phone: customer_details.phone.clone(),
+ },
+ )),
Identifier::Merchant(key_store.merchant_id.clone()),
key,
)
.await
+ .and_then(|val| val.try_into_batchoperation())
.change_context(errors::ApiErrorResponse::InternalServerError)?;
let encryptable_customer =
CustomerRequestWithEmail::from_encryptable(encrypted_data)
diff --git a/crates/router/src/core/pm_auth.rs b/crates/router/src/core/pm_auth.rs
index 8d237da5ed5..fae690732e0 100644
--- a/crates/router/src/core/pm_auth.rs
+++ b/crates/router/src/core/pm_auth.rs
@@ -14,7 +14,7 @@ use common_utils::{
consts,
crypto::{HmacSha256, SignMessage},
ext_traits::AsyncExt,
- generate_id,
+ generate_id, type_name,
types::{self as util_types, keymanager::Identifier, AmountConvertor},
};
use error_stack::ResultExt;
@@ -45,7 +45,7 @@ use crate::{
services::{pm_auth as pm_auth_services, ApplicationResponse},
types::{
self,
- domain::{self, types::decrypt_optional},
+ domain::{self, types::crypto_operation},
storage,
transformers::ForeignTryFrom,
},
@@ -349,13 +349,15 @@ async fn store_bank_details_in_payment_methods(
for pm in payment_methods {
if pm.payment_method == Some(enums::PaymentMethod::BankDebit) {
- let bank_details_pm_data = decrypt_optional::<serde_json::Value, masking::WithType>(
+ let bank_details_pm_data = crypto_operation::<serde_json::Value, masking::WithType>(
&(&state).into(),
- pm.payment_method_data.clone(),
+ type_name!(storage::PaymentMethod),
+ domain::types::CryptoOperation::DecryptOptional(pm.payment_method_data.clone()),
Identifier::Merchant(key_store.merchant_id.clone()),
key,
)
.await
+ .and_then(|val| val.try_into_optionaloperation())
.change_context(ApiErrorResponse::InternalServerError)
.attach_printable("unable to decrypt bank account details")?
.map(|x| x.into_inner().expose())
diff --git a/crates/router/src/core/user.rs b/crates/router/src/core/user.rs
index 457a71dff8b..042e2c19e7c 100644
--- a/crates/router/src/core/user.rs
+++ b/crates/router/src/core/user.rs
@@ -4,7 +4,7 @@ use api_models::{
payments::RedirectionResponse,
user::{self as user_api, InviteMultipleUserResponse},
};
-use common_utils::types::keymanager::Identifier;
+use common_utils::{type_name, types::keymanager::Identifier};
#[cfg(feature = "email")]
use diesel_models::user_role::UserRoleUpdate;
use diesel_models::{
@@ -1929,13 +1929,15 @@ pub async fn update_totp(
totp_status: None,
totp_secret: Some(
// TODO: Impl conversion trait for User and move this there
- domain::types::encrypt::<String, masking::WithType>(
+ domain::types::crypto_operation::<String, masking::WithType>(
&(&state).into(),
- totp.get_secret_base32().into(),
+ type_name!(storage_user::User),
+ domain::types::CryptoOperation::Encrypt(totp.get_secret_base32().into()),
Identifier::User(key_store.user_id.clone()),
key_store.key.peek(),
)
.await
+ .and_then(|val| val.try_into_operation())
.change_context(UserErrors::InternalServerError)?
.into(),
),
diff --git a/crates/router/src/core/webhooks/outgoing.rs b/crates/router/src/core/webhooks/outgoing.rs
index 416075050b3..25c93f8465e 100644
--- a/crates/router/src/core/webhooks/outgoing.rs
+++ b/crates/router/src/core/webhooks/outgoing.rs
@@ -4,10 +4,12 @@ use api_models::{
webhook_events::{OutgoingWebhookRequestContent, OutgoingWebhookResponseContent},
webhooks,
};
-use common_utils::{ext_traits::Encode, request::RequestContent, types::keymanager::Identifier};
+use common_utils::{
+ ext_traits::Encode, request::RequestContent, type_name, types::keymanager::Identifier,
+};
use diesel_models::process_tracker::business_status;
use error_stack::{report, ResultExt};
-use hyperswitch_domain_models::type_encryption::decrypt_optional;
+use hyperswitch_domain_models::type_encryption::{crypto_operation, CryptoOperation};
use masking::{ExposeInterface, Mask, PeekInterface, Secret};
use router_env::{
instrument,
@@ -31,8 +33,7 @@ use crate::{
routes::{app::SessionStateInfo, SessionState},
services,
types::{
- api,
- domain::{self, types as domain_types},
+ api, domain,
storage::{self, enums},
transformers::ForeignFrom,
},
@@ -113,17 +114,21 @@ pub(crate) async fn create_event_and_trigger_outgoing_webhook(
idempotent_event_id: Some(idempotent_event_id.clone()),
initial_attempt_id: Some(event_id.clone()),
request: Some(
- domain_types::encrypt(
+ crypto_operation(
key_manager_state,
- request_content
- .encode_to_string_of_json()
- .change_context(errors::ApiErrorResponse::WebhookProcessingFailure)
- .attach_printable("Failed to encode outgoing webhook request content")
- .map(Secret::new)?,
+ type_name!(domain::Event),
+ CryptoOperation::Encrypt(
+ request_content
+ .encode_to_string_of_json()
+ .change_context(errors::ApiErrorResponse::WebhookProcessingFailure)
+ .attach_printable("Failed to encode outgoing webhook request content")
+ .map(Secret::new)?,
+ ),
Identifier::Merchant(merchant_key_store.merchant_id.clone()),
merchant_key_store.key.get_inner().peek(),
)
.await
+ .and_then(|val| val.try_into_operation())
.change_context(errors::ApiErrorResponse::WebhookProcessingFailure)
.attach_printable("Failed to encrypt outgoing webhook request content")?,
),
@@ -570,15 +575,19 @@ pub(crate) async fn get_outgoing_webhook_request(
let transformed_outgoing_webhook = WebhookType::from(outgoing_webhook);
let payment_response_hash_key = business_profile.payment_response_hash_key.clone();
- let custom_headers = decrypt_optional::<serde_json::Value, masking::WithType>(
+ let custom_headers = crypto_operation::<serde_json::Value, masking::WithType>(
&state.into(),
- business_profile
- .outgoing_webhook_custom_http_headers
- .clone(),
+ type_name!(domain::Event),
+ CryptoOperation::DecryptOptional(
+ business_profile
+ .outgoing_webhook_custom_http_headers
+ .clone(),
+ ),
Identifier::Merchant(key_store.merchant_id.clone()),
key_store.key.get_inner().peek(),
)
.await
+ .and_then(|val| val.try_into_optionaloperation())
.change_context(errors::WebhooksFlowError::OutgoingWebhookEncodingFailed)
.attach_printable("Failed to decrypt outgoing webhook custom HTTP headers")?
.map(|decrypted_value| {
@@ -660,18 +669,22 @@ async fn update_event_if_client_error(
let event_update = domain::EventUpdate::UpdateResponse {
is_webhook_notified,
response: Some(
- domain_types::encrypt(
+ crypto_operation(
key_manager_state,
- response_to_store
- .encode_to_string_of_json()
- .change_context(
- errors::WebhooksFlowError::OutgoingWebhookResponseEncodingFailed,
- )
- .map(Secret::new)?,
+ type_name!(domain::Event),
+ CryptoOperation::Encrypt(
+ response_to_store
+ .encode_to_string_of_json()
+ .change_context(
+ errors::WebhooksFlowError::OutgoingWebhookResponseEncodingFailed,
+ )
+ .map(Secret::new)?,
+ ),
Identifier::Merchant(merchant_key_store.merchant_id.clone()),
merchant_key_store.key.get_inner().peek(),
)
.await
+ .and_then(|val| val.try_into_operation())
.change_context(errors::WebhooksFlowError::WebhookEventUpdationFailed)
.attach_printable("Failed to encrypt outgoing webhook response content")?,
),
@@ -778,18 +791,22 @@ async fn update_event_in_storage(
let event_update = domain::EventUpdate::UpdateResponse {
is_webhook_notified,
response: Some(
- domain_types::encrypt(
+ crypto_operation(
key_manager_state,
- response_to_store
- .encode_to_string_of_json()
- .change_context(
- errors::WebhooksFlowError::OutgoingWebhookResponseEncodingFailed,
- )
- .map(Secret::new)?,
+ type_name!(domain::Event),
+ CryptoOperation::Encrypt(
+ response_to_store
+ .encode_to_string_of_json()
+ .change_context(
+ errors::WebhooksFlowError::OutgoingWebhookResponseEncodingFailed,
+ )
+ .map(Secret::new)?,
+ ),
Identifier::Merchant(merchant_key_store.merchant_id.clone()),
merchant_key_store.key.get_inner().peek(),
)
.await
+ .and_then(|val| val.try_into_operation())
.change_context(errors::WebhooksFlowError::WebhookEventUpdationFailed)
.attach_printable("Failed to encrypt outgoing webhook response content")?,
),
diff --git a/crates/router/src/db/events.rs b/crates/router/src/db/events.rs
index 0cecea9c627..3b0f789cf04 100644
--- a/crates/router/src/db/events.rs
+++ b/crates/router/src/db/events.rs
@@ -770,7 +770,7 @@ impl EventInterface for MockDb {
mod tests {
use std::sync::Arc;
- use common_utils::types::keymanager::Identifier;
+ use common_utils::{type_name, types::keymanager::Identifier};
use diesel_models::{enums, events::EventMetadata};
use time::macros::datetime;
@@ -818,13 +818,17 @@ mod tests {
key_manager_state,
domain::MerchantKeyStore {
merchant_id: merchant_id.clone(),
- key: domain::types::encrypt(
+ key: domain::types::crypto_operation(
key_manager_state,
- services::generate_aes256_key().unwrap().to_vec().into(),
+ type_name!(domain::MerchantKeyStore),
+ domain::types::CryptoOperation::Encrypt(
+ services::generate_aes256_key().unwrap().to_vec().into(),
+ ),
Identifier::Merchant(merchant_id.to_owned()),
master_key,
)
.await
+ .and_then(|val| val.try_into_operation())
.unwrap(),
created_at: datetime!(2023-02-01 0:00),
},
diff --git a/crates/router/src/db/merchant_connector_account.rs b/crates/router/src/db/merchant_connector_account.rs
index 80019012c0b..de69456f349 100644
--- a/crates/router/src/db/merchant_connector_account.rs
+++ b/crates/router/src/db/merchant_connector_account.rs
@@ -1420,7 +1420,7 @@ mod merchant_connector_account_cache_tests {
not(feature = "merchant_connector_account_v2")
))]
use api_models::enums::CountryAlpha2;
- use common_utils::{date_time, types::keymanager::Identifier};
+ use common_utils::{date_time, type_name, types::keymanager::Identifier};
use diesel_models::enums::ConnectorType;
use error_stack::ResultExt;
use masking::PeekInterface;
@@ -1493,13 +1493,17 @@ mod merchant_connector_account_cache_tests {
key_manager_state,
domain::MerchantKeyStore {
merchant_id: merchant_id.clone(),
- key: domain::types::encrypt(
+ key: domain::types::crypto_operation(
key_manager_state,
- services::generate_aes256_key().unwrap().to_vec().into(),
+ type_name!(domain::MerchantKeyStore),
+ domain::types::CryptoOperation::Encrypt(
+ services::generate_aes256_key().unwrap().to_vec().into(),
+ ),
Identifier::Merchant(merchant_id.clone()),
master_key,
)
.await
+ .and_then(|val| val.try_into_operation())
.unwrap(),
created_at: datetime!(2023-02-01 0:00),
},
@@ -1520,13 +1524,15 @@ mod merchant_connector_account_cache_tests {
let mca = domain::MerchantConnectorAccount {
merchant_id: merchant_id.to_owned(),
connector_name: "stripe".to_string(),
- connector_account_details: domain::types::encrypt(
+ connector_account_details: domain::types::crypto_operation(
key_manager_state,
- serde_json::Value::default().into(),
+ type_name!(domain::MerchantConnectorAccount),
+ domain::types::CryptoOperation::Encrypt(serde_json::Value::default().into()),
Identifier::Merchant(merchant_key.merchant_id.clone()),
merchant_key.key.get_inner().peek(),
)
.await
+ .and_then(|val| val.try_into_operation())
.unwrap(),
test_mode: None,
disabled: None,
@@ -1547,13 +1553,15 @@ mod merchant_connector_account_cache_tests {
pm_auth_config: None,
status: common_enums::ConnectorStatus::Inactive,
connector_wallets_details: Some(
- domain::types::encrypt(
+ domain::types::crypto_operation(
key_manager_state,
- serde_json::Value::default().into(),
+ type_name!(domain::MerchantConnectorAccount),
+ domain::types::CryptoOperation::Encrypt(serde_json::Value::default().into()),
Identifier::Merchant(merchant_key.merchant_id.clone()),
merchant_key.key.get_inner().peek(),
)
.await
+ .and_then(|val| val.try_into_operation())
.unwrap(),
),
additional_merchant_data: None,
@@ -1653,13 +1661,17 @@ mod merchant_connector_account_cache_tests {
key_manager_state,
domain::MerchantKeyStore {
merchant_id: merchant_id.clone(),
- key: domain::types::encrypt(
+ key: domain::types::crypto_operation(
key_manager_state,
- services::generate_aes256_key().unwrap().to_vec().into(),
+ type_name!(domain::MerchantConnectorAccount),
+ domain::types::CryptoOperation::Encrypt(
+ services::generate_aes256_key().unwrap().to_vec().into(),
+ ),
Identifier::Merchant(merchant_id.clone()),
master_key,
)
.await
+ .and_then(|val| val.try_into_operation())
.unwrap(),
created_at: datetime!(2023-02-01 0:00),
},
@@ -1681,13 +1693,15 @@ mod merchant_connector_account_cache_tests {
id: id.to_string(),
merchant_id: merchant_id.clone(),
connector_name: "stripe".to_string(),
- connector_account_details: domain::types::encrypt(
+ connector_account_details: domain::types::crypto_operation(
key_manager_state,
- serde_json::Value::default().into(),
+ type_name!(domain::MerchantConnectorAccount),
+ domain::types::CryptoOperation::Encrypt(serde_json::Value::default().into()),
Identifier::Merchant(merchant_key.merchant_id.clone()),
merchant_key.key.get_inner().peek(),
)
.await
+ .and_then(|val| val.try_into_operation())
.unwrap(),
disabled: None,
payment_methods_enabled: None,
@@ -1703,13 +1717,15 @@ mod merchant_connector_account_cache_tests {
pm_auth_config: None,
status: common_enums::ConnectorStatus::Inactive,
connector_wallets_details: Some(
- domain::types::encrypt(
+ domain::types::crypto_operation(
key_manager_state,
- serde_json::Value::default().into(),
+ type_name!(domain::MerchantConnectorAccount),
+ domain::types::CryptoOperation::Encrypt(serde_json::Value::default().into()),
Identifier::Merchant(merchant_key.merchant_id.clone()),
merchant_key.key.get_inner().peek(),
)
.await
+ .and_then(|val| val.try_into_operation())
.unwrap(),
),
additional_merchant_data: None,
diff --git a/crates/router/src/db/merchant_key_store.rs b/crates/router/src/db/merchant_key_store.rs
index 1fe24999b6f..65a5515a391 100644
--- a/crates/router/src/db/merchant_key_store.rs
+++ b/crates/router/src/db/merchant_key_store.rs
@@ -321,7 +321,7 @@ impl MerchantKeyStoreInterface for MockDb {
mod tests {
use std::{borrow::Cow, sync::Arc};
- use common_utils::types::keymanager::Identifier;
+ use common_utils::{type_name, types::keymanager::Identifier};
use time::macros::datetime;
use tokio::sync::oneshot;
@@ -364,13 +364,17 @@ mod tests {
key_manager_state,
domain::MerchantKeyStore {
merchant_id: merchant_id.clone(),
- key: domain::types::encrypt(
+ key: domain::types::crypto_operation(
key_manager_state,
- services::generate_aes256_key().unwrap().to_vec().into(),
+ type_name!(domain::MerchantKeyStore),
+ domain::types::CryptoOperation::Encrypt(
+ 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),
},
@@ -396,13 +400,17 @@ mod tests {
key_manager_state,
domain::MerchantKeyStore {
merchant_id: merchant_id.clone(),
- key: domain::types::encrypt(
+ key: domain::types::crypto_operation(
key_manager_state,
- services::generate_aes256_key().unwrap().to_vec().into(),
+ type_name!(domain::MerchantKeyStore),
+ domain::types::CryptoOperation::Encrypt(
+ 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),
},
diff --git a/crates/router/src/types/api/admin.rs b/crates/router/src/types/api/admin.rs
index e7127e5d53b..c899c54b79d 100644
--- a/crates/router/src/types/api/admin.rs
+++ b/crates/router/src/types/api/admin.rs
@@ -11,11 +11,12 @@ pub use api_models::{
},
organization::{OrganizationId, OrganizationRequest, OrganizationResponse},
};
-use common_utils::{ext_traits::ValueExt, types::keymanager::Identifier};
+use common_utils::{ext_traits::ValueExt, type_name, types::keymanager::Identifier};
use diesel_models::organization::OrganizationBridge;
use error_stack::ResultExt;
use hyperswitch_domain_models::{
- merchant_key_store::MerchantKeyStore, type_encryption::decrypt_optional,
+ merchant_key_store::MerchantKeyStore,
+ type_encryption::{crypto_operation, CryptoOperation},
};
use masking::{ExposeInterface, PeekInterface};
@@ -118,13 +119,15 @@ pub async fn business_profile_response(
key_store: &MerchantKeyStore,
) -> Result<BusinessProfileResponse, error_stack::Report<errors::ParsingError>> {
let outgoing_webhook_custom_http_headers =
- decrypt_optional::<serde_json::Value, masking::WithType>(
+ crypto_operation::<serde_json::Value, masking::WithType>(
&state.into(),
- item.outgoing_webhook_custom_http_headers.clone(),
+ type_name!(storage::business_profile::BusinessProfile),
+ CryptoOperation::DecryptOptional(item.outgoing_webhook_custom_http_headers.clone()),
Identifier::Merchant(key_store.merchant_id.clone()),
key_store.key.get_inner().peek(),
)
.await
+ .and_then(|val| val.try_into_optionaloperation())
.change_context(errors::ParsingError::StructParseFailure(
"Outgoing webhook custom HTTP headers",
))
diff --git a/crates/router/src/types/domain/address.rs b/crates/router/src/types/domain/address.rs
index 55d83679db9..680e26e1f67 100644
--- a/crates/router/src/types/domain/address.rs
+++ b/crates/router/src/types/domain/address.rs
@@ -4,7 +4,7 @@ use common_utils::{
date_time,
encryption::Encryption,
errors::{CustomResult, ValidationError},
- id_type,
+ id_type, type_name,
types::keymanager::{Identifier, KeyManagerState, ToEncryptable},
};
use diesel_models::{address::AddressUpdateInternal, enums};
@@ -188,13 +188,17 @@ impl behaviour::Conversion for Address {
_key_manager_identifier: Identifier,
) -> CustomResult<Self, ValidationError> {
let identifier = Identifier::Merchant(other.merchant_id.clone());
- let decrypted: FxHashMap<String, Encryptable<Secret<String>>> = types::batch_decrypt(
+ let decrypted: FxHashMap<String, Encryptable<Secret<String>>> = types::crypto_operation(
state,
- diesel_models::Address::to_encryptable(other.clone()),
+ type_name!(Self::DstType),
+ types::CryptoOperation::BatchDecrypt(diesel_models::Address::to_encryptable(
+ other.clone(),
+ )),
identifier.clone(),
key.peek(),
)
.await
+ .and_then(|val| val.try_into_batchoperation())
.change_context(ValidationError::InvalidValue {
message: "Failed while decrypting".to_string(),
})?;
diff --git a/crates/router/src/types/domain/event.rs b/crates/router/src/types/domain/event.rs
index 67183a2d3a4..872eb303901 100644
--- a/crates/router/src/types/domain/event.rs
+++ b/crates/router/src/types/domain/event.rs
@@ -1,5 +1,6 @@
use common_utils::{
crypto::OptionalEncryptableSecretString,
+ type_name,
types::keymanager::{KeyManagerState, ToEncryptable},
};
use diesel_models::{
@@ -92,16 +93,20 @@ impl super::behaviour::Conversion for Event {
where
Self: Sized,
{
- let decrypted = types::batch_decrypt(
+ let decrypted = types::crypto_operation(
state,
- EventWithEncryption::to_encryptable(EventWithEncryption {
- request: item.request.clone(),
- response: item.response.clone(),
- }),
+ type_name!(Self::DstType),
+ types::CryptoOperation::BatchDecrypt(EventWithEncryption::to_encryptable(
+ EventWithEncryption {
+ request: item.request.clone(),
+ response: item.response.clone(),
+ },
+ )),
key_manager_identifier,
key.peek(),
)
.await
+ .and_then(|val| val.try_into_batchoperation())
.change_context(ValidationError::InvalidValue {
message: "Failed while decrypting event data".to_string(),
})?;
diff --git a/crates/router/src/types/domain/types.rs b/crates/router/src/types/domain/types.rs
index e105b2eba09..10657adc122 100644
--- a/crates/router/src/types/domain/types.rs
+++ b/crates/router/src/types/domain/types.rs
@@ -1,7 +1,6 @@
use common_utils::types::keymanager::KeyManagerState;
pub use hyperswitch_domain_models::type_encryption::{
- batch_decrypt, batch_encrypt, decrypt, decrypt_optional, encrypt, encrypt_optional, AsyncLift,
- Lift,
+ crypto_operation, AsyncLift, CryptoOperation, Lift,
};
impl From<&crate::SessionState> for KeyManagerState {
diff --git a/crates/router/src/types/domain/user.rs b/crates/router/src/types/domain/user.rs
index 41fbc96f6d2..3df0a11af0e 100644
--- a/crates/router/src/types/domain/user.rs
+++ b/crates/router/src/types/domain/user.rs
@@ -5,7 +5,7 @@ use api_models::{
};
use common_enums::TokenPurpose;
use common_utils::{
- crypto::Encryptable, errors::CustomResult, id_type, new_type::MerchantName, pii,
+ crypto::Encryptable, errors::CustomResult, id_type, new_type::MerchantName, pii, type_name,
types::keymanager::Identifier,
};
use diesel_models::{
@@ -1001,13 +1001,15 @@ impl UserFromStorage {
let key_store = UserKeyStore {
user_id: self.get_user_id().to_string(),
- key: domain_types::encrypt(
+ key: domain_types::crypto_operation(
key_manager_state,
- key.to_vec().into(),
+ type_name!(UserKeyStore),
+ domain_types::CryptoOperation::Encrypt(key.to_vec().into()),
Identifier::User(self.get_user_id().to_string()),
master_key,
)
.await
+ .and_then(|val| val.try_into_operation())
.change_context(UserErrors::InternalServerError)?,
created_at: common_utils::date_time::now(),
};
@@ -1051,13 +1053,15 @@ impl UserFromStorage {
.await
.change_context(UserErrors::InternalServerError)?;
- Ok(domain_types::decrypt_optional::<String, masking::WithType>(
+ Ok(domain_types::crypto_operation::<String, masking::WithType>(
key_manager_state,
- self.0.totp_secret.clone(),
+ type_name!(storage_user::User),
+ domain_types::CryptoOperation::DecryptOptional(self.0.totp_secret.clone()),
Identifier::User(user_key_store.user_id.clone()),
user_key_store.key.peek(),
)
.await
+ .and_then(|val| val.try_into_optionaloperation())
.change_context(UserErrors::InternalServerError)?
.map(Encryptable::into_inner))
}
diff --git a/crates/router/src/types/domain/user_key_store.rs b/crates/router/src/types/domain/user_key_store.rs
index b0b57732cc8..696fab7eef5 100644
--- a/crates/router/src/types/domain/user_key_store.rs
+++ b/crates/router/src/types/domain/user_key_store.rs
@@ -1,10 +1,10 @@
use common_utils::{
crypto::Encryptable,
- date_time,
+ date_time, type_name,
types::keymanager::{Identifier, KeyManagerState},
};
use error_stack::ResultExt;
-use hyperswitch_domain_models::type_encryption::decrypt;
+use hyperswitch_domain_models::type_encryption::{crypto_operation, CryptoOperation};
use masking::{PeekInterface, Secret};
use time::PrimitiveDateTime;
@@ -41,11 +41,18 @@ impl super::behaviour::Conversion for UserKeyStore {
{
let identifier = Identifier::User(item.user_id.clone());
Ok(Self {
- key: decrypt(state, item.key, identifier, key.peek())
- .await
- .change_context(ValidationError::InvalidValue {
- message: "Failed while decrypting customer data".to_string(),
- })?,
+ key: crypto_operation(
+ state,
+ type_name!(Self::DstType),
+ CryptoOperation::Decrypt(item.key),
+ identifier,
+ key.peek(),
+ )
+ .await
+ .and_then(|val| val.try_into_operation())
+ .change_context(ValidationError::InvalidValue {
+ message: "Failed while decrypting customer data".to_string(),
+ })?,
user_id: item.user_id,
created_at: item.created_at,
})
diff --git a/crates/router/src/utils.rs b/crates/router/src/utils.rs
index 5b46dce1392..44396de7ac2 100644
--- a/crates/router/src/utils.rs
+++ b/crates/router/src/utils.rs
@@ -22,8 +22,6 @@ use api_models::{
};
use base64::Engine;
use common_utils::types::keymanager::KeyManagerState;
-#[cfg(all(any(feature = "v1", feature = "v2"), not(feature = "customer_v2")))]
-use common_utils::types::keymanager::{Identifier, ToEncryptable};
pub use common_utils::{
crypto,
ext_traits::{ByteSliceExt, BytesExt, Encode, StringExt, ValueExt},
@@ -31,10 +29,15 @@ pub use common_utils::{
id_type,
validation::validate_email,
};
+#[cfg(all(any(feature = "v1", feature = "v2"), not(feature = "customer_v2")))]
+use common_utils::{
+ type_name,
+ types::keymanager::{Identifier, ToEncryptable},
+};
use error_stack::ResultExt;
use hyperswitch_domain_models::payments::PaymentIntent;
#[cfg(all(any(feature = "v1", feature = "v2"), not(feature = "customer_v2")))]
-use hyperswitch_domain_models::type_encryption::batch_encrypt;
+use hyperswitch_domain_models::type_encryption::{crypto_operation, CryptoOperation};
use image::Luma;
use nanoid::nanoid;
use qrcode;
@@ -794,17 +797,21 @@ impl CustomerAddress for api_models::customers::CustomerRequest {
storage_scheme: storage::enums::MerchantStorageScheme,
merchant_id: id_type::MerchantId,
) -> CustomResult<storage::AddressUpdate, common_utils::errors::CryptoError> {
- let encrypted_data = batch_encrypt(
+ let encrypted_data = crypto_operation(
&state.into(),
- AddressDetailsWithPhone::to_encryptable(AddressDetailsWithPhone {
- address: Some(address_details.clone()),
- phone_number: self.phone.clone(),
- email: self.email.clone(),
- }),
+ type_name!(storage::Address),
+ CryptoOperation::BatchEncrypt(AddressDetailsWithPhone::to_encryptable(
+ AddressDetailsWithPhone {
+ address: Some(address_details.clone()),
+ phone_number: self.phone.clone(),
+ email: self.email.clone(),
+ },
+ )),
Identifier::Merchant(merchant_id),
key,
)
- .await?;
+ .await
+ .and_then(|val| val.try_into_batchoperation())?;
let encryptable_address = AddressDetailsWithPhone::from_encryptable(encrypted_data)
.change_context(common_utils::errors::CryptoError::EncodingFailed)?;
Ok(storage::AddressUpdate::Update {
@@ -833,17 +840,21 @@ impl CustomerAddress for api_models::customers::CustomerRequest {
key: &[u8],
storage_scheme: storage::enums::MerchantStorageScheme,
) -> CustomResult<domain::CustomerAddress, common_utils::errors::CryptoError> {
- let encrypted_data = batch_encrypt(
+ let encrypted_data = crypto_operation(
&state.into(),
- AddressDetailsWithPhone::to_encryptable(AddressDetailsWithPhone {
- address: Some(address_details.clone()),
- phone_number: self.phone.clone(),
- email: self.email.clone(),
- }),
+ type_name!(storage::Address),
+ CryptoOperation::BatchEncrypt(AddressDetailsWithPhone::to_encryptable(
+ AddressDetailsWithPhone {
+ address: Some(address_details.clone()),
+ phone_number: self.phone.clone(),
+ email: self.email.clone(),
+ },
+ )),
Identifier::Merchant(merchant_id.to_owned()),
key,
)
- .await?;
+ .await
+ .and_then(|val| val.try_into_batchoperation())?;
let encryptable_address = AddressDetailsWithPhone::from_encryptable(encrypted_data)
.change_context(common_utils::errors::CryptoError::EncodingFailed)?;
let address = domain::Address {
diff --git a/crates/router/src/utils/user.rs b/crates/router/src/utils/user.rs
index 2dad55c4b89..1de45b74360 100644
--- a/crates/router/src/utils/user.rs
+++ b/crates/router/src/utils/user.rs
@@ -3,7 +3,7 @@ use std::{collections::HashMap, sync::Arc};
use api_models::user as user_api;
use common_enums::UserAuthType;
use common_utils::{
- encryption::Encryption, errors::CustomResult, id_type, types::keymanager::Identifier,
+ encryption::Encryption, errors::CustomResult, id_type, type_name, types::keymanager::Identifier,
};
use diesel_models::{enums::UserStatus, user_role::UserRole};
use error_stack::{report, ResultExt};
@@ -260,15 +260,18 @@ pub async fn construct_public_and_private_db_configs(
.change_context(UserErrors::InternalServerError)
.attach_printable("Failed to convert auth config to json")?;
- let encrypted_config = domain::types::encrypt::<serde_json::Value, masking::WithType>(
- &state.into(),
- private_config_value.into(),
- Identifier::UserAuth(id),
- encryption_key,
- )
- .await
- .change_context(UserErrors::InternalServerError)
- .attach_printable("Failed to encrypt auth config")?;
+ 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()),
@@ -309,13 +312,15 @@ pub async fn decrypt_oidc_private_config(
.change_context(UserErrors::InternalServerError)
.attach_printable("Failed to decode DEK")?;
- let private_config = domain::types::decrypt_optional::<serde_json::Value, masking::WithType>(
+ let private_config = domain::types::crypto_operation::<serde_json::Value, masking::WithType>(
&state.into(),
- encrypted_config,
+ 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)
|
2024-08-01T08:00:17Z
|
## Type of Change
<!-- Put an `x` in the boxes that apply -->
- [x] Enhancement
## Description
<!-- Describe your changes in detail -->
Added a wrapper for Crypto Operation (Encrypt, Decrypt). So any changes in Encryption framework can be done in one place. This also adds logging for table name for which the Encryption and Decryption is happening
## Motivation and Context
<!--
Why is this change required? What problem does it solve?
If it fixes an open issue, please link to the issue here.
If you don't have an issue, we'd recommend starting with one first so the PR
can focus on the implementation (unless it is an obvious bug or documentation fix
that will have little conversation).
-->
This adds two things
- A wrapper for encryption and decryption operation
- A table name field for encryption and decryption logs
## How did you test it?
<!--
Did you write an integration/unit/API test to verify the code changes?
Or did you test this change manually (provide relevant screenshots)?
-->
- All sanity tests for MerchantAccount Create, Payments, Refunds
- Check the table name field in the encryption logs

## Checklist
<!-- Put an `x` in the boxes that apply -->
- [x] I formatted the code `cargo +nightly fmt --all`
- [x] I addressed lints thrown by `cargo clippy`
- [x] I reviewed the submitted code
|
29c5f8a7570513bd0a23e5d0a90d6c2f78c63f6f
|
|
juspay/hyperswitch
|
juspay__hyperswitch-5487
|
Bug: [refactor]: add level support for roles
Determine a given role exists at which level, i.e., determine a entity of each roles which it is associated to.
- This will help users to perform operation accordingly.
- A profile/merchant level user cannot perform org level opertaion.
- Similarly a hierarchy can be maintained where a user (which will be associated to a particular role) can not perform any operations which are for higher entities.
|
diff --git a/crates/api_models/src/user_role/role.rs b/crates/api_models/src/user_role/role.rs
index 6d0bb2154d9..73b25c84af5 100644
--- a/crates/api_models/src/user_role/role.rs
+++ b/crates/api_models/src/user_role/role.rs
@@ -1,4 +1,4 @@
-use common_enums::{PermissionGroup, RoleScope};
+use common_enums::{EntityType, PermissionGroup, RoleScope};
use super::Permission;
@@ -7,6 +7,7 @@ pub struct CreateRoleRequest {
pub role_name: String,
pub groups: Vec<PermissionGroup>,
pub role_scope: RoleScope,
+ pub entity_type: Option<EntityType>,
}
#[derive(Debug, serde::Deserialize, serde::Serialize)]
diff --git a/crates/common_enums/src/enums.rs b/crates/common_enums/src/enums.rs
index 5c8a860c168..516e3d7030d 100644
--- a/crates/common_enums/src/enums.rs
+++ b/crates/common_enums/src/enums.rs
@@ -3026,6 +3026,27 @@ pub enum Owner {
Internal,
}
+#[derive(
+ Clone,
+ Copy,
+ Debug,
+ Eq,
+ PartialEq,
+ serde::Deserialize,
+ serde::Serialize,
+ strum::Display,
+ strum::EnumString,
+)]
+#[router_derive::diesel_enum(storage_type = "text")]
+#[strum(serialize_all = "snake_case")]
+#[serde(rename_all = "snake_case")]
+pub enum EntityType {
+ Internal,
+ Organization,
+ Merchant,
+ Profile,
+}
+
#[derive(Clone, Debug, serde::Serialize)]
#[serde(rename_all = "snake_case")]
pub enum PayoutRetryType {
diff --git a/crates/diesel_models/src/role.rs b/crates/diesel_models/src/role.rs
index 713590adeda..3fb64e645d6 100644
--- a/crates/diesel_models/src/role.rs
+++ b/crates/diesel_models/src/role.rs
@@ -18,6 +18,7 @@ pub struct Role {
pub created_by: String,
pub last_modified_at: PrimitiveDateTime,
pub last_modified_by: String,
+ pub entity_type: Option<enums::EntityType>,
}
#[derive(router_derive::Setter, Clone, Debug, Insertable, router_derive::DebugAsDisplay)]
@@ -34,6 +35,7 @@ pub struct RoleNew {
pub created_by: String,
pub last_modified_at: PrimitiveDateTime,
pub last_modified_by: String,
+ pub entity_type: Option<enums::EntityType>,
}
#[derive(Clone, Debug, AsChangeset, router_derive::DebugAsDisplay)]
diff --git a/crates/diesel_models/src/schema.rs b/crates/diesel_models/src/schema.rs
index 37ba11e4389..d2c66fc37fe 100644
--- a/crates/diesel_models/src/schema.rs
+++ b/crates/diesel_models/src/schema.rs
@@ -1183,6 +1183,8 @@ diesel::table! {
last_modified_at -> Timestamp,
#[max_length = 64]
last_modified_by -> Varchar,
+ #[max_length = 64]
+ entity_type -> Nullable<Varchar>,
}
}
diff --git a/crates/diesel_models/src/schema_v2.rs b/crates/diesel_models/src/schema_v2.rs
index 5854fa5f385..83a44486160 100644
--- a/crates/diesel_models/src/schema_v2.rs
+++ b/crates/diesel_models/src/schema_v2.rs
@@ -1189,6 +1189,8 @@ diesel::table! {
last_modified_at -> Timestamp,
#[max_length = 64]
last_modified_by -> Varchar,
+ #[max_length = 64]
+ entity_type -> Nullable<Varchar>,
}
}
diff --git a/crates/diesel_models/src/user_role.rs b/crates/diesel_models/src/user_role.rs
index d484db2c6ba..87e6f332328 100644
--- a/crates/diesel_models/src/user_role.rs
+++ b/crates/diesel_models/src/user_role.rs
@@ -1,3 +1,4 @@
+use common_enums::EntityType;
use common_utils::id_type;
use diesel::{AsChangeset, Identifiable, Insertable, Queryable, Selectable};
use time::PrimitiveDateTime;
@@ -19,7 +20,7 @@ pub struct UserRole {
pub last_modified: PrimitiveDateTime,
pub profile_id: Option<String>,
pub entity_id: Option<String>,
- pub entity_type: Option<String>,
+ pub entity_type: Option<EntityType>,
pub version: enums::UserRoleVersion,
}
@@ -37,7 +38,7 @@ pub struct UserRoleNew {
pub last_modified: PrimitiveDateTime,
pub profile_id: Option<String>,
pub entity_id: Option<String>,
- pub entity_type: Option<String>,
+ pub entity_type: Option<EntityType>,
pub version: enums::UserRoleVersion,
}
diff --git a/crates/router/src/core/user_role/role.rs b/crates/router/src/core/user_role/role.rs
index 386156f58e7..a286180e202 100644
--- a/crates/router/src/core/user_role/role.rs
+++ b/crates/router/src/core/user_role/role.rs
@@ -87,6 +87,7 @@ pub async fn create_role(
org_id: user_from_token.org_id,
groups: req.groups,
scope: req.role_scope,
+ entity_type: req.entity_type,
created_by: user_from_token.user_id.clone(),
last_modified_by: user_from_token.user_id,
created_at: now,
diff --git a/crates/router/src/db/role.rs b/crates/router/src/db/role.rs
index 286a85190b8..5802142b166 100644
--- a/crates/router/src/db/role.rs
+++ b/crates/router/src/db/role.rs
@@ -144,6 +144,7 @@ impl RoleInterface for MockDb {
org_id: role.org_id,
groups: role.groups,
scope: role.scope,
+ entity_type: role.entity_type,
created_by: role.created_by,
created_at: role.created_at,
last_modified_at: role.last_modified_at,
diff --git a/crates/router/src/services/authorization/roles.rs b/crates/router/src/services/authorization/roles.rs
index cda2371282a..9b506cc5ef7 100644
--- a/crates/router/src/services/authorization/roles.rs
+++ b/crates/router/src/services/authorization/roles.rs
@@ -1,6 +1,6 @@
use std::collections::HashSet;
-use common_enums::{PermissionGroup, RoleScope};
+use common_enums::{EntityType, PermissionGroup, RoleScope};
use common_utils::{errors::CustomResult, id_type};
use super::{permission_groups::get_permissions_vec, permissions::Permission};
@@ -14,6 +14,7 @@ pub struct RoleInfo {
role_name: String,
groups: Vec<PermissionGroup>,
scope: RoleScope,
+ entity_type: EntityType,
is_invitable: bool,
is_deletable: bool,
is_updatable: bool,
@@ -37,6 +38,10 @@ impl RoleInfo {
self.scope
}
+ pub fn get_entity_type(&self) -> EntityType {
+ self.entity_type
+ }
+
pub fn is_invitable(&self) -> bool {
self.is_invitable
}
@@ -91,6 +96,7 @@ impl From<diesel_models::role::Role> for RoleInfo {
role_name: role.role_name,
groups: role.groups.into_iter().map(Into::into).collect(),
scope: role.scope,
+ entity_type: role.entity_type.unwrap_or(EntityType::Merchant),
is_invitable: true,
is_deletable: true,
is_updatable: true,
diff --git a/crates/router/src/services/authorization/roles/predefined_roles.rs b/crates/router/src/services/authorization/roles/predefined_roles.rs
index 568af6e19fd..2f67af9f23a 100644
--- a/crates/router/src/services/authorization/roles/predefined_roles.rs
+++ b/crates/router/src/services/authorization/roles/predefined_roles.rs
@@ -1,6 +1,6 @@
use std::collections::HashMap;
-use common_enums::{PermissionGroup, RoleScope};
+use common_enums::{EntityType, PermissionGroup, RoleScope};
use once_cell::sync::Lazy;
use super::RoleInfo;
@@ -28,6 +28,7 @@ pub static PREDEFINED_ROLES: Lazy<HashMap<&'static str, RoleInfo>> = Lazy::new(|
role_id: consts::user_role::ROLE_ID_INTERNAL_ADMIN.to_string(),
role_name: "internal_admin".to_string(),
scope: RoleScope::Organization,
+ entity_type: EntityType::Internal,
is_invitable: false,
is_deletable: false,
is_updatable: false,
@@ -48,6 +49,7 @@ pub static PREDEFINED_ROLES: Lazy<HashMap<&'static str, RoleInfo>> = Lazy::new(|
role_id: consts::user_role::ROLE_ID_INTERNAL_VIEW_ONLY_USER.to_string(),
role_name: "internal_view_only".to_string(),
scope: RoleScope::Organization,
+ entity_type: EntityType::Internal,
is_invitable: false,
is_deletable: false,
is_updatable: false,
@@ -75,6 +77,7 @@ pub static PREDEFINED_ROLES: Lazy<HashMap<&'static str, RoleInfo>> = Lazy::new(|
role_id: consts::user_role::ROLE_ID_ORGANIZATION_ADMIN.to_string(),
role_name: "organization_admin".to_string(),
scope: RoleScope::Organization,
+ entity_type: EntityType::Organization,
is_invitable: false,
is_deletable: false,
is_updatable: false,
@@ -102,6 +105,7 @@ pub static PREDEFINED_ROLES: Lazy<HashMap<&'static str, RoleInfo>> = Lazy::new(|
role_id: consts::user_role::ROLE_ID_MERCHANT_ADMIN.to_string(),
role_name: "admin".to_string(),
scope: RoleScope::Organization,
+ entity_type: EntityType::Merchant,
is_invitable: true,
is_deletable: true,
is_updatable: true,
@@ -122,6 +126,7 @@ pub static PREDEFINED_ROLES: Lazy<HashMap<&'static str, RoleInfo>> = Lazy::new(|
role_id: consts::user_role::ROLE_ID_MERCHANT_VIEW_ONLY.to_string(),
role_name: "view_only".to_string(),
scope: RoleScope::Organization,
+ entity_type: EntityType::Merchant,
is_invitable: true,
is_deletable: true,
is_updatable: true,
@@ -141,6 +146,7 @@ pub static PREDEFINED_ROLES: Lazy<HashMap<&'static str, RoleInfo>> = Lazy::new(|
role_id: consts::user_role::ROLE_ID_MERCHANT_IAM_ADMIN.to_string(),
role_name: "iam".to_string(),
scope: RoleScope::Organization,
+ entity_type: EntityType::Merchant,
is_invitable: true,
is_deletable: true,
is_updatable: true,
@@ -161,6 +167,7 @@ pub static PREDEFINED_ROLES: Lazy<HashMap<&'static str, RoleInfo>> = Lazy::new(|
role_id: consts::user_role::ROLE_ID_MERCHANT_DEVELOPER.to_string(),
role_name: "developer".to_string(),
scope: RoleScope::Organization,
+ entity_type: EntityType::Merchant,
is_invitable: true,
is_deletable: true,
is_updatable: true,
@@ -182,6 +189,7 @@ pub static PREDEFINED_ROLES: Lazy<HashMap<&'static str, RoleInfo>> = Lazy::new(|
role_id: consts::user_role::ROLE_ID_MERCHANT_OPERATOR.to_string(),
role_name: "operator".to_string(),
scope: RoleScope::Organization,
+ entity_type: EntityType::Merchant,
is_invitable: true,
is_deletable: true,
is_updatable: true,
@@ -200,6 +208,7 @@ pub static PREDEFINED_ROLES: Lazy<HashMap<&'static str, RoleInfo>> = Lazy::new(|
role_id: consts::user_role::ROLE_ID_MERCHANT_CUSTOMER_SUPPORT.to_string(),
role_name: "customer_support".to_string(),
scope: RoleScope::Organization,
+ entity_type: EntityType::Merchant,
is_invitable: true,
is_deletable: true,
is_updatable: true,
diff --git a/migrations/2024-07-30-124102_add_entity_type_to_roles/down.sql b/migrations/2024-07-30-124102_add_entity_type_to_roles/down.sql
new file mode 100644
index 00000000000..af37d90893e
--- /dev/null
+++ b/migrations/2024-07-30-124102_add_entity_type_to_roles/down.sql
@@ -0,0 +1,2 @@
+-- This file should undo anything in `up.sql`
+ALTER TABLE roles DROP COLUMN entity_type;
\ No newline at end of file
diff --git a/migrations/2024-07-30-124102_add_entity_type_to_roles/up.sql b/migrations/2024-07-30-124102_add_entity_type_to_roles/up.sql
new file mode 100644
index 00000000000..14e0f945033
--- /dev/null
+++ b/migrations/2024-07-30-124102_add_entity_type_to_roles/up.sql
@@ -0,0 +1,2 @@
+-- Your SQL goes here
+ALTER TABLE roles ADD COLUMN entity_type VARCHAR(64);
\ No newline at end of file
|
2024-07-31T10:48:31Z
|
## Type of Change
<!-- Put an `x` in the boxes that apply -->
- [ ] Bugfix
- [ ] New feature
- [x] Enhancement
- [x] Refactoring
- [ ] Dependency updates
- [ ] Documentation
- [ ] CI/CD
## Description
Add entity type to roles (predefined and customs)
This can be used to determine at which level a current entity exist, and can perform operations accordingly.
### Additional Changes
- [ ] This PR modifies the API contract
- [x] This PR modifies the database schema
- [ ] This PR modifies application configuration/environment variables
<!--
Provide links to the files with corresponding changes.
Following are the paths where you can find config files:
1. `config`
2. `crates/router/src/configs`
3. `loadtest/config`
-->
## Motivation and Context
Closes [#5487](https://github.com/juspay/hyperswitch/issues/5487)
## How did you test it?
The change is at DB level and can be tested with the upcoming application changes PRs.
## Checklist
<!-- Put an `x` in the boxes that apply -->
- [x] I formatted the code `cargo +nightly fmt --all`
- [x] I addressed lints thrown by `cargo clippy`
- [x] I reviewed the submitted code
- [ ] I added unit tests for my changes where possible
|
540ef071cb238a56d52d06687226aab7fd0dfe68
|
|
juspay/hyperswitch
|
juspay__hyperswitch-5486
|
Bug: [FEATURE] - Add TimeRange based search on GlobalSearch
### Feature Description
Global search be able to give out result based on a given time range and not just rely on the query string given as a parameter in the request
### Possible Implementation
`{
"query": "usd",
"filters": {
"status": [
"succeeded"
]
},
"timeRange": {
"startTime": "2024-07-28T18:30:00Z",
"endTime": "2024-07-30T18:45:00Z"
}
}`
Time Range should be expected in the above manner
### Have you spent some time checking if this feature request has been raised before?
- [X] I checked and didn't find a similar issue
### Have you read the Contributing Guidelines?
- [X] I have read the [Contributing Guidelines](https://github.com/juspay/hyperswitch/blob/main/docs/CONTRIBUTING.md)
### Are you willing to submit a PR?
None
|
diff --git a/crates/analytics/src/opensearch.rs b/crates/analytics/src/opensearch.rs
index 1031c815448..11ea4e4f7ab 100644
--- a/crates/analytics/src/opensearch.rs
+++ b/crates/analytics/src/opensearch.rs
@@ -1,6 +1,7 @@
use api_models::{
analytics::search::SearchIndex,
errors::types::{ApiError, ApiErrorResponse},
+ payments::TimeRange,
};
use aws_config::{self, meta::region::RegionProviderChain, Region};
use common_utils::errors::{CustomResult, ErrorSwitch};
@@ -18,8 +19,9 @@ use opensearch::{
},
MsearchParts, OpenSearch, SearchParts,
};
-use serde_json::{json, Value};
+use serde_json::{json, Map, Value};
use storage_impl::errors::ApplicationError;
+use time::PrimitiveDateTime;
use super::{health_check::HealthCheck, query::QueryResult, types::QueryExecutionError};
use crate::query::QueryBuildingError;
@@ -40,6 +42,23 @@ pub struct OpenSearchIndexes {
pub disputes: String,
}
+#[derive(Debug, Clone, Copy, serde::Serialize, serde::Deserialize, PartialEq, Eq, Hash)]
+pub struct OpensearchTimeRange {
+ #[serde(with = "common_utils::custom_serde::iso8601")]
+ pub gte: PrimitiveDateTime,
+ #[serde(default, with = "common_utils::custom_serde::iso8601::option")]
+ pub lte: Option<PrimitiveDateTime>,
+}
+
+impl From<TimeRange> for OpensearchTimeRange {
+ fn from(time_range: TimeRange) -> Self {
+ Self {
+ gte: time_range.start_time,
+ lte: time_range.end_time,
+ }
+ }
+}
+
#[derive(Clone, Debug, serde::Deserialize)]
pub struct OpenSearchConfig {
host: String,
@@ -377,6 +396,7 @@ pub struct OpenSearchQueryBuilder {
pub offset: Option<i64>,
pub count: Option<i64>,
pub filters: Vec<(String, Vec<String>)>,
+ pub time_range: Option<OpensearchTimeRange>,
}
impl OpenSearchQueryBuilder {
@@ -387,6 +407,7 @@ impl OpenSearchQueryBuilder {
offset: Default::default(),
count: Default::default(),
filters: Default::default(),
+ time_range: Default::default(),
}
}
@@ -396,27 +417,110 @@ impl OpenSearchQueryBuilder {
Ok(())
}
+ pub fn set_time_range(&mut self, time_range: OpensearchTimeRange) -> QueryResult<()> {
+ self.time_range = Some(time_range);
+ Ok(())
+ }
+
pub fn add_filter_clause(&mut self, lhs: String, rhs: Vec<String>) -> QueryResult<()> {
self.filters.push((lhs, rhs));
Ok(())
}
+ pub fn get_status_field(&self, index: &SearchIndex) -> &str {
+ match index {
+ SearchIndex::Refunds => "refund_status.keyword",
+ SearchIndex::Disputes => "dispute_status.keyword",
+ _ => "status.keyword",
+ }
+ }
+
+ pub fn replace_status_field(&self, filters: &[Value], index: &SearchIndex) -> Vec<Value> {
+ filters
+ .iter()
+ .map(|filter| {
+ if let Some(terms) = filter.get("terms").and_then(|v| v.as_object()) {
+ let mut new_filter = filter.clone();
+ if let Some(new_terms) =
+ new_filter.get_mut("terms").and_then(|v| v.as_object_mut())
+ {
+ let key = "status.keyword";
+ if let Some(status_terms) = terms.get(key) {
+ new_terms.remove(key);
+ new_terms.insert(
+ self.get_status_field(index).to_string(),
+ status_terms.clone(),
+ );
+ }
+ }
+ new_filter
+ } else {
+ filter.clone()
+ }
+ })
+ .collect()
+ }
+
+ /// # Panics
+ ///
+ /// This function will panic if:
+ ///
+ /// * The structure of the JSON query is not as expected (e.g., missing keys or incorrect types).
+ ///
+ /// Ensure that the input data and the structure of the query are valid and correctly handled.
pub fn construct_payload(&self, indexes: &[SearchIndex]) -> QueryResult<Vec<Value>> {
- let mut query =
- vec![json!({"multi_match": {"type": "phrase", "query": self.query, "lenient": true}})];
+ let mut query_obj = Map::new();
+ let mut bool_obj = Map::new();
+ let mut filter_array = Vec::new();
+
+ filter_array.push(json!({
+ "multi_match": {
+ "type": "phrase",
+ "query": self.query,
+ "lenient": true
+ }
+ }));
let mut filters = self
.filters
.iter()
- .map(|(k, v)| json!({"terms" : {k : v}}))
+ .map(|(k, v)| json!({"terms": {k: v}}))
.collect::<Vec<Value>>();
- query.append(&mut filters);
+ filter_array.append(&mut filters);
+
+ if let Some(ref time_range) = self.time_range {
+ let range = json!(time_range);
+ filter_array.push(json!({
+ "range": {
+ "timestamp": range
+ }
+ }));
+ }
+
+ bool_obj.insert("filter".to_string(), Value::Array(filter_array));
+ query_obj.insert("bool".to_string(), Value::Object(bool_obj));
+
+ let mut query = Map::new();
+ query.insert("query".to_string(), Value::Object(query_obj));
- // TODO add index specific filters
Ok(indexes
.iter()
- .map(|_index| json!({"query": {"bool": {"filter": query}}}))
+ .map(|index| {
+ let updated_query = query
+ .get("query")
+ .and_then(|q| q.get("bool"))
+ .and_then(|b| b.get("filter"))
+ .and_then(|f| f.as_array())
+ .map(|filters| self.replace_status_field(filters, index))
+ .unwrap_or_default();
+
+ let mut final_query = Map::new();
+ final_query.insert("bool".to_string(), json!({ "filter": updated_query }));
+
+ let payload = json!({ "query": Value::Object(final_query) });
+ payload
+ })
.collect::<Vec<Value>>())
}
}
diff --git a/crates/analytics/src/search.rs b/crates/analytics/src/search.rs
index 12ef7fb8d96..95b7f204b97 100644
--- a/crates/analytics/src/search.rs
+++ b/crates/analytics/src/search.rs
@@ -97,6 +97,10 @@ pub async fn msearch_results(
};
};
+ if let Some(time_range) = req.time_range {
+ query_builder.set_time_range(time_range.into()).switch()?;
+ };
+
let response_text: OpenMsearchOutput = client
.execute(query_builder)
.await
@@ -221,6 +225,11 @@ pub async fn search_results(
}
};
};
+
+ if let Some(time_range) = search_req.time_range {
+ query_builder.set_time_range(time_range.into()).switch()?;
+ };
+
query_builder
.set_offset_n_count(search_req.offset, search_req.count)
.switch()?;
diff --git a/crates/api_models/src/analytics/search.rs b/crates/api_models/src/analytics/search.rs
index f27af75936d..b962f60cae0 100644
--- a/crates/api_models/src/analytics/search.rs
+++ b/crates/api_models/src/analytics/search.rs
@@ -2,6 +2,8 @@ use common_utils::hashing::HashedString;
use masking::WithType;
use serde_json::Value;
+use crate::payments::TimeRange;
+
#[derive(Clone, Debug, Default, serde::Deserialize, serde::Serialize)]
pub struct SearchFilters {
pub payment_method: Option<Vec<String>>,
@@ -26,6 +28,8 @@ pub struct GetGlobalSearchRequest {
pub query: String,
#[serde(default)]
pub filters: Option<SearchFilters>,
+ #[serde(default)]
+ pub time_range: Option<TimeRange>,
}
#[derive(Clone, Debug, serde::Deserialize, serde::Serialize)]
@@ -36,6 +40,8 @@ pub struct GetSearchRequest {
pub query: String,
#[serde(default)]
pub filters: Option<SearchFilters>,
+ #[serde(default)]
+ pub time_range: Option<TimeRange>,
}
#[derive(Clone, Debug, serde::Deserialize, serde::Serialize)]
|
2024-07-29T10:11:46Z
|
## Type of Change
<!-- Put an `x` in the boxes that apply -->
- [ ] Bugfix
- [x] New feature
- [x] Enhancement
- [ ] Refactoring
- [ ] Dependency updates
- [ ] Documentation
- [ ] CI/CD
## Description
<!-- Describe your changes in detail -->
## Task 1
The `status` field is different in different indexes:
- `status` in Payment Attempts and Payment Intents
- `refund_status` in Refunds
- `dispute_status` in Disputes
The correct mapping of status for each index is done, to get the search-results
## Task 2
Added `Time Range based search` for the OpenSearch query
### Additional Changes
- [ ] This PR modifies the API contract
- [ ] This PR modifies the database schema
- [ ] This PR modifies application configuration/environment variables
<!--
Provide links to the files with corresponding changes.
Following are the paths where you can find config files:
1. `config`
2. `crates/router/src/configs`
3. `loadtest/config`
-->
## Motivation and Context
<!--
Why is this change required? What problem does it solve?
If it fixes an open issue, please link to the issue here.
If you don't have an issue, we'd recommend starting with one first so the PR
can focus on the implementation (unless it is an obvious bug or documentation fix
that will have little conversation).
-->
Giving a better search experience for the merchants through the dashboard global-search
## How did you test it?
<!--
Did you write an integration/unit/API test to verify the code changes?
Or did you test this change manually (provide relevant screenshots)?
-->
Tested through Postman curls:
## Task 1
- Make a payment
```bash
curl --location 'http://localhost:8080/payments' \
--header 'Content-Type: application/json' \
--header 'Accept: application/json' \
--header 'api-key: dev_8z4jfpKL8jjyFFbnQ29mzfnGQYbtwi7CAE52JjUFpzro8ZC5iSK5NyFZkr4paZ6o' \
--data-raw '{
"amount": 6540,
"currency": "INR",
"confirm": true,
"capture_method": "automatic",
"capture_on": "2022-09-10T10:11:12Z",
"amount_to_capture": 6540,
"customer_id": "StripeCustomer",
"email": "test@test6.com",
"name": "John Doe",
"phone": "999999999",
"phone_country_code": "+1",
"description": "Its my first payment request",
"authentication_type": "no_three_ds",
"return_url": "https://google.com",
"payment_method": "card",
"payment_method_type": "credit",
"payment_method_data": {
"card": {
"card_number": "4242424242424242",
"card_exp_month": "10",
"card_exp_year": "25",
"card_holder_name": "joseph Doe",
"card_cvc": "123"
}
},
"billing": {
"address": {
"line1": "1467",
"line2": "Harrison Street",
"line3": "Harrison Street",
"city": "San Fransico",
"state": "California",
"zip": "94122",
"country": "US",
"first_name": "joseph",
"last_name": "Doe"
},
"phone": {
"number": "8056594427",
"country_code": "+91"
}
},
"shipping": {
"address": {
"line1": "1467",
"line2": "Harrison Street",
"line3": "Harrison Street",
"city": "San Fransico",
"state": "California",
"zip": "94122",
"country": "US",
"first_name": "joseph",
"last_name": "Doe"
},
"phone": {
"number": "8056594427",
"country_code": "+91"
}
},
"statement_descriptor_name": "joseph",
"statement_descriptor_suffix": "JS",
"feature_metadata": {
"search_tags": ["cc", "dd"]
},
"metadata": {
"data2": "camel",
"new_customer": "true",
"login_date": "2019-09-10T10:11:12Z"
}
}'
```
- Hit the search API with `status` as `success`
This will return the results of `Refunds` as internally, the `status` field gets converted into `refund_status` and `success` is the `Successful operation` in `Refunds`
```bash
curl --location 'http://localhost:8080/analytics/v1/search' \
--header 'Accept: */*' \
--header 'Accept-Language: en-US,en;q=0.9' \
--header 'Connection: keep-alive' \
--header 'Content-Type: application/json' \
--header 'Origin: http://localhost:9000' \
--header 'Referer: http://localhost:9000/' \
--header 'Sec-Fetch-Dest: empty' \
--header 'Sec-Fetch-Mode: cors' \
--header 'Sec-Fetch-Site: same-site' \
--header 'User-Agent: Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/126.0.0.0 Safari/537.36' \
--header 'api-key: hyperswitch' \
--header 'authorization: Bearer eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJ1c2VyX2lkIjoiYjc2ZDVmZjMtNGI1ZS00OTMyLTk1ZDItNmE3MTEyZWZiNTNlIiwibWVyY2hhbnRfaWQiOiJtZXJjaGFudF8xNzIxODE1MjkwIiwicm9sZV9pZCI6Im9yZ19hZG1pbiIsImV4cCI6MTcyMjY3NTU3MSwib3JnX2lkIjoib3JnX3VFNk1LbExxalU5MWlGUEVGck1rIn0.inysDehseXLwSvbWbDEVbL2q3oUJMm2h8okCDss1kGY' \
--header 'sec-ch-ua: "Not/A)Brand";v="8", "Chromium";v="126", "Google Chrome";v="126"' \
--header 'sec-ch-ua-mobile: ?0' \
--header 'sec-ch-ua-platform: "macOS"' \
--data '{
"query": "inr",
"filters": {
"status": [
"success"
]
}
}'
```
<img width="946" alt="image" src="https://github.com/user-attachments/assets/3db4d143-09d1-46b0-80d0-1c4cb52d3ae1">
## Task 2
- Make a payment
```bash
curl --location 'http://localhost:8080/payments' \
--header 'Content-Type: application/json' \
--header 'Accept: application/json' \
--header 'api-key: dev_8z4jfpKL8jjyFFbnQ29mzfnGQYbtwi7CAE52JjUFpzro8ZC5iSK5NyFZkr4paZ6o' \
--data-raw '{
"amount": 6540,
"currency": "INR",
"confirm": true,
"capture_method": "automatic",
"capture_on": "2022-09-10T10:11:12Z",
"amount_to_capture": 6540,
"customer_id": "StripeCustomer",
"email": "test@test6.com",
"name": "John Doe",
"phone": "999999999",
"phone_country_code": "+1",
"description": "Its my first payment request",
"authentication_type": "no_three_ds",
"return_url": "https://google.com",
"payment_method": "card",
"payment_method_type": "credit",
"payment_method_data": {
"card": {
"card_number": "4242424242424242",
"card_exp_month": "10",
"card_exp_year": "25",
"card_holder_name": "joseph Doe",
"card_cvc": "123"
}
},
"billing": {
"address": {
"line1": "1467",
"line2": "Harrison Street",
"line3": "Harrison Street",
"city": "San Fransico",
"state": "California",
"zip": "94122",
"country": "US",
"first_name": "joseph",
"last_name": "Doe"
},
"phone": {
"number": "8056594427",
"country_code": "+91"
}
},
"shipping": {
"address": {
"line1": "1467",
"line2": "Harrison Street",
"line3": "Harrison Street",
"city": "San Fransico",
"state": "California",
"zip": "94122",
"country": "US",
"first_name": "joseph",
"last_name": "Doe"
},
"phone": {
"number": "8056594427",
"country_code": "+91"
}
},
"statement_descriptor_name": "joseph",
"statement_descriptor_suffix": "JS",
"feature_metadata": {
"search_tags": ["cc", "dd"]
},
"metadata": {
"data2": "camel",
"new_customer": "true",
"login_date": "2019-09-10T10:11:12Z"
}
}'
```
- Hit the Search API:
Able to search based on the `timeRange` included in the request body
```bash
curl --location 'http://localhost:8080/analytics/v1/search' \
--header 'Accept: */*' \
--header 'Accept-Language: en-US,en;q=0.9' \
--header 'Connection: keep-alive' \
--header 'Content-Type: application/json' \
--header 'Origin: http://localhost:9000' \
--header 'Referer: http://localhost:9000/' \
--header 'Sec-Fetch-Dest: empty' \
--header 'Sec-Fetch-Mode: cors' \
--header 'Sec-Fetch-Site: same-site' \
--header 'User-Agent: Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/126.0.0.0 Safari/537.36' \
--header 'api-key: hyperswitch' \
--header 'authorization: Bearer eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJ1c2VyX2lkIjoiYjc2ZDVmZjMtNGI1ZS00OTMyLTk1ZDItNmE3MTEyZWZiNTNlIiwibWVyY2hhbnRfaWQiOiJtZXJjaGFudF8xNzIxODE1MjkwIiwicm9sZV9pZCI6Im9yZ19hZG1pbiIsImV4cCI6MTcyMjQxNTgyOSwib3JnX2lkIjoib3JnX3VFNk1LbExxalU5MWlGUEVGck1rIn0.GUmj5mbLgnYVanig6kwrU_gvLARQU4E68s438dvrhdc' \
--header 'sec-ch-ua: "Not/A)Brand";v="8", "Chromium";v="126", "Google Chrome";v="126"' \
--header 'sec-ch-ua-mobile: ?0' \
--header 'sec-ch-ua-platform: "macOS"' \
--data-raw '{
"query": "inr",
"filters": {
"customer_email": [
"test@test6.com"
],
"status": [
"succeeded"
]
},
"timeRange": {
"startTime": "2024-07-29T00:30:00Z",
"endTime": "2024-07-31T18:45:00Z"
}
}'
```
<img width="936" alt="image" src="https://github.com/user-attachments/assets/95045257-86ad-466f-82fe-4121b290d580">
## Checklist
<!-- Put an `x` in the boxes that apply -->
- [x] I formatted the code `cargo +nightly fmt --all`
- [x] I addressed lints thrown by `cargo clippy`
- [x] I reviewed the submitted code
- [ ] I added unit tests for my changes where possible
|
45a149418f1dad0cd27f975dc3dd56c68172b9dd
|
|
juspay/hyperswitch
|
juspay__hyperswitch-5496
|
Bug: [REFACTOR] Refactor routes for creating and activating the routing configs for v2
### Feature Description
Refactor routes for creating and activating the routing configs for v2
### Possible Implementation
Refactor routes for creating and activating the routing configs for v2
### Have you spent some time checking if this feature request has been raised before?
- [X] I checked and didn't find a similar issue
### Have you read the Contributing Guidelines?
- [X] I have read the [Contributing Guidelines](https://github.com/juspay/hyperswitch/blob/main/docs/CONTRIBUTING.md)
### Are you willing to submit a PR?
Yes, I am willing to submit a PR!
|
diff --git a/crates/api_models/Cargo.toml b/crates/api_models/Cargo.toml
index 84f8d2f01e9..b6b6f219bd8 100644
--- a/crates/api_models/Cargo.toml
+++ b/crates/api_models/Cargo.toml
@@ -17,8 +17,9 @@ frm = []
olap = []
openapi = ["common_enums/openapi", "olap", "recon", "dummy_connector", "olap"]
recon = []
+v1 =[]
v2 = []
-v1 = []
+routing_v2 = []
merchant_connector_account_v2 = []
customer_v2 = []
merchant_account_v2 = []
diff --git a/crates/api_models/src/events/routing.rs b/crates/api_models/src/events/routing.rs
index 1f068678c59..4c2c5ca2c0b 100644
--- a/crates/api_models/src/events/routing.rs
+++ b/crates/api_models/src/events/routing.rs
@@ -3,7 +3,7 @@ use common_utils::events::{ApiEventMetric, ApiEventsType};
use crate::routing::{
LinkedRoutingConfigRetrieveResponse, MerchantRoutingAlgorithm, ProfileDefaultRoutingConfig,
RoutingAlgorithmId, RoutingConfigRequest, RoutingDictionaryRecord, RoutingKind,
- RoutingPayloadWrapper, RoutingRetrieveLinkQuery, RoutingRetrieveQuery,
+ RoutingLinkWrapper, RoutingPayloadWrapper, RoutingRetrieveLinkQuery, RoutingRetrieveQuery,
};
impl ApiEventMetric for RoutingKind {
@@ -64,3 +64,9 @@ impl ApiEventMetric for RoutingRetrieveLinkQuery {
Some(ApiEventsType::Routing)
}
}
+
+impl ApiEventMetric for RoutingLinkWrapper {
+ fn get_api_event_type(&self) -> Option<ApiEventsType> {
+ Some(ApiEventsType::Routing)
+ }
+}
diff --git a/crates/api_models/src/routing.rs b/crates/api_models/src/routing.rs
index 7d1bb5bdf30..265d0451117 100644
--- a/crates/api_models/src/routing.rs
+++ b/crates/api_models/src/routing.rs
@@ -1,6 +1,6 @@
use std::fmt::Debug;
-use common_utils::errors::ParsingError;
+use common_utils::{errors::ParsingError, ext_traits::ValueExt, pii};
pub use euclid::{
dssa::types::EuclidAnalysable,
frontend::{
@@ -427,6 +427,14 @@ impl RoutingAlgorithmRef {
self.surcharge_config_algo_id = Some(ids);
self.timestamp = common_utils::date_time::now_unix_timestamp();
}
+
+ pub fn parse_routing_algorithm(
+ value: Option<pii::SecretSerdeValue>,
+ ) -> Result<Option<Self>, error_stack::Report<ParsingError>> {
+ value
+ .map(|val| val.parse_value::<Self>("RoutingAlgorithmRef"))
+ .transpose()
+ }
}
#[derive(Debug, Clone, serde::Serialize, serde::Deserialize, ToSchema)]
@@ -459,6 +467,12 @@ pub enum RoutingKind {
}
#[repr(transparent)]
-#[derive(serde::Serialize, serde::Deserialize, Debug)]
+#[derive(serde::Serialize, serde::Deserialize, Debug, Clone)]
#[serde(transparent)]
pub struct RoutingAlgorithmId(pub String);
+
+#[derive(Debug, Clone, serde::Serialize, serde::Deserialize)]
+pub struct RoutingLinkWrapper {
+ pub profile_id: String,
+ pub algorithm_id: RoutingAlgorithmId,
+}
diff --git a/crates/diesel_models/Cargo.toml b/crates/diesel_models/Cargo.toml
index 9024ffe79d7..c596cb2e2e1 100644
--- a/crates/diesel_models/Cargo.toml
+++ b/crates/diesel_models/Cargo.toml
@@ -10,7 +10,7 @@ license.workspace = true
[features]
default = ["kv_store", "v1"]
kv_store = []
-v1 = []
+v1 =[]
v2 = []
customer_v2 = []
merchant_account_v2 = []
@@ -27,6 +27,7 @@ strum = { version = "0.26.2", features = ["derive"] }
thiserror = "1.0.58"
time = { version = "0.3.35", features = ["serde", "serde-well-known", "std"] }
+
# First party crates
common_enums = { version = "0.1.0", path = "../common_enums" }
common_utils = { version = "0.1.0", path = "../common_utils" }
diff --git a/crates/hyperswitch_domain_models/src/lib.rs b/crates/hyperswitch_domain_models/src/lib.rs
index c48f721b210..450fdac8d8c 100644
--- a/crates/hyperswitch_domain_models/src/lib.rs
+++ b/crates/hyperswitch_domain_models/src/lib.rs
@@ -1,8 +1,10 @@
pub mod api;
+pub mod behaviour;
pub mod customer;
pub mod errors;
pub mod mandates;
pub mod merchant_account;
+pub mod merchant_key_store;
pub mod payment_address;
pub mod payment_method_data;
pub mod payments;
@@ -13,9 +15,6 @@ pub mod router_data_v2;
pub mod router_flow_types;
pub mod router_request_types;
pub mod router_response_types;
-
-pub mod behaviour;
-pub mod merchant_key_store;
pub mod type_encryption;
pub mod types;
diff --git a/crates/router/Cargo.toml b/crates/router/Cargo.toml
index 54cdb068ec5..2c40911f666 100644
--- a/crates/router/Cargo.toml
+++ b/crates/router/Cargo.toml
@@ -36,6 +36,7 @@ v1 = ["api_models/v1", "diesel_models/v1", "hyperswitch_domain_models/v1", "stor
customer_v2 = ["api_models/customer_v2", "diesel_models/customer_v2", "hyperswitch_domain_models/customer_v2"]
merchant_account_v2 = ["api_models/merchant_account_v2", "diesel_models/merchant_account_v2", "hyperswitch_domain_models/merchant_account_v2"]
payment_v2 = ["api_models/payment_v2", "diesel_models/payment_v2", "hyperswitch_domain_models/payment_v2"]
+routing_v2 = ["api_models/routing_v2"]
merchant_connector_account_v2 = ["api_models/merchant_connector_account_v2", "kgraph_utils/merchant_connector_account_v2"]
[dependencies]
diff --git a/crates/router/src/core/routing.rs b/crates/router/src/core/routing.rs
index c8ba5d6a0df..2451156e874 100644
--- a/crates/router/src/core/routing.rs
+++ b/crates/router/src/core/routing.rs
@@ -7,15 +7,23 @@ use api_models::{
self as routing_types, RoutingAlgorithmId, RoutingRetrieveLinkQuery, RoutingRetrieveQuery,
},
};
+#[cfg(all(feature = "v2", feature = "routing_v2"))]
+use diesel_models::routing_algorithm::RoutingAlgorithm;
+#[cfg(all(any(feature = "v1", feature = "v2"), not(feature = "routing_v2")))]
use diesel_models::routing_algorithm::RoutingAlgorithm;
use error_stack::ResultExt;
+#[cfg(all(feature = "v2", feature = "routing_v2"))]
+use masking::Secret;
use rustc_hash::FxHashSet;
use super::payments;
#[cfg(feature = "payouts")]
use super::payouts;
+#[cfg(all(any(feature = "v1", feature = "v2"), not(feature = "routing_v2")))]
+use crate::consts;
+#[cfg(all(feature = "v2", feature = "routing_v2"))]
+use crate::{consts, core::errors::RouterResult, db::StorageInterface};
use crate::{
- consts,
core::{
errors::{self, RouterResponse, StorageErrorExt},
metrics, utils as core_utils,
@@ -28,7 +36,6 @@ use crate::{
},
utils::{self, OptionExt, ValueExt},
};
-
pub enum TransactionData<'a, F>
where
F: Clone,
@@ -38,6 +45,77 @@ where
Payout(&'a payouts::PayoutData),
}
+#[cfg(all(feature = "v2", feature = "routing_v2"))]
+struct RoutingAlgorithmUpdate(RoutingAlgorithm);
+
+#[cfg(all(feature = "v2", feature = "routing_v2"))]
+impl RoutingAlgorithmUpdate {
+ pub fn create_new_routing_algorithm(
+ algorithm: routing_types::RoutingAlgorithm,
+ merchant_id: &common_utils::id_type::MerchantId,
+ name: String,
+ description: String,
+ profile_id: String,
+ transaction_type: &enums::TransactionType,
+ ) -> Self {
+ let algorithm_id = common_utils::generate_id(
+ consts::ROUTING_CONFIG_ID_LENGTH,
+ &format!("routing_{}", merchant_id.get_string_repr()),
+ );
+ let timestamp = common_utils::date_time::now();
+ let algo = RoutingAlgorithm {
+ algorithm_id,
+ profile_id,
+ merchant_id: merchant_id.clone(),
+ name,
+ description: Some(description),
+ kind: algorithm.get_kind().foreign_into(),
+ algorithm_data: serde_json::json!(algorithm),
+ created_at: timestamp,
+ modified_at: timestamp,
+ algorithm_for: transaction_type.to_owned(),
+ };
+ Self(algo)
+ }
+ pub async fn fetch_routing_algo(
+ merchant_id: &common_utils::id_type::MerchantId,
+ algorithm_id: &str,
+ db: &dyn StorageInterface,
+ ) -> RouterResult<Self> {
+ let routing_algo = db
+ .find_routing_algorithm_by_algorithm_id_merchant_id(algorithm_id, merchant_id)
+ .await
+ .change_context(errors::ApiErrorResponse::ResourceIdNotFound)?;
+ Ok(Self(routing_algo))
+ }
+
+ pub fn update_routing_ref_with_algorithm_id(
+ &self,
+ transaction_type: &enums::TransactionType,
+ routing_ref: &mut routing_types::RoutingAlgorithmRef,
+ ) -> RouterResult<()> {
+ utils::when(self.0.algorithm_for != *transaction_type, || {
+ Err(errors::ApiErrorResponse::PreconditionFailed {
+ message: format!(
+ "Cannot use {}'s routing algorithm for {} operation",
+ self.0.algorithm_for, transaction_type
+ ),
+ })
+ })?;
+
+ utils::when(
+ routing_ref.algorithm_id == Some(self.0.algorithm_id.clone()),
+ || {
+ Err(errors::ApiErrorResponse::PreconditionFailed {
+ message: "Algorithm is already active".to_string(),
+ })
+ },
+ )?;
+ routing_ref.update_algorithm_id(self.0.algorithm_id.clone());
+ Ok(())
+ }
+}
+
pub async fn retrieve_merchant_routing_dictionary(
state: SessionState,
merchant_account: domain::MerchantAccount,
@@ -67,6 +145,7 @@ pub async fn retrieve_merchant_routing_dictionary(
))
}
+#[cfg(all(feature = "v2", feature = "routing_v2"))]
pub async fn create_routing_config(
state: SessionState,
merchant_account: domain::MerchantAccount,
@@ -75,8 +154,94 @@ pub async fn create_routing_config(
transaction_type: &enums::TransactionType,
) -> RouterResponse<routing_types::RoutingDictionaryRecord> {
metrics::ROUTING_CREATE_REQUEST_RECEIVED.add(&metrics::CONTEXT, 1, &[]);
- let db = state.store.as_ref();
+ let db = &*state.store;
+ let name = request
+ .name
+ .get_required_value("name")
+ .change_context(errors::ApiErrorResponse::MissingRequiredField { field_name: "name" })
+ .attach_printable("Name of config not given")?;
+
+ let description = request
+ .description
+ .get_required_value("description")
+ .change_context(errors::ApiErrorResponse::MissingRequiredField {
+ field_name: "description",
+ })
+ .attach_printable("Description of config not given")?;
+
+ let algorithm = request
+ .algorithm
+ .get_required_value("algorithm")
+ .change_context(errors::ApiErrorResponse::MissingRequiredField {
+ field_name: "algorithm",
+ })
+ .attach_printable("Algorithm of config not given")?;
+
+ let business_profile = core_utils::validate_and_get_business_profile(
+ db,
+ request.profile_id.as_ref(),
+ merchant_account.get_id(),
+ )
+ .await?
+ .get_required_value("BusinessProfile")?;
+
+ let all_mcas = helpers::MerchantConnectorAccounts::get_all_mcas(
+ merchant_account.get_id(),
+ &key_store,
+ &state,
+ )
+ .await?;
+
+ let name_mca_id_set = helpers::ConnectNameAndMCAIdForProfile(
+ all_mcas.filter_by_profile(&business_profile.profile_id, |mca| {
+ (&mca.connector_name, &mca.merchant_connector_id)
+ }),
+ );
+
+ let name_set = helpers::ConnectNameForProfile(
+ all_mcas.filter_by_profile(&business_profile.profile_id, |mca| &mca.connector_name),
+ );
+
+ let algorithm_helper = helpers::RoutingAlgorithmHelpers {
+ name_mca_id_set,
+ name_set,
+ routing_algorithm: &algorithm,
+ };
+
+ algorithm_helper.validate_connectors_in_routing_config()?;
+
+ let algo = RoutingAlgorithmUpdate::create_new_routing_algorithm(
+ algorithm,
+ merchant_account.get_id(),
+ name,
+ description,
+ business_profile.profile_id,
+ transaction_type,
+ );
+
+ let record = state
+ .store
+ .as_ref()
+ .insert_routing_algorithm(algo.0)
+ .await
+ .to_not_found_response(errors::ApiErrorResponse::ResourceIdNotFound)?;
+
+ let new_record = record.foreign_into();
+ metrics::ROUTING_CREATE_SUCCESS_RESPONSE.add(&metrics::CONTEXT, 1, &[]);
+ Ok(service_api::ApplicationResponse::Json(new_record))
+}
+
+#[cfg(all(any(feature = "v1", feature = "v2"), not(feature = "routing_v2")))]
+pub async fn create_routing_config(
+ state: SessionState,
+ merchant_account: domain::MerchantAccount,
+ key_store: domain::MerchantKeyStore,
+ request: routing_types::RoutingConfigRequest,
+ transaction_type: &enums::TransactionType,
+) -> RouterResponse<routing_types::RoutingDictionaryRecord> {
+ metrics::ROUTING_CREATE_REQUEST_RECEIVED.add(&metrics::CONTEXT, 1, &[]);
+ let db = state.store.as_ref();
let name = request
.name
.get_required_value("name")
@@ -148,6 +313,56 @@ pub async fn create_routing_config(
Ok(service_api::ApplicationResponse::Json(new_record))
}
+#[cfg(all(feature = "v2", feature = "routing_v2"))]
+pub async fn link_routing_config(
+ state: SessionState,
+ merchant_account: domain::MerchantAccount,
+ profile_id: String,
+ algorithm_id: String,
+ transaction_type: &enums::TransactionType,
+) -> RouterResponse<routing_types::RoutingDictionaryRecord> {
+ metrics::ROUTING_LINK_CONFIG.add(&metrics::CONTEXT, 1, &[]);
+ let db = state.store.as_ref();
+
+ let routing_algorithm =
+ RoutingAlgorithmUpdate::fetch_routing_algo(merchant_account.get_id(), &algorithm_id, db)
+ .await?;
+ utils::when(routing_algorithm.0.profile_id != profile_id, || {
+ Err(errors::ApiErrorResponse::PreconditionFailed {
+ message: "Profile Id is invalid for the routing config".to_string(),
+ })
+ })?;
+ let business_profile = core_utils::validate_and_get_business_profile(
+ db,
+ Some(&profile_id),
+ merchant_account.get_id(),
+ )
+ .await?
+ .get_required_value("BusinessProfile")?;
+
+ let mut routing_ref = routing_types::RoutingAlgorithmRef::parse_routing_algorithm(
+ business_profile.routing_algorithm.clone().map(Secret::new),
+ )
+ .change_context(errors::ApiErrorResponse::InternalServerError)
+ .attach_printable("unable to deserialize routing algorithm ref from merchant account")?
+ .unwrap_or_default();
+
+ routing_algorithm.update_routing_ref_with_algorithm_id(transaction_type, &mut routing_ref)?;
+ // TODO move to business profile
+ helpers::update_business_profile_active_algorithm_ref(
+ db,
+ business_profile,
+ routing_ref,
+ transaction_type,
+ )
+ .await?;
+ metrics::ROUTING_LINK_CONFIG_SUCCESS_RESPONSE.add(&metrics::CONTEXT, 1, &[]);
+ Ok(service_api::ApplicationResponse::Json(
+ routing_algorithm.0.foreign_into(),
+ ))
+}
+
+#[cfg(all(any(feature = "v1", feature = "v2"), not(feature = "routing_v2")))]
pub async fn link_routing_config(
state: SessionState,
merchant_account: domain::MerchantAccount,
@@ -249,6 +464,7 @@ pub async fn retrieve_routing_config(
metrics::ROUTING_RETRIEVE_CONFIG_SUCCESS_RESPONSE.add(&metrics::CONTEXT, 1, &[]);
Ok(service_api::ApplicationResponse::Json(response))
}
+
pub async fn unlink_routing_config(
state: SessionState,
merchant_account: domain::MerchantAccount,
@@ -326,6 +542,7 @@ pub async fn unlink_routing_config(
}
}
+//feature update
pub async fn update_default_routing_config(
state: SessionState,
merchant_account: domain::MerchantAccount,
diff --git a/crates/router/src/core/routing/helpers.rs b/crates/router/src/core/routing/helpers.rs
index 5978ef521a8..d4729d1e629 100644
--- a/crates/router/src/core/routing/helpers.rs
+++ b/crates/router/src/core/routing/helpers.rs
@@ -12,6 +12,8 @@ use error_stack::ResultExt;
use rustc_hash::FxHashSet;
use storage_impl::redis::cache;
+#[cfg(all(feature = "v2", feature = "routing_v2"))]
+use crate::types::domain::MerchantConnectorAccount;
use crate::{
core::errors::{self, RouterResult},
db::StorageInterface,
@@ -20,54 +22,6 @@ use crate::{
utils::StringExt,
};
-/// provides the complete merchant routing dictionary that is basically a list of all the routing
-/// configs a merchant configured with an active_id field that specifies the current active routing
-/// config
-// pub async fn get_merchant_routing_dictionary(
-// db: &dyn StorageInterface,
-// merchant_id: &str,
-// ) -> RouterResult<routing_types::RoutingDictionary> {
-// let key = get_routing_dictionary_key(merchant_id);
-// let maybe_dict = db.find_config_by_key(&key).await;
-
-// match maybe_dict {
-// Ok(config) => config
-// .config
-// .parse_struct("RoutingDictionary")
-// .change_context(errors::ApiErrorResponse::InternalServerError)
-// .attach_printable("Merchant routing dictionary has invalid structure"),
-
-// Err(e) if e.current_context().is_db_not_found() => {
-// let new_dictionary = routing_types::RoutingDictionary {
-// merchant_id: merchant_id.to_owned(),
-// active_id: None,
-// records: Vec::new(),
-// };
-
-// let serialized = new_dictionary
-// .encode_to_string_of_json()
-// .change_context(errors::ApiErrorResponse::InternalServerError)
-// .attach_printable("Error serializing newly created merchant dictionary")?;
-
-// let new_config = configs::ConfigNew {
-// key,
-// config: serialized,
-// };
-
-// db.insert_config(new_config)
-// .await
-// .change_context(errors::ApiErrorResponse::InternalServerError)
-// .attach_printable("Error inserting new routing dictionary for merchant")?;
-
-// Ok(new_dictionary)
-// }
-
-// Err(e) => Err(e)
-// .change_context(errors::ApiErrorResponse::InternalServerError)
-// .attach_printable("Error fetching routing dictionary for merchant"),
-// }
-// }
-
/// Provides us with all the configured configs of the Merchant in the ascending time configured
/// manner and chooses the first of them
pub async fn get_merchant_default_config(
@@ -163,28 +117,6 @@ pub async fn update_merchant_routing_dictionary(
Ok(())
}
-pub async fn update_routing_algorithm(
- db: &dyn StorageInterface,
- algorithm_id: String,
- algorithm: routing_types::RoutingAlgorithm,
-) -> RouterResult<()> {
- let algorithm_str = algorithm
- .encode_to_string_of_json()
- .change_context(errors::ApiErrorResponse::InternalServerError)
- .attach_printable("Unable to serialize routing algorithm to string")?;
-
- let config_update = configs::ConfigUpdate::Update {
- config: Some(algorithm_str),
- };
-
- db.update_config_by_key(&algorithm_id, config_update)
- .await
- .change_context(errors::ApiErrorResponse::InternalServerError)
- .attach_printable("Error updating the routing algorithm in DB")?;
-
- Ok(())
-}
-
/// This will help make one of all configured algorithms to be in active state for a particular
/// merchant
pub async fn update_merchant_active_algorithm_ref(
@@ -238,7 +170,7 @@ pub async fn update_merchant_active_algorithm_ref(
Ok(())
}
-
+// TODO: Move it to business_profile
pub async fn update_business_profile_active_algorithm_ref(
db: &dyn StorageInterface,
current_business_profile: BusinessProfile,
@@ -307,6 +239,157 @@ pub async fn update_business_profile_active_algorithm_ref(
Ok(())
}
+#[cfg(all(feature = "v2", feature = "routing_v2"))]
+#[derive(Clone, Debug)]
+pub struct RoutingAlgorithmHelpers<'h> {
+ pub name_mca_id_set: ConnectNameAndMCAIdForProfile<'h>,
+ pub name_set: ConnectNameForProfile<'h>,
+ pub routing_algorithm: &'h routing_types::RoutingAlgorithm,
+}
+
+#[derive(Clone, Debug)]
+pub struct ConnectNameAndMCAIdForProfile<'a>(pub FxHashSet<(&'a String, &'a String)>);
+#[derive(Clone, Debug)]
+pub struct ConnectNameForProfile<'a>(pub FxHashSet<&'a String>);
+
+#[cfg(all(feature = "v2", feature = "routing_v2"))]
+#[derive(Clone, Debug)]
+pub struct MerchantConnectorAccounts(pub Vec<MerchantConnectorAccount>);
+
+#[cfg(all(feature = "v2", feature = "routing_v2"))]
+impl MerchantConnectorAccounts {
+ pub async fn get_all_mcas(
+ merchant_id: &common_utils::id_type::MerchantId,
+ key_store: &domain::MerchantKeyStore,
+ state: &SessionState,
+ ) -> RouterResult<Self> {
+ let db = &*state.store;
+ let key_manager_state = &state.into();
+ Ok(Self(
+ db.find_merchant_connector_account_by_merchant_id_and_disabled_list(
+ key_manager_state,
+ merchant_id,
+ true,
+ key_store,
+ )
+ .await
+ .change_context(
+ errors::ApiErrorResponse::MerchantConnectorAccountNotFound {
+ id: merchant_id.get_string_repr().to_owned(),
+ },
+ )?,
+ ))
+ }
+
+ fn filter_and_map<'a, T>(
+ &'a self,
+ filter: impl Fn(&'a MerchantConnectorAccount) -> bool,
+ func: impl Fn(&'a MerchantConnectorAccount) -> T,
+ ) -> FxHashSet<T>
+ where
+ T: std::hash::Hash + Eq,
+ {
+ self.0
+ .iter()
+ .filter(|mca| filter(mca))
+ .map(func)
+ .collect::<FxHashSet<_>>()
+ }
+
+ pub fn filter_by_profile<'a, T>(
+ &'a self,
+ profile_id: &'a str,
+ func: impl Fn(&'a MerchantConnectorAccount) -> T,
+ ) -> FxHashSet<T>
+ where
+ T: std::hash::Hash + Eq,
+ {
+ self.filter_and_map(|mca| mca.profile_id.as_deref() == Some(profile_id), func)
+ }
+}
+
+#[cfg(all(feature = "v2", feature = "routing_v2"))]
+impl<'h> RoutingAlgorithmHelpers<'h> {
+ fn connector_choice(
+ &self,
+ choice: &routing_types::RoutableConnectorChoice,
+ ) -> RouterResult<()> {
+ if let Some(ref mca_id) = choice.merchant_connector_id {
+ error_stack::ensure!(
+ self.name_mca_id_set.0.contains(&(&choice.connector.to_string(), mca_id)),
+ errors::ApiErrorResponse::InvalidRequestData {
+ message: format!(
+ "connector with name '{}' and merchant connector account id '{}' not found for the given profile",
+ choice.connector,
+ mca_id,
+ )
+ }
+ );
+ } else {
+ error_stack::ensure!(
+ self.name_set.0.contains(&choice.connector.to_string()),
+ errors::ApiErrorResponse::InvalidRequestData {
+ message: format!(
+ "connector with name '{}' not found for the given profile",
+ choice.connector,
+ )
+ }
+ );
+ };
+ Ok(())
+ }
+
+ pub fn validate_connectors_in_routing_config(&self) -> RouterResult<()> {
+ match self.routing_algorithm {
+ routing_types::RoutingAlgorithm::Single(choice) => {
+ self.connector_choice(choice)?;
+ }
+
+ routing_types::RoutingAlgorithm::Priority(list) => {
+ for choice in list {
+ self.connector_choice(choice)?;
+ }
+ }
+
+ routing_types::RoutingAlgorithm::VolumeSplit(splits) => {
+ for split in splits {
+ self.connector_choice(&split.connector)?;
+ }
+ }
+
+ routing_types::RoutingAlgorithm::Advanced(program) => {
+ let check_connector_selection =
+ |selection: &routing_types::ConnectorSelection| -> RouterResult<()> {
+ match selection {
+ routing_types::ConnectorSelection::VolumeSplit(splits) => {
+ for split in splits {
+ self.connector_choice(&split.connector)?;
+ }
+ }
+
+ routing_types::ConnectorSelection::Priority(list) => {
+ for choice in list {
+ self.connector_choice(choice)?;
+ }
+ }
+ }
+
+ Ok(())
+ };
+
+ check_connector_selection(&program.default_selection)?;
+
+ for rule in &program.rules {
+ check_connector_selection(&rule.connector_selection)?;
+ }
+ }
+ }
+
+ Ok(())
+ }
+}
+
+#[cfg(all(any(feature = "v1", feature = "v2"), not(feature = "routing_v2")))]
pub async fn validate_connectors_in_routing_config(
state: &SessionState,
key_store: &domain::MerchantKeyStore,
@@ -326,7 +409,6 @@ pub async fn validate_connectors_in_routing_config(
.change_context(errors::ApiErrorResponse::MerchantConnectorAccountNotFound {
id: merchant_id.get_string_repr().to_owned(),
})?;
-
let name_mca_id_set = all_mcas
.iter()
.filter(|mca| mca.profile_id.as_deref() == Some(profile_id))
@@ -339,7 +421,7 @@ pub async fn validate_connectors_in_routing_config(
.map(|mca| &mca.connector_name)
.collect::<FxHashSet<_>>();
- let check_connector_choice = |choice: &routing_types::RoutableConnectorChoice| {
+ let connector_choice = |choice: &routing_types::RoutableConnectorChoice| {
if let Some(ref mca_id) = choice.merchant_connector_id {
error_stack::ensure!(
name_mca_id_set.contains(&(&choice.connector.to_string(), mca_id)),
@@ -368,18 +450,18 @@ pub async fn validate_connectors_in_routing_config(
match routing_algorithm {
routing_types::RoutingAlgorithm::Single(choice) => {
- check_connector_choice(choice)?;
+ connector_choice(choice)?;
}
routing_types::RoutingAlgorithm::Priority(list) => {
for choice in list {
- check_connector_choice(choice)?;
+ connector_choice(choice)?;
}
}
routing_types::RoutingAlgorithm::VolumeSplit(splits) => {
for split in splits {
- check_connector_choice(&split.connector)?;
+ connector_choice(&split.connector)?;
}
}
@@ -389,13 +471,13 @@ pub async fn validate_connectors_in_routing_config(
match selection {
routing_types::ConnectorSelection::VolumeSplit(splits) => {
for split in splits {
- check_connector_choice(&split.connector)?;
+ connector_choice(&split.connector)?;
}
}
routing_types::ConnectorSelection::Priority(list) => {
for choice in list {
- check_connector_choice(choice)?;
+ connector_choice(choice)?;
}
}
}
diff --git a/crates/router/src/routes/app.rs b/crates/router/src/routes/app.rs
index 08d960e6693..709cdae6355 100644
--- a/crates/router/src/routes/app.rs
+++ b/crates/router/src/routes/app.rs
@@ -1,7 +1,11 @@
use std::{collections::HashMap, sync::Arc};
use actix_web::{web, Scope};
-#[cfg(feature = "olap")]
+#[cfg(all(
+ feature = "olap",
+ any(feature = "v1", feature = "v2"),
+ not(feature = "routing_v2")
+))]
use api_models::routing::RoutingRetrieveQuery;
#[cfg(feature = "olap")]
use common_enums::TransactionType;
@@ -39,7 +43,7 @@ use super::pm_auth;
#[cfg(feature = "oltp")]
use super::poll::retrieve_poll_status;
#[cfg(feature = "olap")]
-use super::routing as cloud_routing;
+use super::routing;
#[cfg(feature = "olap")]
use super::verification::{apple_pay_merchant_registration, retrieve_apple_pay_verified_domains};
#[cfg(feature = "olap")]
@@ -62,7 +66,6 @@ use crate::routes::fraud_check as frm_routes;
use crate::routes::recon as recon_routes;
pub use crate::{
configs::settings,
- core::routing,
db::{CommonStorageInterface, GlobalStorageInterface, StorageImpl, StorageInterface},
events::EventsHandler,
routes::cards_info::card_iin_info,
@@ -567,7 +570,27 @@ impl Forex {
#[cfg(feature = "olap")]
pub struct Routing;
-#[cfg(feature = "olap")]
+#[cfg(all(feature = "olap", feature = "v2", feature = "routing_v2"))]
+impl Routing {
+ pub fn server(state: AppState) -> Scope {
+ web::scope("/v2/routing_algorithm")
+ .app_data(web::Data::new(state.clone()))
+ .service(
+ web::resource("").route(web::post().to(|state, req, payload| {
+ routing::routing_create_config(state, req, payload, &TransactionType::Payment)
+ })),
+ )
+ .service(
+ web::resource("/{algorithm_id}")
+ .route(web::get().to(routing::routing_retrieve_config)),
+ )
+ }
+}
+#[cfg(all(
+ feature = "olap",
+ any(feature = "v1", feature = "v2"),
+ not(feature = "routing_v2")
+))]
impl Routing {
pub fn server(state: AppState) -> Scope {
#[allow(unused_mut)]
@@ -575,7 +598,7 @@ impl Routing {
.app_data(web::Data::new(state.clone()))
.service(
web::resource("/active").route(web::get().to(|state, req, query_params| {
- cloud_routing::routing_retrieve_linked_config(
+ routing::routing_retrieve_linked_config(
state,
req,
query_params,
@@ -587,7 +610,7 @@ impl Routing {
web::resource("")
.route(
web::get().to(|state, req, path: web::Query<RoutingRetrieveQuery>| {
- cloud_routing::list_routing_configs(
+ routing::list_routing_configs(
state,
req,
path,
@@ -596,7 +619,7 @@ impl Routing {
}),
)
.route(web::post().to(|state, req, payload| {
- cloud_routing::routing_create_config(
+ routing::routing_create_config(
state,
req,
payload,
@@ -607,14 +630,14 @@ impl Routing {
.service(
web::resource("/default")
.route(web::get().to(|state, req| {
- cloud_routing::routing_retrieve_default_config(
+ routing::routing_retrieve_default_config(
state,
req,
&TransactionType::Payment,
)
}))
.route(web::post().to(|state, req, payload| {
- cloud_routing::routing_update_default_config(
+ routing::routing_update_default_config(
state,
req,
payload,
@@ -624,32 +647,25 @@ impl Routing {
)
.service(
web::resource("/deactivate").route(web::post().to(|state, req, payload| {
- cloud_routing::routing_unlink_config(
- state,
- req,
- payload,
- &TransactionType::Payment,
- )
+ routing::routing_unlink_config(state, req, payload, &TransactionType::Payment)
})),
)
.service(
web::resource("/decision")
- .route(web::put().to(cloud_routing::upsert_decision_manager_config))
- .route(web::get().to(cloud_routing::retrieve_decision_manager_config))
- .route(web::delete().to(cloud_routing::delete_decision_manager_config)),
+ .route(web::put().to(routing::upsert_decision_manager_config))
+ .route(web::get().to(routing::retrieve_decision_manager_config))
+ .route(web::delete().to(routing::delete_decision_manager_config)),
)
.service(
web::resource("/decision/surcharge")
- .route(web::put().to(cloud_routing::upsert_surcharge_decision_manager_config))
- .route(web::get().to(cloud_routing::retrieve_surcharge_decision_manager_config))
- .route(
- web::delete().to(cloud_routing::delete_surcharge_decision_manager_config),
- ),
+ .route(web::put().to(routing::upsert_surcharge_decision_manager_config))
+ .route(web::get().to(routing::retrieve_surcharge_decision_manager_config))
+ .route(web::delete().to(routing::delete_surcharge_decision_manager_config)),
)
.service(
web::resource("/default/profile/{profile_id}").route(web::post().to(
|state, req, path, payload| {
- cloud_routing::routing_update_default_config_for_profile(
+ routing::routing_update_default_config_for_profile(
state,
req,
path,
@@ -661,7 +677,7 @@ impl Routing {
)
.service(
web::resource("/default/profile").route(web::get().to(|state, req| {
- cloud_routing::routing_retrieve_default_config_for_profiles(
+ routing::routing_retrieve_default_config_for_profiles(
state,
req,
&TransactionType::Payment,
@@ -676,7 +692,7 @@ impl Routing {
web::resource("/payouts")
.route(web::get().to(
|state, req, path: web::Query<RoutingRetrieveQuery>| {
- cloud_routing::list_routing_configs(
+ routing::list_routing_configs(
state,
req,
path,
@@ -685,7 +701,7 @@ impl Routing {
},
))
.route(web::post().to(|state, req, payload| {
- cloud_routing::routing_create_config(
+ routing::routing_create_config(
state,
req,
payload,
@@ -695,7 +711,7 @@ impl Routing {
)
.service(web::resource("/payouts/active").route(web::get().to(
|state, req, query_params| {
- cloud_routing::routing_retrieve_linked_config(
+ routing::routing_retrieve_linked_config(
state,
req,
query_params,
@@ -706,14 +722,14 @@ impl Routing {
.service(
web::resource("/payouts/default")
.route(web::get().to(|state, req| {
- cloud_routing::routing_retrieve_default_config(
+ routing::routing_retrieve_default_config(
state,
req,
&TransactionType::Payout,
)
}))
.route(web::post().to(|state, req, payload| {
- cloud_routing::routing_update_default_config(
+ routing::routing_update_default_config(
state,
req,
payload,
@@ -724,18 +740,13 @@ impl Routing {
.service(
web::resource("/payouts/{algorithm_id}/activate").route(web::post().to(
|state, req, path| {
- cloud_routing::routing_link_config(
- state,
- req,
- path,
- &TransactionType::Payout,
- )
+ routing::routing_link_config(state, req, path, &TransactionType::Payout)
},
)),
)
.service(web::resource("/payouts/deactivate").route(web::post().to(
|state, req, payload| {
- cloud_routing::routing_unlink_config(
+ routing::routing_unlink_config(
state,
req,
payload,
@@ -746,7 +757,7 @@ impl Routing {
.service(
web::resource("/payouts/default/profile/{profile_id}").route(web::post().to(
|state, req, path, payload| {
- cloud_routing::routing_update_default_config_for_profile(
+ routing::routing_update_default_config_for_profile(
state,
req,
path,
@@ -758,7 +769,7 @@ impl Routing {
)
.service(
web::resource("/payouts/default/profile").route(web::get().to(|state, req| {
- cloud_routing::routing_retrieve_default_config_for_profiles(
+ routing::routing_retrieve_default_config_for_profiles(
state,
req,
&TransactionType::Payout,
@@ -770,17 +781,12 @@ impl Routing {
route = route
.service(
web::resource("/{algorithm_id}")
- .route(web::get().to(cloud_routing::routing_retrieve_config)),
+ .route(web::get().to(routing::routing_retrieve_config)),
)
.service(
web::resource("/{algorithm_id}/activate").route(web::post().to(
|state, req, path| {
- cloud_routing::routing_link_config(
- state,
- req,
- path,
- &TransactionType::Payment,
- )
+ routing::routing_link_config(state, req, path, &TransactionType::Payment)
},
)),
);
@@ -1365,8 +1371,64 @@ impl PayoutLink {
}
pub struct BusinessProfile;
-
-#[cfg(feature = "olap")]
+#[cfg(all(feature = "olap", feature = "v2", feature = "routing_v2"))]
+impl BusinessProfile {
+ pub fn server(state: AppState) -> Scope {
+ web::scope("/v2/profiles")
+ .app_data(web::Data::new(state))
+ .service(
+ web::scope("/{profile_id}")
+ .service(
+ web::resource("/fallback_routing")
+ .route(web::get().to(|state, req| {
+ routing::routing_retrieve_default_config(
+ state,
+ req,
+ &TransactionType::Payment,
+ )
+ }))
+ .route(web::post().to(|state, req, payload| {
+ routing::routing_update_default_config(
+ state,
+ req,
+ payload,
+ &TransactionType::Payment,
+ )
+ })),
+ )
+ .service(
+ web::resource("/activate_routing_algorithm").route(web::patch().to(
+ |state, req, path, payload| {
+ routing::routing_link_config(
+ state,
+ req,
+ path,
+ payload,
+ &TransactionType::Payment,
+ )
+ },
+ )),
+ )
+ .service(
+ web::resource("/deactivate_routing_algorithm").route(web::post().to(
+ |state, req, path| {
+ routing::routing_unlink_config(
+ state,
+ req,
+ path,
+ &TransactionType::Payment,
+ )
+ },
+ )),
+ ),
+ )
+ }
+}
+#[cfg(all(
+ feature = "olap",
+ any(feature = "v1", feature = "v2"),
+ not(feature = "routing_v2")
+))]
impl BusinessProfile {
pub fn server(state: AppState) -> Scope {
web::scope("/account/{account_id}/business_profile")
diff --git a/crates/router/src/routes/routing.rs b/crates/router/src/routes/routing.rs
index 788acd4ba2d..f410a79028e 100644
--- a/crates/router/src/routes/routing.rs
+++ b/crates/router/src/routes/routing.rs
@@ -53,7 +53,11 @@ pub async fn routing_create_config(
.await
}
-#[cfg(feature = "olap")]
+#[cfg(all(
+ feature = "olap",
+ any(feature = "v1", feature = "v2"),
+ not(feature = "routing_v2")
+))]
#[instrument(skip_all)]
pub async fn routing_link_config(
state: web::Data<AppState>,
@@ -88,6 +92,48 @@ pub async fn routing_link_config(
.await
}
+#[cfg(all(feature = "olap", feature = "v2", feature = "routing_v2"))]
+#[instrument(skip_all)]
+pub async fn routing_link_config(
+ state: web::Data<AppState>,
+ req: HttpRequest,
+ path: web::Path<String>,
+ 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,
+ |state, auth: auth::AuthenticationData, wrapper, _| {
+ routing::link_routing_config(
+ state,
+ auth.merchant_account,
+ wrapper.profile_id,
+ wrapper.algorithm_id.0,
+ transaction_type,
+ )
+ },
+ #[cfg(not(feature = "release"))]
+ auth::auth_type(
+ &auth::ApiKeyAuth,
+ &auth::JWTAuth(Permission::RoutingWrite),
+ req.headers(),
+ ),
+ #[cfg(feature = "release")]
+ &auth::JWTAuth(Permission::RoutingWrite),
+ api_locking::LockAction::NotApplicable,
+ ))
+ .await
+}
+
#[cfg(feature = "olap")]
#[instrument(skip_all)]
pub async fn routing_retrieve_config(
diff --git a/justfile b/justfile
index b755e3d7de0..228653a007a 100644
--- a/justfile
+++ b/justfile
@@ -55,7 +55,7 @@ check_v2 *FLAGS:
jq -r '
[ ( .workspace_members | sort ) as $package_ids # Store workspace crate package IDs in `package_ids` array
| .packages[] | select( IN(.id; $package_ids[]) ) | .features | keys[] ] | unique # Select all unique features from all workspace crates
- | del( .[] | select( any( . ; . == ("v1", "merchant_account_v2", "payment_v2") ) ) ) # Exclude some features from features list
+ | del( .[] | select( any( . ; . == ("v1", "merchant_account_v2", "payment_v2","routing_v2") ) ) ) # Exclude some features from features list
| join(",") # Construct a comma-separated string of features for passing to `cargo`
')"
|
2024-07-23T19:12:18Z
|
## Type of Change
<!-- Put an `x` in the boxes that apply -->
- [ ] Bugfix
- [ ] New feature
- [ ] Enhancement
- [x] Refactoring
- [ ] Dependency updates
- [ ] Documentation
- [ ] CI/CD
## Description
This PR adds a `Routing_v2` flag and renames all the endpoints, and refactors the create and activate endpoints
### Additional Changes
- [ ] This PR modifies the API contract
- [ ] This PR modifies the database schema
- [ ] This PR modifies application configuration/environment variables
<!--
Provide links to the files with corresponding changes.
Following are the paths where you can find config files:
1. `config`
2. `crates/router/src/configs`
3. `loadtest/config`
-->
## Motivation and Context
<!--
Why is this change required? What problem does it solve?
If it fixes an open issue, please link to the issue here.
If you don't have an issue, we'd recommend starting with one first so the PR
can focus on the implementation (unless it is an obvious bug or documentation fix
that will have little conversation).
-->
## How did you test it?
- Create routing
```
curl --location 'http://localhost:8080/routing_algorithm' \
--header 'Content-Type: application/json' \
--header 'api-key: dev_1ZYFaypqi4RKpkjTFbHHkdgAqvUsG6TYJXoH53D59BQ1uFMrBIcxrF4f7FiJkOWw' \
--data '{
"name": "newalgo",
"description": "It is my ADVANCED config",
"algorithm": {
"type": "advanced",
"data": {
"defaultSelection": {
"type": "priority",
"data": [
{"connector": "adyen",
"merchant_connector_id":"mca_XcrOMvDBAiq6ln7ESbu0"}
]
},
"rules": [
{
"name": "adyen",
"connectorSelection": {
"type": "priority",
"data": [
{ "connector": "adyen",
"merchant_connector_id":"mca_XcrOMvDBAiq6ln7ESbu0"},
{
"connector": "cybersource",
"merchant_connector_id":"mca_8uCqbT9Bt9bmKUVuR3IA"
}
]
},
"statements": [
{
"condition": [
{
"lhs": "payment_amount",
"comparison": "greater_than",
"value": {
"type": "number",
"value": 100077
},
"metadata": {}
}
],
"nested": null
}
]
}
],
"metadata": {}
}
},
"profile_id":"pro_r6qEFW0XLe7UnQoaaQ67"
}'
```
- Activate Routing Algorihtm
```
curl --location --request PATCH 'http://localhost:8080/v2/profiles/pro_r6qEFW0XLe7UnQoaaQ67/activate_routing_algorithm' \
--header 'Content-Type: application/json' \
--header 'api-key: dev_1ZYFaypqi4RKpkjTFbHHkdgAqvUsG6TYJXoH53D59BQ1uFMrBIcxrF4f7FiJkOWw' \
--data '"routing_merchant_1721842459_WWHyZVY3oW"
'
```
- The activated algorithm is then store in Business Profile Against that profile_id
<img width="1728" alt="Screenshot 2024-07-29 at 2 33 56 PM" src="https://github.com/user-attachments/assets/f66170fe-9bfd-479e-a8b2-5d4b42f75e66">
## Checklist
<!-- Put an `x` in the boxes that apply -->
- [ ] I formatted the code `cargo +nightly fmt --all`
- [ ] I addressed lints thrown by `cargo clippy`
- [ ] I reviewed the submitted code
- [ ] I added unit tests for my changes where possible
|
540ef071cb238a56d52d06687226aab7fd0dfe68
|
|
juspay/hyperswitch
|
juspay__hyperswitch-5491
|
Bug: feat(auth): Support profile level authentication
- After the dashboard is changed to profile level, there will be 3 types of APIs based on the level
1. Merchant Level only
- API Keys
- Merchant Account
- Business profile
2. Profile Level only
- Connectors
- Routing
- Operations (Payment, refund, disputes except list and filter)
- etc...
1. Profile + Merchant
- Operations list and filter
- etc...
### Merchant Level APIs
- No changes here.
### Profile Level only
- These should start accepting an optional profile_id in the function parameter, which will be passed from auth layer.
- There are some APIs which are currently at pseudo profile level like payments create and refunds create.
- Currently these kind APIs take profile_id in the payload or query param.
- From now on, these should not accept these in the request and take those values from the auth layer.
- To support the current API calls, these will fallback to body if profile_id in header is not present.
### Profile + Merchant Level
- These APIs should operate both in merchant level and profile level.
- These APIs accept a vec of profile_ids in the function parameter.
- There should be different routes for these APIs and probably the core function will remain same.
- The route function will be different for each route but calls the same core function.
- If the profile_id vec is not empty, then the API will send the data for those specific profile_ids else for the whole merchant.
## Breaking changes
- Current APIs will be changed in a way that the current calls will work without any changes. So there shouldn't be any breaking changes.
## Auth
- Auth layer will now give either
1. org_id, merchant_id and profile_id
2. org_id, merchant_id and Vec<profile_id>
- There are currently two types of JWT Auths.
1. JWTAuth
2. JWTMerchantFromRoute
- Both of these will have a new implementation which will send the data as mentioned in the first point.
- Both of these have profile_id as optional type for backwards compatibility.
- Once we have a stable version where profile_id is always present in the JWT, then we can have following JWT Auths for more checks.
1. JWTAuth
2. JWTMerchantFromRoute
3. JWTProfileFromRoute
4. JWTMerchantAndProfileFromRoute
- These will always have profile_id in the payload.
- Routes can choose to pass or not to pass the profile data to the core function.
|
diff --git a/crates/router/src/core/user.rs b/crates/router/src/core/user.rs
index 40741c76198..457a71dff8b 100644
--- a/crates/router/src/core/user.rs
+++ b/crates/router/src/core/user.rs
@@ -138,7 +138,9 @@ pub async fn signup(
.await?;
utils::user_role::set_role_permissions_in_cache_by_user_role(&state, &user_role).await;
- let token = utils::user::generate_jwt_auth_token(&state, &user_from_db, &user_role).await?;
+ let token =
+ utils::user::generate_jwt_auth_token_without_profile(&state, &user_from_db, &user_role)
+ .await?;
let response =
utils::user::get_dashboard_entry_response(&state, user_from_db, user_role, token.clone())?;
@@ -894,6 +896,7 @@ async fn handle_new_user_invitation(
merchant_id: user_from_token.merchant_id.clone(),
org_id: user_from_token.org_id.clone(),
role_id: request.role_id.clone(),
+ profile_id: None,
};
let set_metadata_request = SetMetaDataRequest::IsChangePasswordRequired;
@@ -1036,8 +1039,12 @@ pub async fn accept_invite_from_email(
.change_context(UserErrors::InternalServerError)?
.into();
- let token =
- utils::user::generate_jwt_auth_token(&state, &user_from_db, &update_status_result).await?;
+ let token = utils::user::generate_jwt_auth_token_without_profile(
+ &state,
+ &user_from_db,
+ &update_status_result,
+ )
+ .await?;
utils::user_role::set_role_permissions_in_cache_by_user_role(&state, &update_status_result)
.await;
@@ -1263,6 +1270,7 @@ pub async fn switch_merchant_id(
request.merchant_id.clone(),
org_id.clone(),
user_from_token.role_id.clone(),
+ None,
)
.await?;
@@ -1295,7 +1303,8 @@ pub async fn switch_merchant_id(
.ok_or(report!(UserErrors::InvalidRoleOperation))
.attach_printable("User doesn't have access to switch")?;
- let token = utils::user::generate_jwt_auth_token(&state, &user, user_role).await?;
+ let token =
+ utils::user::generate_jwt_auth_token_without_profile(&state, &user, user_role).await?;
utils::user_role::set_role_permissions_in_cache_by_user_role(&state, user_role).await;
(token, user_role.role_id.clone())
diff --git a/crates/router/src/core/user_role.rs b/crates/router/src/core/user_role.rs
index a728836857c..b5c7f6db016 100644
--- a/crates/router/src/core/user_role.rs
+++ b/crates/router/src/core/user_role.rs
@@ -169,7 +169,9 @@ pub async fn transfer_org_ownership(
utils::user_role::set_role_permissions_in_cache_by_user_role(&state, &user_role).await;
- let token = utils::user::generate_jwt_auth_token(&state, &user_from_db, &user_role).await?;
+ let token =
+ utils::user::generate_jwt_auth_token_without_profile(&state, &user_from_db, &user_role)
+ .await?;
let response =
utils::user::get_dashboard_entry_response(&state, user_from_db, user_role, token.clone())?;
@@ -246,7 +248,9 @@ pub async fn merchant_select(
utils::user_role::set_role_permissions_in_cache_by_user_role(&state, &user_role).await;
- let token = utils::user::generate_jwt_auth_token(&state, &user_from_db, &user_role).await?;
+ let token =
+ utils::user::generate_jwt_auth_token_without_profile(&state, &user_from_db, &user_role)
+ .await?;
let response = utils::user::get_dashboard_entry_response(
&state,
user_from_db,
diff --git a/crates/router/src/db/merchant_account.rs b/crates/router/src/db/merchant_account.rs
index d707ec17c3a..2e43d469815 100644
--- a/crates/router/src/db/merchant_account.rs
+++ b/crates/router/src/db/merchant_account.rs
@@ -273,6 +273,7 @@ impl MerchantAccountInterface for Store {
.change_context(errors::StorageError::DecryptionError)?,
key_store,
+ profile_id: None,
})
}
diff --git a/crates/router/src/services/authentication.rs b/crates/router/src/services/authentication.rs
index df59083537f..0b2066fdb13 100644
--- a/crates/router/src/services/authentication.rs
+++ b/crates/router/src/services/authentication.rs
@@ -54,6 +54,14 @@ mod detached;
pub struct AuthenticationData {
pub merchant_account: domain::MerchantAccount,
pub key_store: domain::MerchantKeyStore,
+ pub profile_id: Option<String>,
+}
+
+#[derive(Clone)]
+pub struct AuthenticationDataWithMultipleProfiles {
+ pub merchant_account: domain::MerchantAccount,
+ pub key_store: domain::MerchantKeyStore,
+ pub profile_id_list: Option<Vec<String>>,
}
#[derive(Clone, Debug, Eq, PartialEq, Serialize)]
@@ -178,6 +186,7 @@ pub struct AuthToken {
pub role_id: String,
pub exp: u64,
pub org_id: id_type::OrganizationId,
+ pub profile_id: Option<String>,
}
#[cfg(feature = "olap")]
@@ -188,6 +197,7 @@ impl AuthToken {
role_id: String,
settings: &Settings,
org_id: id_type::OrganizationId,
+ profile_id: Option<String>,
) -> UserResult<String> {
let exp_duration = std::time::Duration::from_secs(consts::JWT_TOKEN_TIME_IN_SECS);
let exp = jwt::generate_exp(exp_duration)?.as_secs();
@@ -197,6 +207,7 @@ impl AuthToken {
role_id,
exp,
org_id,
+ profile_id,
};
jwt::generate_jwt(&token_payload, settings).await
}
@@ -208,6 +219,7 @@ pub struct UserFromToken {
pub merchant_id: id_type::MerchantId,
pub role_id: String,
pub org_id: id_type::OrganizationId,
+ pub profile_id: Option<String>,
}
pub struct UserIdFromAuth {
@@ -376,6 +388,7 @@ where
let auth = AuthenticationData {
merchant_account: merchant,
key_store,
+ profile_id: None,
};
Ok((
auth.clone(),
@@ -512,6 +525,7 @@ where
let auth = AuthenticationData {
merchant_account: merchant,
key_store,
+ profile_id: None,
};
Ok(auth)
@@ -735,6 +749,7 @@ where
let auth = AuthenticationData {
merchant_account: merchant,
key_store,
+ profile_id: None,
};
Ok((
auth.clone(),
@@ -852,6 +867,61 @@ where
merchant_id: payload.merchant_id.clone(),
org_id: payload.org_id,
role_id: payload.role_id,
+ profile_id: payload.profile_id,
+ },
+ AuthenticationType::MerchantJwt {
+ merchant_id: payload.merchant_id,
+ user_id: Some(payload.user_id),
+ },
+ ))
+ }
+}
+
+#[cfg(feature = "olap")]
+#[async_trait]
+impl<A> AuthenticateAndFetch<AuthenticationDataWithMultipleProfiles, A> for JWTAuth
+where
+ A: SessionStateInfo + Sync,
+{
+ async fn authenticate_and_fetch(
+ &self,
+ request_headers: &HeaderMap,
+ state: &A,
+ ) -> RouterResult<(AuthenticationDataWithMultipleProfiles, AuthenticationType)> {
+ let payload = parse_jwt_payload::<A, AuthToken>(request_headers, state).await?;
+ if payload.check_in_blacklist(state).await? {
+ return Err(errors::ApiErrorResponse::InvalidJwtToken.into());
+ }
+
+ let permissions = authorization::get_permissions(state, &payload).await?;
+ authorization::check_authorization(&self.0, &permissions)?;
+ let key_manager_state = &(&state.session_state()).into();
+ let key_store = state
+ .store()
+ .get_merchant_key_store_by_merchant_id(
+ key_manager_state,
+ &payload.merchant_id,
+ &state.store().get_master_key().to_vec().into(),
+ )
+ .await
+ .change_context(errors::ApiErrorResponse::InvalidJwtToken)
+ .attach_printable("Failed to fetch merchant key store for the merchant id")?;
+
+ let merchant = state
+ .store()
+ .find_merchant_account_by_merchant_id(
+ key_manager_state,
+ &payload.merchant_id,
+ &key_store,
+ )
+ .await
+ .change_context(errors::ApiErrorResponse::InvalidJwtToken)?;
+
+ Ok((
+ AuthenticationDataWithMultipleProfiles {
+ key_store,
+ merchant_account: merchant,
+ profile_id_list: None,
},
AuthenticationType::MerchantJwt {
merchant_id: payload.merchant_id,
@@ -1020,6 +1090,7 @@ where
let auth = AuthenticationData {
merchant_account: merchant,
key_store,
+ profile_id: payload.profile_id,
};
Ok((
auth.clone(),
@@ -1075,6 +1146,7 @@ where
let auth = AuthenticationData {
merchant_account: merchant,
key_store,
+ profile_id: payload.profile_id,
};
Ok((
(auth.clone(), payload.user_id.clone()),
@@ -1110,6 +1182,7 @@ where
merchant_id: payload.merchant_id.clone(),
org_id: payload.org_id,
role_id: payload.role_id,
+ profile_id: payload.profile_id,
},
AuthenticationType::MerchantJwt {
merchant_id: payload.merchant_id,
@@ -1175,6 +1248,7 @@ where
let auth = AuthenticationData {
merchant_account: merchant,
key_store,
+ profile_id: payload.profile_id,
};
Ok((
auth.clone(),
diff --git a/crates/router/src/types/domain/user.rs b/crates/router/src/types/domain/user.rs
index 1a2ac3fa054..41fbc96f6d2 100644
--- a/crates/router/src/types/domain/user.rs
+++ b/crates/router/src/types/domain/user.rs
@@ -1144,8 +1144,12 @@ impl SignInWithSingleRoleStrategy {
self,
state: &SessionState,
) -> UserResult<user_api::SignInResponse> {
- let token =
- utils::user::generate_jwt_auth_token(state, &self.user, &self.user_role).await?;
+ let token = utils::user::generate_jwt_auth_token_without_profile(
+ state,
+ &self.user,
+ &self.user_role,
+ )
+ .await?;
utils::user_role::set_role_permissions_in_cache_by_user_role(state, &self.user_role).await;
let dashboard_entry_response =
diff --git a/crates/router/src/types/domain/user/decision_manager.rs b/crates/router/src/types/domain/user/decision_manager.rs
index cffdd05448a..92f1d4ba5ba 100644
--- a/crates/router/src/types/domain/user/decision_manager.rs
+++ b/crates/router/src/types/domain/user/decision_manager.rs
@@ -101,7 +101,7 @@ impl JWTFlow {
Ok(true)
}
- pub async fn generate_jwt(
+ pub async fn generate_jwt_without_profile(
self,
state: &SessionState,
next_flow: &NextFlow,
@@ -119,6 +119,7 @@ impl JWTFlow {
.org_id
.clone()
.ok_or(report!(UserErrors::InternalServerError))?,
+ None,
)
.await
.map(|token| token.into())
@@ -293,7 +294,9 @@ impl NextFlow {
utils::user_role::set_role_permissions_in_cache_by_user_role(state, &user_role)
.await;
- jwt_flow.generate_jwt(state, self, &user_role).await
+ jwt_flow
+ .generate_jwt_without_profile(state, self, &user_role)
+ .await
}
}
}
@@ -313,7 +316,9 @@ impl NextFlow {
utils::user_role::set_role_permissions_in_cache_by_user_role(state, user_role)
.await;
- jwt_flow.generate_jwt(state, self, user_role).await
+ jwt_flow
+ .generate_jwt_without_profile(state, self, user_role)
+ .await
}
}
}
diff --git a/crates/router/src/utils/user.rs b/crates/router/src/utils/user.rs
index 72d2b83c6b4..2dad55c4b89 100644
--- a/crates/router/src/utils/user.rs
+++ b/crates/router/src/utils/user.rs
@@ -81,7 +81,7 @@ impl UserFromToken {
}
}
-pub async fn generate_jwt_auth_token(
+pub async fn generate_jwt_auth_token_without_profile(
state: &SessionState,
user: &UserFromStorage,
user_role: &UserRole,
@@ -102,6 +102,7 @@ pub async fn generate_jwt_auth_token(
.ok_or(report!(UserErrors::InternalServerError))
.attach_printable("org_id not found for user_role")?
.clone(),
+ None,
)
.await?;
Ok(Secret::new(token))
@@ -113,6 +114,7 @@ pub async fn generate_jwt_auth_token_with_custom_role_attributes(
merchant_id: id_type::MerchantId,
org_id: id_type::OrganizationId,
role_id: String,
+ profile_id: Option<String>,
) -> UserResult<Secret<String>> {
let token = AuthToken::new_token(
user.get_user_id().to_string(),
@@ -120,6 +122,7 @@ pub async fn generate_jwt_auth_token_with_custom_role_attributes(
role_id,
&state.conf,
org_id,
+ profile_id,
)
.await?;
Ok(Secret::new(token))
|
2024-07-31T13:15:50Z
|
## Type of Change
<!-- Put an `x` in the boxes that apply -->
- [ ] Bugfix
- [x] New feature
- [ ] Enhancement
- [ ] Refactoring
- [ ] Dependency updates
- [ ] Documentation
- [ ] CI/CD
## Description
<!-- Describe your changes in detail -->
Since we are going to change the dashboard to profile level, we need profile level authentication.
This PR introduces profile_id in the AuthenticationData. Core API will take this into consideration before sending any response.
### Additional Changes
- [ ] This PR modifies the API contract
- [ ] This PR modifies the database schema
- [ ] This PR modifies application configuration/environment variables
<!--
Provide links to the files with corresponding changes.
Following are the paths where you can find config files:
1. `config`
2. `crates/router/src/configs`
3. `loadtest/config`
-->
## Motivation and Context
<!--
Why is this change required? What problem does it solve?
If it fixes an open issue, please link to the issue here.
If you don't have an issue, we'd recommend starting with one first so the PR
can focus on the implementation (unless it is an obvious bug or documentation fix
that will have little conversation).
-->
Closes #5491.
## How did you test it?
<!--
Did you write an integration/unit/API test to verify the code changes?
Or did you test this change manually (provide relevant screenshots)?
-->
All the APIs which are using JWT, should not fail in the authentication layer.
## Checklist
<!-- Put an `x` in the boxes that apply -->
- [x] I formatted the code `cargo +nightly fmt --all`
- [x] I addressed lints thrown by `cargo clippy`
- [x] I reviewed the submitted code
- [ ] I added unit tests for my changes where possible
|
85209d12ae3439b555983d62b2cc3bf764c1b441
|
|
juspay/hyperswitch
|
juspay__hyperswitch-5480
|
Bug: [FEATURE] Add Connector Config for Plaid
### Feature Description
Need to add connector config for Plaid for wasm
### Possible Implementation
Adding config in respective files
### Have you spent some time checking if this feature request has been raised before?
- [X] I checked and didn't find a similar issue
### Have you read the Contributing Guidelines?
- [X] I have read the [Contributing Guidelines](https://github.com/juspay/hyperswitch/blob/main/docs/CONTRIBUTING.md)
### Are you willing to submit a PR?
Yes, I am willing to submit a PR!
|
diff --git a/crates/connector_configs/src/connector.rs b/crates/connector_configs/src/connector.rs
index bc781e05294..bf74adbc106 100644
--- a/crates/connector_configs/src/connector.rs
+++ b/crates/connector_configs/src/connector.rs
@@ -117,6 +117,7 @@ pub struct ConnectorTomlConfig {
pub bank_transfer: Option<Vec<Provider>>,
pub bank_redirect: Option<Vec<Provider>>,
pub bank_debit: Option<Vec<Provider>>,
+ pub open_banking: Option<Vec<Provider>>,
pub pay_later: Option<Vec<Provider>>,
pub wallet: Option<Vec<Provider>>,
pub crypto: Option<Vec<Provider>>,
diff --git a/crates/connector_configs/toml/development.toml b/crates/connector_configs/toml/development.toml
index 331d9ba744d..89b7ed2a23d 100644
--- a/crates/connector_configs/toml/development.toml
+++ b/crates/connector_configs/toml/development.toml
@@ -2513,6 +2513,13 @@ type="Text"
api_key="Login"
key1="Trankey"
+[plaid]
+[[plaid.open_banking]]
+ payment_method_type = "open_banking_pis"
+[plaid.connector_auth.BodyKey]
+api_key="client_id"
+key1="secret"
+
[powertranz]
[[powertranz.credit]]
payment_method_type = "Mastercard"
diff --git a/crates/connector_configs/toml/production.toml b/crates/connector_configs/toml/production.toml
index cfdc2e4b635..ef2367b6f15 100644
--- a/crates/connector_configs/toml/production.toml
+++ b/crates/connector_configs/toml/production.toml
@@ -2436,6 +2436,13 @@ key1="Payme Public Key"
merchant_secret="Payme Client Secret"
additional_secret="Payme Client Key"
+[plaid]
+[[plaid.open_banking]]
+ payment_method_type = "open_banking_pis"
+[plaid.connector_auth.BodyKey]
+api_key="client_id"
+key1="secret"
+
[powertranz]
[[powertranz.credit]]
payment_method_type = "Mastercard"
diff --git a/crates/connector_configs/toml/sandbox.toml b/crates/connector_configs/toml/sandbox.toml
index ca5f6fb72e6..e095edbee49 100644
--- a/crates/connector_configs/toml/sandbox.toml
+++ b/crates/connector_configs/toml/sandbox.toml
@@ -2508,6 +2508,13 @@ type="Text"
api_key="Login"
key1="Trankey"
+[plaid]
+[[plaid.open_banking]]
+ payment_method_type = "open_banking_pis"
+[plaid.connector_auth.BodyKey]
+api_key="client_id"
+key1="secret"
+
[powertranz]
[[powertranz.credit]]
payment_method_type = "Mastercard"
|
2024-07-30T12:36:27Z
|
## Type of Change
<!-- Put an `x` in the boxes that apply -->
- [ ] Bugfix
- [x] New feature
- [ ] Enhancement
- [ ] Refactoring
- [ ] Dependency updates
- [ ] Documentation
- [ ] CI/CD
## Description
<!-- Describe your changes in detail -->
Added connector config for wasm for Plaid
### Additional Changes
- [ ] This PR modifies the API contract
- [ ] This PR modifies the database schema
- [x] This PR modifies application configuration/environment variables
<!--
Provide links to the files with corresponding changes.
Following are the paths where you can find config files:
1. `config`
2. `crates/router/src/configs`
3. `loadtest/config`
-->
## Motivation and Context
<!--
Why is this change required? What problem does it solve?
If it fixes an open issue, please link to the issue here.
If you don't have an issue, we'd recommend starting with one first so the PR
can focus on the implementation (unless it is an obvious bug or documentation fix
that will have little conversation).
-->
## How did you test it?
<!--
Did you write an integration/unit/API test to verify the code changes?
Or did you test this change manually (provide relevant screenshots)?
-->
## Checklist
<!-- Put an `x` in the boxes that apply -->
- [x] I formatted the code `cargo +nightly fmt --all`
- [x] I addressed lints thrown by `cargo clippy`
- [ ] I reviewed the submitted code
- [ ] I added unit tests for my changes where possible
|
4ef3420ee8ad39ee28a0fb496b30fe2a7e108813
|
|
juspay/hyperswitch
|
juspay__hyperswitch-5483
|
Bug: [BUG] : fix postgreSQL database url
### Have you spent some time checking if this bug has been raised before?
- [X] I checked and didn't find a similar issue
### Have you read the Contributing Guidelines?
- [X] I have read the [Contributing Guidelines](https://github.com/juspay/hyperswitch/blob/main/docs/CONTRIBUTING.md)
### Are you willing to submit a PR?
Yes, I am willing to submit a PR!
|
2024-07-30T14:52:14Z
|
## Type of Change
<!-- Put an `x` in the boxes that apply -->
- [x] Bugfix
- [ ] New feature
- [ ] Enhancement
- [ ] Refactoring
- [ ] Dependency updates
- [ ] Documentation
- [ ] CI/CD
## Description
<!-- Describe your changes in detail -->
Before
`export DATABASE_URL=$DB_USER:$DB_PASS@localhost:5432/$DB_NAME`
After
`export DATABASE_URL=postgres://$DB_USER:$DB_PASS@localhost:5432/$DB_NAME`
## Checklist
<!-- Put an `x` in the boxes that apply -->
- [x] I formatted the code `cargo +nightly fmt --all`
- [x] I addressed lints thrown by `cargo clippy`
- [x] I reviewed the submitted code
- [ ] I added unit tests for my changes where possible
|
be9347b8d56c0a6cf0d04cf51c75dd6426d3a21a
|
||
juspay/hyperswitch
|
juspay__hyperswitch-5475
|
Bug: refactor(configs): include env for cybersource in intergration_test
## Description
Include configs for cybersource in `Integration_test` file to facilitate successful cypress tests on our Integ environment
|
diff --git a/config/deployments/integration_test.toml b/config/deployments/integration_test.toml
index a498ad38995..39b19fd0535 100644
--- a/config/deployments/integration_test.toml
+++ b/config/deployments/integration_test.toml
@@ -289,6 +289,12 @@ ideal = { country = "NL", currency = "EUR" }
klarna = { country = "AU,AT,BE,CA,CZ,DK,FI,FR,DE,GR,IE,IT,NL,NZ,NO,PL,PT,ES,SE,CH,GB,US", currency = "AUD,CAD,CHF,CZK,DKK,EUR,GBP,NOK,NZD,PLN,SEK,USD" }
sofort = { country = "AT,BE,DE,IT,NL,ES", currency = "EUR" }
+[pm_filters.cybersource]
+credit = { currency = "USD" }
+debit = { currency = "USD" }
+apple_pay = { currency = "USD" }
+google_pay = { currency = "USD" }
+
[pm_filters.volt]
open_banking_uk = {country = "DE,GB,AT,BE,CY,EE,ES,FI,FR,GR,HR,IE,IT,LT,LU,LV,MT,NL,PT,SI,SK,BG,CZ,DK,HU,NO,PL,RO,SE,AU,BR", currency = "EUR,GBP,DKK,NOK,PLN,SEK,AUD,BRL"}
|
2024-07-29T17:14:56Z
|
## Type of Change
<!-- Put an `x` in the boxes that apply -->
- [ ] Bugfix
- [ ] New feature
- [ ] Enhancement
- [x] Refactoring
- [ ] Dependency updates
- [ ] Documentation
- [ ] CI/CD
## Description
<!-- Describe your changes in detail -->
This will add the config for cybersource in Integ.
### Additional Changes
- [ ] This PR modifies the API contract
- [ ] This PR modifies the database schema
- [x] This PR modifies application configuration/environment variables
<!--
Provide links to the files with corresponding changes.
Following are the paths where you can find config files:
1. `config`
2. `crates/router/src/configs`
3. `loadtest/config`
-->
## Motivation and Context
<!--
Why is this change required? What problem does it solve?
If it fixes an open issue, please link to the issue here.
If you don't have an issue, we'd recommend starting with one first so the PR
can focus on the implementation (unless it is an obvious bug or documentation fix
that will have little conversation).
-->
Due to configs not present the Cypress tests(blocklist) are failing.
## How did you test it?
<!--
Did you write an integration/unit/API test to verify the code changes?
Or did you test this change manually (provide relevant screenshots)?
-->
This is an env change, hence wouldn't require testing as such.
## Checklist
<!-- Put an `x` in the boxes that apply -->
- [ ] I formatted the code `cargo +nightly fmt --all`
- [ ] I addressed lints thrown by `cargo clippy`
- [ ] I reviewed the submitted code
- [ ] I added unit tests for my changes where possible
|
45a149418f1dad0cd27f975dc3dd56c68172b9dd
|
|
juspay/hyperswitch
|
juspay__hyperswitch-5469
|
Bug: feat(opensearch): Update status filter field name to match index
The `status` field is different in different indexes:
- `status` in Payment Attempts and Payment Intents
- `refund_status` in Refunds
- `dispute_status` in Disputes
The correct mapping of `status` for each index is required, to get the correct search-results from the respective index
|
diff --git a/crates/analytics/src/opensearch.rs b/crates/analytics/src/opensearch.rs
index 1031c815448..11ea4e4f7ab 100644
--- a/crates/analytics/src/opensearch.rs
+++ b/crates/analytics/src/opensearch.rs
@@ -1,6 +1,7 @@
use api_models::{
analytics::search::SearchIndex,
errors::types::{ApiError, ApiErrorResponse},
+ payments::TimeRange,
};
use aws_config::{self, meta::region::RegionProviderChain, Region};
use common_utils::errors::{CustomResult, ErrorSwitch};
@@ -18,8 +19,9 @@ use opensearch::{
},
MsearchParts, OpenSearch, SearchParts,
};
-use serde_json::{json, Value};
+use serde_json::{json, Map, Value};
use storage_impl::errors::ApplicationError;
+use time::PrimitiveDateTime;
use super::{health_check::HealthCheck, query::QueryResult, types::QueryExecutionError};
use crate::query::QueryBuildingError;
@@ -40,6 +42,23 @@ pub struct OpenSearchIndexes {
pub disputes: String,
}
+#[derive(Debug, Clone, Copy, serde::Serialize, serde::Deserialize, PartialEq, Eq, Hash)]
+pub struct OpensearchTimeRange {
+ #[serde(with = "common_utils::custom_serde::iso8601")]
+ pub gte: PrimitiveDateTime,
+ #[serde(default, with = "common_utils::custom_serde::iso8601::option")]
+ pub lte: Option<PrimitiveDateTime>,
+}
+
+impl From<TimeRange> for OpensearchTimeRange {
+ fn from(time_range: TimeRange) -> Self {
+ Self {
+ gte: time_range.start_time,
+ lte: time_range.end_time,
+ }
+ }
+}
+
#[derive(Clone, Debug, serde::Deserialize)]
pub struct OpenSearchConfig {
host: String,
@@ -377,6 +396,7 @@ pub struct OpenSearchQueryBuilder {
pub offset: Option<i64>,
pub count: Option<i64>,
pub filters: Vec<(String, Vec<String>)>,
+ pub time_range: Option<OpensearchTimeRange>,
}
impl OpenSearchQueryBuilder {
@@ -387,6 +407,7 @@ impl OpenSearchQueryBuilder {
offset: Default::default(),
count: Default::default(),
filters: Default::default(),
+ time_range: Default::default(),
}
}
@@ -396,27 +417,110 @@ impl OpenSearchQueryBuilder {
Ok(())
}
+ pub fn set_time_range(&mut self, time_range: OpensearchTimeRange) -> QueryResult<()> {
+ self.time_range = Some(time_range);
+ Ok(())
+ }
+
pub fn add_filter_clause(&mut self, lhs: String, rhs: Vec<String>) -> QueryResult<()> {
self.filters.push((lhs, rhs));
Ok(())
}
+ pub fn get_status_field(&self, index: &SearchIndex) -> &str {
+ match index {
+ SearchIndex::Refunds => "refund_status.keyword",
+ SearchIndex::Disputes => "dispute_status.keyword",
+ _ => "status.keyword",
+ }
+ }
+
+ pub fn replace_status_field(&self, filters: &[Value], index: &SearchIndex) -> Vec<Value> {
+ filters
+ .iter()
+ .map(|filter| {
+ if let Some(terms) = filter.get("terms").and_then(|v| v.as_object()) {
+ let mut new_filter = filter.clone();
+ if let Some(new_terms) =
+ new_filter.get_mut("terms").and_then(|v| v.as_object_mut())
+ {
+ let key = "status.keyword";
+ if let Some(status_terms) = terms.get(key) {
+ new_terms.remove(key);
+ new_terms.insert(
+ self.get_status_field(index).to_string(),
+ status_terms.clone(),
+ );
+ }
+ }
+ new_filter
+ } else {
+ filter.clone()
+ }
+ })
+ .collect()
+ }
+
+ /// # Panics
+ ///
+ /// This function will panic if:
+ ///
+ /// * The structure of the JSON query is not as expected (e.g., missing keys or incorrect types).
+ ///
+ /// Ensure that the input data and the structure of the query are valid and correctly handled.
pub fn construct_payload(&self, indexes: &[SearchIndex]) -> QueryResult<Vec<Value>> {
- let mut query =
- vec![json!({"multi_match": {"type": "phrase", "query": self.query, "lenient": true}})];
+ let mut query_obj = Map::new();
+ let mut bool_obj = Map::new();
+ let mut filter_array = Vec::new();
+
+ filter_array.push(json!({
+ "multi_match": {
+ "type": "phrase",
+ "query": self.query,
+ "lenient": true
+ }
+ }));
let mut filters = self
.filters
.iter()
- .map(|(k, v)| json!({"terms" : {k : v}}))
+ .map(|(k, v)| json!({"terms": {k: v}}))
.collect::<Vec<Value>>();
- query.append(&mut filters);
+ filter_array.append(&mut filters);
+
+ if let Some(ref time_range) = self.time_range {
+ let range = json!(time_range);
+ filter_array.push(json!({
+ "range": {
+ "timestamp": range
+ }
+ }));
+ }
+
+ bool_obj.insert("filter".to_string(), Value::Array(filter_array));
+ query_obj.insert("bool".to_string(), Value::Object(bool_obj));
+
+ let mut query = Map::new();
+ query.insert("query".to_string(), Value::Object(query_obj));
- // TODO add index specific filters
Ok(indexes
.iter()
- .map(|_index| json!({"query": {"bool": {"filter": query}}}))
+ .map(|index| {
+ let updated_query = query
+ .get("query")
+ .and_then(|q| q.get("bool"))
+ .and_then(|b| b.get("filter"))
+ .and_then(|f| f.as_array())
+ .map(|filters| self.replace_status_field(filters, index))
+ .unwrap_or_default();
+
+ let mut final_query = Map::new();
+ final_query.insert("bool".to_string(), json!({ "filter": updated_query }));
+
+ let payload = json!({ "query": Value::Object(final_query) });
+ payload
+ })
.collect::<Vec<Value>>())
}
}
diff --git a/crates/analytics/src/search.rs b/crates/analytics/src/search.rs
index 12ef7fb8d96..95b7f204b97 100644
--- a/crates/analytics/src/search.rs
+++ b/crates/analytics/src/search.rs
@@ -97,6 +97,10 @@ pub async fn msearch_results(
};
};
+ if let Some(time_range) = req.time_range {
+ query_builder.set_time_range(time_range.into()).switch()?;
+ };
+
let response_text: OpenMsearchOutput = client
.execute(query_builder)
.await
@@ -221,6 +225,11 @@ pub async fn search_results(
}
};
};
+
+ if let Some(time_range) = search_req.time_range {
+ query_builder.set_time_range(time_range.into()).switch()?;
+ };
+
query_builder
.set_offset_n_count(search_req.offset, search_req.count)
.switch()?;
diff --git a/crates/api_models/src/analytics/search.rs b/crates/api_models/src/analytics/search.rs
index f27af75936d..b962f60cae0 100644
--- a/crates/api_models/src/analytics/search.rs
+++ b/crates/api_models/src/analytics/search.rs
@@ -2,6 +2,8 @@ use common_utils::hashing::HashedString;
use masking::WithType;
use serde_json::Value;
+use crate::payments::TimeRange;
+
#[derive(Clone, Debug, Default, serde::Deserialize, serde::Serialize)]
pub struct SearchFilters {
pub payment_method: Option<Vec<String>>,
@@ -26,6 +28,8 @@ pub struct GetGlobalSearchRequest {
pub query: String,
#[serde(default)]
pub filters: Option<SearchFilters>,
+ #[serde(default)]
+ pub time_range: Option<TimeRange>,
}
#[derive(Clone, Debug, serde::Deserialize, serde::Serialize)]
@@ -36,6 +40,8 @@ pub struct GetSearchRequest {
pub query: String,
#[serde(default)]
pub filters: Option<SearchFilters>,
+ #[serde(default)]
+ pub time_range: Option<TimeRange>,
}
#[derive(Clone, Debug, serde::Deserialize, serde::Serialize)]
|
2024-07-29T10:11:46Z
|
## Type of Change
<!-- Put an `x` in the boxes that apply -->
- [ ] Bugfix
- [x] New feature
- [x] Enhancement
- [ ] Refactoring
- [ ] Dependency updates
- [ ] Documentation
- [ ] CI/CD
## Description
<!-- Describe your changes in detail -->
## Task 1
The `status` field is different in different indexes:
- `status` in Payment Attempts and Payment Intents
- `refund_status` in Refunds
- `dispute_status` in Disputes
The correct mapping of status for each index is done, to get the search-results
## Task 2
Added `Time Range based search` for the OpenSearch query
### Additional Changes
- [ ] This PR modifies the API contract
- [ ] This PR modifies the database schema
- [ ] This PR modifies application configuration/environment variables
<!--
Provide links to the files with corresponding changes.
Following are the paths where you can find config files:
1. `config`
2. `crates/router/src/configs`
3. `loadtest/config`
-->
## Motivation and Context
<!--
Why is this change required? What problem does it solve?
If it fixes an open issue, please link to the issue here.
If you don't have an issue, we'd recommend starting with one first so the PR
can focus on the implementation (unless it is an obvious bug or documentation fix
that will have little conversation).
-->
Giving a better search experience for the merchants through the dashboard global-search
## How did you test it?
<!--
Did you write an integration/unit/API test to verify the code changes?
Or did you test this change manually (provide relevant screenshots)?
-->
Tested through Postman curls:
## Task 1
- Make a payment
```bash
curl --location 'http://localhost:8080/payments' \
--header 'Content-Type: application/json' \
--header 'Accept: application/json' \
--header 'api-key: dev_8z4jfpKL8jjyFFbnQ29mzfnGQYbtwi7CAE52JjUFpzro8ZC5iSK5NyFZkr4paZ6o' \
--data-raw '{
"amount": 6540,
"currency": "INR",
"confirm": true,
"capture_method": "automatic",
"capture_on": "2022-09-10T10:11:12Z",
"amount_to_capture": 6540,
"customer_id": "StripeCustomer",
"email": "test@test6.com",
"name": "John Doe",
"phone": "999999999",
"phone_country_code": "+1",
"description": "Its my first payment request",
"authentication_type": "no_three_ds",
"return_url": "https://google.com",
"payment_method": "card",
"payment_method_type": "credit",
"payment_method_data": {
"card": {
"card_number": "4242424242424242",
"card_exp_month": "10",
"card_exp_year": "25",
"card_holder_name": "joseph Doe",
"card_cvc": "123"
}
},
"billing": {
"address": {
"line1": "1467",
"line2": "Harrison Street",
"line3": "Harrison Street",
"city": "San Fransico",
"state": "California",
"zip": "94122",
"country": "US",
"first_name": "joseph",
"last_name": "Doe"
},
"phone": {
"number": "8056594427",
"country_code": "+91"
}
},
"shipping": {
"address": {
"line1": "1467",
"line2": "Harrison Street",
"line3": "Harrison Street",
"city": "San Fransico",
"state": "California",
"zip": "94122",
"country": "US",
"first_name": "joseph",
"last_name": "Doe"
},
"phone": {
"number": "8056594427",
"country_code": "+91"
}
},
"statement_descriptor_name": "joseph",
"statement_descriptor_suffix": "JS",
"feature_metadata": {
"search_tags": ["cc", "dd"]
},
"metadata": {
"data2": "camel",
"new_customer": "true",
"login_date": "2019-09-10T10:11:12Z"
}
}'
```
- Hit the search API with `status` as `success`
This will return the results of `Refunds` as internally, the `status` field gets converted into `refund_status` and `success` is the `Successful operation` in `Refunds`
```bash
curl --location 'http://localhost:8080/analytics/v1/search' \
--header 'Accept: */*' \
--header 'Accept-Language: en-US,en;q=0.9' \
--header 'Connection: keep-alive' \
--header 'Content-Type: application/json' \
--header 'Origin: http://localhost:9000' \
--header 'Referer: http://localhost:9000/' \
--header 'Sec-Fetch-Dest: empty' \
--header 'Sec-Fetch-Mode: cors' \
--header 'Sec-Fetch-Site: same-site' \
--header 'User-Agent: Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/126.0.0.0 Safari/537.36' \
--header 'api-key: hyperswitch' \
--header 'authorization: Bearer eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJ1c2VyX2lkIjoiYjc2ZDVmZjMtNGI1ZS00OTMyLTk1ZDItNmE3MTEyZWZiNTNlIiwibWVyY2hhbnRfaWQiOiJtZXJjaGFudF8xNzIxODE1MjkwIiwicm9sZV9pZCI6Im9yZ19hZG1pbiIsImV4cCI6MTcyMjY3NTU3MSwib3JnX2lkIjoib3JnX3VFNk1LbExxalU5MWlGUEVGck1rIn0.inysDehseXLwSvbWbDEVbL2q3oUJMm2h8okCDss1kGY' \
--header 'sec-ch-ua: "Not/A)Brand";v="8", "Chromium";v="126", "Google Chrome";v="126"' \
--header 'sec-ch-ua-mobile: ?0' \
--header 'sec-ch-ua-platform: "macOS"' \
--data '{
"query": "inr",
"filters": {
"status": [
"success"
]
}
}'
```
<img width="946" alt="image" src="https://github.com/user-attachments/assets/3db4d143-09d1-46b0-80d0-1c4cb52d3ae1">
## Task 2
- Make a payment
```bash
curl --location 'http://localhost:8080/payments' \
--header 'Content-Type: application/json' \
--header 'Accept: application/json' \
--header 'api-key: dev_8z4jfpKL8jjyFFbnQ29mzfnGQYbtwi7CAE52JjUFpzro8ZC5iSK5NyFZkr4paZ6o' \
--data-raw '{
"amount": 6540,
"currency": "INR",
"confirm": true,
"capture_method": "automatic",
"capture_on": "2022-09-10T10:11:12Z",
"amount_to_capture": 6540,
"customer_id": "StripeCustomer",
"email": "test@test6.com",
"name": "John Doe",
"phone": "999999999",
"phone_country_code": "+1",
"description": "Its my first payment request",
"authentication_type": "no_three_ds",
"return_url": "https://google.com",
"payment_method": "card",
"payment_method_type": "credit",
"payment_method_data": {
"card": {
"card_number": "4242424242424242",
"card_exp_month": "10",
"card_exp_year": "25",
"card_holder_name": "joseph Doe",
"card_cvc": "123"
}
},
"billing": {
"address": {
"line1": "1467",
"line2": "Harrison Street",
"line3": "Harrison Street",
"city": "San Fransico",
"state": "California",
"zip": "94122",
"country": "US",
"first_name": "joseph",
"last_name": "Doe"
},
"phone": {
"number": "8056594427",
"country_code": "+91"
}
},
"shipping": {
"address": {
"line1": "1467",
"line2": "Harrison Street",
"line3": "Harrison Street",
"city": "San Fransico",
"state": "California",
"zip": "94122",
"country": "US",
"first_name": "joseph",
"last_name": "Doe"
},
"phone": {
"number": "8056594427",
"country_code": "+91"
}
},
"statement_descriptor_name": "joseph",
"statement_descriptor_suffix": "JS",
"feature_metadata": {
"search_tags": ["cc", "dd"]
},
"metadata": {
"data2": "camel",
"new_customer": "true",
"login_date": "2019-09-10T10:11:12Z"
}
}'
```
- Hit the Search API:
Able to search based on the `timeRange` included in the request body
```bash
curl --location 'http://localhost:8080/analytics/v1/search' \
--header 'Accept: */*' \
--header 'Accept-Language: en-US,en;q=0.9' \
--header 'Connection: keep-alive' \
--header 'Content-Type: application/json' \
--header 'Origin: http://localhost:9000' \
--header 'Referer: http://localhost:9000/' \
--header 'Sec-Fetch-Dest: empty' \
--header 'Sec-Fetch-Mode: cors' \
--header 'Sec-Fetch-Site: same-site' \
--header 'User-Agent: Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/126.0.0.0 Safari/537.36' \
--header 'api-key: hyperswitch' \
--header 'authorization: Bearer eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJ1c2VyX2lkIjoiYjc2ZDVmZjMtNGI1ZS00OTMyLTk1ZDItNmE3MTEyZWZiNTNlIiwibWVyY2hhbnRfaWQiOiJtZXJjaGFudF8xNzIxODE1MjkwIiwicm9sZV9pZCI6Im9yZ19hZG1pbiIsImV4cCI6MTcyMjQxNTgyOSwib3JnX2lkIjoib3JnX3VFNk1LbExxalU5MWlGUEVGck1rIn0.GUmj5mbLgnYVanig6kwrU_gvLARQU4E68s438dvrhdc' \
--header 'sec-ch-ua: "Not/A)Brand";v="8", "Chromium";v="126", "Google Chrome";v="126"' \
--header 'sec-ch-ua-mobile: ?0' \
--header 'sec-ch-ua-platform: "macOS"' \
--data-raw '{
"query": "inr",
"filters": {
"customer_email": [
"test@test6.com"
],
"status": [
"succeeded"
]
},
"timeRange": {
"startTime": "2024-07-29T00:30:00Z",
"endTime": "2024-07-31T18:45:00Z"
}
}'
```
<img width="936" alt="image" src="https://github.com/user-attachments/assets/95045257-86ad-466f-82fe-4121b290d580">
## Checklist
<!-- Put an `x` in the boxes that apply -->
- [x] I formatted the code `cargo +nightly fmt --all`
- [x] I addressed lints thrown by `cargo clippy`
- [x] I reviewed the submitted code
- [ ] I added unit tests for my changes where possible
|
45a149418f1dad0cd27f975dc3dd56c68172b9dd
|
|
juspay/hyperswitch
|
juspay__hyperswitch-5489
|
Bug: [FEATURE] : Paybox payments integration
### Feature Description
Payone is payout connector
Documentation link: http://www1.paybox.com/wp-content/uploads/2017/08/ManuelIntegrationVerifone_PayboxDirect_V8.1_EN.pdf
Website url: [Paybox.com](http://paybox.com/)
### Have you spent some time to check if this feature request has been raised before?
- [X] I checked and didn't find similar issue
### Have you read the Contributing Guidelines?
- [X] I have read the [Contributing Guidelines](https://github.com/juspay/hyperswitch/blob/main/docs/CONTRIBUTING.md)
### Are you willing to submit a PR?
Yes I am willing to submit a PR!
|
diff --git a/config/config.example.toml b/config/config.example.toml
index 92bdaf6b924..7cbd6551303 100644
--- a/config/config.example.toml
+++ b/config/config.example.toml
@@ -227,6 +227,7 @@ noon.key_mode = "Test"
nuvei.base_url = "https://ppp-test.nuvei.com/"
opayo.base_url = "https://pi-test.sagepay.com/"
opennode.base_url = "https://dev-api.opennode.com"
+paybox.base_url = "https://preprod-ppps.paybox.com/PPPS.php"
payeezy.base_url = "https://api-cert.payeezy.com/"
payme.base_url = "https://sandbox.payme.io/"
payone.base_url = "https://payment.preprod.payone.com/"
diff --git a/config/deployments/integration_test.toml b/config/deployments/integration_test.toml
index 39b19fd0535..69d268e2162 100644
--- a/config/deployments/integration_test.toml
+++ b/config/deployments/integration_test.toml
@@ -66,6 +66,7 @@ noon.key_mode = "Test"
nuvei.base_url = "https://ppp-test.nuvei.com/"
opayo.base_url = "https://pi-test.sagepay.com/"
opennode.base_url = "https://dev-api.opennode.com"
+paybox.base_url = "https://preprod-ppps.paybox.com/PPPS.php"
payeezy.base_url = "https://api-cert.payeezy.com/"
payme.base_url = "https://sandbox.payme.io/"
payone.base_url = "https://payment.preprod.payone.com/"
diff --git a/config/deployments/production.toml b/config/deployments/production.toml
index 4630b969224..17f4b2fa994 100644
--- a/config/deployments/production.toml
+++ b/config/deployments/production.toml
@@ -70,6 +70,7 @@ noon.key_mode = "Live"
nuvei.base_url = "https://ppp-test.nuvei.com/"
opayo.base_url = "https://pi-live.sagepay.com/"
opennode.base_url = "https://api.opennode.com"
+paybox.base_url = "https://preprod-ppps.paybox.com/PPPS.php"
payeezy.base_url = "https://api.payeezy.com/"
payme.base_url = "https://live.payme.io/"
payone.base_url = "https://payment.payone.com/"
diff --git a/config/deployments/sandbox.toml b/config/deployments/sandbox.toml
index e79e096436b..730f7829198 100644
--- a/config/deployments/sandbox.toml
+++ b/config/deployments/sandbox.toml
@@ -70,6 +70,7 @@ noon.key_mode = "Test"
nuvei.base_url = "https://ppp-test.nuvei.com/"
opayo.base_url = "https://pi-test.sagepay.com/"
opennode.base_url = "https://dev-api.opennode.com"
+paybox.base_url = "https://preprod-ppps.paybox.com/PPPS.php"
payeezy.base_url = "https://api-cert.payeezy.com/"
payme.base_url = "https://sandbox.payme.io/"
payone.base_url = "https://payment.preprod.payone.com/"
diff --git a/config/development.toml b/config/development.toml
index 108e67e8849..e1b180d300a 100644
--- a/config/development.toml
+++ b/config/development.toml
@@ -135,6 +135,7 @@ cards = [
"nuvei",
"opayo",
"opennode",
+ "paybox",
"payeezy",
"payme",
"payone",
@@ -223,6 +224,7 @@ noon.key_mode = "Test"
nuvei.base_url = "https://ppp-test.nuvei.com/"
opayo.base_url = "https://pi-test.sagepay.com/"
opennode.base_url = "https://dev-api.opennode.com"
+paybox.base_url = "https://preprod-ppps.paybox.com/PPPS.php"
payeezy.base_url = "https://api-cert.payeezy.com/"
payme.base_url = "https://sandbox.payme.io/"
payone.base_url = "https://payment.preprod.payone.com/"
diff --git a/config/docker_compose.toml b/config/docker_compose.toml
index f6cb52803ad..4d8f287a077 100644
--- a/config/docker_compose.toml
+++ b/config/docker_compose.toml
@@ -156,6 +156,7 @@ noon.key_mode = "Test"
nuvei.base_url = "https://ppp-test.nuvei.com/"
opayo.base_url = "https://pi-test.sagepay.com/"
opennode.base_url = "https://dev-api.opennode.com"
+paybox.base_url = "https://preprod-ppps.paybox.com/PPPS.php"
payeezy.base_url = "https://api-cert.payeezy.com/"
payme.base_url = "https://sandbox.payme.io/"
payone.base_url = "https://payment.preprod.payone.com/"
@@ -235,6 +236,7 @@ cards = [
"nuvei",
"opayo",
"opennode",
+ "paybox",
"payeezy",
"payme",
"payone",
diff --git a/crates/api_models/src/enums.rs b/crates/api_models/src/enums.rs
index c87c94084b0..f0405376739 100644
--- a/crates/api_models/src/enums.rs
+++ b/crates/api_models/src/enums.rs
@@ -115,6 +115,7 @@ pub enum Connector {
Nuvei,
// Opayo, added as template code for future usage
Opennode,
+ // Paybox, added as template code for future usage
// Payeezy, As psync and rsync are not supported by this connector, it is added as template code for future usage
Payme,
Payone,
@@ -239,6 +240,7 @@ impl Connector {
| Self::Nexinets
| Self::Nuvei
| Self::Opennode
+ // | Self::Paybox added as template code for future usage
| Self::Payme
| Self::Payone
| Self::Paypal
diff --git a/crates/common_enums/src/enums.rs b/crates/common_enums/src/enums.rs
index 2bd2e8c03b9..1f59aa3e131 100644
--- a/crates/common_enums/src/enums.rs
+++ b/crates/common_enums/src/enums.rs
@@ -228,6 +228,7 @@ pub enum RoutableConnectors {
// Opayo, added as template code for future usage
Opennode,
// Payeezy, As psync and rsync are not supported by this connector, it is added as template code for future usage
+ // Paybox, added as template code for future usage
Payme,
Payone,
Paypal,
diff --git a/crates/connector_configs/src/connector.rs b/crates/connector_configs/src/connector.rs
index d4c90248831..bc781e05294 100644
--- a/crates/connector_configs/src/connector.rs
+++ b/crates/connector_configs/src/connector.rs
@@ -174,6 +174,7 @@ pub struct ConnectorConfig {
pub nmi: Option<ConnectorTomlConfig>,
pub noon: Option<ConnectorTomlConfig>,
pub nuvei: Option<ConnectorTomlConfig>,
+ // pub paybox: Option<ConnectorTomlConfig>, added for future usage
pub payme: Option<ConnectorTomlConfig>,
#[cfg(feature = "payouts")]
pub payone_payout: Option<ConnectorTomlConfig>,
@@ -350,6 +351,7 @@ impl ConnectorConfig {
#[cfg(feature = "dummy_connector")]
Connector::DummyConnector7 => Ok(connector_data.paypal_test),
Connector::Netcetera => Ok(connector_data.netcetera),
+ // Connector::Paybox => Ok(connector_data.paybox), added for future usage
}
}
}
diff --git a/crates/hyperswitch_interfaces/src/configs.rs b/crates/hyperswitch_interfaces/src/configs.rs
index 7634c006a7b..cb3fa0313c1 100644
--- a/crates/hyperswitch_interfaces/src/configs.rs
+++ b/crates/hyperswitch_interfaces/src/configs.rs
@@ -56,6 +56,7 @@ pub struct Connectors {
pub nuvei: ConnectorParams,
pub opayo: ConnectorParams,
pub opennode: ConnectorParams,
+ pub paybox: ConnectorParams,
pub payeezy: ConnectorParams,
pub payme: ConnectorParams,
pub payone: ConnectorParams,
diff --git a/crates/router/src/connector.rs b/crates/router/src/connector.rs
index 7d5fc28e2ba..f97d428c178 100644
--- a/crates/router/src/connector.rs
+++ b/crates/router/src/connector.rs
@@ -37,6 +37,7 @@ pub mod noon;
pub mod nuvei;
pub mod opayo;
pub mod opennode;
+pub mod paybox;
pub mod payeezy;
pub mod payme;
pub mod payone;
@@ -81,10 +82,11 @@ pub use self::{
globalpay::Globalpay, globepay::Globepay, gocardless::Gocardless, gpayments::Gpayments,
iatapay::Iatapay, itaubank::Itaubank, klarna::Klarna, mifinity::Mifinity, mollie::Mollie,
multisafepay::Multisafepay, netcetera::Netcetera, nexinets::Nexinets, nmi::Nmi, noon::Noon,
- nuvei::Nuvei, opayo::Opayo, opennode::Opennode, payeezy::Payeezy, payme::Payme, payone::Payone,
- paypal::Paypal, payu::Payu, placetopay::Placetopay, plaid::Plaid, powertranz::Powertranz,
- prophetpay::Prophetpay, rapyd::Rapyd, razorpay::Razorpay, riskified::Riskified, shift4::Shift4,
- signifyd::Signifyd, square::Square, stripe::Stripe, threedsecureio::Threedsecureio,
- trustpay::Trustpay, tsys::Tsys, volt::Volt, wellsfargo::Wellsfargo, wise::Wise,
- worldline::Worldline, worldpay::Worldpay, zen::Zen, zsl::Zsl,
+ nuvei::Nuvei, opayo::Opayo, opennode::Opennode, paybox::Paybox, payeezy::Payeezy, payme::Payme,
+ payone::Payone, paypal::Paypal, payu::Payu, placetopay::Placetopay, plaid::Plaid,
+ powertranz::Powertranz, prophetpay::Prophetpay, rapyd::Rapyd, razorpay::Razorpay,
+ riskified::Riskified, shift4::Shift4, signifyd::Signifyd, square::Square, stripe::Stripe,
+ threedsecureio::Threedsecureio, trustpay::Trustpay, tsys::Tsys, volt::Volt,
+ wellsfargo::Wellsfargo, wise::Wise, worldline::Worldline, worldpay::Worldpay, zen::Zen,
+ zsl::Zsl,
};
diff --git a/crates/router/src/connector/paybox.rs b/crates/router/src/connector/paybox.rs
new file mode 100644
index 00000000000..720f0a00c6a
--- /dev/null
+++ b/crates/router/src/connector/paybox.rs
@@ -0,0 +1,574 @@
+pub mod transformers;
+
+use common_utils::types::{AmountConvertor, MinorUnit, MinorUnitForConnector};
+use error_stack::{report, ResultExt};
+use masking::ExposeInterface;
+use transformers as paybox;
+
+use super::utils::{self as connector_utils};
+use crate::{
+ configs::settings,
+ core::errors::{self, CustomResult},
+ events::connector_api_logs::ConnectorEvent,
+ headers,
+ services::{
+ self,
+ request::{self, Mask},
+ ConnectorIntegration, ConnectorValidation,
+ },
+ types::{
+ self,
+ api::{self, ConnectorCommon, ConnectorCommonExt},
+ ErrorResponse, RequestContent, Response,
+ },
+ utils::BytesExt,
+};
+
+#[derive(Clone)]
+pub struct Paybox {
+ amount_converter: &'static (dyn AmountConvertor<Output = MinorUnit> + Sync),
+}
+
+impl Paybox {
+ pub fn new() -> &'static Self {
+ &Self {
+ amount_converter: &MinorUnitForConnector,
+ }
+ }
+}
+
+impl api::Payment for Paybox {}
+impl api::PaymentSession for Paybox {}
+impl api::ConnectorAccessToken for Paybox {}
+impl api::MandateSetup for Paybox {}
+impl api::PaymentAuthorize for Paybox {}
+impl api::PaymentSync for Paybox {}
+impl api::PaymentCapture for Paybox {}
+impl api::PaymentVoid for Paybox {}
+impl api::Refund for Paybox {}
+impl api::RefundExecute for Paybox {}
+impl api::RefundSync for Paybox {}
+impl api::PaymentToken for Paybox {}
+
+impl
+ ConnectorIntegration<
+ api::PaymentMethodToken,
+ types::PaymentMethodTokenizationData,
+ types::PaymentsResponseData,
+ > for Paybox
+{
+ // Not Implemented (R)
+}
+
+impl<Flow, Request, Response> ConnectorCommonExt<Flow, Request, Response> for Paybox
+where
+ Self: ConnectorIntegration<Flow, Request, Response>,
+{
+ fn build_headers(
+ &self,
+ req: &types::RouterData<Flow, Request, Response>,
+ _connectors: &settings::Connectors,
+ ) -> CustomResult<Vec<(String, request::Maskable<String>)>, errors::ConnectorError> {
+ let mut header = vec![(
+ headers::CONTENT_TYPE.to_string(),
+ self.get_content_type().to_string().into(),
+ )];
+ let mut api_key = self.get_auth_header(&req.connector_auth_type)?;
+ header.append(&mut api_key);
+ Ok(header)
+ }
+}
+
+impl ConnectorCommon for Paybox {
+ fn id(&self) -> &'static str {
+ "paybox"
+ }
+
+ // fn get_currency_unit(&self) -> api::CurrencyUnit {
+ // // todo!()
+ // // TODO! Check connector documentation, on which unit they are processing the currency.
+ // // If the connector accepts amount in lower unit ( i.e cents for USD) then return api::CurrencyUnit::Minor,
+ // // if connector accepts amount in base unit (i.e dollars for USD) then return api::CurrencyUnit::Base
+ // }
+
+ fn common_get_content_type(&self) -> &'static str {
+ "application/json"
+ }
+
+ fn base_url<'a>(&self, connectors: &'a settings::Connectors) -> &'a str {
+ connectors.paybox.base_url.as_ref()
+ }
+
+ fn get_auth_header(
+ &self,
+ auth_type: &types::ConnectorAuthType,
+ ) -> CustomResult<Vec<(String, request::Maskable<String>)>, errors::ConnectorError> {
+ let auth = paybox::PayboxAuthType::try_from(auth_type)
+ .change_context(errors::ConnectorError::FailedToObtainAuthType)?;
+ Ok(vec![(
+ headers::AUTHORIZATION.to_string(),
+ auth.api_key.expose().into_masked(),
+ )])
+ }
+
+ fn build_error_response(
+ &self,
+ res: Response,
+ event_builder: Option<&mut ConnectorEvent>,
+ ) -> CustomResult<ErrorResponse, errors::ConnectorError> {
+ let response: paybox::PayboxErrorResponse = res
+ .response
+ .parse_struct("PayboxErrorResponse")
+ .change_context(errors::ConnectorError::ResponseDeserializationFailed)?;
+
+ event_builder.map(|i| i.set_response_body(&response));
+ router_env::logger::info!(connector_response=?response);
+
+ Ok(ErrorResponse {
+ status_code: res.status_code,
+ code: response.code,
+ message: response.message,
+ reason: response.reason,
+ attempt_status: None,
+ connector_transaction_id: None,
+ })
+ }
+}
+
+impl ConnectorValidation for Paybox {
+ //TODO: implement functions when support enabled
+}
+
+impl ConnectorIntegration<api::Session, types::PaymentsSessionData, types::PaymentsResponseData>
+ for Paybox
+{
+ //TODO: implement sessions flow
+}
+
+impl ConnectorIntegration<api::AccessTokenAuth, types::AccessTokenRequestData, types::AccessToken>
+ for Paybox
+{
+}
+
+impl
+ ConnectorIntegration<
+ api::SetupMandate,
+ types::SetupMandateRequestData,
+ types::PaymentsResponseData,
+ > for Paybox
+{
+}
+
+impl ConnectorIntegration<api::Authorize, types::PaymentsAuthorizeData, types::PaymentsResponseData>
+ for Paybox
+{
+ fn get_headers(
+ &self,
+ req: &types::PaymentsAuthorizeRouterData,
+ connectors: &settings::Connectors,
+ ) -> CustomResult<Vec<(String, request::Maskable<String>)>, errors::ConnectorError> {
+ self.build_headers(req, connectors)
+ }
+
+ fn get_content_type(&self) -> &'static str {
+ self.common_get_content_type()
+ }
+
+ fn get_url(
+ &self,
+ _req: &types::PaymentsAuthorizeRouterData,
+ _connectors: &settings::Connectors,
+ ) -> CustomResult<String, errors::ConnectorError> {
+ Err(errors::ConnectorError::NotImplemented("get_url method".to_string()).into())
+ }
+
+ fn get_request_body(
+ &self,
+ req: &types::PaymentsAuthorizeRouterData,
+ _connectors: &settings::Connectors,
+ ) -> CustomResult<RequestContent, errors::ConnectorError> {
+ let amount = connector_utils::convert_amount(
+ self.amount_converter,
+ req.request.minor_amount,
+ req.request.currency,
+ )?;
+
+ let connector_router_data = paybox::PayboxRouterData::from((amount, req));
+ let connector_req = paybox::PayboxPaymentsRequest::try_from(&connector_router_data)?;
+ Ok(RequestContent::Json(Box::new(connector_req)))
+ }
+
+ fn build_request(
+ &self,
+ req: &types::PaymentsAuthorizeRouterData,
+ connectors: &settings::Connectors,
+ ) -> CustomResult<Option<services::Request>, errors::ConnectorError> {
+ Ok(Some(
+ services::RequestBuilder::new()
+ .method(services::Method::Post)
+ .url(&types::PaymentsAuthorizeType::get_url(
+ self, req, connectors,
+ )?)
+ .attach_default_headers()
+ .headers(types::PaymentsAuthorizeType::get_headers(
+ self, req, connectors,
+ )?)
+ .set_body(types::PaymentsAuthorizeType::get_request_body(
+ self, req, connectors,
+ )?)
+ .build(),
+ ))
+ }
+
+ fn handle_response(
+ &self,
+ data: &types::PaymentsAuthorizeRouterData,
+ event_builder: Option<&mut ConnectorEvent>,
+ res: Response,
+ ) -> CustomResult<types::PaymentsAuthorizeRouterData, errors::ConnectorError> {
+ let response: paybox::PayboxPaymentsResponse = res
+ .response
+ .parse_struct("Paybox PaymentsAuthorizeResponse")
+ .change_context(errors::ConnectorError::ResponseDeserializationFailed)?;
+ event_builder.map(|i| i.set_response_body(&response));
+ router_env::logger::info!(connector_response=?response);
+ types::RouterData::try_from(types::ResponseRouterData {
+ response,
+ data: data.clone(),
+ http_code: res.status_code,
+ })
+ }
+
+ fn get_error_response(
+ &self,
+ res: Response,
+ event_builder: Option<&mut ConnectorEvent>,
+ ) -> CustomResult<ErrorResponse, errors::ConnectorError> {
+ self.build_error_response(res, event_builder)
+ }
+}
+
+impl ConnectorIntegration<api::PSync, types::PaymentsSyncData, types::PaymentsResponseData>
+ for Paybox
+{
+ fn get_headers(
+ &self,
+ req: &types::PaymentsSyncRouterData,
+ connectors: &settings::Connectors,
+ ) -> CustomResult<Vec<(String, request::Maskable<String>)>, errors::ConnectorError> {
+ self.build_headers(req, connectors)
+ }
+
+ fn get_content_type(&self) -> &'static str {
+ self.common_get_content_type()
+ }
+
+ fn get_url(
+ &self,
+ _req: &types::PaymentsSyncRouterData,
+ _connectors: &settings::Connectors,
+ ) -> CustomResult<String, errors::ConnectorError> {
+ Err(errors::ConnectorError::NotImplemented("get_url method".to_string()).into())
+ }
+
+ fn build_request(
+ &self,
+ req: &types::PaymentsSyncRouterData,
+ connectors: &settings::Connectors,
+ ) -> CustomResult<Option<services::Request>, errors::ConnectorError> {
+ Ok(Some(
+ services::RequestBuilder::new()
+ .method(services::Method::Get)
+ .url(&types::PaymentsSyncType::get_url(self, req, connectors)?)
+ .attach_default_headers()
+ .headers(types::PaymentsSyncType::get_headers(self, req, connectors)?)
+ .build(),
+ ))
+ }
+
+ fn handle_response(
+ &self,
+ data: &types::PaymentsSyncRouterData,
+ event_builder: Option<&mut ConnectorEvent>,
+ res: Response,
+ ) -> CustomResult<types::PaymentsSyncRouterData, errors::ConnectorError> {
+ let response: paybox::PayboxPaymentsResponse = res
+ .response
+ .parse_struct("paybox PaymentsSyncResponse")
+ .change_context(errors::ConnectorError::ResponseDeserializationFailed)?;
+ event_builder.map(|i| i.set_response_body(&response));
+ router_env::logger::info!(connector_response=?response);
+ types::RouterData::try_from(types::ResponseRouterData {
+ response,
+ data: data.clone(),
+ http_code: res.status_code,
+ })
+ }
+
+ fn get_error_response(
+ &self,
+ res: Response,
+ event_builder: Option<&mut ConnectorEvent>,
+ ) -> CustomResult<ErrorResponse, errors::ConnectorError> {
+ self.build_error_response(res, event_builder)
+ }
+}
+
+impl ConnectorIntegration<api::Capture, types::PaymentsCaptureData, types::PaymentsResponseData>
+ for Paybox
+{
+ fn get_headers(
+ &self,
+ req: &types::PaymentsCaptureRouterData,
+ connectors: &settings::Connectors,
+ ) -> CustomResult<Vec<(String, request::Maskable<String>)>, errors::ConnectorError> {
+ self.build_headers(req, connectors)
+ }
+
+ fn get_content_type(&self) -> &'static str {
+ self.common_get_content_type()
+ }
+
+ fn get_url(
+ &self,
+ _req: &types::PaymentsCaptureRouterData,
+ _connectors: &settings::Connectors,
+ ) -> CustomResult<String, errors::ConnectorError> {
+ Err(errors::ConnectorError::NotImplemented("get_url method".to_string()).into())
+ }
+
+ fn get_request_body(
+ &self,
+ _req: &types::PaymentsCaptureRouterData,
+ _connectors: &settings::Connectors,
+ ) -> CustomResult<RequestContent, errors::ConnectorError> {
+ Err(errors::ConnectorError::NotImplemented("get_request_body method".to_string()).into())
+ }
+
+ fn build_request(
+ &self,
+ req: &types::PaymentsCaptureRouterData,
+ connectors: &settings::Connectors,
+ ) -> CustomResult<Option<services::Request>, errors::ConnectorError> {
+ Ok(Some(
+ services::RequestBuilder::new()
+ .method(services::Method::Post)
+ .url(&types::PaymentsCaptureType::get_url(self, req, connectors)?)
+ .attach_default_headers()
+ .headers(types::PaymentsCaptureType::get_headers(
+ self, req, connectors,
+ )?)
+ .set_body(types::PaymentsCaptureType::get_request_body(
+ self, req, connectors,
+ )?)
+ .build(),
+ ))
+ }
+
+ fn handle_response(
+ &self,
+ data: &types::PaymentsCaptureRouterData,
+ event_builder: Option<&mut ConnectorEvent>,
+ res: Response,
+ ) -> CustomResult<types::PaymentsCaptureRouterData, errors::ConnectorError> {
+ let response: paybox::PayboxPaymentsResponse = res
+ .response
+ .parse_struct("Paybox PaymentsCaptureResponse")
+ .change_context(errors::ConnectorError::ResponseDeserializationFailed)?;
+ event_builder.map(|i| i.set_response_body(&response));
+ router_env::logger::info!(connector_response=?response);
+ types::RouterData::try_from(types::ResponseRouterData {
+ response,
+ data: data.clone(),
+ http_code: res.status_code,
+ })
+ }
+
+ fn get_error_response(
+ &self,
+ res: Response,
+ event_builder: Option<&mut ConnectorEvent>,
+ ) -> CustomResult<ErrorResponse, errors::ConnectorError> {
+ self.build_error_response(res, event_builder)
+ }
+}
+
+impl ConnectorIntegration<api::Void, types::PaymentsCancelData, types::PaymentsResponseData>
+ for Paybox
+{
+}
+
+impl ConnectorIntegration<api::Execute, types::RefundsData, types::RefundsResponseData> for Paybox {
+ fn get_headers(
+ &self,
+ req: &types::RefundsRouterData<api::Execute>,
+ connectors: &settings::Connectors,
+ ) -> CustomResult<Vec<(String, request::Maskable<String>)>, errors::ConnectorError> {
+ self.build_headers(req, connectors)
+ }
+
+ fn get_content_type(&self) -> &'static str {
+ self.common_get_content_type()
+ }
+
+ fn get_url(
+ &self,
+ _req: &types::RefundsRouterData<api::Execute>,
+ _connectors: &settings::Connectors,
+ ) -> CustomResult<String, errors::ConnectorError> {
+ Err(errors::ConnectorError::NotImplemented("get_url method".to_string()).into())
+ }
+
+ fn get_request_body(
+ &self,
+ req: &types::RefundsRouterData<api::Execute>,
+ _connectors: &settings::Connectors,
+ ) -> CustomResult<RequestContent, errors::ConnectorError> {
+ let refund_amount = connector_utils::convert_amount(
+ self.amount_converter,
+ req.request.minor_refund_amount,
+ req.request.currency,
+ )?;
+
+ let connector_router_data = paybox::PayboxRouterData::from((refund_amount, req));
+ let connector_req = paybox::PayboxRefundRequest::try_from(&connector_router_data)?;
+ Ok(RequestContent::Json(Box::new(connector_req)))
+ }
+
+ fn build_request(
+ &self,
+ req: &types::RefundsRouterData<api::Execute>,
+ connectors: &settings::Connectors,
+ ) -> CustomResult<Option<services::Request>, errors::ConnectorError> {
+ let request = services::RequestBuilder::new()
+ .method(services::Method::Post)
+ .url(&types::RefundExecuteType::get_url(self, req, connectors)?)
+ .attach_default_headers()
+ .headers(types::RefundExecuteType::get_headers(
+ self, req, connectors,
+ )?)
+ .set_body(types::RefundExecuteType::get_request_body(
+ self, req, connectors,
+ )?)
+ .build();
+ Ok(Some(request))
+ }
+
+ fn handle_response(
+ &self,
+ data: &types::RefundsRouterData<api::Execute>,
+ event_builder: Option<&mut ConnectorEvent>,
+ res: Response,
+ ) -> CustomResult<types::RefundsRouterData<api::Execute>, errors::ConnectorError> {
+ let response: paybox::RefundResponse =
+ res.response
+ .parse_struct("paybox RefundResponse")
+ .change_context(errors::ConnectorError::ResponseDeserializationFailed)?;
+ event_builder.map(|i| i.set_response_body(&response));
+ router_env::logger::info!(connector_response=?response);
+ types::RouterData::try_from(types::ResponseRouterData {
+ response,
+ data: data.clone(),
+ http_code: res.status_code,
+ })
+ }
+
+ fn get_error_response(
+ &self,
+ res: Response,
+ event_builder: Option<&mut ConnectorEvent>,
+ ) -> CustomResult<ErrorResponse, errors::ConnectorError> {
+ self.build_error_response(res, event_builder)
+ }
+}
+
+impl ConnectorIntegration<api::RSync, types::RefundsData, types::RefundsResponseData> for Paybox {
+ fn get_headers(
+ &self,
+ req: &types::RefundSyncRouterData,
+ connectors: &settings::Connectors,
+ ) -> CustomResult<Vec<(String, request::Maskable<String>)>, errors::ConnectorError> {
+ self.build_headers(req, connectors)
+ }
+
+ fn get_content_type(&self) -> &'static str {
+ self.common_get_content_type()
+ }
+
+ fn get_url(
+ &self,
+ _req: &types::RefundSyncRouterData,
+ _connectors: &settings::Connectors,
+ ) -> CustomResult<String, errors::ConnectorError> {
+ Err(errors::ConnectorError::NotImplemented("get_url method".to_string()).into())
+ }
+
+ fn build_request(
+ &self,
+ req: &types::RefundSyncRouterData,
+ connectors: &settings::Connectors,
+ ) -> CustomResult<Option<services::Request>, errors::ConnectorError> {
+ Ok(Some(
+ services::RequestBuilder::new()
+ .method(services::Method::Get)
+ .url(&types::RefundSyncType::get_url(self, req, connectors)?)
+ .attach_default_headers()
+ .headers(types::RefundSyncType::get_headers(self, req, connectors)?)
+ .set_body(types::RefundSyncType::get_request_body(
+ self, req, connectors,
+ )?)
+ .build(),
+ ))
+ }
+
+ fn handle_response(
+ &self,
+ data: &types::RefundSyncRouterData,
+ event_builder: Option<&mut ConnectorEvent>,
+ res: Response,
+ ) -> CustomResult<types::RefundSyncRouterData, errors::ConnectorError> {
+ let response: paybox::RefundResponse = res
+ .response
+ .parse_struct("paybox RefundSyncResponse")
+ .change_context(errors::ConnectorError::ResponseDeserializationFailed)?;
+ event_builder.map(|i| i.set_response_body(&response));
+ router_env::logger::info!(connector_response=?response);
+ types::RouterData::try_from(types::ResponseRouterData {
+ response,
+ data: data.clone(),
+ http_code: res.status_code,
+ })
+ }
+
+ fn get_error_response(
+ &self,
+ res: Response,
+ event_builder: Option<&mut ConnectorEvent>,
+ ) -> CustomResult<ErrorResponse, errors::ConnectorError> {
+ self.build_error_response(res, event_builder)
+ }
+}
+
+#[async_trait::async_trait]
+impl api::IncomingWebhook for Paybox {
+ fn get_webhook_object_reference_id(
+ &self,
+ _request: &api::IncomingWebhookRequestDetails<'_>,
+ ) -> CustomResult<api::webhooks::ObjectReferenceId, errors::ConnectorError> {
+ Err(report!(errors::ConnectorError::WebhooksNotImplemented))
+ }
+
+ fn get_webhook_event_type(
+ &self,
+ _request: &api::IncomingWebhookRequestDetails<'_>,
+ ) -> CustomResult<api::IncomingWebhookEvent, errors::ConnectorError> {
+ Err(report!(errors::ConnectorError::WebhooksNotImplemented))
+ }
+
+ fn get_webhook_resource_object(
+ &self,
+ _request: &api::IncomingWebhookRequestDetails<'_>,
+ ) -> CustomResult<Box<dyn masking::ErasedMaskSerialize>, errors::ConnectorError> {
+ Err(report!(errors::ConnectorError::WebhooksNotImplemented))
+ }
+}
diff --git a/crates/router/src/connector/paybox/transformers.rs b/crates/router/src/connector/paybox/transformers.rs
new file mode 100644
index 00000000000..d83c4261c19
--- /dev/null
+++ b/crates/router/src/connector/paybox/transformers.rs
@@ -0,0 +1,226 @@
+use common_utils::types::MinorUnit;
+use masking::Secret;
+use serde::{Deserialize, Serialize};
+
+use crate::{
+ connector::utils::PaymentsAuthorizeRequestData,
+ core::errors,
+ types::{self, api, domain, storage::enums},
+};
+
+//TODO: Fill the struct with respective fields
+pub struct PayboxRouterData<T> {
+ pub amount: MinorUnit, // The type of amount that a connector accepts, for example, String, i64, f64, etc.
+ pub router_data: T,
+}
+
+impl<T> From<(MinorUnit, T)> for PayboxRouterData<T> {
+ fn from((amount, item): (MinorUnit, T)) -> Self {
+ //Todo : use utils to convert the amount to the type of amount that a connector accepts
+ Self {
+ amount,
+ router_data: item,
+ }
+ }
+}
+
+//TODO: Fill the struct with respective fields
+#[derive(Default, Debug, Serialize, PartialEq)]
+pub struct PayboxPaymentsRequest {
+ amount: MinorUnit,
+ card: PayboxCard,
+}
+
+#[derive(Default, Debug, Serialize, Eq, PartialEq)]
+pub struct PayboxCard {
+ number: cards::CardNumber,
+ expiry_month: Secret<String>,
+ expiry_year: Secret<String>,
+ cvc: Secret<String>,
+ complete: bool,
+}
+
+impl TryFrom<&PayboxRouterData<&types::PaymentsAuthorizeRouterData>> for PayboxPaymentsRequest {
+ type Error = error_stack::Report<errors::ConnectorError>;
+ fn try_from(
+ item: &PayboxRouterData<&types::PaymentsAuthorizeRouterData>,
+ ) -> Result<Self, Self::Error> {
+ match item.router_data.request.payment_method_data.clone() {
+ domain::PaymentMethodData::Card(req_card) => {
+ let card = PayboxCard {
+ number: req_card.card_number,
+ expiry_month: req_card.card_exp_month,
+ expiry_year: req_card.card_exp_year,
+ cvc: req_card.card_cvc,
+ complete: item.router_data.request.is_auto_capture()?,
+ };
+ Ok(Self {
+ amount: item.amount,
+ card,
+ })
+ }
+ _ => Err(errors::ConnectorError::NotImplemented("Payment methods".to_string()).into()),
+ }
+ }
+}
+
+//TODO: Fill the struct with respective fields
+// Auth Struct
+pub struct PayboxAuthType {
+ pub(super) api_key: Secret<String>,
+}
+
+impl TryFrom<&types::ConnectorAuthType> for PayboxAuthType {
+ type Error = error_stack::Report<errors::ConnectorError>;
+ fn try_from(auth_type: &types::ConnectorAuthType) -> Result<Self, Self::Error> {
+ match auth_type {
+ types::ConnectorAuthType::HeaderKey { api_key } => Ok(Self {
+ api_key: api_key.to_owned(),
+ }),
+ _ => Err(errors::ConnectorError::FailedToObtainAuthType.into()),
+ }
+ }
+}
+// PaymentsResponse
+//TODO: Append the remaining status flags
+#[derive(Debug, Clone, Default, Serialize, Deserialize, PartialEq)]
+#[serde(rename_all = "lowercase")]
+pub enum PayboxPaymentStatus {
+ Succeeded,
+ Failed,
+ #[default]
+ Processing,
+}
+
+impl From<PayboxPaymentStatus> for enums::AttemptStatus {
+ fn from(item: PayboxPaymentStatus) -> Self {
+ match item {
+ PayboxPaymentStatus::Succeeded => Self::Charged,
+ PayboxPaymentStatus::Failed => Self::Failure,
+ PayboxPaymentStatus::Processing => Self::Authorizing,
+ }
+ }
+}
+
+//TODO: Fill the struct with respective fields
+#[derive(Default, Debug, Clone, Serialize, Deserialize, PartialEq)]
+pub struct PayboxPaymentsResponse {
+ status: PayboxPaymentStatus,
+ id: String,
+}
+
+impl<F, T>
+ TryFrom<types::ResponseRouterData<F, PayboxPaymentsResponse, T, types::PaymentsResponseData>>
+ for types::RouterData<F, T, types::PaymentsResponseData>
+{
+ type Error = error_stack::Report<errors::ConnectorError>;
+ fn try_from(
+ item: types::ResponseRouterData<F, PayboxPaymentsResponse, T, types::PaymentsResponseData>,
+ ) -> Result<Self, Self::Error> {
+ Ok(Self {
+ status: enums::AttemptStatus::from(item.response.status),
+ response: Ok(types::PaymentsResponseData::TransactionResponse {
+ resource_id: types::ResponseId::ConnectorTransactionId(item.response.id),
+ redirection_data: None,
+ mandate_reference: None,
+ connector_metadata: None,
+ network_txn_id: None,
+ connector_response_reference_id: None,
+ incremental_authorization_allowed: None,
+ charge_id: None,
+ }),
+ ..item.data
+ })
+ }
+}
+
+//TODO: Fill the struct with respective fields
+// REFUND :
+// Type definition for RefundRequest
+#[derive(Default, Debug, Serialize)]
+pub struct PayboxRefundRequest {
+ pub amount: MinorUnit,
+}
+
+impl<F> TryFrom<&PayboxRouterData<&types::RefundsRouterData<F>>> for PayboxRefundRequest {
+ type Error = error_stack::Report<errors::ConnectorError>;
+ fn try_from(
+ item: &PayboxRouterData<&types::RefundsRouterData<F>>,
+ ) -> Result<Self, Self::Error> {
+ Ok(Self {
+ amount: item.amount.to_owned(),
+ })
+ }
+}
+
+// Type definition for Refund Response
+
+#[allow(dead_code)]
+#[derive(Debug, Serialize, Default, Deserialize, Clone)]
+pub enum RefundStatus {
+ Succeeded,
+ Failed,
+ #[default]
+ Processing,
+}
+
+impl From<RefundStatus> for enums::RefundStatus {
+ fn from(item: RefundStatus) -> Self {
+ match item {
+ RefundStatus::Succeeded => Self::Success,
+ RefundStatus::Failed => Self::Failure,
+ RefundStatus::Processing => Self::Pending,
+ //TODO: Review mapping
+ }
+ }
+}
+
+//TODO: Fill the struct with respective fields
+#[derive(Default, Debug, Clone, Serialize, Deserialize)]
+pub struct RefundResponse {
+ id: String,
+ status: RefundStatus,
+}
+
+impl TryFrom<types::RefundsResponseRouterData<api::Execute, RefundResponse>>
+ for types::RefundsRouterData<api::Execute>
+{
+ type Error = error_stack::Report<errors::ConnectorError>;
+ fn try_from(
+ item: types::RefundsResponseRouterData<api::Execute, RefundResponse>,
+ ) -> Result<Self, Self::Error> {
+ Ok(Self {
+ response: Ok(types::RefundsResponseData {
+ connector_refund_id: item.response.id.to_string(),
+ refund_status: enums::RefundStatus::from(item.response.status),
+ }),
+ ..item.data
+ })
+ }
+}
+
+impl TryFrom<types::RefundsResponseRouterData<api::RSync, RefundResponse>>
+ for types::RefundsRouterData<api::RSync>
+{
+ type Error = error_stack::Report<errors::ConnectorError>;
+ fn try_from(
+ item: types::RefundsResponseRouterData<api::RSync, RefundResponse>,
+ ) -> Result<Self, Self::Error> {
+ Ok(Self {
+ response: Ok(types::RefundsResponseData {
+ connector_refund_id: item.response.id.to_string(),
+ refund_status: enums::RefundStatus::from(item.response.status),
+ }),
+ ..item.data
+ })
+ }
+}
+
+//TODO: Fill the struct with respective fields
+#[derive(Default, Debug, Serialize, Deserialize, PartialEq)]
+pub struct PayboxErrorResponse {
+ pub status_code: u16,
+ pub code: String,
+ pub message: String,
+ pub reason: Option<String>,
+}
diff --git a/crates/router/src/core/admin.rs b/crates/router/src/core/admin.rs
index 530f8579507..964c24cc838 100644
--- a/crates/router/src/core/admin.rs
+++ b/crates/router/src/core/admin.rs
@@ -1420,6 +1420,7 @@ impl<'a> ConnectorAuthTypeAndMetadataValidation<'a> {
opennode::transformers::OpennodeAuthType::try_from(self.auth_type)?;
Ok(())
}
+ // api_enums::Connector::Paybox => todo!(), added for future usage
api_enums::Connector::Payme => {
payme::transformers::PaymeAuthType::try_from(self.auth_type)?;
Ok(())
diff --git a/crates/router/src/core/payments/connector_integration_v2_impls.rs b/crates/router/src/core/payments/connector_integration_v2_impls.rs
index 4090dc40462..92ec7c0094d 100644
--- a/crates/router/src/core/payments/connector_integration_v2_impls.rs
+++ b/crates/router/src/core/payments/connector_integration_v2_impls.rs
@@ -671,6 +671,7 @@ default_imp_for_new_connector_integration_payment!(
connector::Nuvei,
connector::Opayo,
connector::Opennode,
+ connector::Paybox,
connector::Payeezy,
connector::Payme,
connector::Payone,
@@ -753,6 +754,7 @@ default_imp_for_new_connector_integration_refund!(
connector::Nuvei,
connector::Opayo,
connector::Opennode,
+ connector::Paybox,
connector::Payeezy,
connector::Payme,
connector::Payone,
@@ -830,6 +832,7 @@ default_imp_for_new_connector_integration_connector_access_token!(
connector::Nuvei,
connector::Opayo,
connector::Opennode,
+ connector::Paybox,
connector::Payeezy,
connector::Payme,
connector::Payone,
@@ -929,6 +932,7 @@ default_imp_for_new_connector_integration_accept_dispute!(
connector::Nuvei,
connector::Opayo,
connector::Opennode,
+ connector::Paybox,
connector::Payeezy,
connector::Payme,
connector::Payone,
@@ -1010,6 +1014,7 @@ default_imp_for_new_connector_integration_defend_dispute!(
connector::Nuvei,
connector::Opayo,
connector::Opennode,
+ connector::Paybox,
connector::Payeezy,
connector::Payme,
connector::Payone,
@@ -1075,6 +1080,7 @@ default_imp_for_new_connector_integration_submit_evidence!(
connector::Nuvei,
connector::Opayo,
connector::Opennode,
+ connector::Paybox,
connector::Payeezy,
connector::Payme,
connector::Payone,
@@ -1167,6 +1173,7 @@ default_imp_for_new_connector_integration_file_upload!(
connector::Nuvei,
connector::Opayo,
connector::Opennode,
+ connector::Paybox,
connector::Payeezy,
connector::Payme,
connector::Payone,
@@ -1245,6 +1252,7 @@ default_imp_for_new_connector_integration_payouts!(
connector::Nuvei,
connector::Opayo,
connector::Opennode,
+ connector::Paybox,
connector::Payeezy,
connector::Payme,
connector::Payone,
@@ -1330,6 +1338,7 @@ default_imp_for_new_connector_integration_payouts_create!(
connector::Nuvei,
connector::Opayo,
connector::Opennode,
+ connector::Paybox,
connector::Payeezy,
connector::Payme,
connector::Payone,
@@ -1414,6 +1423,7 @@ default_imp_for_new_connector_integration_payouts_eligibility!(
connector::Nuvei,
connector::Opayo,
connector::Opennode,
+ connector::Paybox,
connector::Payeezy,
connector::Payme,
connector::Payone,
@@ -1498,6 +1508,7 @@ default_imp_for_new_connector_integration_payouts_fulfill!(
connector::Nuvei,
connector::Opayo,
connector::Opennode,
+ connector::Paybox,
connector::Payeezy,
connector::Payme,
connector::Payone,
@@ -1582,6 +1593,7 @@ default_imp_for_new_connector_integration_payouts_cancel!(
connector::Nuvei,
connector::Opayo,
connector::Opennode,
+ connector::Paybox,
connector::Payeezy,
connector::Payme,
connector::Payone,
@@ -1666,6 +1678,7 @@ default_imp_for_new_connector_integration_payouts_quote!(
connector::Nuvei,
connector::Opayo,
connector::Opennode,
+ connector::Paybox,
connector::Payeezy,
connector::Payme,
connector::Payone,
@@ -1750,6 +1763,7 @@ default_imp_for_new_connector_integration_payouts_recipient!(
connector::Nuvei,
connector::Opayo,
connector::Opennode,
+ connector::Paybox,
connector::Payeezy,
connector::Payme,
connector::Payone,
@@ -1834,6 +1848,7 @@ default_imp_for_new_connector_integration_payouts_sync!(
connector::Nuvei,
connector::Opayo,
connector::Opennode,
+ connector::Paybox,
connector::Payeezy,
connector::Payme,
connector::Payone,
@@ -1918,6 +1933,7 @@ default_imp_for_new_connector_integration_payouts_recipient_account!(
connector::Nuvei,
connector::Opayo,
connector::Opennode,
+ connector::Paybox,
connector::Payeezy,
connector::Payme,
connector::Payone,
@@ -2000,6 +2016,7 @@ default_imp_for_new_connector_integration_webhook_source_verification!(
connector::Nuvei,
connector::Opayo,
connector::Opennode,
+ connector::Paybox,
connector::Payeezy,
connector::Payme,
connector::Payone,
@@ -2078,6 +2095,7 @@ default_imp_for_new_connector_integration_frm!(
connector::Nuvei,
connector::Opayo,
connector::Opennode,
+ connector::Paybox,
connector::Payeezy,
connector::Payme,
connector::Payone,
@@ -2163,6 +2181,7 @@ default_imp_for_new_connector_integration_frm_sale!(
connector::Nuvei,
connector::Opayo,
connector::Opennode,
+ connector::Paybox,
connector::Payeezy,
connector::Payme,
connector::Payone,
@@ -2247,6 +2266,7 @@ default_imp_for_new_connector_integration_frm_checkout!(
connector::Nuvei,
connector::Opayo,
connector::Opennode,
+ connector::Paybox,
connector::Payeezy,
connector::Payme,
connector::Payone,
@@ -2331,6 +2351,7 @@ default_imp_for_new_connector_integration_frm_transaction!(
connector::Nuvei,
connector::Opayo,
connector::Opennode,
+ connector::Paybox,
connector::Payeezy,
connector::Payme,
connector::Payone,
@@ -2415,6 +2436,7 @@ default_imp_for_new_connector_integration_frm_fulfillment!(
connector::Nuvei,
connector::Opayo,
connector::Opennode,
+ connector::Paybox,
connector::Payeezy,
connector::Payme,
connector::Payone,
@@ -2499,6 +2521,7 @@ default_imp_for_new_connector_integration_frm_record_return!(
connector::Nuvei,
connector::Opayo,
connector::Opennode,
+ connector::Paybox,
connector::Payeezy,
connector::Payme,
connector::Payone,
@@ -2580,6 +2603,7 @@ default_imp_for_new_connector_integration_revoking_mandates!(
connector::Nuvei,
connector::Opayo,
connector::Opennode,
+ connector::Paybox,
connector::Payeezy,
connector::Payme,
connector::Payone,
@@ -2693,6 +2717,7 @@ default_imp_for_new_connector_integration_connector_authentication!(
connector::Nuvei,
connector::Opayo,
connector::Opennode,
+ connector::Paybox,
connector::Payeezy,
connector::Payme,
connector::Payone,
diff --git a/crates/router/src/core/payments/flows.rs b/crates/router/src/core/payments/flows.rs
index af56c7e4ba6..f5abd22480b 100644
--- a/crates/router/src/core/payments/flows.rs
+++ b/crates/router/src/core/payments/flows.rs
@@ -214,6 +214,7 @@ default_imp_for_complete_authorize!(
connector::Noon,
connector::Opayo,
connector::Opennode,
+ connector::Paybox,
connector::Payeezy,
connector::Payone,
connector::Payu,
@@ -300,6 +301,7 @@ default_imp_for_webhook_source_verification!(
connector::Nuvei,
connector::Opayo,
connector::Opennode,
+ connector::Paybox,
connector::Payeezy,
connector::Payme,
connector::Payone,
@@ -391,6 +393,7 @@ default_imp_for_create_customer!(
connector::Nuvei,
connector::Opayo,
connector::Opennode,
+ connector::Paybox,
connector::Payeezy,
connector::Payme,
connector::Payone,
@@ -475,6 +478,7 @@ default_imp_for_connector_redirect_response!(
connector::Nexinets,
connector::Opayo,
connector::Opennode,
+ connector::Paybox,
connector::Payeezy,
connector::Payone,
connector::Payu,
@@ -550,6 +554,7 @@ default_imp_for_connector_request_id!(
connector::Nuvei,
connector::Opayo,
connector::Opennode,
+ connector::Paybox,
connector::Payeezy,
connector::Payme,
connector::Payone,
@@ -645,6 +650,7 @@ default_imp_for_accept_dispute!(
connector::Nuvei,
connector::Opayo,
connector::Opennode,
+ connector::Paybox,
connector::Payeezy,
connector::Payme,
connector::Payone,
@@ -758,6 +764,7 @@ default_imp_for_file_upload!(
connector::Noon,
connector::Nuvei,
connector::Opayo,
+ connector::Paybox,
connector::Payeezy,
connector::Payme,
connector::Payone,
@@ -849,6 +856,7 @@ default_imp_for_submit_evidence!(
connector::Noon,
connector::Nuvei,
connector::Opayo,
+ connector::Paybox,
connector::Payeezy,
connector::Payme,
connector::Payone,
@@ -940,6 +948,7 @@ default_imp_for_defend_dispute!(
connector::Noon,
connector::Nuvei,
connector::Opayo,
+ connector::Paybox,
connector::Payeezy,
connector::Payme,
connector::Payone,
@@ -1043,6 +1052,7 @@ default_imp_for_pre_processing_steps!(
connector::Noon,
connector::Opayo,
connector::Opennode,
+ connector::Paybox,
connector::Payeezy,
connector::Payone,
connector::Payu,
@@ -1121,6 +1131,7 @@ default_imp_for_post_processing_steps!(
connector::Noon,
connector::Opayo,
connector::Opennode,
+ connector::Paybox,
connector::Payeezy,
connector::Payone,
connector::Payu,
@@ -1192,6 +1203,7 @@ default_imp_for_payouts!(
connector::Nuvei,
connector::Opayo,
connector::Opennode,
+ connector::Paybox,
connector::Payeezy,
connector::Payme,
connector::Payu,
@@ -1281,6 +1293,7 @@ default_imp_for_payouts_create!(
connector::Nuvei,
connector::Opayo,
connector::Opennode,
+ connector::Paybox,
connector::Payeezy,
connector::Payme,
connector::Payone,
@@ -1372,6 +1385,7 @@ default_imp_for_payouts_retrieve!(
connector::Nuvei,
connector::Opayo,
connector::Opennode,
+ connector::Paybox,
connector::Payeezy,
connector::Payme,
connector::Payone,
@@ -1466,6 +1480,7 @@ default_imp_for_payouts_eligibility!(
connector::Nuvei,
connector::Opayo,
connector::Opennode,
+ connector::Paybox,
connector::Payeezy,
connector::Payme,
connector::Payone,
@@ -1555,6 +1570,7 @@ default_imp_for_payouts_fulfill!(
connector::Nuvei,
connector::Opayo,
connector::Opennode,
+ connector::Paybox,
connector::Payeezy,
connector::Payme,
connector::Payu,
@@ -1643,6 +1659,7 @@ default_imp_for_payouts_cancel!(
connector::Nuvei,
connector::Opayo,
connector::Opennode,
+ connector::Paybox,
connector::Payeezy,
connector::Payme,
connector::Payone,
@@ -1734,6 +1751,7 @@ default_imp_for_payouts_quote!(
connector::Nuvei,
connector::Opayo,
connector::Opennode,
+ connector::Paybox,
connector::Payeezy,
connector::Payme,
connector::Payone,
@@ -1826,6 +1844,7 @@ default_imp_for_payouts_recipient!(
connector::Nuvei,
connector::Opayo,
connector::Opennode,
+ connector::Paybox,
connector::Payeezy,
connector::Payme,
connector::Payone,
@@ -1921,6 +1940,7 @@ default_imp_for_payouts_recipient_account!(
connector::Nuvei,
connector::Opayo,
connector::Opennode,
+ connector::Paybox,
connector::Payeezy,
connector::Payme,
connector::Payone,
@@ -2013,6 +2033,7 @@ default_imp_for_approve!(
connector::Nuvei,
connector::Opayo,
connector::Opennode,
+ connector::Paybox,
connector::Payeezy,
connector::Payme,
connector::Payone,
@@ -2106,6 +2127,7 @@ default_imp_for_reject!(
connector::Nuvei,
connector::Opayo,
connector::Opennode,
+ connector::Paybox,
connector::Payeezy,
connector::Payme,
connector::Payone,
@@ -2187,6 +2209,7 @@ default_imp_for_fraud_check!(
connector::Nuvei,
connector::Opayo,
connector::Opennode,
+ connector::Paybox,
connector::Payeezy,
connector::Payme,
connector::Payone,
@@ -2281,6 +2304,7 @@ default_imp_for_frm_sale!(
connector::Nuvei,
connector::Opayo,
connector::Opennode,
+ connector::Paybox,
connector::Payeezy,
connector::Payme,
connector::Payone,
@@ -2374,6 +2398,7 @@ default_imp_for_frm_checkout!(
connector::Nuvei,
connector::Opayo,
connector::Opennode,
+ connector::Paybox,
connector::Payeezy,
connector::Payme,
connector::Payone,
@@ -2467,6 +2492,7 @@ default_imp_for_frm_transaction!(
connector::Nuvei,
connector::Opayo,
connector::Opennode,
+ connector::Paybox,
connector::Payeezy,
connector::Payme,
connector::Payone,
@@ -2560,6 +2586,7 @@ default_imp_for_frm_fulfillment!(
connector::Nuvei,
connector::Opayo,
connector::Opennode,
+ connector::Paybox,
connector::Payeezy,
connector::Payme,
connector::Payone,
@@ -2653,6 +2680,7 @@ default_imp_for_frm_record_return!(
connector::Nuvei,
connector::Opayo,
connector::Opennode,
+ connector::Paybox,
connector::Payeezy,
connector::Payme,
connector::Payone,
@@ -2743,6 +2771,7 @@ default_imp_for_incremental_authorization!(
connector::Nuvei,
connector::Opayo,
connector::Opennode,
+ connector::Paybox,
connector::Payeezy,
connector::Payme,
connector::Payone,
@@ -2832,6 +2861,7 @@ default_imp_for_revoking_mandates!(
connector::Nuvei,
connector::Opayo,
connector::Opennode,
+ connector::Paybox,
connector::Payeezy,
connector::Payme,
connector::Payone,
@@ -2986,6 +3016,7 @@ default_imp_for_connector_authentication!(
connector::Nuvei,
connector::Opayo,
connector::Opennode,
+ connector::Paybox,
connector::Payeezy,
connector::Payme,
connector::Payone,
@@ -3075,6 +3106,7 @@ default_imp_for_authorize_session_token!(
connector::Noon,
connector::Opayo,
connector::Opennode,
+ connector::Paybox,
connector::Payeezy,
connector::Payme,
connector::Payone,
diff --git a/crates/router/src/types/api.rs b/crates/router/src/types/api.rs
index e117f8c290a..c85b60d13d4 100644
--- a/crates/router/src/types/api.rs
+++ b/crates/router/src/types/api.rs
@@ -399,6 +399,7 @@ impl ConnectorData {
enums::Connector::Opennode => {
Ok(ConnectorEnum::Old(Box::new(&connector::Opennode)))
}
+ // enums::Connector::Paybox => Ok(ConnectorEnum::Old(Box::new(connector::Paybox::new()))), // added for future use
// "payeezy" => Ok(ConnectorIntegrationEnum::Old(Box::new(&connector::Payeezy)), As psync and rsync are not supported by this connector, it is added as template code for future usage
enums::Connector::Payme => {
Ok(ConnectorEnum::Old(Box::new(connector::Payme::new())))
diff --git a/crates/router/src/types/transformers.rs b/crates/router/src/types/transformers.rs
index 83518cfbc3d..ce59a85dc9b 100644
--- a/crates/router/src/types/transformers.rs
+++ b/crates/router/src/types/transformers.rs
@@ -270,6 +270,7 @@ impl ForeignTryFrom<api_enums::Connector> for common_enums::RoutableConnectors {
api_enums::Connector::Noon => Self::Noon,
api_enums::Connector::Nuvei => Self::Nuvei,
api_enums::Connector::Opennode => Self::Opennode,
+ // api_enums::Connector::Paybox => Self::Paybox, added for future usage
api_enums::Connector::Payme => Self::Payme,
api_enums::Connector::Payone => Self::Payone,
api_enums::Connector::Paypal => Self::Paypal,
diff --git a/crates/router/tests/connectors/main.rs b/crates/router/tests/connectors/main.rs
index bbf2077f0c9..a701f11748e 100644
--- a/crates/router/tests/connectors/main.rs
+++ b/crates/router/tests/connectors/main.rs
@@ -50,6 +50,7 @@ mod nuvei;
#[cfg(feature = "dummy_connector")]
mod opayo;
mod opennode;
+mod paybox;
#[cfg(feature = "dummy_connector")]
mod payeezy;
mod payme;
diff --git a/crates/router/tests/connectors/paybox.rs b/crates/router/tests/connectors/paybox.rs
new file mode 100644
index 00000000000..0741e3a1a37
--- /dev/null
+++ b/crates/router/tests/connectors/paybox.rs
@@ -0,0 +1,420 @@
+use masking::Secret;
+use router::types::{self, api, domain, storage::enums};
+use test_utils::connector_auth;
+
+use crate::utils::{self, ConnectorActions};
+
+#[derive(Clone, Copy)]
+struct PayboxTest;
+impl ConnectorActions for PayboxTest {}
+impl utils::Connector for PayboxTest {
+ fn get_data(&self) -> api::ConnectorData {
+ use router::connector::Paybox;
+ utils::construct_connector_data_old(
+ Box::new(Paybox::new()),
+ types::Connector::Plaid,
+ api::GetToken::Connector,
+ None,
+ )
+ }
+
+ fn get_auth_token(&self) -> types::ConnectorAuthType {
+ utils::to_connector_auth_type(
+ connector_auth::ConnectorAuthentication::new()
+ .paybox
+ .expect("Missing connector authentication configuration")
+ .into(),
+ )
+ }
+
+ fn get_name(&self) -> String {
+ "paybox".to_string()
+ }
+}
+
+static CONNECTOR: PayboxTest = PayboxTest {};
+
+fn get_default_payment_info() -> Option<utils::PaymentInfo> {
+ None
+}
+
+fn payment_method_details() -> Option<types::PaymentsAuthorizeData> {
+ None
+}
+
+// Cards Positive Tests
+// Creates a payment using the manual capture flow (Non 3DS).
+#[actix_web::test]
+async fn should_only_authorize_payment() {
+ let response = CONNECTOR
+ .authorize_payment(payment_method_details(), get_default_payment_info())
+ .await
+ .expect("Authorize payment response");
+ assert_eq!(response.status, enums::AttemptStatus::Authorized);
+}
+
+// Captures a payment using the manual capture flow (Non 3DS).
+#[actix_web::test]
+async fn should_capture_authorized_payment() {
+ let response = CONNECTOR
+ .authorize_and_capture_payment(payment_method_details(), None, get_default_payment_info())
+ .await
+ .expect("Capture payment response");
+ assert_eq!(response.status, enums::AttemptStatus::Charged);
+}
+
+// Partially captures a payment using the manual capture flow (Non 3DS).
+#[actix_web::test]
+async fn should_partially_capture_authorized_payment() {
+ let response = CONNECTOR
+ .authorize_and_capture_payment(
+ payment_method_details(),
+ Some(types::PaymentsCaptureData {
+ amount_to_capture: 50,
+ ..utils::PaymentCaptureType::default().0
+ }),
+ get_default_payment_info(),
+ )
+ .await
+ .expect("Capture payment response");
+ assert_eq!(response.status, enums::AttemptStatus::Charged);
+}
+
+// Synchronizes a payment using the manual capture flow (Non 3DS).
+#[actix_web::test]
+async fn should_sync_authorized_payment() {
+ let authorize_response = CONNECTOR
+ .authorize_payment(payment_method_details(), get_default_payment_info())
+ .await
+ .expect("Authorize payment response");
+ let txn_id = utils::get_connector_transaction_id(authorize_response.response);
+ let response = CONNECTOR
+ .psync_retry_till_status_matches(
+ enums::AttemptStatus::Authorized,
+ Some(types::PaymentsSyncData {
+ connector_transaction_id: types::ResponseId::ConnectorTransactionId(
+ txn_id.unwrap(),
+ ),
+ ..Default::default()
+ }),
+ get_default_payment_info(),
+ )
+ .await
+ .expect("PSync response");
+ assert_eq!(response.status, enums::AttemptStatus::Authorized,);
+}
+
+// Voids a payment using the manual capture flow (Non 3DS).
+#[actix_web::test]
+async fn should_void_authorized_payment() {
+ let response = CONNECTOR
+ .authorize_and_void_payment(
+ payment_method_details(),
+ Some(types::PaymentsCancelData {
+ connector_transaction_id: String::from(""),
+ cancellation_reason: Some("requested_by_customer".to_string()),
+ ..Default::default()
+ }),
+ get_default_payment_info(),
+ )
+ .await
+ .expect("Void payment response");
+ assert_eq!(response.status, enums::AttemptStatus::Voided);
+}
+
+// Refunds a payment using the manual capture flow (Non 3DS).
+#[actix_web::test]
+async fn should_refund_manually_captured_payment() {
+ let response = CONNECTOR
+ .capture_payment_and_refund(
+ payment_method_details(),
+ None,
+ None,
+ get_default_payment_info(),
+ )
+ .await
+ .unwrap();
+ assert_eq!(
+ response.response.unwrap().refund_status,
+ enums::RefundStatus::Success,
+ );
+}
+
+// Partially refunds a payment using the manual capture flow (Non 3DS).
+#[actix_web::test]
+async fn should_partially_refund_manually_captured_payment() {
+ let response = CONNECTOR
+ .capture_payment_and_refund(
+ payment_method_details(),
+ None,
+ Some(types::RefundsData {
+ refund_amount: 50,
+ ..utils::PaymentRefundType::default().0
+ }),
+ get_default_payment_info(),
+ )
+ .await
+ .unwrap();
+ assert_eq!(
+ response.response.unwrap().refund_status,
+ enums::RefundStatus::Success,
+ );
+}
+
+// Synchronizes a refund using the manual capture flow (Non 3DS).
+#[actix_web::test]
+async fn should_sync_manually_captured_refund() {
+ let refund_response = CONNECTOR
+ .capture_payment_and_refund(
+ payment_method_details(),
+ None,
+ None,
+ get_default_payment_info(),
+ )
+ .await
+ .unwrap();
+ let response = CONNECTOR
+ .rsync_retry_till_status_matches(
+ enums::RefundStatus::Success,
+ refund_response.response.unwrap().connector_refund_id,
+ None,
+ get_default_payment_info(),
+ )
+ .await
+ .unwrap();
+ assert_eq!(
+ response.response.unwrap().refund_status,
+ enums::RefundStatus::Success,
+ );
+}
+
+// Creates a payment using the automatic capture flow (Non 3DS).
+#[actix_web::test]
+async fn should_make_payment() {
+ let authorize_response = CONNECTOR
+ .make_payment(payment_method_details(), get_default_payment_info())
+ .await
+ .unwrap();
+ assert_eq!(authorize_response.status, enums::AttemptStatus::Charged);
+}
+
+// Synchronizes a payment using the automatic capture flow (Non 3DS).
+#[actix_web::test]
+async fn should_sync_auto_captured_payment() {
+ let authorize_response = CONNECTOR
+ .make_payment(payment_method_details(), get_default_payment_info())
+ .await
+ .unwrap();
+ assert_eq!(authorize_response.status, enums::AttemptStatus::Charged);
+ let txn_id = utils::get_connector_transaction_id(authorize_response.response);
+ assert_ne!(txn_id, None, "Empty connector transaction id");
+ let response = CONNECTOR
+ .psync_retry_till_status_matches(
+ enums::AttemptStatus::Charged,
+ Some(types::PaymentsSyncData {
+ connector_transaction_id: types::ResponseId::ConnectorTransactionId(
+ txn_id.unwrap(),
+ ),
+ capture_method: Some(enums::CaptureMethod::Automatic),
+ ..Default::default()
+ }),
+ get_default_payment_info(),
+ )
+ .await
+ .unwrap();
+ assert_eq!(response.status, enums::AttemptStatus::Charged,);
+}
+
+// Refunds a payment using the automatic capture flow (Non 3DS).
+#[actix_web::test]
+async fn should_refund_auto_captured_payment() {
+ let response = CONNECTOR
+ .make_payment_and_refund(payment_method_details(), None, get_default_payment_info())
+ .await
+ .unwrap();
+ assert_eq!(
+ response.response.unwrap().refund_status,
+ enums::RefundStatus::Success,
+ );
+}
+
+// Partially refunds a payment using the automatic capture flow (Non 3DS).
+#[actix_web::test]
+async fn should_partially_refund_succeeded_payment() {
+ let refund_response = CONNECTOR
+ .make_payment_and_refund(
+ payment_method_details(),
+ Some(types::RefundsData {
+ refund_amount: 50,
+ ..utils::PaymentRefundType::default().0
+ }),
+ get_default_payment_info(),
+ )
+ .await
+ .unwrap();
+ assert_eq!(
+ refund_response.response.unwrap().refund_status,
+ enums::RefundStatus::Success,
+ );
+}
+
+// Creates multiple refunds against a payment using the automatic capture flow (Non 3DS).
+#[actix_web::test]
+async fn should_refund_succeeded_payment_multiple_times() {
+ CONNECTOR
+ .make_payment_and_multiple_refund(
+ payment_method_details(),
+ Some(types::RefundsData {
+ refund_amount: 50,
+ ..utils::PaymentRefundType::default().0
+ }),
+ get_default_payment_info(),
+ )
+ .await;
+}
+
+// Synchronizes a refund using the automatic capture flow (Non 3DS).
+#[actix_web::test]
+async fn should_sync_refund() {
+ let refund_response = CONNECTOR
+ .make_payment_and_refund(payment_method_details(), None, get_default_payment_info())
+ .await
+ .unwrap();
+ let response = CONNECTOR
+ .rsync_retry_till_status_matches(
+ enums::RefundStatus::Success,
+ refund_response.response.unwrap().connector_refund_id,
+ None,
+ get_default_payment_info(),
+ )
+ .await
+ .unwrap();
+ assert_eq!(
+ response.response.unwrap().refund_status,
+ enums::RefundStatus::Success,
+ );
+}
+
+// Cards Negative scenarios
+// Creates a payment with incorrect CVC.
+#[actix_web::test]
+async fn should_fail_payment_for_incorrect_cvc() {
+ let response = CONNECTOR
+ .make_payment(
+ Some(types::PaymentsAuthorizeData {
+ payment_method_data: domain::PaymentMethodData::Card(domain::Card {
+ card_cvc: Secret::new("12345".to_string()),
+ ..utils::CCardType::default().0
+ }),
+ ..utils::PaymentAuthorizeType::default().0
+ }),
+ get_default_payment_info(),
+ )
+ .await
+ .unwrap();
+ assert_eq!(
+ response.response.unwrap_err().message,
+ "Your card's security code is invalid.".to_string(),
+ );
+}
+
+// Creates a payment with incorrect expiry month.
+#[actix_web::test]
+async fn should_fail_payment_for_invalid_exp_month() {
+ let response = CONNECTOR
+ .make_payment(
+ Some(types::PaymentsAuthorizeData {
+ payment_method_data: domain::PaymentMethodData::Card(domain::Card {
+ card_exp_month: Secret::new("20".to_string()),
+ ..utils::CCardType::default().0
+ }),
+ ..utils::PaymentAuthorizeType::default().0
+ }),
+ get_default_payment_info(),
+ )
+ .await
+ .unwrap();
+ assert_eq!(
+ response.response.unwrap_err().message,
+ "Your card's expiration month is invalid.".to_string(),
+ );
+}
+
+// Creates a payment with incorrect expiry year.
+#[actix_web::test]
+async fn should_fail_payment_for_incorrect_expiry_year() {
+ let response = CONNECTOR
+ .make_payment(
+ Some(types::PaymentsAuthorizeData {
+ payment_method_data: domain::PaymentMethodData::Card(domain::Card {
+ card_exp_year: Secret::new("2000".to_string()),
+ ..utils::CCardType::default().0
+ }),
+ ..utils::PaymentAuthorizeType::default().0
+ }),
+ get_default_payment_info(),
+ )
+ .await
+ .unwrap();
+ assert_eq!(
+ response.response.unwrap_err().message,
+ "Your card's expiration year is invalid.".to_string(),
+ );
+}
+
+// Voids a payment using automatic capture flow (Non 3DS).
+#[actix_web::test]
+async fn should_fail_void_payment_for_auto_capture() {
+ let authorize_response = CONNECTOR
+ .make_payment(payment_method_details(), get_default_payment_info())
+ .await
+ .unwrap();
+ assert_eq!(authorize_response.status, enums::AttemptStatus::Charged);
+ let txn_id = utils::get_connector_transaction_id(authorize_response.response);
+ assert_ne!(txn_id, None, "Empty connector transaction id");
+ let void_response = CONNECTOR
+ .void_payment(txn_id.unwrap(), None, get_default_payment_info())
+ .await
+ .unwrap();
+ assert_eq!(
+ void_response.response.unwrap_err().message,
+ "You cannot cancel this PaymentIntent because it has a status of succeeded."
+ );
+}
+
+// Captures a payment using invalid connector payment id.
+#[actix_web::test]
+async fn should_fail_capture_for_invalid_payment() {
+ let capture_response = CONNECTOR
+ .capture_payment("123456789".to_string(), None, get_default_payment_info())
+ .await
+ .unwrap();
+ assert_eq!(
+ capture_response.response.unwrap_err().message,
+ String::from("No such payment_intent: '123456789'")
+ );
+}
+
+// Refunds a payment with refund amount higher than payment amount.
+#[actix_web::test]
+async fn should_fail_for_refund_amount_higher_than_payment_amount() {
+ let response = CONNECTOR
+ .make_payment_and_refund(
+ payment_method_details(),
+ Some(types::RefundsData {
+ refund_amount: 150,
+ ..utils::PaymentRefundType::default().0
+ }),
+ get_default_payment_info(),
+ )
+ .await
+ .unwrap();
+ assert_eq!(
+ response.response.unwrap_err().message,
+ "Refund amount (₹1.50) is greater than charge amount (₹1.00)",
+ );
+}
+
+// Connector dependent test cases goes here
+
+// [#478]: add unit tests for non 3DS, wallets & webhooks in connector tests
diff --git a/crates/router/tests/connectors/sample_auth.toml b/crates/router/tests/connectors/sample_auth.toml
index 0df5cc09b07..278bffa6aed 100644
--- a/crates/router/tests/connectors/sample_auth.toml
+++ b/crates/router/tests/connectors/sample_auth.toml
@@ -253,4 +253,7 @@ api_key="API Key"
[wellsfargo]
api_key = "MyApiKey"
key1 = "Merchant id"
-api_secret = "Secret key"
\ No newline at end of file
+api_secret = "Secret key"
+
+[paybox]
+api_key="API Key"
diff --git a/crates/test_utils/src/connector_auth.rs b/crates/test_utils/src/connector_auth.rs
index 13d7da931f6..154e4e28fd0 100644
--- a/crates/test_utils/src/connector_auth.rs
+++ b/crates/test_utils/src/connector_auth.rs
@@ -54,6 +54,7 @@ pub struct ConnectorAuthentication {
pub nuvei: Option<SignatureKey>,
pub opayo: Option<HeaderKey>,
pub opennode: Option<HeaderKey>,
+ pub paybox: Option<HeaderKey>,
pub payeezy: Option<SignatureKey>,
pub payme: Option<BodyKey>,
pub payone: Option<HeaderKey>,
diff --git a/loadtest/config/development.toml b/loadtest/config/development.toml
index b09958f02f3..d64d246dff2 100644
--- a/loadtest/config/development.toml
+++ b/loadtest/config/development.toml
@@ -121,6 +121,7 @@ noon.key_mode = "Test"
nuvei.base_url = "https://ppp-test.nuvei.com/"
opayo.base_url = "https://pi-test.sagepay.com/"
opennode.base_url = "https://dev-api.opennode.com"
+paybox.base_url = "https://preprod-ppps.paybox.com/PPPS.php"
payeezy.base_url = "https://api-cert.payeezy.com/"
payme.base_url = "https://sandbox.payme.io/"
payone.base_url = "https://payment.preprod.payone.com/"
@@ -200,6 +201,7 @@ cards = [
"nuvei",
"opayo",
"opennode",
+ "paybox",
"payeezy",
"payme",
"payone",
diff --git a/scripts/add_connector.sh b/scripts/add_connector.sh
index 62a6140fcc2..b29972b9e3b 100755
--- a/scripts/add_connector.sh
+++ b/scripts/add_connector.sh
@@ -6,7 +6,7 @@ function find_prev_connector() {
git checkout $self
cp $self $self.tmp
# Add new connector to existing list and sort it
- connectors=(aci adyen adyenplatform airwallex applepay authorizedotnet bambora bamboraapac bankofamerica billwerk bitpay bluesnap boku braintree cashtocode checkout coinbase cryptopay cybersource datatrans dlocal dummyconnector ebanx fiserv forte globalpay globepay gocardless gpayments helcim iatapay itaubank klarna mifinity mollie multisafepay netcetera nexinets noon nuvei opayo opennode payeezy payme payone paypal payu placetopay plaid powertranz prophetpay rapyd razorpay shift4 square stax stripe threedsecureio trustpay tsys volt wellsfargo wise worldline worldpay zsl "$1")
+ connectors=(aci adyen adyenplatform airwallex applepay authorizedotnet bambora bamboraapac bankofamerica billwerk bitpay bluesnap boku braintree cashtocode checkout coinbase cryptopay cybersource datatrans dlocal dummyconnector ebanx fiserv forte globalpay globepay gocardless gpayments helcim iatapay itaubank klarna mifinity mollie multisafepay netcetera nexinets noon nuvei opayo opennode paybox payeezy payme payone paypal payu placetopay plaid powertranz prophetpay rapyd razorpay shift4 square stax stripe threedsecureio trustpay tsys volt wellsfargo wise worldline worldpay zsl "$1")
IFS=$'\n' sorted=($(sort <<<"${connectors[*]}")); unset IFS
res=`echo ${sorted[@]}`
sed -i'' -e "s/^ connectors=.*/ connectors=($res \"\$1\")/" $self.tmp
|
2024-07-30T19:25:30Z
|
## Type of Change
<!-- Put an `x` in the boxes that apply -->
- [x] New feature
## Description
<!-- Describe your changes in detail -->
Template code for Paybox
### Additional Changes
- [ ] This PR modifies the API contract
- [ ] This PR modifies the database schema
- [ ] This PR modifies application configuration/environment variables
<!--
Provide links to the files with corresponding changes.
Following are the paths where you can find config files:
1. `config`
2. `crates/router/src/configs`
3. `loadtest/config`
-->
## Motivation and Context
<!--
Why is this change required? What problem does it solve?
If it fixes an open issue, please link to the issue here.
If you don't have an issue, we'd recommend starting with one first so the PR
can focus on the implementation (unless it is an obvious bug or documentation fix
that will have little conversation).
-->
https://github.com/juspay/hyperswitch/issues/5489
## How did you test it?
<!--
Did you write an integration/unit/API test to verify the code changes?
Or did you test this change manually (provide relevant screenshots)?
-->
This is template code so, no api testing required
## Checklist
<!-- Put an `x` in the boxes that apply -->
- [x] I formatted the code `cargo +nightly fmt --all`
- [x] I addressed lints thrown by `cargo clippy`
- [x] I reviewed the submitted code
- [ ] I added unit tests for my changes where possible
|
540ef071cb238a56d52d06687226aab7fd0dfe68
|
|
juspay/hyperswitch
|
juspay__hyperswitch-5454
|
Bug: [FEATURE] Set Code owners for Pyament Methods
### Feature Description
Need to set code owners for Payment Method suite
### Possible Implementation
Changing the codeowners file
### Have you spent some time checking if this feature request has been raised before?
- [X] I checked and didn't find a similar issue
### Have you read the Contributing Guidelines?
- [X] I have read the [Contributing Guidelines](https://github.com/juspay/hyperswitch/blob/main/docs/CONTRIBUTING.md)
### Are you willing to submit a PR?
Yes, I am willing to submit a PR!
|
2024-07-26T10:32:42Z
|
## Type of Change
<!-- Put an `x` in the boxes that apply -->
- [ ] Bugfix
- [x] New feature
- [ ] Enhancement
- [ ] Refactoring
- [ ] Dependency updates
- [ ] Documentation
- [ ] CI/CD
## Description
<!-- Describe your changes in detail -->
Have set code owners for Payment Methods
### Additional Changes
- [ ] This PR modifies the API contract
- [ ] This PR modifies the database schema
- [ ] This PR modifies application configuration/environment variables
<!--
Provide links to the files with corresponding changes.
Following are the paths where you can find config files:
1. `config`
2. `crates/router/src/configs`
3. `loadtest/config`
-->
## Motivation and Context
<!--
Why is this change required? What problem does it solve?
If it fixes an open issue, please link to the issue here.
If you don't have an issue, we'd recommend starting with one first so the PR
can focus on the implementation (unless it is an obvious bug or documentation fix
that will have little conversation).
-->
## How did you test it?
<!--
Did you write an integration/unit/API test to verify the code changes?
Or did you test this change manually (provide relevant screenshots)?
-->
## Checklist
<!-- Put an `x` in the boxes that apply -->
- [x] I formatted the code `cargo +nightly fmt --all`
- [x] I addressed lints thrown by `cargo clippy`
- [ ] I reviewed the submitted code
- [ ] I added unit tests for my changes where possible
|
2bee694d5bb7393c11817bbee26b459609f6dd8c
|
||
juspay/hyperswitch
|
juspay__hyperswitch-5437
|
Bug: fix: change country in SessionFlowRouting
## Description
Currently Shipping country is being used in SessionFlowRouting, which affects the PaymentMethodList as the later depends on billing country.
|
diff --git a/crates/router/src/core/payment_methods/cards.rs b/crates/router/src/core/payment_methods/cards.rs
index 5f5e59a89a5..6ed12388c4a 100644
--- a/crates/router/src/core/payment_methods/cards.rs
+++ b/crates/router/src/core/payment_methods/cards.rs
@@ -2556,7 +2556,7 @@ pub async fn list_payment_methods(
}
let sfr = SessionFlowRoutingInput {
state: &state,
- country: shipping_address.clone().and_then(|ad| ad.country),
+ country: billing_address.clone().and_then(|ad| ad.country),
key_store: &key_store,
merchant_account: &merchant_account,
payment_attempt,
|
2024-07-24T17:45:01Z
|
## Type of Change
<!-- Put an `x` in the boxes that apply -->
- [x] Bugfix
- [ ] New feature
- [ ] Enhancement
- [ ] Refactoring
- [ ] Dependency updates
- [ ] Documentation
- [ ] CI/CD
## Description
<!-- Describe your changes in detail -->
Currently Shipping country is being used in SessionFlowRouting, which affects the PaymentMethodList as the later depends on billing country.
### Additional Changes
- [ ] This PR modifies the API contract
- [ ] This PR modifies the database schema
- [ ] This PR modifies application configuration/environment variables
<!--
Provide links to the files with corresponding changes.
Following are the paths where you can find config files:
1. `config`
2. `crates/router/src/configs`
3. `loadtest/config`
-->
## Motivation and Context
<!--
Why is this change required? What problem does it solve?
If it fixes an open issue, please link to the issue here.
If you don't have an issue, we'd recommend starting with one first so the PR
can focus on the implementation (unless it is an obvious bug or documentation fix
that will have little conversation).
-->
Payment method list was failing due to shipping country being used in SessionFlowRouting.
## How did you test it?
<!--
Did you write an integration/unit/API test to verify the code changes?
Or did you test this change manually (provide relevant screenshots)?
-->
## Flow followed
### Request 1: mca create request (Adyen)
```
curl --location 'http://127.0.0.1:8080/account/merchant_1721842730/connectors' \
--header 'Content-Type: application/json' \
--header 'Accept: application/json' \
--header 'api-key: xxxxxx' \
--data '
{
"connector_type": "fiz_operations",
"connector_name": "adyen",
"connector_account_details": {
"auth_type": "BodyKey",
"api_key": "{{connector_api_key}}",
"key1": "{{connector_key1}}",
"api_secret": "{{connector_api_secret}}"
},
"test_mode": false,
"disabled": false,
"business_country": "US",
"business_label": "default",
"payment_methods_enabled": [
{
"payment_method": "bank_redirect",
"payment_method_types": [
{
"payment_method_type": "ideal",
"recurring_enabled": true,
"installment_payment_enabled": true,
"payment_experience": "redirect_to_url"
}
]
}
],
"metadata": {
"endpoint_prefix": ""
},
"connector_webhook_details": {
"merchant_secret": "xxxxxx"
}
}'
```
### Request 2: Payment Create Request (with `billing_country = NL` & `shipping_country = IN`)
```
curl --location 'http://127.0.0.1:8080/payments' \
--header 'Content-Type: application/json' \
--header 'Accept: application/json' \
--header 'api-key:xxxxxx' \
--data-raw '
{
"amount": 6540,
"currency": "EUR",
"confirm": false,
"capture_method": "automatic",
"capture_on": "2022-09-10T10:11:12Z",
"amount_to_capture": 6540,
"customer_id": "cus26",
"email": "guest@example.com",
"name": "John Doe",
"phone": "999999999",
"phone_country_code": "+65",
"description": "Its my first payment request",
"authentication_type": "no_three_ds",
"return_url": "https://google.com",
"billing": {
"address": {
"line1": "1467",
"line2": "Harrison Street",
"line3": "Harrison Street",
"city": "San Fransico",
"state": "California",
"zip": "94122",
"country": "NL",
"first_name": "joseph",
"last_name": "Doe"
},
"phone": {
"number": "8056594427",
"country_code": "+91"
}
},
"shipping": {
"address": {
"line1": "1467",
"line2": "Harrison Street",
"line3": "Harrison Street",
"city": "San Fransico",
"state": "California",
"zip": "94122",
"country": "IN",
"first_name": "joseph",
"last_name": "Doe"
},
"phone": {
"number": "8056594427",
"country_code": "+91"
}
},
"statement_descriptor_name": "joseph",
"statement_descriptor_suffix": "JS",
"metadata": {
"udf1": "value1",
"new_customer": "true",
"login_date": "2019-09-10T10:11:12Z"
}
}
'
```
### Request 3: List Merchant Payment Methods
```
curl --location 'http://127.0.0.1:8080/account/payment_methods?client_secret=pay_pjPrnplx4iezrnZVq9OP_secret_G0Oc8N6SoTMKJpfYMEqZ' \
--header 'Accept: application/json' \
--header 'api-key: pk_dev_a5ea68aa142c4bb8ad07d0570166d26a' \
--data ''
```
**Response**
Ideal should come
## Checklist
<!-- Put an `x` in the boxes that apply -->
- [ ] I formatted the code `cargo +nightly fmt --all`
- [ ] I addressed lints thrown by `cargo clippy`
- [x] I reviewed the submitted code
- [ ] I added unit tests for my changes where possible
|
8e7de9068428e585c6848d3de5b1b4f292324dfc
|
|
juspay/hyperswitch
|
juspay__hyperswitch-5438
|
Bug: fix: refactor error codes for failing cypress tests
## Description
Cypress tests are failing due to some recent refactors in error codes, which needs to be revamped to the correct ones in cypress framework.
|
2024-07-24T07:31:25Z
|
## Type of Change
<!-- Put an `x` in the boxes that apply -->
- [ ] Bugfix
- [ ] New feature
- [ ] Enhancement
- [ ] Refactoring
- [ ] Dependency updates
- [ ] Documentation
- [ ] CI/CD
## Description
<!-- Describe your changes in detail -->
Changing of error codes to match cypress mappings
### Additional Changes
- [ ] This PR modifies the API contract
- [ ] This PR modifies the database schema
- [ ] This PR modifies application configuration/environment variables
<!--
Provide links to the files with corresponding changes.
Following are the paths where you can find config files:
1. `config`
2. `crates/router/src/configs`
3. `loadtest/config`
-->
## Motivation and Context
<!--
Why is this change required? What problem does it solve?
If it fixes an open issue, please link to the issue here.
If you don't have an issue, we'd recommend starting with one first so the PR
can focus on the implementation (unless it is an obvious bug or documentation fix
that will have little conversation).
-->
To fix failing Cypress-tests
## How did you test it?
<!--
Did you write an integration/unit/API test to verify the code changes?
Or did you test this change manually (provide relevant screenshots)?
-->
Tested locally for the following connectors:
PS: The failing tests are not due to error codes they are due to expected status 200 but instead receiving error in routing.
stripe
<img width="674" alt="Screenshot 2024-07-25 at 9 05 33 AM" src="https://github.com/user-attachments/assets/01ff4e3d-75e3-4831-a121-0459d6665b66">
blluesnap
<img width="692" alt="Screenshot 2024-07-25 at 9 10 21 AM" src="https://github.com/user-attachments/assets/8d7f2e4a-4dbd-426f-b0ec-1c47fe0e8b21">
## Checklist
<!-- Put an `x` in the boxes that apply -->
- [ ] I formatted the code `cargo +nightly fmt --all`
- [ ] I addressed lints thrown by `cargo clippy`
- [ ] I reviewed the submitted code
- [ ] I added unit tests for my changes where possible
|
26b878308f7e493d6adb8c08b54a5498406eb28a
|
||
juspay/hyperswitch
|
juspay__hyperswitch-5440
|
Bug: [FEATURE] [FISERV] Move connector code for fiserv to crate hyperswitch_connectors
### Feature Description
Connector code for `fiserv` needs to be moved from crate router to new crate hyperswitch_connectors
### Possible Implementation
Connector code for `fiserv` needs to be moved from crate router to new crate hyperswitch_connectors
### Have you spent some time checking if this feature request has been raised before?
- [X] I checked and didn't find a similar issue
### Have you read the Contributing Guidelines?
- [X] I have read the [Contributing Guidelines](https://github.com/juspay/hyperswitch/blob/main/docs/CONTRIBUTING.md)
### Are you willing to submit a PR?
Yes, I am willing to submit a PR!
|
diff --git a/Cargo.lock b/Cargo.lock
index c5eac1ef868..45556ef401e 100644
--- a/Cargo.lock
+++ b/Cargo.lock
@@ -3836,6 +3836,7 @@ version = "0.1.0"
dependencies = [
"api_models",
"async-trait",
+ "base64 0.22.0",
"cards",
"common_enums",
"common_utils",
@@ -3843,10 +3844,13 @@ dependencies = [
"hyperswitch_domain_models",
"hyperswitch_interfaces",
"masking",
+ "ring 0.17.8",
"router_env",
"serde",
"serde_json",
"strum 0.26.2",
+ "time",
+ "uuid",
]
[[package]]
diff --git a/crates/hyperswitch_connectors/Cargo.toml b/crates/hyperswitch_connectors/Cargo.toml
index 0e620c6b9f0..30671d43bd9 100644
--- a/crates/hyperswitch_connectors/Cargo.toml
+++ b/crates/hyperswitch_connectors/Cargo.toml
@@ -11,10 +11,14 @@ payouts = ["hyperswitch_domain_models/payouts", "api_models/payouts", "hyperswit
[dependencies]
async-trait = "0.1.79"
+base64 = "0.22.0"
error-stack = "0.4.1"
+ring = "0.17.8"
serde = { version = "1.0.197", features = ["derive"] }
serde_json = "1.0.115"
strum = { version = "0.26", features = ["derive"] }
+time = "0.3.35"
+uuid = { version = "1.8.0", features = ["v4"] }
# First party crates
api_models = { version = "0.1.0", path = "../api_models", features = ["errors"] , default-features = false}
diff --git a/crates/hyperswitch_connectors/src/connectors.rs b/crates/hyperswitch_connectors/src/connectors.rs
index a2d78ede2b9..0481939feb4 100644
--- a/crates/hyperswitch_connectors/src/connectors.rs
+++ b/crates/hyperswitch_connectors/src/connectors.rs
@@ -1,2 +1,4 @@
+pub mod fiserv;
pub mod helcim;
-pub use self::helcim::Helcim;
+
+pub use self::{fiserv::Fiserv, helcim::Helcim};
diff --git a/crates/router/src/connector/fiserv.rs b/crates/hyperswitch_connectors/src/connectors/fiserv.rs
similarity index 67%
rename from crates/router/src/connector/fiserv.rs
rename to crates/hyperswitch_connectors/src/connectors/fiserv.rs
index 75147fe780c..fc67cd2fde7 100644
--- a/crates/router/src/connector/fiserv.rs
+++ b/crates/hyperswitch_connectors/src/connectors/fiserv.rs
@@ -3,34 +3,45 @@ pub mod transformers;
use std::fmt::Debug;
use base64::Engine;
-use common_utils::request::RequestContent;
-use diesel_models::enums;
+use common_enums::enums;
+use common_utils::{
+ errors::CustomResult,
+ ext_traits::BytesExt,
+ request::{Method, Request, RequestBuilder, RequestContent},
+};
use error_stack::{report, ResultExt};
-use masking::{ExposeInterface, PeekInterface};
+use hyperswitch_domain_models::{
+ router_data::{AccessToken, ConnectorAuthType, ErrorResponse, RouterData},
+ router_flow_types::{
+ access_token_auth::AccessTokenAuth,
+ payments::{Authorize, Capture, PSync, PaymentMethodToken, Session, SetupMandate, Void},
+ refunds::{Execute, RSync},
+ },
+ router_request_types::{
+ AccessTokenRequestData, PaymentMethodTokenizationData, PaymentsAuthorizeData,
+ PaymentsCancelData, PaymentsCaptureData, PaymentsSessionData, PaymentsSyncData,
+ RefundsData, SetupMandateRequestData,
+ },
+ router_response_types::{PaymentsResponseData, RefundsResponseData},
+ types::{
+ PaymentsAuthorizeRouterData, PaymentsCancelRouterData, PaymentsCaptureRouterData,
+ PaymentsSyncRouterData, RefundSyncRouterData, RefundsRouterData,
+ },
+};
+use hyperswitch_interfaces::{
+ api::{self, ConnectorCommon, ConnectorCommonExt, ConnectorIntegration, ConnectorValidation},
+ configs::Connectors,
+ consts, errors,
+ events::connector_api_logs::ConnectorEvent,
+ types, webhooks,
+};
+use masking::{ExposeInterface, Mask, PeekInterface};
use ring::hmac;
use time::OffsetDateTime;
use transformers as fiserv;
use uuid::Uuid;
-use crate::{
- configs::settings,
- connector::utils as connector_utils,
- consts,
- core::errors::{self, CustomResult},
- events::connector_api_logs::ConnectorEvent,
- headers, logger,
- services::{
- self,
- api::ConnectorIntegration,
- request::{self, Mask},
- ConnectorValidation,
- },
- types::{
- self,
- api::{self, ConnectorCommon, ConnectorCommonExt},
- },
- utils::BytesExt,
-};
+use crate::{constants::headers, types::ResponseRouterData, utils};
#[derive(Debug, Clone)]
pub struct Fiserv;
@@ -51,8 +62,8 @@ impl Fiserv {
let raw_signature = format!("{}{request_id}{timestamp}{payload}", api_key.peek());
let key = hmac::Key::new(hmac::HMAC_SHA256, api_secret.expose().as_bytes());
- let signature_value =
- consts::BASE64_ENGINE.encode(hmac::sign(&key, raw_signature.as_bytes()).as_ref());
+ let signature_value = common_utils::consts::BASE64_ENGINE
+ .encode(hmac::sign(&key, raw_signature.as_bytes()).as_ref());
Ok(signature_value)
}
}
@@ -63,9 +74,9 @@ where
{
fn build_headers(
&self,
- req: &types::RouterData<Flow, Request, Response>,
- connectors: &settings::Connectors,
- ) -> CustomResult<Vec<(String, request::Maskable<String>)>, errors::ConnectorError> {
+ req: &RouterData<Flow, Request, Response>,
+ connectors: &Connectors,
+ ) -> CustomResult<Vec<(String, masking::Maskable<String>)>, errors::ConnectorError> {
let timestamp = OffsetDateTime::now_utc().unix_timestamp_nanos() / 1_000_000;
let auth: fiserv::FiservAuthType =
fiserv::FiservAuthType::try_from(&req.connector_auth_type)?;
@@ -112,13 +123,13 @@ impl ConnectorCommon for Fiserv {
"application/json"
}
- fn base_url<'a>(&self, connectors: &'a settings::Connectors) -> &'a str {
+ fn base_url<'a>(&self, connectors: &'a Connectors) -> &'a str {
connectors.fiserv.base_url.as_ref()
}
fn get_auth_header(
&self,
- auth_type: &types::ConnectorAuthType,
- ) -> CustomResult<Vec<(String, request::Maskable<String>)>, errors::ConnectorError> {
+ auth_type: &ConnectorAuthType,
+ ) -> CustomResult<Vec<(String, masking::Maskable<String>)>, errors::ConnectorError> {
let auth = fiserv::FiservAuthType::try_from(auth_type)
.change_context(errors::ConnectorError::FailedToObtainAuthType)?;
Ok(vec![(
@@ -130,7 +141,7 @@ impl ConnectorCommon for Fiserv {
&self,
res: types::Response,
event_builder: Option<&mut ConnectorEvent>,
- ) -> CustomResult<types::ErrorResponse, errors::ConnectorError> {
+ ) -> CustomResult<ErrorResponse, errors::ConnectorError> {
let response: fiserv::ErrorResponse = res
.response
.parse_struct("Fiserv ErrorResponse")
@@ -144,21 +155,19 @@ impl ConnectorCommon for Fiserv {
Ok(error
.or(details)
.and_then(|error_details| {
- error_details
- .first()
- .map(|first_error| types::ErrorResponse {
- code: first_error
- .code
- .to_owned()
- .unwrap_or_else(|| consts::NO_ERROR_CODE.to_string()),
- message: first_error.message.to_owned(),
- reason: first_error.field.to_owned(),
- status_code: res.status_code,
- attempt_status: None,
- connector_transaction_id: None,
- })
+ error_details.first().map(|first_error| ErrorResponse {
+ code: first_error
+ .code
+ .to_owned()
+ .unwrap_or_else(|| consts::NO_ERROR_CODE.to_string()),
+ message: first_error.message.to_owned(),
+ reason: first_error.field.to_owned(),
+ status_code: res.status_code,
+ attempt_status: None,
+ connector_transaction_id: None,
+ })
})
- .unwrap_or(types::ErrorResponse {
+ .unwrap_or(ErrorResponse {
code: consts::NO_ERROR_CODE.to_string(),
message: consts::NO_ERROR_MESSAGE.to_string(),
reason: None,
@@ -179,7 +188,7 @@ impl ConnectorValidation for Fiserv {
match capture_method {
enums::CaptureMethod::Automatic | enums::CaptureMethod::Manual => Ok(()),
enums::CaptureMethod::ManualMultiple | enums::CaptureMethod::Scheduled => Err(
- connector_utils::construct_not_implemented_error_report(capture_method, self.id()),
+ utils::construct_not_implemented_error_report(capture_method, self.id()),
),
}
}
@@ -187,9 +196,7 @@ impl ConnectorValidation for Fiserv {
impl api::ConnectorAccessToken for Fiserv {}
-impl ConnectorIntegration<api::AccessTokenAuth, types::AccessTokenRequestData, types::AccessToken>
- for Fiserv
-{
+impl ConnectorIntegration<AccessTokenAuth, AccessTokenRequestData, AccessToken> for Fiserv {
// Not Implemented (R)
}
@@ -197,12 +204,8 @@ impl api::Payment for Fiserv {}
impl api::PaymentToken for Fiserv {}
-impl
- ConnectorIntegration<
- api::PaymentMethodToken,
- types::PaymentMethodTokenizationData,
- types::PaymentsResponseData,
- > for Fiserv
+impl ConnectorIntegration<PaymentMethodToken, PaymentMethodTokenizationData, PaymentsResponseData>
+ for Fiserv
{
// Not Implemented (R)
}
@@ -210,22 +213,12 @@ impl
impl api::MandateSetup for Fiserv {}
#[allow(dead_code)]
-impl
- ConnectorIntegration<
- api::SetupMandate,
- types::SetupMandateRequestData,
- types::PaymentsResponseData,
- > for Fiserv
-{
+impl ConnectorIntegration<SetupMandate, SetupMandateRequestData, PaymentsResponseData> for Fiserv {
fn build_request(
&self,
- _req: &types::RouterData<
- api::SetupMandate,
- types::SetupMandateRequestData,
- types::PaymentsResponseData,
- >,
- _connectors: &settings::Connectors,
- ) -> CustomResult<Option<services::Request>, errors::ConnectorError> {
+ _req: &RouterData<SetupMandate, SetupMandateRequestData, PaymentsResponseData>,
+ _connectors: &Connectors,
+ ) -> CustomResult<Option<Request>, errors::ConnectorError> {
Err(
errors::ConnectorError::NotImplemented("Setup Mandate flow for Fiserv".to_string())
.into(),
@@ -236,14 +229,12 @@ impl
impl api::PaymentVoid for Fiserv {}
#[allow(dead_code)]
-impl ConnectorIntegration<api::Void, types::PaymentsCancelData, types::PaymentsResponseData>
- for Fiserv
-{
+impl ConnectorIntegration<Void, PaymentsCancelData, PaymentsResponseData> for Fiserv {
fn get_headers(
&self,
- req: &types::PaymentsCancelRouterData,
- connectors: &settings::Connectors,
- ) -> CustomResult<Vec<(String, request::Maskable<String>)>, errors::ConnectorError> {
+ req: &PaymentsCancelRouterData,
+ connectors: &Connectors,
+ ) -> CustomResult<Vec<(String, masking::Maskable<String>)>, errors::ConnectorError> {
self.build_headers(req, connectors)
}
@@ -253,8 +244,8 @@ impl ConnectorIntegration<api::Void, types::PaymentsCancelData, types::PaymentsR
fn get_url(
&self,
- _req: &types::PaymentsCancelRouterData,
- connectors: &settings::Connectors,
+ _req: &PaymentsCancelRouterData,
+ connectors: &Connectors,
) -> CustomResult<String, errors::ConnectorError> {
Ok(format!(
//The docs has this url wrong, cancels is the working endpoint
@@ -265,8 +256,8 @@ impl ConnectorIntegration<api::Void, types::PaymentsCancelData, types::PaymentsR
fn get_request_body(
&self,
- req: &types::PaymentsCancelRouterData,
- _connectors: &settings::Connectors,
+ req: &PaymentsCancelRouterData,
+ _connectors: &Connectors,
) -> CustomResult<RequestContent, errors::ConnectorError> {
let connector_req = fiserv::FiservCancelRequest::try_from(req)?;
Ok(RequestContent::Json(Box::new(connector_req)))
@@ -274,12 +265,12 @@ impl ConnectorIntegration<api::Void, types::PaymentsCancelData, types::PaymentsR
fn build_request(
&self,
- req: &types::PaymentsCancelRouterData,
- connectors: &settings::Connectors,
- ) -> CustomResult<Option<services::Request>, errors::ConnectorError> {
+ req: &PaymentsCancelRouterData,
+ connectors: &Connectors,
+ ) -> CustomResult<Option<Request>, errors::ConnectorError> {
let request = Some(
- services::RequestBuilder::new()
- .method(services::Method::Post)
+ RequestBuilder::new()
+ .method(Method::Post)
.url(&types::PaymentsVoidType::get_url(self, req, connectors)?)
.attach_default_headers()
.headers(types::PaymentsVoidType::get_headers(self, req, connectors)?)
@@ -294,17 +285,17 @@ impl ConnectorIntegration<api::Void, types::PaymentsCancelData, types::PaymentsR
fn handle_response(
&self,
- data: &types::PaymentsCancelRouterData,
+ data: &PaymentsCancelRouterData,
event_builder: Option<&mut ConnectorEvent>,
res: types::Response,
- ) -> CustomResult<types::PaymentsCancelRouterData, errors::ConnectorError> {
+ ) -> CustomResult<PaymentsCancelRouterData, errors::ConnectorError> {
let response: fiserv::FiservPaymentsResponse = res
.response
.parse_struct("Fiserv PaymentResponse")
.change_context(errors::ConnectorError::ResponseDeserializationFailed)?;
event_builder.map(|i| i.set_response_body(&response));
router_env::logger::info!(connector_response=?response);
- types::RouterData::try_from(types::ResponseRouterData {
+ RouterData::try_from(ResponseRouterData {
response,
data: data.clone(),
http_code: res.status_code,
@@ -316,7 +307,7 @@ impl ConnectorIntegration<api::Void, types::PaymentsCancelData, types::PaymentsR
&self,
res: types::Response,
event_builder: Option<&mut ConnectorEvent>,
- ) -> CustomResult<types::ErrorResponse, errors::ConnectorError> {
+ ) -> CustomResult<ErrorResponse, errors::ConnectorError> {
self.build_error_response(res, event_builder)
}
}
@@ -324,14 +315,12 @@ impl ConnectorIntegration<api::Void, types::PaymentsCancelData, types::PaymentsR
impl api::PaymentSync for Fiserv {}
#[allow(dead_code)]
-impl ConnectorIntegration<api::PSync, types::PaymentsSyncData, types::PaymentsResponseData>
- for Fiserv
-{
+impl ConnectorIntegration<PSync, PaymentsSyncData, PaymentsResponseData> for Fiserv {
fn get_headers(
&self,
- req: &types::PaymentsSyncRouterData,
- connectors: &settings::Connectors,
- ) -> CustomResult<Vec<(String, request::Maskable<String>)>, errors::ConnectorError> {
+ req: &PaymentsSyncRouterData,
+ connectors: &Connectors,
+ ) -> CustomResult<Vec<(String, masking::Maskable<String>)>, errors::ConnectorError> {
self.build_headers(req, connectors)
}
@@ -341,8 +330,8 @@ impl ConnectorIntegration<api::PSync, types::PaymentsSyncData, types::PaymentsRe
fn get_url(
&self,
- _req: &types::PaymentsSyncRouterData,
- connectors: &settings::Connectors,
+ _req: &PaymentsSyncRouterData,
+ connectors: &Connectors,
) -> CustomResult<String, errors::ConnectorError> {
Ok(format!(
"{}ch/payments/v1/transaction-inquiry",
@@ -352,8 +341,8 @@ impl ConnectorIntegration<api::PSync, types::PaymentsSyncData, types::PaymentsRe
fn get_request_body(
&self,
- req: &types::PaymentsSyncRouterData,
- _connectors: &settings::Connectors,
+ req: &PaymentsSyncRouterData,
+ _connectors: &Connectors,
) -> CustomResult<RequestContent, errors::ConnectorError> {
let connector_req = fiserv::FiservSyncRequest::try_from(req)?;
Ok(RequestContent::Json(Box::new(connector_req)))
@@ -361,12 +350,12 @@ impl ConnectorIntegration<api::PSync, types::PaymentsSyncData, types::PaymentsRe
fn build_request(
&self,
- req: &types::PaymentsSyncRouterData,
- connectors: &settings::Connectors,
- ) -> CustomResult<Option<services::Request>, errors::ConnectorError> {
+ req: &PaymentsSyncRouterData,
+ connectors: &Connectors,
+ ) -> CustomResult<Option<Request>, errors::ConnectorError> {
let request = Some(
- services::RequestBuilder::new()
- .method(services::Method::Post)
+ RequestBuilder::new()
+ .method(Method::Post)
.url(&types::PaymentsSyncType::get_url(self, req, connectors)?)
.attach_default_headers()
.headers(types::PaymentsSyncType::get_headers(self, req, connectors)?)
@@ -380,17 +369,17 @@ impl ConnectorIntegration<api::PSync, types::PaymentsSyncData, types::PaymentsRe
fn handle_response(
&self,
- data: &types::PaymentsSyncRouterData,
+ data: &PaymentsSyncRouterData,
event_builder: Option<&mut ConnectorEvent>,
res: types::Response,
- ) -> CustomResult<types::PaymentsSyncRouterData, errors::ConnectorError> {
+ ) -> CustomResult<PaymentsSyncRouterData, errors::ConnectorError> {
let response: fiserv::FiservSyncResponse = res
.response
.parse_struct("Fiserv PaymentSyncResponse")
.change_context(errors::ConnectorError::ResponseDeserializationFailed)?;
event_builder.map(|i| i.set_response_body(&response));
router_env::logger::info!(connector_response=?response);
- types::RouterData::try_from(types::ResponseRouterData {
+ RouterData::try_from(ResponseRouterData {
response,
data: data.clone(),
http_code: res.status_code,
@@ -402,20 +391,18 @@ impl ConnectorIntegration<api::PSync, types::PaymentsSyncData, types::PaymentsRe
&self,
res: types::Response,
event_builder: Option<&mut ConnectorEvent>,
- ) -> CustomResult<types::ErrorResponse, errors::ConnectorError> {
+ ) -> CustomResult<ErrorResponse, errors::ConnectorError> {
self.build_error_response(res, event_builder)
}
}
impl api::PaymentCapture for Fiserv {}
-impl ConnectorIntegration<api::Capture, types::PaymentsCaptureData, types::PaymentsResponseData>
- for Fiserv
-{
+impl ConnectorIntegration<Capture, PaymentsCaptureData, PaymentsResponseData> for Fiserv {
fn get_headers(
&self,
- req: &types::PaymentsCaptureRouterData,
- connectors: &settings::Connectors,
- ) -> CustomResult<Vec<(String, request::Maskable<String>)>, errors::ConnectorError> {
+ req: &PaymentsCaptureRouterData,
+ connectors: &Connectors,
+ ) -> CustomResult<Vec<(String, masking::Maskable<String>)>, errors::ConnectorError> {
self.build_headers(req, connectors)
}
@@ -425,8 +412,8 @@ impl ConnectorIntegration<api::Capture, types::PaymentsCaptureData, types::Payme
fn get_request_body(
&self,
- req: &types::PaymentsCaptureRouterData,
- _connectors: &settings::Connectors,
+ req: &PaymentsCaptureRouterData,
+ _connectors: &Connectors,
) -> CustomResult<RequestContent, errors::ConnectorError> {
let router_obj = fiserv::FiservRouterData::try_from((
&self.get_currency_unit(),
@@ -440,12 +427,12 @@ impl ConnectorIntegration<api::Capture, types::PaymentsCaptureData, types::Payme
fn build_request(
&self,
- req: &types::PaymentsCaptureRouterData,
- connectors: &settings::Connectors,
- ) -> CustomResult<Option<services::Request>, errors::ConnectorError> {
+ req: &PaymentsCaptureRouterData,
+ connectors: &Connectors,
+ ) -> CustomResult<Option<Request>, errors::ConnectorError> {
let request = Some(
- services::RequestBuilder::new()
- .method(services::Method::Post)
+ RequestBuilder::new()
+ .method(Method::Post)
.url(&types::PaymentsCaptureType::get_url(self, req, connectors)?)
.attach_default_headers()
.headers(types::PaymentsCaptureType::get_headers(
@@ -461,10 +448,10 @@ impl ConnectorIntegration<api::Capture, types::PaymentsCaptureData, types::Payme
fn handle_response(
&self,
- data: &types::PaymentsCaptureRouterData,
+ data: &PaymentsCaptureRouterData,
event_builder: Option<&mut ConnectorEvent>,
res: types::Response,
- ) -> CustomResult<types::PaymentsCaptureRouterData, errors::ConnectorError> {
+ ) -> CustomResult<PaymentsCaptureRouterData, errors::ConnectorError> {
let response: fiserv::FiservPaymentsResponse = res
.response
.parse_struct("Fiserv Payment Response")
@@ -473,7 +460,7 @@ impl ConnectorIntegration<api::Capture, types::PaymentsCaptureData, types::Payme
event_builder.map(|i| i.set_response_body(&response));
router_env::logger::info!(connector_response=?response);
- types::RouterData::try_from(types::ResponseRouterData {
+ RouterData::try_from(ResponseRouterData {
response,
data: data.clone(),
http_code: res.status_code,
@@ -483,8 +470,8 @@ impl ConnectorIntegration<api::Capture, types::PaymentsCaptureData, types::Payme
fn get_url(
&self,
- _req: &types::PaymentsCaptureRouterData,
- connectors: &settings::Connectors,
+ _req: &PaymentsCaptureRouterData,
+ connectors: &Connectors,
) -> CustomResult<String, errors::ConnectorError> {
Ok(format!(
"{}ch/payments/v1/charges",
@@ -496,7 +483,7 @@ impl ConnectorIntegration<api::Capture, types::PaymentsCaptureData, types::Payme
&self,
res: types::Response,
event_builder: Option<&mut ConnectorEvent>,
- ) -> CustomResult<types::ErrorResponse, errors::ConnectorError> {
+ ) -> CustomResult<ErrorResponse, errors::ConnectorError> {
self.build_error_response(res, event_builder)
}
}
@@ -504,21 +491,16 @@ impl ConnectorIntegration<api::Capture, types::PaymentsCaptureData, types::Payme
impl api::PaymentSession for Fiserv {}
#[allow(dead_code)]
-impl ConnectorIntegration<api::Session, types::PaymentsSessionData, types::PaymentsResponseData>
- for Fiserv
-{
-}
+impl ConnectorIntegration<Session, PaymentsSessionData, PaymentsResponseData> for Fiserv {}
impl api::PaymentAuthorize for Fiserv {}
-impl ConnectorIntegration<api::Authorize, types::PaymentsAuthorizeData, types::PaymentsResponseData>
- for Fiserv
-{
+impl ConnectorIntegration<Authorize, PaymentsAuthorizeData, PaymentsResponseData> for Fiserv {
fn get_headers(
&self,
- req: &types::PaymentsAuthorizeRouterData,
- connectors: &settings::Connectors,
- ) -> CustomResult<Vec<(String, request::Maskable<String>)>, errors::ConnectorError> {
+ req: &PaymentsAuthorizeRouterData,
+ connectors: &Connectors,
+ ) -> CustomResult<Vec<(String, masking::Maskable<String>)>, errors::ConnectorError> {
self.build_headers(req, connectors)
}
@@ -528,8 +510,8 @@ impl ConnectorIntegration<api::Authorize, types::PaymentsAuthorizeData, types::P
fn get_url(
&self,
- _req: &types::PaymentsAuthorizeRouterData,
- connectors: &settings::Connectors,
+ _req: &PaymentsAuthorizeRouterData,
+ connectors: &Connectors,
) -> CustomResult<String, errors::ConnectorError> {
Ok(format!(
"{}ch/payments/v1/charges",
@@ -539,8 +521,8 @@ impl ConnectorIntegration<api::Authorize, types::PaymentsAuthorizeData, types::P
fn get_request_body(
&self,
- req: &types::PaymentsAuthorizeRouterData,
- _connectors: &settings::Connectors,
+ req: &PaymentsAuthorizeRouterData,
+ _connectors: &Connectors,
) -> CustomResult<RequestContent, errors::ConnectorError> {
let router_obj = fiserv::FiservRouterData::try_from((
&self.get_currency_unit(),
@@ -554,12 +536,12 @@ impl ConnectorIntegration<api::Authorize, types::PaymentsAuthorizeData, types::P
fn build_request(
&self,
- req: &types::PaymentsAuthorizeRouterData,
- connectors: &settings::Connectors,
- ) -> CustomResult<Option<services::Request>, errors::ConnectorError> {
+ req: &PaymentsAuthorizeRouterData,
+ connectors: &Connectors,
+ ) -> CustomResult<Option<Request>, errors::ConnectorError> {
let request = Some(
- services::RequestBuilder::new()
- .method(services::Method::Post)
+ RequestBuilder::new()
+ .method(Method::Post)
.url(&types::PaymentsAuthorizeType::get_url(
self, req, connectors,
)?)
@@ -578,17 +560,17 @@ impl ConnectorIntegration<api::Authorize, types::PaymentsAuthorizeData, types::P
fn handle_response(
&self,
- data: &types::PaymentsAuthorizeRouterData,
+ data: &PaymentsAuthorizeRouterData,
event_builder: Option<&mut ConnectorEvent>,
res: types::Response,
- ) -> CustomResult<types::PaymentsAuthorizeRouterData, errors::ConnectorError> {
+ ) -> CustomResult<PaymentsAuthorizeRouterData, errors::ConnectorError> {
let response: fiserv::FiservPaymentsResponse = res
.response
.parse_struct("Fiserv PaymentResponse")
.change_context(errors::ConnectorError::ResponseDeserializationFailed)?;
event_builder.map(|i| i.set_response_body(&response));
router_env::logger::info!(connector_response=?response);
- types::RouterData::try_from(types::ResponseRouterData {
+ RouterData::try_from(ResponseRouterData {
response,
data: data.clone(),
http_code: res.status_code,
@@ -600,7 +582,7 @@ impl ConnectorIntegration<api::Authorize, types::PaymentsAuthorizeData, types::P
&self,
res: types::Response,
event_builder: Option<&mut ConnectorEvent>,
- ) -> CustomResult<types::ErrorResponse, errors::ConnectorError> {
+ ) -> CustomResult<ErrorResponse, errors::ConnectorError> {
self.build_error_response(res, event_builder)
}
}
@@ -610,12 +592,12 @@ impl api::RefundExecute for Fiserv {}
impl api::RefundSync for Fiserv {}
#[allow(dead_code)]
-impl ConnectorIntegration<api::Execute, types::RefundsData, types::RefundsResponseData> for Fiserv {
+impl ConnectorIntegration<Execute, RefundsData, RefundsResponseData> for Fiserv {
fn get_headers(
&self,
- req: &types::RefundsRouterData<api::Execute>,
- connectors: &settings::Connectors,
- ) -> CustomResult<Vec<(String, request::Maskable<String>)>, errors::ConnectorError> {
+ req: &RefundsRouterData<Execute>,
+ connectors: &Connectors,
+ ) -> CustomResult<Vec<(String, masking::Maskable<String>)>, errors::ConnectorError> {
self.build_headers(req, connectors)
}
fn get_content_type(&self) -> &'static str {
@@ -623,8 +605,8 @@ impl ConnectorIntegration<api::Execute, types::RefundsData, types::RefundsRespon
}
fn get_url(
&self,
- _req: &types::RefundsRouterData<api::Execute>,
- connectors: &settings::Connectors,
+ _req: &RefundsRouterData<Execute>,
+ connectors: &Connectors,
) -> CustomResult<String, errors::ConnectorError> {
Ok(format!(
"{}ch/payments/v1/refunds",
@@ -633,8 +615,8 @@ impl ConnectorIntegration<api::Execute, types::RefundsData, types::RefundsRespon
}
fn get_request_body(
&self,
- req: &types::RefundsRouterData<api::Execute>,
- _connectors: &settings::Connectors,
+ req: &RefundsRouterData<Execute>,
+ _connectors: &Connectors,
) -> CustomResult<RequestContent, errors::ConnectorError> {
let router_obj = fiserv::FiservRouterData::try_from((
&self.get_currency_unit(),
@@ -647,11 +629,11 @@ impl ConnectorIntegration<api::Execute, types::RefundsData, types::RefundsRespon
}
fn build_request(
&self,
- req: &types::RefundsRouterData<api::Execute>,
- connectors: &settings::Connectors,
- ) -> CustomResult<Option<services::Request>, errors::ConnectorError> {
- let request = services::RequestBuilder::new()
- .method(services::Method::Post)
+ req: &RefundsRouterData<Execute>,
+ connectors: &Connectors,
+ ) -> CustomResult<Option<Request>, errors::ConnectorError> {
+ let request = RequestBuilder::new()
+ .method(Method::Post)
.url(&types::RefundExecuteType::get_url(self, req, connectors)?)
.attach_default_headers()
.headers(types::RefundExecuteType::get_headers(
@@ -666,18 +648,18 @@ impl ConnectorIntegration<api::Execute, types::RefundsData, types::RefundsRespon
fn handle_response(
&self,
- data: &types::RefundsRouterData<api::Execute>,
+ data: &RefundsRouterData<Execute>,
event_builder: Option<&mut ConnectorEvent>,
res: types::Response,
- ) -> CustomResult<types::RefundsRouterData<api::Execute>, errors::ConnectorError> {
- logger::debug!(target: "router::connector::fiserv", response=?res);
+ ) -> CustomResult<RefundsRouterData<Execute>, errors::ConnectorError> {
+ router_env::logger::debug!(target: "router::connector::fiserv", response=?res);
let response: fiserv::RefundResponse =
res.response
.parse_struct("fiserv RefundResponse")
.change_context(errors::ConnectorError::RequestEncodingFailed)?;
event_builder.map(|i| i.set_response_body(&response));
router_env::logger::info!(connector_response=?response);
- types::RouterData::try_from(types::ResponseRouterData {
+ RouterData::try_from(ResponseRouterData {
response,
data: data.clone(),
http_code: res.status_code,
@@ -688,18 +670,18 @@ impl ConnectorIntegration<api::Execute, types::RefundsData, types::RefundsRespon
&self,
res: types::Response,
event_builder: Option<&mut ConnectorEvent>,
- ) -> CustomResult<types::ErrorResponse, errors::ConnectorError> {
+ ) -> CustomResult<ErrorResponse, errors::ConnectorError> {
self.build_error_response(res, event_builder)
}
}
#[allow(dead_code)]
-impl ConnectorIntegration<api::RSync, types::RefundsData, types::RefundsResponseData> for Fiserv {
+impl ConnectorIntegration<RSync, RefundsData, RefundsResponseData> for Fiserv {
fn get_headers(
&self,
- req: &types::RefundSyncRouterData,
- connectors: &settings::Connectors,
- ) -> CustomResult<Vec<(String, request::Maskable<String>)>, errors::ConnectorError> {
+ req: &RefundSyncRouterData,
+ connectors: &Connectors,
+ ) -> CustomResult<Vec<(String, masking::Maskable<String>)>, errors::ConnectorError> {
self.build_headers(req, connectors)
}
@@ -709,8 +691,8 @@ impl ConnectorIntegration<api::RSync, types::RefundsData, types::RefundsResponse
fn get_url(
&self,
- _req: &types::RefundSyncRouterData,
- connectors: &settings::Connectors,
+ _req: &RefundSyncRouterData,
+ connectors: &Connectors,
) -> CustomResult<String, errors::ConnectorError> {
Ok(format!(
"{}ch/payments/v1/transaction-inquiry",
@@ -720,8 +702,8 @@ impl ConnectorIntegration<api::RSync, types::RefundsData, types::RefundsResponse
fn get_request_body(
&self,
- req: &types::RefundSyncRouterData,
- _connectors: &settings::Connectors,
+ req: &RefundSyncRouterData,
+ _connectors: &Connectors,
) -> CustomResult<RequestContent, errors::ConnectorError> {
let connector_req = fiserv::FiservSyncRequest::try_from(req)?;
Ok(RequestContent::Json(Box::new(connector_req)))
@@ -729,12 +711,12 @@ impl ConnectorIntegration<api::RSync, types::RefundsData, types::RefundsResponse
fn build_request(
&self,
- req: &types::RefundSyncRouterData,
- connectors: &settings::Connectors,
- ) -> CustomResult<Option<services::Request>, errors::ConnectorError> {
+ req: &RefundSyncRouterData,
+ connectors: &Connectors,
+ ) -> CustomResult<Option<Request>, errors::ConnectorError> {
let request = Some(
- services::RequestBuilder::new()
- .method(services::Method::Post)
+ RequestBuilder::new()
+ .method(Method::Post)
.url(&types::RefundSyncType::get_url(self, req, connectors)?)
.attach_default_headers()
.headers(types::RefundSyncType::get_headers(self, req, connectors)?)
@@ -748,11 +730,11 @@ impl ConnectorIntegration<api::RSync, types::RefundsData, types::RefundsResponse
fn handle_response(
&self,
- data: &types::RefundSyncRouterData,
+ data: &RefundSyncRouterData,
event_builder: Option<&mut ConnectorEvent>,
res: types::Response,
- ) -> CustomResult<types::RefundSyncRouterData, errors::ConnectorError> {
- logger::debug!(target: "router::connector::fiserv", response=?res);
+ ) -> CustomResult<RefundSyncRouterData, errors::ConnectorError> {
+ router_env::logger::debug!(target: "router::connector::fiserv", response=?res);
let response: fiserv::FiservSyncResponse = res
.response
@@ -760,7 +742,7 @@ impl ConnectorIntegration<api::RSync, types::RefundsData, types::RefundsResponse
.change_context(errors::ConnectorError::ResponseDeserializationFailed)?;
event_builder.map(|i| i.set_response_body(&response));
router_env::logger::info!(connector_response=?response);
- types::RouterData::try_from(types::ResponseRouterData {
+ RouterData::try_from(ResponseRouterData {
response,
data: data.clone(),
http_code: res.status_code,
@@ -772,30 +754,30 @@ impl ConnectorIntegration<api::RSync, types::RefundsData, types::RefundsResponse
&self,
res: types::Response,
event_builder: Option<&mut ConnectorEvent>,
- ) -> CustomResult<types::ErrorResponse, errors::ConnectorError> {
+ ) -> CustomResult<ErrorResponse, errors::ConnectorError> {
self.build_error_response(res, event_builder)
}
}
#[async_trait::async_trait]
-impl api::IncomingWebhook for Fiserv {
+impl webhooks::IncomingWebhook for Fiserv {
fn get_webhook_object_reference_id(
&self,
- _request: &api::IncomingWebhookRequestDetails<'_>,
+ _request: &webhooks::IncomingWebhookRequestDetails<'_>,
) -> CustomResult<api_models::webhooks::ObjectReferenceId, errors::ConnectorError> {
Err(report!(errors::ConnectorError::WebhooksNotImplemented))
}
fn get_webhook_event_type(
&self,
- _request: &api::IncomingWebhookRequestDetails<'_>,
- ) -> CustomResult<api::IncomingWebhookEvent, errors::ConnectorError> {
- Ok(api::IncomingWebhookEvent::EventNotSupported)
+ _request: &webhooks::IncomingWebhookRequestDetails<'_>,
+ ) -> CustomResult<api_models::webhooks::IncomingWebhookEvent, errors::ConnectorError> {
+ Ok(api_models::webhooks::IncomingWebhookEvent::EventNotSupported)
}
fn get_webhook_resource_object(
&self,
- _request: &api::IncomingWebhookRequestDetails<'_>,
+ _request: &webhooks::IncomingWebhookRequestDetails<'_>,
) -> CustomResult<Box<dyn masking::ErasedMaskSerialize>, errors::ConnectorError> {
Err(report!(errors::ConnectorError::WebhooksNotImplemented))
}
diff --git a/crates/router/src/connector/fiserv/transformers.rs b/crates/hyperswitch_connectors/src/connectors/fiserv/transformers.rs
similarity index 88%
rename from crates/router/src/connector/fiserv/transformers.rs
rename to crates/hyperswitch_connectors/src/connectors/fiserv/transformers.rs
index 1a149c6af78..0ae59d4526e 100644
--- a/crates/router/src/connector/fiserv/transformers.rs
+++ b/crates/hyperswitch_connectors/src/connectors/fiserv/transformers.rs
@@ -1,15 +1,24 @@
+use common_enums::enums;
use common_utils::{ext_traits::ValueExt, pii};
use error_stack::ResultExt;
+use hyperswitch_domain_models::{
+ payment_method_data::PaymentMethodData,
+ router_data::{ConnectorAuthType, RouterData},
+ router_flow_types::refunds::{Execute, RSync},
+ router_request_types::ResponseId,
+ router_response_types::{PaymentsResponseData, RefundsResponseData},
+ types,
+};
+use hyperswitch_interfaces::{api, errors};
+use masking::Secret;
use serde::{Deserialize, Serialize};
use crate::{
- connector::utils::{
+ types::{RefundsResponseRouterData, ResponseRouterData},
+ utils::{
self, CardData as CardDataUtil, PaymentsCancelRequestData, PaymentsSyncRequestData,
- RouterData,
+ RouterData as _,
},
- core::errors,
- pii::Secret,
- types::{self, api, domain, storage::enums},
};
#[derive(Debug, Serialize)]
@@ -166,7 +175,7 @@ impl TryFrom<&FiservRouterData<&types::PaymentsAuthorizeRouterData>> for FiservP
pos_condition_code: TransactionInteractionPosConditionCode::CardNotPresentEcom,
};
let source = match item.router_data.request.payment_method_data.clone() {
- domain::PaymentMethodData::Card(ref ccard) => {
+ PaymentMethodData::Card(ref ccard) => {
let card = CardData {
card_data: ccard.card_number.clone(),
expiration_month: ccard.card_exp_month.clone(),
@@ -175,21 +184,21 @@ impl TryFrom<&FiservRouterData<&types::PaymentsAuthorizeRouterData>> for FiservP
};
Source::PaymentCard { card }
}
- domain::PaymentMethodData::Wallet(_)
- | domain::PaymentMethodData::PayLater(_)
- | domain::PaymentMethodData::BankRedirect(_)
- | domain::PaymentMethodData::BankDebit(_)
- | domain::PaymentMethodData::CardRedirect(_)
- | domain::PaymentMethodData::BankTransfer(_)
- | domain::PaymentMethodData::Crypto(_)
- | domain::PaymentMethodData::MandatePayment
- | domain::PaymentMethodData::Reward
- | domain::PaymentMethodData::RealTimePayment(_)
- | domain::PaymentMethodData::Upi(_)
- | domain::PaymentMethodData::Voucher(_)
- | domain::PaymentMethodData::GiftCard(_)
- | domain::PaymentMethodData::OpenBanking(_)
- | domain::PaymentMethodData::CardToken(_) => {
+ PaymentMethodData::Wallet(_)
+ | PaymentMethodData::PayLater(_)
+ | PaymentMethodData::BankRedirect(_)
+ | PaymentMethodData::BankDebit(_)
+ | PaymentMethodData::CardRedirect(_)
+ | PaymentMethodData::BankTransfer(_)
+ | PaymentMethodData::Crypto(_)
+ | PaymentMethodData::MandatePayment
+ | PaymentMethodData::Reward
+ | PaymentMethodData::RealTimePayment(_)
+ | PaymentMethodData::Upi(_)
+ | PaymentMethodData::Voucher(_)
+ | PaymentMethodData::GiftCard(_)
+ | PaymentMethodData::OpenBanking(_)
+ | PaymentMethodData::CardToken(_) => {
Err(errors::ConnectorError::NotImplemented(
utils::get_unimplemented_payment_method_error_message("fiserv"),
))
@@ -211,10 +220,10 @@ pub struct FiservAuthType {
pub(super) api_secret: Secret<String>,
}
-impl TryFrom<&types::ConnectorAuthType> for FiservAuthType {
+impl TryFrom<&ConnectorAuthType> for FiservAuthType {
type Error = error_stack::Report<errors::ConnectorError>;
- fn try_from(auth_type: &types::ConnectorAuthType) -> Result<Self, Self::Error> {
- if let types::ConnectorAuthType::SignatureKey {
+ fn try_from(auth_type: &ConnectorAuthType) -> Result<Self, Self::Error> {
+ if let ConnectorAuthType::SignatureKey {
api_key,
key1,
api_secret,
@@ -348,20 +357,19 @@ pub struct TransactionProcessingDetails {
transaction_id: String,
}
-impl<F, T>
- TryFrom<types::ResponseRouterData<F, FiservPaymentsResponse, T, types::PaymentsResponseData>>
- for types::RouterData<F, T, types::PaymentsResponseData>
+impl<F, T> TryFrom<ResponseRouterData<F, FiservPaymentsResponse, T, PaymentsResponseData>>
+ for RouterData<F, T, PaymentsResponseData>
{
type Error = error_stack::Report<errors::ConnectorError>;
fn try_from(
- item: types::ResponseRouterData<F, FiservPaymentsResponse, T, types::PaymentsResponseData>,
+ item: ResponseRouterData<F, FiservPaymentsResponse, T, PaymentsResponseData>,
) -> Result<Self, Self::Error> {
let gateway_resp = item.response.gateway_response;
Ok(Self {
status: enums::AttemptStatus::from(gateway_resp.transaction_state),
- response: Ok(types::PaymentsResponseData::TransactionResponse {
- resource_id: types::ResponseId::ConnectorTransactionId(
+ response: Ok(PaymentsResponseData::TransactionResponse {
+ resource_id: ResponseId::ConnectorTransactionId(
gateway_resp.transaction_processing_details.transaction_id,
),
redirection_data: None,
@@ -379,12 +387,12 @@ impl<F, T>
}
}
-impl<F, T> TryFrom<types::ResponseRouterData<F, FiservSyncResponse, T, types::PaymentsResponseData>>
- for types::RouterData<F, T, types::PaymentsResponseData>
+impl<F, T> TryFrom<ResponseRouterData<F, FiservSyncResponse, T, PaymentsResponseData>>
+ for RouterData<F, T, PaymentsResponseData>
{
type Error = error_stack::Report<errors::ConnectorError>;
fn try_from(
- item: types::ResponseRouterData<F, FiservSyncResponse, T, types::PaymentsResponseData>,
+ item: ResponseRouterData<F, FiservSyncResponse, T, PaymentsResponseData>,
) -> Result<Self, Self::Error> {
let gateway_resp = match item.response.sync_responses.first() {
Some(gateway_response) => gateway_response,
@@ -395,8 +403,8 @@ impl<F, T> TryFrom<types::ResponseRouterData<F, FiservSyncResponse, T, types::Pa
status: enums::AttemptStatus::from(
gateway_resp.gateway_response.transaction_state.clone(),
),
- response: Ok(types::PaymentsResponseData::TransactionResponse {
- resource_id: types::ResponseId::ConnectorTransactionId(
+ response: Ok(PaymentsResponseData::TransactionResponse {
+ resource_id: ResponseId::ConnectorTransactionId(
gateway_resp
.gateway_response
.transaction_processing_details
@@ -590,15 +598,15 @@ pub struct RefundResponse {
gateway_response: GatewayResponse,
}
-impl TryFrom<types::RefundsResponseRouterData<api::Execute, RefundResponse>>
- for types::RefundsRouterData<api::Execute>
+impl TryFrom<RefundsResponseRouterData<Execute, RefundResponse>>
+ for types::RefundsRouterData<Execute>
{
type Error = error_stack::Report<errors::ConnectorError>;
fn try_from(
- item: types::RefundsResponseRouterData<api::Execute, RefundResponse>,
+ item: RefundsResponseRouterData<Execute, RefundResponse>,
) -> Result<Self, Self::Error> {
Ok(Self {
- response: Ok(types::RefundsResponseData {
+ response: Ok(RefundsResponseData {
connector_refund_id: item
.response
.gateway_response
@@ -613,12 +621,12 @@ impl TryFrom<types::RefundsResponseRouterData<api::Execute, RefundResponse>>
}
}
-impl TryFrom<types::RefundsResponseRouterData<api::RSync, FiservSyncResponse>>
- for types::RefundsRouterData<api::RSync>
+impl TryFrom<RefundsResponseRouterData<RSync, FiservSyncResponse>>
+ for types::RefundsRouterData<RSync>
{
type Error = error_stack::Report<errors::ConnectorError>;
fn try_from(
- item: types::RefundsResponseRouterData<api::RSync, FiservSyncResponse>,
+ item: RefundsResponseRouterData<RSync, FiservSyncResponse>,
) -> Result<Self, Self::Error> {
let gateway_resp = item
.response
@@ -626,7 +634,7 @@ impl TryFrom<types::RefundsResponseRouterData<api::RSync, FiservSyncResponse>>
.first()
.ok_or(errors::ConnectorError::ResponseHandlingFailed)?;
Ok(Self {
- response: Ok(types::RefundsResponseData {
+ response: Ok(RefundsResponseData {
connector_refund_id: gateway_resp
.gateway_response
.transaction_processing_details
diff --git a/crates/hyperswitch_connectors/src/constants.rs b/crates/hyperswitch_connectors/src/constants.rs
index 9f5285bd2e1..8a5a2ff543a 100644
--- a/crates/hyperswitch_connectors/src/constants.rs
+++ b/crates/hyperswitch_connectors/src/constants.rs
@@ -1,6 +1,9 @@
/// Header Constants
pub(crate) mod headers {
+ pub(crate) const API_KEY: &str = "API-KEY";
pub(crate) const API_TOKEN: &str = "Api-Token";
+ pub(crate) const AUTHORIZATION: &str = "Authorization";
pub(crate) const CONTENT_TYPE: &str = "Content-Type";
pub(crate) const IDEMPOTENCY_KEY: &str = "Idempotency-Key";
+ pub(crate) const TIMESTAMP: &str = "Timestamp";
}
diff --git a/crates/hyperswitch_connectors/src/default_implementations.rs b/crates/hyperswitch_connectors/src/default_implementations.rs
index 2273b8c31da..d8e2e121318 100644
--- a/crates/hyperswitch_connectors/src/default_implementations.rs
+++ b/crates/hyperswitch_connectors/src/default_implementations.rs
@@ -81,7 +81,7 @@ macro_rules! default_imp_for_authorize_session_token {
};
}
-default_imp_for_authorize_session_token!(connectors::Helcim);
+default_imp_for_authorize_session_token!(connectors::Fiserv, connectors::Helcim);
use crate::connectors;
macro_rules! default_imp_for_complete_authorize {
@@ -99,7 +99,7 @@ macro_rules! default_imp_for_complete_authorize {
};
}
-default_imp_for_complete_authorize!(connectors::Helcim);
+default_imp_for_complete_authorize!(connectors::Fiserv, connectors::Helcim);
macro_rules! default_imp_for_incremental_authorization {
($($path:ident::$connector:ident),*) => {
@@ -116,7 +116,7 @@ macro_rules! default_imp_for_incremental_authorization {
};
}
-default_imp_for_incremental_authorization!(connectors::Helcim);
+default_imp_for_incremental_authorization!(connectors::Fiserv, connectors::Helcim);
macro_rules! default_imp_for_create_customer {
($($path:ident::$connector:ident),*) => {
@@ -133,7 +133,7 @@ macro_rules! default_imp_for_create_customer {
};
}
-default_imp_for_create_customer!(connectors::Helcim);
+default_imp_for_create_customer!(connectors::Fiserv, connectors::Helcim);
macro_rules! default_imp_for_pre_processing_steps{
($($path:ident::$connector:ident),*)=> {
@@ -150,7 +150,7 @@ macro_rules! default_imp_for_pre_processing_steps{
};
}
-default_imp_for_pre_processing_steps!(connectors::Helcim);
+default_imp_for_pre_processing_steps!(connectors::Fiserv, connectors::Helcim);
macro_rules! default_imp_for_post_processing_steps{
($($path:ident::$connector:ident),*)=> {
@@ -167,7 +167,7 @@ macro_rules! default_imp_for_post_processing_steps{
};
}
-default_imp_for_post_processing_steps!(connectors::Helcim);
+default_imp_for_post_processing_steps!(connectors::Fiserv, connectors::Helcim);
macro_rules! default_imp_for_approve {
($($path:ident::$connector:ident),*) => {
@@ -184,7 +184,7 @@ macro_rules! default_imp_for_approve {
};
}
-default_imp_for_approve!(connectors::Helcim);
+default_imp_for_approve!(connectors::Fiserv, connectors::Helcim);
macro_rules! default_imp_for_reject {
($($path:ident::$connector:ident),*) => {
@@ -201,7 +201,7 @@ macro_rules! default_imp_for_reject {
};
}
-default_imp_for_reject!(connectors::Helcim);
+default_imp_for_reject!(connectors::Fiserv, connectors::Helcim);
macro_rules! default_imp_for_webhook_source_verification {
($($path:ident::$connector:ident),*) => {
@@ -218,7 +218,7 @@ macro_rules! default_imp_for_webhook_source_verification {
};
}
-default_imp_for_webhook_source_verification!(connectors::Helcim);
+default_imp_for_webhook_source_verification!(connectors::Fiserv, connectors::Helcim);
macro_rules! default_imp_for_accept_dispute {
($($path:ident::$connector:ident),*) => {
@@ -236,7 +236,7 @@ macro_rules! default_imp_for_accept_dispute {
};
}
-default_imp_for_accept_dispute!(connectors::Helcim);
+default_imp_for_accept_dispute!(connectors::Fiserv, connectors::Helcim);
macro_rules! default_imp_for_submit_evidence {
($($path:ident::$connector:ident),*) => {
@@ -253,7 +253,7 @@ macro_rules! default_imp_for_submit_evidence {
};
}
-default_imp_for_submit_evidence!(connectors::Helcim);
+default_imp_for_submit_evidence!(connectors::Fiserv, connectors::Helcim);
macro_rules! default_imp_for_defend_dispute {
($($path:ident::$connector:ident),*) => {
@@ -270,7 +270,7 @@ macro_rules! default_imp_for_defend_dispute {
};
}
-default_imp_for_defend_dispute!(connectors::Helcim);
+default_imp_for_defend_dispute!(connectors::Fiserv, connectors::Helcim);
macro_rules! default_imp_for_file_upload {
($($path:ident::$connector:ident),*) => {
@@ -296,7 +296,7 @@ macro_rules! default_imp_for_file_upload {
};
}
-default_imp_for_file_upload!(connectors::Helcim);
+default_imp_for_file_upload!(connectors::Fiserv, connectors::Helcim);
#[cfg(feature = "payouts")]
macro_rules! default_imp_for_payouts_create {
@@ -315,7 +315,7 @@ macro_rules! default_imp_for_payouts_create {
}
#[cfg(feature = "payouts")]
-default_imp_for_payouts_create!(connectors::Helcim);
+default_imp_for_payouts_create!(connectors::Fiserv, connectors::Helcim);
#[cfg(feature = "payouts")]
macro_rules! default_imp_for_payouts_retrieve {
@@ -334,7 +334,7 @@ macro_rules! default_imp_for_payouts_retrieve {
}
#[cfg(feature = "payouts")]
-default_imp_for_payouts_retrieve!(connectors::Helcim);
+default_imp_for_payouts_retrieve!(connectors::Fiserv, connectors::Helcim);
#[cfg(feature = "payouts")]
macro_rules! default_imp_for_payouts_eligibility {
@@ -353,7 +353,7 @@ macro_rules! default_imp_for_payouts_eligibility {
}
#[cfg(feature = "payouts")]
-default_imp_for_payouts_eligibility!(connectors::Helcim);
+default_imp_for_payouts_eligibility!(connectors::Fiserv, connectors::Helcim);
#[cfg(feature = "payouts")]
macro_rules! default_imp_for_payouts_fulfill {
@@ -372,7 +372,7 @@ macro_rules! default_imp_for_payouts_fulfill {
}
#[cfg(feature = "payouts")]
-default_imp_for_payouts_fulfill!(connectors::Helcim);
+default_imp_for_payouts_fulfill!(connectors::Fiserv, connectors::Helcim);
#[cfg(feature = "payouts")]
macro_rules! default_imp_for_payouts_cancel {
@@ -391,7 +391,7 @@ macro_rules! default_imp_for_payouts_cancel {
}
#[cfg(feature = "payouts")]
-default_imp_for_payouts_cancel!(connectors::Helcim);
+default_imp_for_payouts_cancel!(connectors::Fiserv, connectors::Helcim);
#[cfg(feature = "payouts")]
macro_rules! default_imp_for_payouts_quote {
@@ -410,7 +410,7 @@ macro_rules! default_imp_for_payouts_quote {
}
#[cfg(feature = "payouts")]
-default_imp_for_payouts_quote!(connectors::Helcim);
+default_imp_for_payouts_quote!(connectors::Fiserv, connectors::Helcim);
#[cfg(feature = "payouts")]
macro_rules! default_imp_for_payouts_recipient {
@@ -429,7 +429,7 @@ macro_rules! default_imp_for_payouts_recipient {
}
#[cfg(feature = "payouts")]
-default_imp_for_payouts_recipient!(connectors::Helcim);
+default_imp_for_payouts_recipient!(connectors::Fiserv, connectors::Helcim);
#[cfg(feature = "payouts")]
macro_rules! default_imp_for_payouts_recipient_account {
@@ -448,7 +448,7 @@ macro_rules! default_imp_for_payouts_recipient_account {
}
#[cfg(feature = "payouts")]
-default_imp_for_payouts_recipient_account!(connectors::Helcim);
+default_imp_for_payouts_recipient_account!(connectors::Fiserv, connectors::Helcim);
#[cfg(feature = "frm")]
macro_rules! default_imp_for_frm_sale {
@@ -467,7 +467,7 @@ macro_rules! default_imp_for_frm_sale {
}
#[cfg(feature = "frm")]
-default_imp_for_frm_sale!(connectors::Helcim);
+default_imp_for_frm_sale!(connectors::Fiserv, connectors::Helcim);
#[cfg(feature = "frm")]
macro_rules! default_imp_for_frm_checkout {
@@ -486,7 +486,7 @@ macro_rules! default_imp_for_frm_checkout {
}
#[cfg(feature = "frm")]
-default_imp_for_frm_checkout!(connectors::Helcim);
+default_imp_for_frm_checkout!(connectors::Fiserv, connectors::Helcim);
#[cfg(feature = "frm")]
macro_rules! default_imp_for_frm_transaction {
@@ -505,7 +505,7 @@ macro_rules! default_imp_for_frm_transaction {
}
#[cfg(feature = "frm")]
-default_imp_for_frm_transaction!(connectors::Helcim);
+default_imp_for_frm_transaction!(connectors::Fiserv, connectors::Helcim);
#[cfg(feature = "frm")]
macro_rules! default_imp_for_frm_fulfillment {
@@ -524,7 +524,7 @@ macro_rules! default_imp_for_frm_fulfillment {
}
#[cfg(feature = "frm")]
-default_imp_for_frm_fulfillment!(connectors::Helcim);
+default_imp_for_frm_fulfillment!(connectors::Fiserv, connectors::Helcim);
#[cfg(feature = "frm")]
macro_rules! default_imp_for_frm_record_return {
@@ -543,7 +543,7 @@ macro_rules! default_imp_for_frm_record_return {
}
#[cfg(feature = "frm")]
-default_imp_for_frm_record_return!(connectors::Helcim);
+default_imp_for_frm_record_return!(connectors::Fiserv, connectors::Helcim);
macro_rules! default_imp_for_revoking_mandates {
($($path:ident::$connector:ident),*) => {
@@ -559,4 +559,4 @@ macro_rules! default_imp_for_revoking_mandates {
};
}
-default_imp_for_revoking_mandates!(connectors::Helcim);
+default_imp_for_revoking_mandates!(connectors::Fiserv, connectors::Helcim);
diff --git a/crates/hyperswitch_connectors/src/default_implementations_v2.rs b/crates/hyperswitch_connectors/src/default_implementations_v2.rs
index df72d3d9c48..f420447fd74 100644
--- a/crates/hyperswitch_connectors/src/default_implementations_v2.rs
+++ b/crates/hyperswitch_connectors/src/default_implementations_v2.rs
@@ -180,7 +180,7 @@ macro_rules! default_imp_for_new_connector_integration_payment {
};
}
-default_imp_for_new_connector_integration_payment!(connectors::Helcim);
+default_imp_for_new_connector_integration_payment!(connectors::Fiserv, connectors::Helcim);
macro_rules! default_imp_for_new_connector_integration_refund {
($($path:ident::$connector:ident),*) => {
@@ -198,7 +198,7 @@ macro_rules! default_imp_for_new_connector_integration_refund {
};
}
-default_imp_for_new_connector_integration_refund!(connectors::Helcim);
+default_imp_for_new_connector_integration_refund!(connectors::Fiserv, connectors::Helcim);
macro_rules! default_imp_for_new_connector_integration_connector_access_token {
($($path:ident::$connector:ident),*) => {
@@ -211,7 +211,10 @@ macro_rules! default_imp_for_new_connector_integration_connector_access_token {
};
}
-default_imp_for_new_connector_integration_connector_access_token!(connectors::Helcim);
+default_imp_for_new_connector_integration_connector_access_token!(
+ connectors::Fiserv,
+ connectors::Helcim
+);
macro_rules! default_imp_for_new_connector_integration_accept_dispute {
($($path:ident::$connector:ident),*) => {
@@ -230,7 +233,7 @@ macro_rules! default_imp_for_new_connector_integration_accept_dispute {
};
}
-default_imp_for_new_connector_integration_accept_dispute!(connectors::Helcim);
+default_imp_for_new_connector_integration_accept_dispute!(connectors::Fiserv, connectors::Helcim);
macro_rules! default_imp_for_new_connector_integration_submit_evidence {
($($path:ident::$connector:ident),*) => {
@@ -248,7 +251,7 @@ macro_rules! default_imp_for_new_connector_integration_submit_evidence {
};
}
-default_imp_for_new_connector_integration_submit_evidence!(connectors::Helcim);
+default_imp_for_new_connector_integration_submit_evidence!(connectors::Fiserv, connectors::Helcim);
macro_rules! default_imp_for_new_connector_integration_defend_dispute {
($($path:ident::$connector:ident),*) => {
@@ -266,7 +269,7 @@ macro_rules! default_imp_for_new_connector_integration_defend_dispute {
};
}
-default_imp_for_new_connector_integration_defend_dispute!(connectors::Helcim);
+default_imp_for_new_connector_integration_defend_dispute!(connectors::Fiserv, connectors::Helcim);
macro_rules! default_imp_for_new_connector_integration_file_upload {
($($path:ident::$connector:ident),*) => {
@@ -294,7 +297,7 @@ macro_rules! default_imp_for_new_connector_integration_file_upload {
};
}
-default_imp_for_new_connector_integration_file_upload!(connectors::Helcim);
+default_imp_for_new_connector_integration_file_upload!(connectors::Fiserv, connectors::Helcim);
#[cfg(feature = "payouts")]
macro_rules! default_imp_for_new_connector_integration_payouts_create {
@@ -314,7 +317,7 @@ macro_rules! default_imp_for_new_connector_integration_payouts_create {
}
#[cfg(feature = "payouts")]
-default_imp_for_new_connector_integration_payouts_create!(connectors::Helcim);
+default_imp_for_new_connector_integration_payouts_create!(connectors::Fiserv, connectors::Helcim);
#[cfg(feature = "payouts")]
macro_rules! default_imp_for_new_connector_integration_payouts_eligibility {
@@ -334,7 +337,10 @@ macro_rules! default_imp_for_new_connector_integration_payouts_eligibility {
}
#[cfg(feature = "payouts")]
-default_imp_for_new_connector_integration_payouts_eligibility!(connectors::Helcim);
+default_imp_for_new_connector_integration_payouts_eligibility!(
+ connectors::Fiserv,
+ connectors::Helcim
+);
#[cfg(feature = "payouts")]
macro_rules! default_imp_for_new_connector_integration_payouts_fulfill {
@@ -354,7 +360,7 @@ macro_rules! default_imp_for_new_connector_integration_payouts_fulfill {
}
#[cfg(feature = "payouts")]
-default_imp_for_new_connector_integration_payouts_fulfill!(connectors::Helcim);
+default_imp_for_new_connector_integration_payouts_fulfill!(connectors::Fiserv, connectors::Helcim);
#[cfg(feature = "payouts")]
macro_rules! default_imp_for_new_connector_integration_payouts_cancel {
@@ -374,7 +380,7 @@ macro_rules! default_imp_for_new_connector_integration_payouts_cancel {
}
#[cfg(feature = "payouts")]
-default_imp_for_new_connector_integration_payouts_cancel!(connectors::Helcim);
+default_imp_for_new_connector_integration_payouts_cancel!(connectors::Fiserv, connectors::Helcim);
#[cfg(feature = "payouts")]
macro_rules! default_imp_for_new_connector_integration_payouts_quote {
@@ -394,7 +400,7 @@ macro_rules! default_imp_for_new_connector_integration_payouts_quote {
}
#[cfg(feature = "payouts")]
-default_imp_for_new_connector_integration_payouts_quote!(connectors::Helcim);
+default_imp_for_new_connector_integration_payouts_quote!(connectors::Fiserv, connectors::Helcim);
#[cfg(feature = "payouts")]
macro_rules! default_imp_for_new_connector_integration_payouts_recipient {
@@ -414,7 +420,10 @@ macro_rules! default_imp_for_new_connector_integration_payouts_recipient {
}
#[cfg(feature = "payouts")]
-default_imp_for_new_connector_integration_payouts_recipient!(connectors::Helcim);
+default_imp_for_new_connector_integration_payouts_recipient!(
+ connectors::Fiserv,
+ connectors::Helcim
+);
#[cfg(feature = "payouts")]
macro_rules! default_imp_for_new_connector_integration_payouts_sync {
@@ -434,7 +443,7 @@ macro_rules! default_imp_for_new_connector_integration_payouts_sync {
}
#[cfg(feature = "payouts")]
-default_imp_for_new_connector_integration_payouts_sync!(connectors::Helcim);
+default_imp_for_new_connector_integration_payouts_sync!(connectors::Fiserv, connectors::Helcim);
#[cfg(feature = "payouts")]
macro_rules! default_imp_for_new_connector_integration_payouts_recipient_account {
@@ -454,7 +463,10 @@ macro_rules! default_imp_for_new_connector_integration_payouts_recipient_account
}
#[cfg(feature = "payouts")]
-default_imp_for_new_connector_integration_payouts_recipient_account!(connectors::Helcim);
+default_imp_for_new_connector_integration_payouts_recipient_account!(
+ connectors::Fiserv,
+ connectors::Helcim
+);
macro_rules! default_imp_for_new_connector_integration_webhook_source_verification {
($($path:ident::$connector:ident),*) => {
@@ -472,7 +484,10 @@ macro_rules! default_imp_for_new_connector_integration_webhook_source_verificati
};
}
-default_imp_for_new_connector_integration_webhook_source_verification!(connectors::Helcim);
+default_imp_for_new_connector_integration_webhook_source_verification!(
+ connectors::Fiserv,
+ connectors::Helcim
+);
#[cfg(feature = "frm")]
macro_rules! default_imp_for_new_connector_integration_frm_sale {
@@ -492,7 +507,7 @@ macro_rules! default_imp_for_new_connector_integration_frm_sale {
}
#[cfg(feature = "frm")]
-default_imp_for_new_connector_integration_frm_sale!(connectors::Helcim);
+default_imp_for_new_connector_integration_frm_sale!(connectors::Fiserv, connectors::Helcim);
#[cfg(feature = "frm")]
macro_rules! default_imp_for_new_connector_integration_frm_checkout {
@@ -512,7 +527,7 @@ macro_rules! default_imp_for_new_connector_integration_frm_checkout {
}
#[cfg(feature = "frm")]
-default_imp_for_new_connector_integration_frm_checkout!(connectors::Helcim);
+default_imp_for_new_connector_integration_frm_checkout!(connectors::Fiserv, connectors::Helcim);
#[cfg(feature = "frm")]
macro_rules! default_imp_for_new_connector_integration_frm_transaction {
@@ -532,7 +547,7 @@ macro_rules! default_imp_for_new_connector_integration_frm_transaction {
}
#[cfg(feature = "frm")]
-default_imp_for_new_connector_integration_frm_transaction!(connectors::Helcim);
+default_imp_for_new_connector_integration_frm_transaction!(connectors::Fiserv, connectors::Helcim);
#[cfg(feature = "frm")]
macro_rules! default_imp_for_new_connector_integration_frm_fulfillment {
@@ -552,7 +567,7 @@ macro_rules! default_imp_for_new_connector_integration_frm_fulfillment {
}
#[cfg(feature = "frm")]
-default_imp_for_new_connector_integration_frm_fulfillment!(connectors::Helcim);
+default_imp_for_new_connector_integration_frm_fulfillment!(connectors::Fiserv, connectors::Helcim);
#[cfg(feature = "frm")]
macro_rules! default_imp_for_new_connector_integration_frm_record_return {
@@ -572,7 +587,10 @@ macro_rules! default_imp_for_new_connector_integration_frm_record_return {
}
#[cfg(feature = "frm")]
-default_imp_for_new_connector_integration_frm_record_return!(connectors::Helcim);
+default_imp_for_new_connector_integration_frm_record_return!(
+ connectors::Fiserv,
+ connectors::Helcim
+);
macro_rules! default_imp_for_new_connector_integration_revoking_mandates {
($($path:ident::$connector:ident),*) => {
@@ -589,4 +607,7 @@ macro_rules! default_imp_for_new_connector_integration_revoking_mandates {
};
}
-default_imp_for_new_connector_integration_revoking_mandates!(connectors::Helcim);
+default_imp_for_new_connector_integration_revoking_mandates!(
+ connectors::Fiserv,
+ connectors::Helcim
+);
diff --git a/crates/hyperswitch_connectors/src/utils.rs b/crates/hyperswitch_connectors/src/utils.rs
index 0b8ecac9b07..40f98b6efdb 100644
--- a/crates/hyperswitch_connectors/src/utils.rs
+++ b/crates/hyperswitch_connectors/src/utils.rs
@@ -1,7 +1,7 @@
use api_models::payments::{self, Address, AddressDetails, OrderDetailsWithAmount, PhoneDetails};
use common_enums::{enums, enums::FutureUsage};
use common_utils::{
- errors::ReportSwitchExt,
+ errors::{CustomResult, ReportSwitchExt},
ext_traits::{OptionExt, ValueExt},
id_type,
pii::{self, Email, IpAddress},
@@ -12,11 +12,12 @@ use hyperswitch_domain_models::{
router_data::{PaymentMethodToken, RecurringMandatePaymentData},
router_request_types::{
AuthenticationData, BrowserInformation, PaymentsAuthorizeData, PaymentsCancelData,
- PaymentsCaptureData, RefundsData, SetupMandateRequestData,
+ PaymentsCaptureData, PaymentsSyncData, RefundsData, ResponseId, SetupMandateRequestData,
},
};
use hyperswitch_interfaces::{api, errors};
use masking::{ExposeInterface, PeekInterface, Secret};
+use serde::Serializer;
type Error = error_stack::Report<errors::ConnectorError>;
@@ -31,6 +32,27 @@ pub(crate) fn construct_not_supported_error_report(
.into()
}
+pub(crate) fn get_amount_as_string(
+ currency_unit: &api::CurrencyUnit,
+ amount: i64,
+ currency: enums::Currency,
+) -> Result<String, error_stack::Report<errors::ConnectorError>> {
+ let amount = match currency_unit {
+ api::CurrencyUnit::Minor => amount.to_string(),
+ api::CurrencyUnit::Base => to_currency_base_unit(amount, currency)?,
+ };
+ Ok(amount)
+}
+
+pub(crate) fn to_currency_base_unit(
+ amount: i64,
+ currency: enums::Currency,
+) -> Result<String, error_stack::Report<errors::ConnectorError>> {
+ currency
+ .to_currency_base_unit(amount)
+ .change_context(errors::ConnectorError::ParsingFailed)
+}
+
pub(crate) fn get_amount_as_f64(
currency_unit: &api::CurrencyUnit,
amount: i64,
@@ -54,6 +76,18 @@ pub(crate) fn to_currency_base_unit_asf64(
.change_context(errors::ConnectorError::ParsingFailed)
}
+pub(crate) fn to_connector_meta_from_secret<T>(
+ connector_meta: Option<Secret<serde_json::Value>>,
+) -> Result<T, Error>
+where
+ T: serde::de::DeserializeOwned,
+{
+ let connector_meta_secret =
+ connector_meta.ok_or_else(missing_field_err("connector_meta_data"))?;
+ let json = connector_meta_secret.expose();
+ json.parse_value(std::any::type_name::<T>()).switch()
+}
+
pub(crate) fn missing_field_err(
message: &'static str,
) -> Box<dyn Fn() -> error_stack::Report<errors::ConnectorError> + '_> {
@@ -65,6 +99,24 @@ pub(crate) fn missing_field_err(
})
}
+pub(crate) fn construct_not_implemented_error_report(
+ capture_method: enums::CaptureMethod,
+ connector_name: &str,
+) -> error_stack::Report<errors::ConnectorError> {
+ errors::ConnectorError::NotImplemented(format!("{} for {}", capture_method, connector_name))
+ .into()
+}
+
+pub(crate) fn str_to_f32<S>(value: &str, serializer: S) -> Result<S::Ok, S::Error>
+where
+ S: Serializer,
+{
+ let float_value = value.parse::<f64>().map_err(|_| {
+ serde::ser::Error::custom("Invalid string, cannot be converted to float value")
+ })?;
+ serializer.serialize_f64(float_value)
+}
+
pub(crate) const SELECTED_PAYMENT_METHOD: &str = "Selected payment method";
pub(crate) fn get_unimplemented_payment_method_error_message(connector: &str) -> String {
@@ -943,6 +995,33 @@ impl PaymentsCaptureRequestData for PaymentsCaptureData {
}
}
+pub trait PaymentsSyncRequestData {
+ fn is_auto_capture(&self) -> Result<bool, Error>;
+ fn get_connector_transaction_id(&self) -> CustomResult<String, errors::ConnectorError>;
+}
+
+impl PaymentsSyncRequestData for PaymentsSyncData {
+ fn is_auto_capture(&self) -> Result<bool, Error> {
+ match self.capture_method {
+ Some(enums::CaptureMethod::Automatic) | None => Ok(true),
+ Some(enums::CaptureMethod::Manual) => Ok(false),
+ Some(_) => Err(errors::ConnectorError::CaptureMethodNotSupported.into()),
+ }
+ }
+ fn get_connector_transaction_id(&self) -> CustomResult<String, errors::ConnectorError> {
+ match self.connector_transaction_id.clone() {
+ ResponseId::ConnectorTransactionId(txn_id) => Ok(txn_id),
+ _ => Err(
+ common_utils::errors::ValidationError::IncorrectValueProvided {
+ field_name: "connector_transaction_id",
+ },
+ )
+ .attach_printable("Expected connector transaction ID not found")
+ .change_context(errors::ConnectorError::MissingConnectorTransactionID)?,
+ }
+ }
+}
+
pub trait PaymentsCancelRequestData {
fn get_amount(&self) -> Result<i64, Error>;
fn get_currency(&self) -> Result<enums::Currency, Error>;
diff --git a/crates/router/src/connector.rs b/crates/router/src/connector.rs
index 365b0ca87a6..a421c931203 100644
--- a/crates/router/src/connector.rs
+++ b/crates/router/src/connector.rs
@@ -21,7 +21,6 @@ pub mod dlocal;
#[cfg(feature = "dummy_connector")]
pub mod dummyconnector;
pub mod ebanx;
-pub mod fiserv;
pub mod forte;
pub mod globalpay;
pub mod globepay;
@@ -69,7 +68,7 @@ pub mod worldpay;
pub mod zen;
pub mod zsl;
-pub use hyperswitch_connectors::connectors::{helcim, helcim::Helcim};
+pub use hyperswitch_connectors::connectors::{fiserv, fiserv::Fiserv, helcim, helcim::Helcim};
#[cfg(feature = "dummy_connector")]
pub use self::dummyconnector::DummyConnector;
@@ -79,14 +78,14 @@ pub use self::{
bankofamerica::Bankofamerica, billwerk::Billwerk, bitpay::Bitpay, bluesnap::Bluesnap,
boku::Boku, braintree::Braintree, cashtocode::Cashtocode, checkout::Checkout,
coinbase::Coinbase, cryptopay::Cryptopay, cybersource::Cybersource, datatrans::Datatrans,
- dlocal::Dlocal, ebanx::Ebanx, fiserv::Fiserv, forte::Forte, globalpay::Globalpay,
- globepay::Globepay, gocardless::Gocardless, gpayments::Gpayments, iatapay::Iatapay,
- itaubank::Itaubank, klarna::Klarna, mifinity::Mifinity, mollie::Mollie,
- multisafepay::Multisafepay, netcetera::Netcetera, nexinets::Nexinets, nmi::Nmi, noon::Noon,
- nuvei::Nuvei, opayo::Opayo, opennode::Opennode, payeezy::Payeezy, payme::Payme, payone::Payone,
- paypal::Paypal, payu::Payu, placetopay::Placetopay, plaid::Plaid, powertranz::Powertranz,
- prophetpay::Prophetpay, rapyd::Rapyd, razorpay::Razorpay, riskified::Riskified, shift4::Shift4,
- signifyd::Signifyd, square::Square, stax::Stax, stripe::Stripe, threedsecureio::Threedsecureio,
- trustpay::Trustpay, tsys::Tsys, volt::Volt, wellsfargo::Wellsfargo, wise::Wise,
- worldline::Worldline, worldpay::Worldpay, zen::Zen, zsl::Zsl,
+ dlocal::Dlocal, ebanx::Ebanx, forte::Forte, globalpay::Globalpay, globepay::Globepay,
+ gocardless::Gocardless, gpayments::Gpayments, iatapay::Iatapay, itaubank::Itaubank,
+ klarna::Klarna, mifinity::Mifinity, mollie::Mollie, multisafepay::Multisafepay,
+ netcetera::Netcetera, nexinets::Nexinets, nmi::Nmi, noon::Noon, nuvei::Nuvei, opayo::Opayo,
+ opennode::Opennode, payeezy::Payeezy, payme::Payme, payone::Payone, paypal::Paypal, payu::Payu,
+ placetopay::Placetopay, plaid::Plaid, powertranz::Powertranz, prophetpay::Prophetpay,
+ rapyd::Rapyd, razorpay::Razorpay, riskified::Riskified, shift4::Shift4, signifyd::Signifyd,
+ square::Square, stax::Stax, stripe::Stripe, threedsecureio::Threedsecureio, trustpay::Trustpay,
+ tsys::Tsys, volt::Volt, wellsfargo::Wellsfargo, wise::Wise, worldline::Worldline,
+ worldpay::Worldpay, zen::Zen, zsl::Zsl,
};
diff --git a/crates/router/src/core/payments/connector_integration_v2_impls.rs b/crates/router/src/core/payments/connector_integration_v2_impls.rs
index dbb50b18032..019020b0b52 100644
--- a/crates/router/src/core/payments/connector_integration_v2_impls.rs
+++ b/crates/router/src/core/payments/connector_integration_v2_impls.rs
@@ -655,7 +655,6 @@ default_imp_for_new_connector_integration_payment!(
connector::Datatrans,
connector::Dlocal,
connector::Ebanx,
- connector::Fiserv,
connector::Forte,
connector::Globalpay,
connector::Globepay,
@@ -741,7 +740,6 @@ default_imp_for_new_connector_integration_refund!(
connector::Datatrans,
connector::Dlocal,
connector::Ebanx,
- connector::Fiserv,
connector::Forte,
connector::Globalpay,
connector::Globepay,
@@ -822,7 +820,6 @@ default_imp_for_new_connector_integration_connector_access_token!(
connector::Datatrans,
connector::Dlocal,
connector::Ebanx,
- connector::Fiserv,
connector::Forte,
connector::Globalpay,
connector::Globepay,
@@ -925,7 +922,6 @@ default_imp_for_new_connector_integration_accept_dispute!(
connector::Datatrans,
connector::Dlocal,
connector::Ebanx,
- connector::Fiserv,
connector::Forte,
connector::Globalpay,
connector::Globepay,
@@ -1010,7 +1006,6 @@ default_imp_for_new_connector_integration_defend_dispute!(
connector::Datatrans,
connector::Dlocal,
connector::Ebanx,
- connector::Fiserv,
connector::Forte,
connector::Globalpay,
connector::Globepay,
@@ -1079,7 +1074,6 @@ default_imp_for_new_connector_integration_submit_evidence!(
connector::Datatrans,
connector::Dlocal,
connector::Ebanx,
- connector::Fiserv,
connector::Forte,
connector::Globalpay,
connector::Globepay,
@@ -1175,7 +1169,6 @@ default_imp_for_new_connector_integration_file_upload!(
connector::Datatrans,
connector::Dlocal,
connector::Ebanx,
- connector::Fiserv,
connector::Forte,
connector::Globalpay,
connector::Globepay,
@@ -1342,7 +1335,6 @@ default_imp_for_new_connector_integration_payouts_create!(
connector::Datatrans,
connector::Dlocal,
connector::Ebanx,
- connector::Fiserv,
connector::Forte,
connector::Globalpay,
connector::Globepay,
@@ -1430,7 +1422,6 @@ default_imp_for_new_connector_integration_payouts_eligibility!(
connector::Datatrans,
connector::Dlocal,
connector::Ebanx,
- connector::Fiserv,
connector::Forte,
connector::Globalpay,
connector::Globepay,
@@ -1518,7 +1509,6 @@ default_imp_for_new_connector_integration_payouts_fulfill!(
connector::Datatrans,
connector::Dlocal,
connector::Ebanx,
- connector::Fiserv,
connector::Forte,
connector::Globalpay,
connector::Globepay,
@@ -1606,7 +1596,6 @@ default_imp_for_new_connector_integration_payouts_cancel!(
connector::Datatrans,
connector::Dlocal,
connector::Ebanx,
- connector::Fiserv,
connector::Forte,
connector::Globalpay,
connector::Globepay,
@@ -1694,7 +1683,6 @@ default_imp_for_new_connector_integration_payouts_quote!(
connector::Datatrans,
connector::Dlocal,
connector::Ebanx,
- connector::Fiserv,
connector::Forte,
connector::Globalpay,
connector::Globepay,
@@ -1782,7 +1770,6 @@ default_imp_for_new_connector_integration_payouts_recipient!(
connector::Datatrans,
connector::Dlocal,
connector::Ebanx,
- connector::Fiserv,
connector::Forte,
connector::Globalpay,
connector::Globepay,
@@ -1870,7 +1857,6 @@ default_imp_for_new_connector_integration_payouts_sync!(
connector::Datatrans,
connector::Dlocal,
connector::Ebanx,
- connector::Fiserv,
connector::Forte,
connector::Globalpay,
connector::Globepay,
@@ -1958,7 +1944,6 @@ default_imp_for_new_connector_integration_payouts_recipient_account!(
connector::Datatrans,
connector::Dlocal,
connector::Ebanx,
- connector::Fiserv,
connector::Forte,
connector::Globalpay,
connector::Globepay,
@@ -2044,7 +2029,6 @@ default_imp_for_new_connector_integration_webhook_source_verification!(
connector::Datatrans,
connector::Dlocal,
connector::Ebanx,
- connector::Fiserv,
connector::Forte,
connector::Globalpay,
connector::Globepay,
@@ -2211,7 +2195,6 @@ default_imp_for_new_connector_integration_frm_sale!(
connector::Datatrans,
connector::Dlocal,
connector::Ebanx,
- connector::Fiserv,
connector::Forte,
connector::Globalpay,
connector::Globepay,
@@ -2299,7 +2282,6 @@ default_imp_for_new_connector_integration_frm_checkout!(
connector::Datatrans,
connector::Dlocal,
connector::Ebanx,
- connector::Fiserv,
connector::Forte,
connector::Globalpay,
connector::Globepay,
@@ -2387,7 +2369,6 @@ default_imp_for_new_connector_integration_frm_transaction!(
connector::Datatrans,
connector::Dlocal,
connector::Ebanx,
- connector::Fiserv,
connector::Forte,
connector::Globalpay,
connector::Globepay,
@@ -2475,7 +2456,6 @@ default_imp_for_new_connector_integration_frm_fulfillment!(
connector::Datatrans,
connector::Dlocal,
connector::Ebanx,
- connector::Fiserv,
connector::Forte,
connector::Globalpay,
connector::Globepay,
@@ -2563,7 +2543,6 @@ default_imp_for_new_connector_integration_frm_record_return!(
connector::Datatrans,
connector::Dlocal,
connector::Ebanx,
- connector::Fiserv,
connector::Forte,
connector::Globalpay,
connector::Globepay,
@@ -2648,7 +2627,6 @@ default_imp_for_new_connector_integration_revoking_mandates!(
connector::Datatrans,
connector::Dlocal,
connector::Ebanx,
- connector::Fiserv,
connector::Forte,
connector::Globalpay,
connector::Globepay,
diff --git a/crates/router/src/core/payments/flows.rs b/crates/router/src/core/payments/flows.rs
index 32d739bcf9f..6756b9ff5dc 100644
--- a/crates/router/src/core/payments/flows.rs
+++ b/crates/router/src/core/payments/flows.rs
@@ -201,7 +201,6 @@ default_imp_for_complete_authorize!(
connector::Datatrans,
connector::Dlocal,
connector::Ebanx,
- connector::Fiserv,
connector::Forte,
connector::Globepay,
connector::Gocardless,
@@ -287,7 +286,6 @@ default_imp_for_webhook_source_verification!(
connector::Datatrans,
connector::Dlocal,
connector::Ebanx,
- connector::Fiserv,
connector::Forte,
connector::Globalpay,
connector::Globepay,
@@ -383,7 +381,6 @@ default_imp_for_create_customer!(
connector::Datatrans,
connector::Dlocal,
connector::Ebanx,
- connector::Fiserv,
connector::Forte,
connector::Globalpay,
connector::Globepay,
@@ -643,7 +640,6 @@ default_imp_for_accept_dispute!(
connector::Datatrans,
connector::Dlocal,
connector::Ebanx,
- connector::Fiserv,
connector::Forte,
connector::Globalpay,
connector::Globepay,
@@ -761,7 +757,6 @@ default_imp_for_file_upload!(
connector::Datatrans,
connector::Dlocal,
connector::Ebanx,
- connector::Fiserv,
connector::Forte,
connector::Globalpay,
connector::Globepay,
@@ -856,7 +851,6 @@ default_imp_for_submit_evidence!(
connector::Datatrans,
connector::Dlocal,
connector::Ebanx,
- connector::Fiserv,
connector::Forte,
connector::Globalpay,
connector::Globepay,
@@ -951,7 +945,6 @@ default_imp_for_defend_dispute!(
connector::Datatrans,
connector::Dlocal,
connector::Ebanx,
- connector::Fiserv,
connector::Globepay,
connector::Forte,
connector::Globalpay,
@@ -1062,7 +1055,6 @@ default_imp_for_pre_processing_steps!(
connector::Ebanx,
connector::Iatapay,
connector::Itaubank,
- connector::Fiserv,
connector::Forte,
connector::Globalpay,
connector::Globepay,
@@ -1144,7 +1136,6 @@ default_imp_for_post_processing_steps!(
connector::Ebanx,
connector::Iatapay,
connector::Itaubank,
- connector::Fiserv,
connector::Forte,
connector::Globalpay,
connector::Globepay,
@@ -1303,7 +1294,6 @@ default_imp_for_payouts_create!(
connector::Coinbase,
connector::Datatrans,
connector::Dlocal,
- connector::Fiserv,
connector::Forte,
connector::Globalpay,
connector::Globepay,
@@ -1398,7 +1388,6 @@ default_imp_for_payouts_retrieve!(
connector::Datatrans,
connector::Dlocal,
connector::Ebanx,
- connector::Fiserv,
connector::Forte,
connector::Globalpay,
connector::Globepay,
@@ -1496,7 +1485,6 @@ default_imp_for_payouts_eligibility!(
connector::Coinbase,
connector::Datatrans,
connector::Dlocal,
- connector::Fiserv,
connector::Forte,
connector::Globalpay,
connector::Globepay,
@@ -1589,7 +1577,6 @@ default_imp_for_payouts_fulfill!(
connector::Coinbase,
connector::Datatrans,
connector::Dlocal,
- connector::Fiserv,
connector::Forte,
connector::Globalpay,
connector::Globepay,
@@ -1681,7 +1668,6 @@ default_imp_for_payouts_cancel!(
connector::Coinbase,
connector::Datatrans,
connector::Dlocal,
- connector::Fiserv,
connector::Forte,
connector::Globalpay,
connector::Globepay,
@@ -1776,7 +1762,6 @@ default_imp_for_payouts_quote!(
connector::Coinbase,
connector::Datatrans,
connector::Dlocal,
- connector::Fiserv,
connector::Forte,
connector::Globalpay,
connector::Globepay,
@@ -1872,7 +1857,6 @@ default_imp_for_payouts_recipient!(
connector::Coinbase,
connector::Datatrans,
connector::Dlocal,
- connector::Fiserv,
connector::Forte,
connector::Globalpay,
connector::Globepay,
@@ -1971,7 +1955,6 @@ default_imp_for_payouts_recipient_account!(
connector::Datatrans,
connector::Dlocal,
connector::Ebanx,
- connector::Fiserv,
connector::Forte,
connector::Globalpay,
connector::Globepay,
@@ -2067,7 +2050,6 @@ default_imp_for_approve!(
connector::Datatrans,
connector::Dlocal,
connector::Ebanx,
- connector::Fiserv,
connector::Forte,
connector::Globalpay,
connector::Globepay,
@@ -2164,7 +2146,6 @@ default_imp_for_reject!(
connector::Datatrans,
connector::Dlocal,
connector::Ebanx,
- connector::Fiserv,
connector::Forte,
connector::Globalpay,
connector::Globepay,
@@ -2343,7 +2324,6 @@ default_imp_for_frm_sale!(
connector::Datatrans,
connector::Dlocal,
connector::Ebanx,
- connector::Fiserv,
connector::Forte,
connector::Globalpay,
connector::Globepay,
@@ -2440,7 +2420,6 @@ default_imp_for_frm_checkout!(
connector::Datatrans,
connector::Dlocal,
connector::Ebanx,
- connector::Fiserv,
connector::Forte,
connector::Globalpay,
connector::Globepay,
@@ -2537,7 +2516,6 @@ default_imp_for_frm_transaction!(
connector::Datatrans,
connector::Dlocal,
connector::Ebanx,
- connector::Fiserv,
connector::Forte,
connector::Globalpay,
connector::Globepay,
@@ -2634,7 +2612,6 @@ default_imp_for_frm_fulfillment!(
connector::Datatrans,
connector::Dlocal,
connector::Ebanx,
- connector::Fiserv,
connector::Forte,
connector::Globalpay,
connector::Globepay,
@@ -2731,7 +2708,6 @@ default_imp_for_frm_record_return!(
connector::Datatrans,
connector::Dlocal,
connector::Ebanx,
- connector::Fiserv,
connector::Forte,
connector::Globalpay,
connector::Globepay,
@@ -2825,7 +2801,6 @@ default_imp_for_incremental_authorization!(
connector::Datatrans,
connector::Dlocal,
connector::Ebanx,
- connector::Fiserv,
connector::Forte,
connector::Globalpay,
connector::Globepay,
@@ -2919,7 +2894,6 @@ default_imp_for_revoking_mandates!(
connector::Datatrans,
connector::Dlocal,
connector::Ebanx,
- connector::Fiserv,
connector::Forte,
connector::Globalpay,
connector::Globepay,
@@ -3166,7 +3140,6 @@ default_imp_for_authorize_session_token!(
connector::Datatrans,
connector::Dlocal,
connector::Ebanx,
- connector::Fiserv,
connector::Forte,
connector::Globalpay,
connector::Globepay,
|
2024-07-25T11:30:36Z
|
## Type of Change
<!-- Put an `x` in the boxes that apply -->
- [ ] Bugfix
- [x] New feature
- [ ] Enhancement
- [ ] Refactoring
- [ ] Dependency updates
- [ ] Documentation
- [ ] CI/CD
## Description
<!-- Describe your changes in detail -->
Move connector code for `fiserv` from crate `router` to crate `hyperswitch_connectors`.
### Additional Changes
- [ ] This PR modifies the API contract
- [ ] This PR modifies the database schema
- [ ] This PR modifies application configuration/environment variables
<!--
Provide links to the files with corresponding changes.
Following are the paths where you can find config files:
1. `config`
2. `crates/router/src/configs`
3. `loadtest/config`
-->
## Motivation and Context
<!--
Why is this change required? What problem does it solve?
If it fixes an open issue, please link to the issue here.
If you don't have an issue, we'd recommend starting with one first so the PR
can focus on the implementation (unless it is an obvious bug or documentation fix
that will have little conversation).
-->
https://github.com/juspay/hyperswitch/issues/5440
## How did you test it?
<!--
Did you write an integration/unit/API test to verify the code changes?
Or did you test this change manually (provide relevant screenshots)?
-->
The following flows need to be tested for connector `Fiserv`:
- Authorize:
Request:
```
curl --location 'http://localhost:8080/payments' \
--header 'Content-Type: application/json' \
--header 'Accept: application/json' \
--header 'api-key: dev_xo3RNH4SJGVUfv9B27JQjb6PAN9jmHcJqE4LQjPkLEjvfeFt9MGPENcooNOOEj92' \
--data-raw '{
"amount": 1234,
"currency": "USD",
"confirm": true,
"profile_id": null,
"capture_on": "2022-09-10T10:11:12Z",
"authentication_type": "no_three_ds",
"setup_future_usage": "on_session",
"customer": {
"id": "customer123",
"name": "John Doe",
"email": "customer@gmail.com",
"phone": "9999999999",
"phone_country_code": "+1"
},
"customer_id": "customer123",
"phone_country_code": "+1",
"routing": {
"type": "single",
"data": "stripe"
},
"description": "Its my first payment request",
"return_url": "https://google.com",
"payment_method": "card",
"payment_method_type": "credit",
"payment_method_data": {
"card": {
"card_number": "4761739001010010",
"card_exp_month": "10",
"card_exp_year": "24",
"card_holder_name": "joseph Doe",
"card_cvc": "002"
}
},
"billing": {
"address": {
"line1": "1467",
"line2": "Harrison Street",
"line3": "Harrison Street",
"city": "San Fransico",
"state": "California",
"zip": "94122",
"country": "US",
"first_name": "joseph",
"last_name": "Doe"
},
"phone": {
"number": "8056594427",
"country_code": "+91"
},
"email": "guest@example.com"
},
"shipping": {
"address": {
"line1": "1467",
"line2": "Harrison Street",
"line3": "Harrison Street",
"city": "San Fransico",
"state": "California",
"zip": "94122",
"country": "US",
"first_name": "joseph",
"last_name": "Doe"
},
"phone": {
"number": "8056594427",
"country_code": "+91"
},
"email": "guest@example.com"
},
"statement_descriptor_name": "joseph",
"statement_descriptor_suffix": "JS",
"order_details": [
{
"product_name": "Apple iphone 15",
"quantity": 1,
"amount": 6540,
"account_name": "transaction_processing"
}
],
"metadata": {
"udf1": "value1",
"new_customer": "true",
"login_date": "2019-09-10T10:11:12Z"
},
"browser_info": {
"user_agent": "Mozilla\/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit\/537.36 (KHTML, like Gecko) Chrome\/70.0.3538.110 Safari\/537.36",
"accept_header": "text\/html,application\/xhtml+xml,application\/xml;q=0.9,image\/webp,image\/apng,*\/*;q=0.8",
"language": "nl-NL",
"color_depth": 24,
"screen_height": 723,
"screen_width": 1536,
"time_zone": 0,
"java_enabled": true,
"java_script_enabled": true,
"ip_address": "128.0.0.1"
},
"customer_acceptance": {
"acceptance_type": "offline",
"accepted_at": "1963-05-03T04:07:52.723Z",
"online": {
"ip_address": "125.0.0.1",
"user_agent": "amet irure esse"
}
},
"connector_metadata": {
"noon": {
"order_category": "pay"
}
},
"payment_link": false,
"payment_link_config": {
"theme": "",
"logo": "",
"seller_name": "",
"sdk_layout": "",
"display_sdk_only": false,
"enabled_saved_payment_method": false
},
"payment_type": "normal",
"request_incremental_authorization": false,
"merchant_order_reference_id": "test_ord",
"session_expiry": 900
}'
```
Response:
```
{
"payment_id": "pay_FQo68sYrGp2PMAtWbcsV",
"merchant_id": "merchant_1721912543",
"status": "succeeded",
"amount": 1234,
"net_amount": 1234,
"amount_capturable": 0,
"amount_received": 1234,
"connector": "fiserv",
"client_secret": "pay_FQo68sYrGp2PMAtWbcsV_secret_SlOkENIz0C98x01CtlUt",
"created": "2024-07-25T13:02:28.674Z",
"currency": "USD",
"customer_id": "customer123",
"customer": {
"id": "customer123",
"name": "John Doe",
"email": "customer@gmail.com",
"phone": "9999999999",
"phone_country_code": "+1"
},
"description": "Its my first payment request",
"refunds": null,
"disputes": null,
"mandate_id": null,
"mandate_data": null,
"setup_future_usage": "on_session",
"off_session": null,
"capture_on": null,
"capture_method": null,
"payment_method": "card",
"payment_method_data": {
"card": {
"last4": "0010",
"card_type": null,
"card_network": null,
"card_issuer": null,
"card_issuing_country": null,
"card_isin": "476173",
"card_extended_bin": null,
"card_exp_month": "10",
"card_exp_year": "24",
"card_holder_name": "joseph Doe",
"payment_checks": null,
"authentication_data": null
},
"billing": null
},
"payment_token": null,
"shipping": {
"address": {
"city": "San Fransico",
"country": "US",
"line1": "1467",
"line2": "Harrison Street",
"line3": "Harrison Street",
"zip": "94122",
"state": "California",
"first_name": "joseph",
"last_name": "Doe"
},
"phone": {
"number": "8056594427",
"country_code": "+91"
},
"email": "guest@example.com"
},
"billing": {
"address": {
"city": "San Fransico",
"country": "US",
"line1": "1467",
"line2": "Harrison Street",
"line3": "Harrison Street",
"zip": "94122",
"state": "California",
"first_name": "joseph",
"last_name": "Doe"
},
"phone": {
"number": "8056594427",
"country_code": "+91"
},
"email": "guest@example.com"
},
"order_details": [
{
"brand": null,
"amount": 6540,
"category": null,
"quantity": 1,
"product_id": null,
"product_name": "Apple iphone 15",
"product_type": null,
"sub_category": null,
"product_img_link": null,
"requires_shipping": null
}
],
"email": "customer@gmail.com",
"name": "John Doe",
"phone": "9999999999",
"return_url": "https://google.com/",
"authentication_type": "no_three_ds",
"statement_descriptor_name": "joseph",
"statement_descriptor_suffix": "JS",
"next_action": null,
"cancellation_reason": null,
"error_code": null,
"error_message": null,
"unified_code": null,
"unified_message": null,
"payment_experience": null,
"payment_method_type": "credit",
"connector_label": null,
"business_country": null,
"business_label": "default",
"business_sub_label": null,
"allowed_payment_method_types": null,
"ephemeral_key": {
"customer_id": "customer123",
"created_at": 1721912548,
"expires": 1721916148,
"secret": "epk_fc69bafa3d934476a530ddb4381048a9"
},
"manual_retry_allowed": false,
"connector_transaction_id": "93e099f7bea84ead817b8cd9acd602c3",
"frm_message": null,
"metadata": {
"udf1": "value1",
"login_date": "2019-09-10T10:11:12Z",
"new_customer": "true"
},
"connector_metadata": {
"apple_pay": null,
"airwallex": null,
"noon": {
"order_category": "pay"
}
},
"feature_metadata": null,
"reference_id": "CHG01ad814ffc7b1515d4bcfd70acac2bf3dc",
"payment_link": null,
"profile_id": "pro_V2NRX76RhIrMwvvIR0Nm",
"surcharge_details": null,
"attempt_count": 1,
"merchant_decision": null,
"merchant_connector_id": "mca_Kt2D5qGfkiYgqdacoKDh",
"incremental_authorization_allowed": false,
"authorization_count": null,
"incremental_authorizations": null,
"external_authentication_details": null,
"external_3ds_authentication_attempted": false,
"expires_on": "2024-07-25T13:17:28.674Z",
"fingerprint": null,
"browser_info": {
"language": "nl-NL",
"time_zone": 0,
"ip_address": "128.0.0.1",
"user_agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/70.0.3538.110 Safari/537.36",
"color_depth": 24,
"java_enabled": true,
"screen_width": 1536,
"accept_header": "text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,image/apng,*/*;q=0.8",
"screen_height": 723,
"java_script_enabled": true
},
"payment_method_id": null,
"payment_method_status": null,
"updated": "2024-07-25T13:02:30.109Z",
"charges": null,
"frm_metadata": null,
"merchant_order_reference_id": "test_ord"
}
```
- Capture:
Request:
```
curl --location 'http://localhost:8080/payments/pay_dJgBr13y9CERMpHskTPQ/capture' \
--header 'Content-Type: application/json' \
--header 'Accept: application/json' \
--header 'api-key: dev_xo3RNH4SJGVUfv9B27JQjb6PAN9jmHcJqE4LQjPkLEjvfeFt9MGPENcooNOOEj92' \
--data '{
}'
```
Response:
```
{
"payment_id": "pay_dJgBr13y9CERMpHskTPQ",
"merchant_id": "merchant_1721912543",
"status": "succeeded",
"amount": 1122,
"net_amount": 1122,
"amount_capturable": 0,
"amount_received": 1122,
"connector": "fiserv",
"client_secret": "pay_dJgBr13y9CERMpHskTPQ_secret_cgu5pDtquNjRf8XHjtKQ",
"created": "2024-07-25T13:03:44.641Z",
"currency": "USD",
"customer_id": "customer123",
"customer": {
"id": "customer123",
"name": "John Doe",
"email": "customer@gmail.com",
"phone": "9999999999",
"phone_country_code": "+1"
},
"description": "Its my first payment request",
"refunds": null,
"disputes": null,
"mandate_id": null,
"mandate_data": null,
"setup_future_usage": "on_session",
"off_session": null,
"capture_on": null,
"capture_method": "manual",
"payment_method": "card",
"payment_method_data": {
"card": {
"last4": "0010",
"card_type": null,
"card_network": null,
"card_issuer": null,
"card_issuing_country": null,
"card_isin": "476173",
"card_extended_bin": null,
"card_exp_month": "10",
"card_exp_year": "24",
"card_holder_name": "joseph Doe",
"payment_checks": null,
"authentication_data": null
},
"billing": null
},
"payment_token": null,
"shipping": {
"address": {
"city": "San Fransico",
"country": "US",
"line1": "1467",
"line2": "Harrison Street",
"line3": "Harrison Street",
"zip": "94122",
"state": "California",
"first_name": "joseph",
"last_name": "Doe"
},
"phone": {
"number": "8056594427",
"country_code": "+91"
},
"email": "guest@example.com"
},
"billing": {
"address": {
"city": "San Fransico",
"country": "US",
"line1": "1467",
"line2": "Harrison Street",
"line3": "Harrison Street",
"zip": "94122",
"state": "California",
"first_name": "joseph",
"last_name": "Doe"
},
"phone": {
"number": "8056594427",
"country_code": "+91"
},
"email": "guest@example.com"
},
"order_details": [
{
"brand": null,
"amount": 6540,
"category": null,
"quantity": 1,
"product_id": null,
"product_name": "Apple iphone 15",
"product_type": null,
"sub_category": null,
"product_img_link": null,
"requires_shipping": null
}
],
"email": "customer@gmail.com",
"name": "John Doe",
"phone": "9999999999",
"return_url": "https://google.com/",
"authentication_type": "no_three_ds",
"statement_descriptor_name": "joseph",
"statement_descriptor_suffix": "JS",
"next_action": null,
"cancellation_reason": null,
"error_code": null,
"error_message": null,
"unified_code": null,
"unified_message": null,
"payment_experience": null,
"payment_method_type": "credit",
"connector_label": null,
"business_country": null,
"business_label": "default",
"business_sub_label": null,
"allowed_payment_method_types": null,
"ephemeral_key": null,
"manual_retry_allowed": false,
"connector_transaction_id": "001c2342e963418ba6542b75cf9d0d83",
"frm_message": null,
"metadata": {
"udf1": "value1",
"login_date": "2019-09-10T10:11:12Z",
"new_customer": "true"
},
"connector_metadata": {
"apple_pay": null,
"airwallex": null,
"noon": {
"order_category": "pay"
}
},
"feature_metadata": null,
"reference_id": "CHG01cc9131f876fc42eff0c26fdf01ffa8d3",
"payment_link": null,
"profile_id": "pro_V2NRX76RhIrMwvvIR0Nm",
"surcharge_details": null,
"attempt_count": 1,
"merchant_decision": null,
"merchant_connector_id": "mca_Kt2D5qGfkiYgqdacoKDh",
"incremental_authorization_allowed": false,
"authorization_count": null,
"incremental_authorizations": null,
"external_authentication_details": null,
"external_3ds_authentication_attempted": false,
"expires_on": "2024-07-25T13:18:44.641Z",
"fingerprint": null,
"browser_info": {
"language": "nl-NL",
"time_zone": 0,
"ip_address": "128.0.0.1",
"user_agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/70.0.3538.110 Safari/537.36",
"color_depth": 24,
"java_enabled": true,
"screen_width": 1536,
"accept_header": "text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,image/apng,*/*;q=0.8",
"screen_height": 723,
"java_script_enabled": true
},
"payment_method_id": "pm_MbbhL5b2ZolS8jlPLkx7",
"payment_method_status": null,
"updated": "2024-07-25T13:03:54.219Z",
"charges": null,
"frm_metadata": null,
"merchant_order_reference_id": "test_ord"
}
```
- Refund:
Request:
```
curl --location 'http://localhost:8080/refunds' \
--header 'Content-Type: application/json' \
--header 'Accept: application/json' \
--header 'api-key: dev_xo3RNH4SJGVUfv9B27JQjb6PAN9jmHcJqE4LQjPkLEjvfeFt9MGPENcooNOOEj92' \
--data '{
"payment_id": "pay_FQo68sYrGp2PMAtWbcsV",
"reason": "Customer returned product",
"refund_type": "instant",
"metadata": {
"udf1": "value1",
"new_customer": "true",
"login_date": "2019-09-10T10:11:12Z"
}
}'
```
Response:
```
{
"refund_id": "ref_7LNld1IUNJQDf3y3jjlo",
"payment_id": "pay_FQo68sYrGp2PMAtWbcsV",
"amount": 1234,
"currency": "USD",
"status": "succeeded",
"reason": "Customer returned product",
"metadata": {
"udf1": "value1",
"new_customer": "true",
"login_date": "2019-09-10T10:11:12Z"
},
"error_message": null,
"error_code": null,
"created_at": "2024-07-25T13:03:09.268Z",
"updated_at": "2024-07-25T13:03:10.669Z",
"connector": "fiserv",
"profile_id": "pro_V2NRX76RhIrMwvvIR0Nm",
"merchant_connector_id": "mca_Kt2D5qGfkiYgqdacoKDh",
"charges": null
}
```
## Checklist
<!-- Put an `x` in the boxes that apply -->
- [x] I formatted the code `cargo +nightly fmt --all`
- [x] I addressed lints thrown by `cargo clippy`
- [x] I reviewed the submitted code
- [ ] I added unit tests for my changes where possible
|
979539702190363c67045d509be04498efd9a1fa
|
|
juspay/hyperswitch
|
juspay__hyperswitch-5451
|
Bug: [FEATURE] [BAMBORA, BITPAY, STAX] Move connector code for stax to crate hyperswitch_connectors
### Feature Description
Connector code for `bambora, bitpay and stax` needs to be moved from crate router to new crate hyperswitch_connectors
### Possible Implementation
Connector code for `bambora, bitpay and stax` needs to be moved from crate router to new crate hyperswitch_connectors
### Have you spent some time checking if this feature request has been raised before?
- [X] I checked and didn't find a similar issue
### Have you read the Contributing Guidelines?
- [X] I have read the [Contributing Guidelines](https://github.com/juspay/hyperswitch/blob/main/docs/CONTRIBUTING.md)
### Are you willing to submit a PR?
Yes, I am willing to submit a PR!
|
diff --git a/Cargo.lock b/Cargo.lock
index 45556ef401e..fde659c77c7 100644
--- a/Cargo.lock
+++ b/Cargo.lock
@@ -3850,6 +3850,7 @@ dependencies = [
"serde_json",
"strum 0.26.2",
"time",
+ "url",
"uuid",
]
diff --git a/crates/common_enums/src/enums.rs b/crates/common_enums/src/enums.rs
index 3454a6ba020..2bd2e8c03b9 100644
--- a/crates/common_enums/src/enums.rs
+++ b/crates/common_enums/src/enums.rs
@@ -486,6 +486,25 @@ pub enum ConnectorType {
AuthenticationProcessor,
}
+#[derive(Debug, Eq, PartialEq)]
+pub enum PaymentAction {
+ PSync,
+ CompleteAuthorize,
+ PaymentAuthenticateCompleteAuthorize,
+}
+
+#[derive(Clone, PartialEq)]
+pub enum CallConnectorAction {
+ Trigger,
+ Avoid,
+ StatusUpdate {
+ status: AttemptStatus,
+ error_code: Option<String>,
+ error_message: Option<String>,
+ },
+ HandleResponse(Vec<u8>),
+}
+
/// The three letter ISO currency code in uppercase. Eg: 'USD' for the United States Dollar.
#[allow(clippy::upper_case_acronyms)]
#[derive(
diff --git a/crates/hyperswitch_connectors/Cargo.toml b/crates/hyperswitch_connectors/Cargo.toml
index 30671d43bd9..2b199a3f722 100644
--- a/crates/hyperswitch_connectors/Cargo.toml
+++ b/crates/hyperswitch_connectors/Cargo.toml
@@ -18,6 +18,7 @@ serde = { version = "1.0.197", features = ["derive"] }
serde_json = "1.0.115"
strum = { version = "0.26", features = ["derive"] }
time = "0.3.35"
+url = "2.5.0"
uuid = { version = "1.8.0", features = ["v4"] }
# First party crates
diff --git a/crates/hyperswitch_connectors/src/connectors.rs b/crates/hyperswitch_connectors/src/connectors.rs
index 0481939feb4..473ba5f6c85 100644
--- a/crates/hyperswitch_connectors/src/connectors.rs
+++ b/crates/hyperswitch_connectors/src/connectors.rs
@@ -1,4 +1,7 @@
+pub mod bambora;
+pub mod bitpay;
pub mod fiserv;
pub mod helcim;
+pub mod stax;
-pub use self::{fiserv::Fiserv, helcim::Helcim};
+pub use self::{bambora::Bambora, bitpay::Bitpay, fiserv::Fiserv, helcim::Helcim, stax::Stax};
diff --git a/crates/router/src/connector/bambora.rs b/crates/hyperswitch_connectors/src/connectors/bambora.rs
similarity index 64%
rename from crates/router/src/connector/bambora.rs
rename to crates/hyperswitch_connectors/src/connectors/bambora.rs
index 684c5ddc1ce..4731546b3d3 100644
--- a/crates/router/src/connector/bambora.rs
+++ b/crates/hyperswitch_connectors/src/connectors/bambora.rs
@@ -2,32 +2,54 @@ pub mod transformers;
use std::fmt::Debug;
-use common_utils::request::RequestContent;
-use diesel_models::enums;
+use common_enums::enums;
+use common_utils::{
+ errors::CustomResult,
+ ext_traits::BytesExt,
+ request::{Method, Request, RequestBuilder, RequestContent},
+};
use error_stack::{report, ResultExt};
-use transformers as bambora;
-
-use super::utils::RefundsRequestData;
-use crate::{
- configs::settings,
- connector::{utils as connector_utils, utils::to_connector_meta},
- core::{
- errors::{self, CustomResult},
- payments,
+use hyperswitch_domain_models::{
+ router_data::{AccessToken, ConnectorAuthType, ErrorResponse, RouterData},
+ router_flow_types::{
+ access_token_auth::AccessTokenAuth,
+ payments::{Authorize, Capture, PSync, PaymentMethodToken, Session, SetupMandate, Void},
+ refunds::{Execute, RSync},
+ CompleteAuthorize,
},
- events::connector_api_logs::ConnectorEvent,
- headers,
- services::{
- self,
- request::{self, Mask},
- ConnectorIntegration, ConnectorValidation,
+ router_request_types::{
+ AccessTokenRequestData, CompleteAuthorizeData, PaymentMethodTokenizationData,
+ PaymentsAuthorizeData, PaymentsCancelData, PaymentsCaptureData, PaymentsSessionData,
+ PaymentsSyncData, RefundsData, SetupMandateRequestData,
},
+ router_response_types::{PaymentsResponseData, RefundsResponseData},
+ types::{
+ PaymentsAuthorizeRouterData, PaymentsCancelRouterData, PaymentsCaptureRouterData,
+ PaymentsCompleteAuthorizeRouterData, PaymentsSyncRouterData, RefundSyncRouterData,
+ RefundsRouterData,
+ },
+};
+use hyperswitch_interfaces::{
+ api::{
+ self, ConnectorCommon, ConnectorCommonExt, ConnectorIntegration, ConnectorRedirectResponse,
+ ConnectorValidation,
+ },
+ configs::Connectors,
+ errors,
+ events::connector_api_logs::ConnectorEvent,
types::{
- self,
- api::{self, ConnectorCommon, ConnectorCommonExt},
- ErrorResponse, Response,
+ self, PaymentsAuthorizeType, PaymentsCaptureType, PaymentsCompleteAuthorizeType,
+ PaymentsSyncType, PaymentsVoidType, Response,
},
- utils::BytesExt,
+ webhooks,
+};
+use masking::Mask;
+use transformers as bambora;
+
+use crate::{
+ constants::headers,
+ types::ResponseRouterData,
+ utils::{self, RefundsRequestData},
};
#[derive(Debug, Clone)]
@@ -53,12 +75,12 @@ where
{
fn build_headers(
&self,
- req: &types::RouterData<Flow, Request, Response>,
- _connectors: &settings::Connectors,
- ) -> CustomResult<Vec<(String, request::Maskable<String>)>, errors::ConnectorError> {
+ req: &RouterData<Flow, Request, Response>,
+ _connectors: &Connectors,
+ ) -> CustomResult<Vec<(String, masking::Maskable<String>)>, errors::ConnectorError> {
let mut header = vec![(
headers::CONTENT_TYPE.to_string(),
- types::PaymentsAuthorizeType::get_content_type(self)
+ PaymentsAuthorizeType::get_content_type(self)
.to_string()
.into(),
)];
@@ -81,14 +103,14 @@ impl ConnectorCommon for Bambora {
"application/json"
}
- fn base_url<'a>(&self, connectors: &'a settings::Connectors) -> &'a str {
+ fn base_url<'a>(&self, connectors: &'a Connectors) -> &'a str {
connectors.bambora.base_url.as_ref()
}
fn get_auth_header(
&self,
- auth_type: &types::ConnectorAuthType,
- ) -> CustomResult<Vec<(String, request::Maskable<String>)>, errors::ConnectorError> {
+ auth_type: &ConnectorAuthType,
+ ) -> CustomResult<Vec<(String, masking::Maskable<String>)>, errors::ConnectorError> {
let auth = bambora::BamboraAuthType::try_from(auth_type)
.change_context(errors::ConnectorError::FailedToObtainAuthType)?;
Ok(vec![(
@@ -114,7 +136,7 @@ impl ConnectorCommon for Bambora {
status_code: res.status_code,
code: response.code.to_string(),
message: serde_json::to_string(&response.details)
- .unwrap_or(crate::consts::NO_ERROR_MESSAGE.to_string()),
+ .unwrap_or(hyperswitch_interfaces::consts::NO_ERROR_MESSAGE.to_string()),
reason: Some(response.message),
attempt_status: None,
connector_transaction_id: None,
@@ -132,49 +154,30 @@ impl ConnectorValidation for Bambora {
match capture_method {
enums::CaptureMethod::Automatic | enums::CaptureMethod::Manual => Ok(()),
enums::CaptureMethod::ManualMultiple | enums::CaptureMethod::Scheduled => Err(
- connector_utils::construct_not_implemented_error_report(capture_method, self.id()),
+ utils::construct_not_implemented_error_report(capture_method, self.id()),
),
}
}
}
-impl
- ConnectorIntegration<
- api::PaymentMethodToken,
- types::PaymentMethodTokenizationData,
- types::PaymentsResponseData,
- > for Bambora
+impl ConnectorIntegration<PaymentMethodToken, PaymentMethodTokenizationData, PaymentsResponseData>
+ for Bambora
{
// Not Implemented (R)
}
-impl ConnectorIntegration<api::AccessTokenAuth, types::AccessTokenRequestData, types::AccessToken>
- for Bambora
-{
-}
+impl ConnectorIntegration<AccessTokenAuth, AccessTokenRequestData, AccessToken> for Bambora {}
-impl ConnectorIntegration<api::Session, types::PaymentsSessionData, types::PaymentsResponseData>
- for Bambora
-{
+impl ConnectorIntegration<Session, PaymentsSessionData, PaymentsResponseData> for Bambora {
//TODO: implement sessions flow
}
-impl
- ConnectorIntegration<
- api::SetupMandate,
- types::SetupMandateRequestData,
- types::PaymentsResponseData,
- > for Bambora
-{
+impl ConnectorIntegration<SetupMandate, SetupMandateRequestData, PaymentsResponseData> for Bambora {
fn build_request(
&self,
- _req: &types::RouterData<
- api::SetupMandate,
- types::SetupMandateRequestData,
- types::PaymentsResponseData,
- >,
- _connectors: &settings::Connectors,
- ) -> CustomResult<Option<services::Request>, errors::ConnectorError> {
+ _req: &RouterData<SetupMandate, SetupMandateRequestData, PaymentsResponseData>,
+ _connectors: &Connectors,
+ ) -> CustomResult<Option<Request>, errors::ConnectorError> {
Err(
errors::ConnectorError::NotImplemented("Setup Mandate flow for Bambora".to_string())
.into(),
@@ -182,14 +185,12 @@ impl
}
}
-impl ConnectorIntegration<api::Authorize, types::PaymentsAuthorizeData, types::PaymentsResponseData>
- for Bambora
-{
+impl ConnectorIntegration<Authorize, PaymentsAuthorizeData, PaymentsResponseData> for Bambora {
fn get_headers(
&self,
- req: &types::PaymentsAuthorizeRouterData,
- connectors: &settings::Connectors,
- ) -> CustomResult<Vec<(String, request::Maskable<String>)>, errors::ConnectorError> {
+ req: &PaymentsAuthorizeRouterData,
+ connectors: &Connectors,
+ ) -> CustomResult<Vec<(String, masking::Maskable<String>)>, errors::ConnectorError> {
self.build_headers(req, connectors)
}
@@ -199,16 +200,16 @@ impl ConnectorIntegration<api::Authorize, types::PaymentsAuthorizeData, types::P
fn get_url(
&self,
- _req: &types::PaymentsAuthorizeRouterData,
- connectors: &settings::Connectors,
+ _req: &PaymentsAuthorizeRouterData,
+ connectors: &Connectors,
) -> CustomResult<String, errors::ConnectorError> {
Ok(format!("{}{}", self.base_url(connectors), "/v1/payments"))
}
fn get_request_body(
&self,
- req: &types::PaymentsAuthorizeRouterData,
- _connectors: &settings::Connectors,
+ req: &PaymentsAuthorizeRouterData,
+ _connectors: &Connectors,
) -> CustomResult<RequestContent, errors::ConnectorError> {
let connector_router_data = bambora::BamboraRouterData::try_from((
&self.get_currency_unit(),
@@ -223,20 +224,16 @@ impl ConnectorIntegration<api::Authorize, types::PaymentsAuthorizeData, types::P
fn build_request(
&self,
- req: &types::PaymentsAuthorizeRouterData,
- connectors: &settings::Connectors,
- ) -> CustomResult<Option<services::Request>, errors::ConnectorError> {
+ req: &PaymentsAuthorizeRouterData,
+ connectors: &Connectors,
+ ) -> CustomResult<Option<Request>, errors::ConnectorError> {
Ok(Some(
- services::RequestBuilder::new()
- .method(services::Method::Post)
- .url(&types::PaymentsAuthorizeType::get_url(
- self, req, connectors,
- )?)
+ RequestBuilder::new()
+ .method(Method::Post)
+ .url(&PaymentsAuthorizeType::get_url(self, req, connectors)?)
.attach_default_headers()
- .headers(types::PaymentsAuthorizeType::get_headers(
- self, req, connectors,
- )?)
- .set_body(types::PaymentsAuthorizeType::get_request_body(
+ .headers(PaymentsAuthorizeType::get_headers(self, req, connectors)?)
+ .set_body(PaymentsAuthorizeType::get_request_body(
self, req, connectors,
)?)
.build(),
@@ -245,10 +242,10 @@ impl ConnectorIntegration<api::Authorize, types::PaymentsAuthorizeData, types::P
fn handle_response(
&self,
- data: &types::PaymentsAuthorizeRouterData,
+ data: &PaymentsAuthorizeRouterData,
event_builder: Option<&mut ConnectorEvent>,
res: Response,
- ) -> CustomResult<types::PaymentsAuthorizeRouterData, errors::ConnectorError> {
+ ) -> CustomResult<PaymentsAuthorizeRouterData, errors::ConnectorError> {
let response: bambora::BamboraResponse = res
.response
.parse_struct("PaymentIntentResponse")
@@ -256,7 +253,7 @@ impl ConnectorIntegration<api::Authorize, types::PaymentsAuthorizeData, types::P
event_builder.map(|i| i.set_response_body(&response));
router_env::logger::info!(connector_response=?response);
- types::RouterData::try_from(types::ResponseRouterData {
+ RouterData::try_from(ResponseRouterData {
response,
data: data.clone(),
http_code: res.status_code,
@@ -272,18 +269,14 @@ impl ConnectorIntegration<api::Authorize, types::PaymentsAuthorizeData, types::P
}
}
-impl
- ConnectorIntegration<
- api::CompleteAuthorize,
- types::CompleteAuthorizeData,
- types::PaymentsResponseData,
- > for Bambora
+impl ConnectorIntegration<CompleteAuthorize, CompleteAuthorizeData, PaymentsResponseData>
+ for Bambora
{
fn get_headers(
&self,
- req: &types::PaymentsCompleteAuthorizeRouterData,
- connectors: &settings::Connectors,
- ) -> CustomResult<Vec<(String, request::Maskable<String>)>, errors::ConnectorError> {
+ req: &PaymentsCompleteAuthorizeRouterData,
+ connectors: &Connectors,
+ ) -> CustomResult<Vec<(String, masking::Maskable<String>)>, errors::ConnectorError> {
self.build_headers(req, connectors)
}
@@ -293,10 +286,11 @@ impl
fn get_url(
&self,
- req: &types::PaymentsCompleteAuthorizeRouterData,
- connectors: &settings::Connectors,
+ req: &PaymentsCompleteAuthorizeRouterData,
+ connectors: &Connectors,
) -> CustomResult<String, errors::ConnectorError> {
- let meta: bambora::BamboraMeta = to_connector_meta(req.request.connector_meta.clone())?;
+ let meta: bambora::BamboraMeta =
+ utils::to_connector_meta(req.request.connector_meta.clone())?;
Ok(format!(
"{}/v1/payments/{}{}",
self.base_url(connectors),
@@ -307,8 +301,8 @@ impl
fn get_request_body(
&self,
- req: &types::PaymentsCompleteAuthorizeRouterData,
- _connectors: &settings::Connectors,
+ req: &PaymentsCompleteAuthorizeRouterData,
+ _connectors: &Connectors,
) -> CustomResult<RequestContent, errors::ConnectorError> {
let connector_req = bambora::BamboraThreedsContinueRequest::try_from(&req.request)?;
@@ -317,18 +311,19 @@ impl
fn build_request(
&self,
- req: &types::PaymentsCompleteAuthorizeRouterData,
- connectors: &settings::Connectors,
- ) -> CustomResult<Option<services::Request>, errors::ConnectorError> {
- let request = services::RequestBuilder::new()
- .method(services::Method::Post)
- .url(&types::PaymentsCompleteAuthorizeType::get_url(
+ req: &PaymentsCompleteAuthorizeRouterData,
+ connectors: &Connectors,
+ ) -> CustomResult<Option<Request>, errors::ConnectorError> {
+ let request = RequestBuilder::new()
+ .method(Method::Post)
+ .url(&PaymentsCompleteAuthorizeType::get_url(
self, req, connectors,
)?)
- .headers(types::PaymentsCompleteAuthorizeType::get_headers(
+ .attach_default_headers()
+ .headers(PaymentsCompleteAuthorizeType::get_headers(
self, req, connectors,
)?)
- .set_body(types::PaymentsCompleteAuthorizeType::get_request_body(
+ .set_body(PaymentsCompleteAuthorizeType::get_request_body(
self, req, connectors,
)?)
.build();
@@ -337,10 +332,10 @@ impl
fn handle_response(
&self,
- data: &types::PaymentsCompleteAuthorizeRouterData,
+ data: &PaymentsCompleteAuthorizeRouterData,
event_builder: Option<&mut ConnectorEvent>,
res: Response,
- ) -> CustomResult<types::PaymentsCompleteAuthorizeRouterData, errors::ConnectorError> {
+ ) -> CustomResult<PaymentsCompleteAuthorizeRouterData, errors::ConnectorError> {
let response: bambora::BamboraPaymentsResponse = res
.response
.parse_struct("BamboraPaymentsResponse")
@@ -348,7 +343,7 @@ impl
event_builder.map(|i| i.set_response_body(&response));
router_env::logger::info!(connector_response=?response);
- types::RouterData::try_from(types::ResponseRouterData {
+ RouterData::try_from(ResponseRouterData {
response,
data: data.clone(),
http_code: res.status_code,
@@ -365,14 +360,12 @@ impl
}
}
-impl ConnectorIntegration<api::PSync, types::PaymentsSyncData, types::PaymentsResponseData>
- for Bambora
-{
+impl ConnectorIntegration<PSync, PaymentsSyncData, PaymentsResponseData> for Bambora {
fn get_headers(
&self,
- req: &types::PaymentsSyncRouterData,
- connectors: &settings::Connectors,
- ) -> CustomResult<Vec<(String, request::Maskable<String>)>, errors::ConnectorError> {
+ req: &PaymentsSyncRouterData,
+ connectors: &Connectors,
+ ) -> CustomResult<Vec<(String, masking::Maskable<String>)>, errors::ConnectorError> {
self.build_headers(req, connectors)
}
@@ -382,8 +375,8 @@ impl ConnectorIntegration<api::PSync, types::PaymentsSyncData, types::PaymentsRe
fn get_url(
&self,
- req: &types::PaymentsSyncRouterData,
- connectors: &settings::Connectors,
+ req: &PaymentsSyncRouterData,
+ connectors: &Connectors,
) -> CustomResult<String, errors::ConnectorError> {
let connector_payment_id = req
.request
@@ -398,15 +391,15 @@ impl ConnectorIntegration<api::PSync, types::PaymentsSyncData, types::PaymentsRe
fn build_request(
&self,
- req: &types::PaymentsSyncRouterData,
- connectors: &settings::Connectors,
- ) -> CustomResult<Option<services::Request>, errors::ConnectorError> {
+ req: &PaymentsSyncRouterData,
+ connectors: &Connectors,
+ ) -> CustomResult<Option<Request>, errors::ConnectorError> {
Ok(Some(
- services::RequestBuilder::new()
- .method(services::Method::Get)
- .url(&types::PaymentsSyncType::get_url(self, req, connectors)?)
+ RequestBuilder::new()
+ .method(Method::Get)
+ .url(&PaymentsSyncType::get_url(self, req, connectors)?)
.attach_default_headers()
- .headers(types::PaymentsSyncType::get_headers(self, req, connectors)?)
+ .headers(PaymentsSyncType::get_headers(self, req, connectors)?)
.build(),
))
}
@@ -421,10 +414,10 @@ impl ConnectorIntegration<api::PSync, types::PaymentsSyncData, types::PaymentsRe
fn handle_response(
&self,
- data: &types::PaymentsSyncRouterData,
+ data: &PaymentsSyncRouterData,
event_builder: Option<&mut ConnectorEvent>,
res: Response,
- ) -> CustomResult<types::PaymentsSyncRouterData, errors::ConnectorError> {
+ ) -> CustomResult<PaymentsSyncRouterData, errors::ConnectorError> {
let response: bambora::BamboraPaymentsResponse = res
.response
.parse_struct("bambora PaymentsResponse")
@@ -433,7 +426,7 @@ impl ConnectorIntegration<api::PSync, types::PaymentsSyncData, types::PaymentsRe
event_builder.map(|i| i.set_response_body(&response));
router_env::logger::info!(connector_response=?response);
- types::RouterData::try_from(types::ResponseRouterData {
+ RouterData::try_from(ResponseRouterData {
response,
data: data.clone(),
http_code: res.status_code,
@@ -442,14 +435,12 @@ impl ConnectorIntegration<api::PSync, types::PaymentsSyncData, types::PaymentsRe
}
}
-impl ConnectorIntegration<api::Capture, types::PaymentsCaptureData, types::PaymentsResponseData>
- for Bambora
-{
+impl ConnectorIntegration<Capture, PaymentsCaptureData, PaymentsResponseData> for Bambora {
fn get_headers(
&self,
- req: &types::PaymentsCaptureRouterData,
- connectors: &settings::Connectors,
- ) -> CustomResult<Vec<(String, request::Maskable<String>)>, errors::ConnectorError> {
+ req: &PaymentsCaptureRouterData,
+ connectors: &Connectors,
+ ) -> CustomResult<Vec<(String, masking::Maskable<String>)>, errors::ConnectorError> {
self.build_headers(req, connectors)
}
@@ -459,8 +450,8 @@ impl ConnectorIntegration<api::Capture, types::PaymentsCaptureData, types::Payme
fn get_url(
&self,
- req: &types::PaymentsCaptureRouterData,
- connectors: &settings::Connectors,
+ req: &PaymentsCaptureRouterData,
+ connectors: &Connectors,
) -> CustomResult<String, errors::ConnectorError> {
Ok(format!(
"{}/v1/payments/{}/completions",
@@ -471,8 +462,8 @@ impl ConnectorIntegration<api::Capture, types::PaymentsCaptureData, types::Payme
fn get_request_body(
&self,
- req: &types::PaymentsCaptureRouterData,
- _connectors: &settings::Connectors,
+ req: &PaymentsCaptureRouterData,
+ _connectors: &Connectors,
) -> CustomResult<RequestContent, errors::ConnectorError> {
let connector_router_data = bambora::BamboraRouterData::try_from((
&self.get_currency_unit(),
@@ -488,17 +479,15 @@ impl ConnectorIntegration<api::Capture, types::PaymentsCaptureData, types::Payme
fn build_request(
&self,
- req: &types::PaymentsCaptureRouterData,
- connectors: &settings::Connectors,
- ) -> CustomResult<Option<services::Request>, errors::ConnectorError> {
+ req: &PaymentsCaptureRouterData,
+ connectors: &Connectors,
+ ) -> CustomResult<Option<Request>, errors::ConnectorError> {
Ok(Some(
- services::RequestBuilder::new()
- .method(services::Method::Post)
- .url(&types::PaymentsCaptureType::get_url(self, req, connectors)?)
+ RequestBuilder::new()
+ .method(Method::Post)
+ .url(&PaymentsCaptureType::get_url(self, req, connectors)?)
.attach_default_headers()
- .headers(types::PaymentsCaptureType::get_headers(
- self, req, connectors,
- )?)
+ .headers(PaymentsCaptureType::get_headers(self, req, connectors)?)
.set_body(self.get_request_body(req, connectors)?)
.build(),
))
@@ -506,10 +495,10 @@ impl ConnectorIntegration<api::Capture, types::PaymentsCaptureData, types::Payme
fn handle_response(
&self,
- data: &types::PaymentsCaptureRouterData,
+ data: &PaymentsCaptureRouterData,
event_builder: Option<&mut ConnectorEvent>,
res: Response,
- ) -> CustomResult<types::PaymentsCaptureRouterData, errors::ConnectorError> {
+ ) -> CustomResult<PaymentsCaptureRouterData, errors::ConnectorError> {
let response: bambora::BamboraPaymentsResponse = res
.response
.parse_struct("Bambora PaymentsResponse")
@@ -518,7 +507,7 @@ impl ConnectorIntegration<api::Capture, types::PaymentsCaptureData, types::Payme
event_builder.map(|i| i.set_response_body(&response));
router_env::logger::info!(connector_response=?response);
- types::RouterData::try_from(types::ResponseRouterData {
+ RouterData::try_from(ResponseRouterData {
response,
data: data.clone(),
http_code: res.status_code,
@@ -535,14 +524,12 @@ impl ConnectorIntegration<api::Capture, types::PaymentsCaptureData, types::Payme
}
}
-impl ConnectorIntegration<api::Void, types::PaymentsCancelData, types::PaymentsResponseData>
- for Bambora
-{
+impl ConnectorIntegration<Void, PaymentsCancelData, PaymentsResponseData> for Bambora {
fn get_headers(
&self,
- req: &types::PaymentsCancelRouterData,
- connectors: &settings::Connectors,
- ) -> CustomResult<Vec<(String, request::Maskable<String>)>, errors::ConnectorError> {
+ req: &PaymentsCancelRouterData,
+ connectors: &Connectors,
+ ) -> CustomResult<Vec<(String, masking::Maskable<String>)>, errors::ConnectorError> {
self.build_headers(req, connectors)
}
@@ -552,8 +539,8 @@ impl ConnectorIntegration<api::Void, types::PaymentsCancelData, types::PaymentsR
fn get_url(
&self,
- req: &types::PaymentsCancelRouterData,
- connectors: &settings::Connectors,
+ req: &PaymentsCancelRouterData,
+ connectors: &Connectors,
) -> CustomResult<String, errors::ConnectorError> {
let connector_payment_id = req.request.connector_transaction_id.clone();
Ok(format!(
@@ -565,8 +552,8 @@ impl ConnectorIntegration<api::Void, types::PaymentsCancelData, types::PaymentsR
fn get_request_body(
&self,
- req: &types::PaymentsCancelRouterData,
- _connectors: &settings::Connectors,
+ req: &PaymentsCancelRouterData,
+ _connectors: &Connectors,
) -> CustomResult<RequestContent, errors::ConnectorError> {
let connector_router_data = bambora::BamboraRouterData::try_from((
&self.get_currency_unit(),
@@ -590,15 +577,15 @@ impl ConnectorIntegration<api::Void, types::PaymentsCancelData, types::PaymentsR
fn build_request(
&self,
- req: &types::PaymentsCancelRouterData,
- connectors: &settings::Connectors,
- ) -> CustomResult<Option<services::Request>, errors::ConnectorError> {
+ req: &PaymentsCancelRouterData,
+ connectors: &Connectors,
+ ) -> CustomResult<Option<Request>, errors::ConnectorError> {
Ok(Some(
- services::RequestBuilder::new()
- .method(services::Method::Post)
- .url(&types::PaymentsVoidType::get_url(self, req, connectors)?)
+ RequestBuilder::new()
+ .method(Method::Post)
+ .url(&PaymentsVoidType::get_url(self, req, connectors)?)
.attach_default_headers()
- .headers(types::PaymentsVoidType::get_headers(self, req, connectors)?)
+ .headers(PaymentsVoidType::get_headers(self, req, connectors)?)
.set_body(self.get_request_body(req, connectors)?)
.build(),
))
@@ -606,10 +593,10 @@ impl ConnectorIntegration<api::Void, types::PaymentsCancelData, types::PaymentsR
fn handle_response(
&self,
- data: &types::PaymentsCancelRouterData,
+ data: &PaymentsCancelRouterData,
event_builder: Option<&mut ConnectorEvent>,
res: Response,
- ) -> CustomResult<types::PaymentsCancelRouterData, errors::ConnectorError> {
+ ) -> CustomResult<PaymentsCancelRouterData, errors::ConnectorError> {
let response: bambora::BamboraPaymentsResponse = res
.response
.parse_struct("bambora PaymentsResponse")
@@ -618,7 +605,7 @@ impl ConnectorIntegration<api::Void, types::PaymentsCancelData, types::PaymentsR
event_builder.map(|i| i.set_response_body(&response));
router_env::logger::info!(connector_response=?response);
- types::RouterData::try_from(types::ResponseRouterData {
+ RouterData::try_from(ResponseRouterData {
response,
data: data.clone(),
http_code: res.status_code,
@@ -635,31 +622,29 @@ impl ConnectorIntegration<api::Void, types::PaymentsCancelData, types::PaymentsR
}
}
-impl services::ConnectorRedirectResponse for Bambora {
+impl ConnectorRedirectResponse for Bambora {
fn get_flow_type(
&self,
_query_params: &str,
_json_payload: Option<serde_json::Value>,
- action: services::PaymentAction,
- ) -> CustomResult<payments::CallConnectorAction, errors::ConnectorError> {
+ action: enums::PaymentAction,
+ ) -> CustomResult<enums::CallConnectorAction, errors::ConnectorError> {
match action {
- services::PaymentAction::PSync
- | services::PaymentAction::CompleteAuthorize
- | services::PaymentAction::PaymentAuthenticateCompleteAuthorize => {
- Ok(payments::CallConnectorAction::Trigger)
+ enums::PaymentAction::PSync
+ | enums::PaymentAction::CompleteAuthorize
+ | enums::PaymentAction::PaymentAuthenticateCompleteAuthorize => {
+ Ok(enums::CallConnectorAction::Trigger)
}
}
}
}
-impl ConnectorIntegration<api::Execute, types::RefundsData, types::RefundsResponseData>
- for Bambora
-{
+impl ConnectorIntegration<Execute, RefundsData, RefundsResponseData> for Bambora {
fn get_headers(
&self,
- req: &types::RefundsRouterData<api::Execute>,
- connectors: &settings::Connectors,
- ) -> CustomResult<Vec<(String, request::Maskable<String>)>, errors::ConnectorError> {
+ req: &RefundsRouterData<Execute>,
+ connectors: &Connectors,
+ ) -> CustomResult<Vec<(String, masking::Maskable<String>)>, errors::ConnectorError> {
self.build_headers(req, connectors)
}
@@ -669,8 +654,8 @@ impl ConnectorIntegration<api::Execute, types::RefundsData, types::RefundsRespon
fn get_url(
&self,
- req: &types::RefundsRouterData<api::Execute>,
- connectors: &settings::Connectors,
+ req: &RefundsRouterData<Execute>,
+ connectors: &Connectors,
) -> CustomResult<String, errors::ConnectorError> {
let connector_payment_id = req.request.connector_transaction_id.clone();
Ok(format!(
@@ -682,8 +667,8 @@ impl ConnectorIntegration<api::Execute, types::RefundsData, types::RefundsRespon
fn get_request_body(
&self,
- req: &types::RefundsRouterData<api::Execute>,
- _connectors: &settings::Connectors,
+ req: &RefundsRouterData<Execute>,
+ _connectors: &Connectors,
) -> CustomResult<RequestContent, errors::ConnectorError> {
let connector_router_data = bambora::BamboraRouterData::try_from((
&self.get_currency_unit(),
@@ -697,11 +682,11 @@ impl ConnectorIntegration<api::Execute, types::RefundsData, types::RefundsRespon
fn build_request(
&self,
- req: &types::RefundsRouterData<api::Execute>,
- connectors: &settings::Connectors,
- ) -> CustomResult<Option<services::Request>, errors::ConnectorError> {
- let request = services::RequestBuilder::new()
- .method(services::Method::Post)
+ req: &RefundsRouterData<Execute>,
+ connectors: &Connectors,
+ ) -> CustomResult<Option<Request>, errors::ConnectorError> {
+ let request = RequestBuilder::new()
+ .method(Method::Post)
.url(&types::RefundExecuteType::get_url(self, req, connectors)?)
.attach_default_headers()
.headers(types::RefundExecuteType::get_headers(
@@ -716,10 +701,10 @@ impl ConnectorIntegration<api::Execute, types::RefundsData, types::RefundsRespon
fn handle_response(
&self,
- data: &types::RefundsRouterData<api::Execute>,
+ data: &RefundsRouterData<Execute>,
event_builder: Option<&mut ConnectorEvent>,
res: Response,
- ) -> CustomResult<types::RefundsRouterData<api::Execute>, errors::ConnectorError> {
+ ) -> CustomResult<RefundsRouterData<Execute>, errors::ConnectorError> {
let response: bambora::RefundResponse = res
.response
.parse_struct("bambora RefundResponse")
@@ -728,7 +713,7 @@ impl ConnectorIntegration<api::Execute, types::RefundsData, types::RefundsRespon
event_builder.map(|i| i.set_response_body(&response));
router_env::logger::info!(connector_response=?response);
- types::RouterData::try_from(types::ResponseRouterData {
+ RouterData::try_from(ResponseRouterData {
response,
data: data.clone(),
http_code: res.status_code,
@@ -745,12 +730,12 @@ impl ConnectorIntegration<api::Execute, types::RefundsData, types::RefundsRespon
}
}
-impl ConnectorIntegration<api::RSync, types::RefundsData, types::RefundsResponseData> for Bambora {
+impl ConnectorIntegration<RSync, RefundsData, RefundsResponseData> for Bambora {
fn get_headers(
&self,
- req: &types::RefundSyncRouterData,
- connectors: &settings::Connectors,
- ) -> CustomResult<Vec<(String, request::Maskable<String>)>, errors::ConnectorError> {
+ req: &RefundSyncRouterData,
+ connectors: &Connectors,
+ ) -> CustomResult<Vec<(String, masking::Maskable<String>)>, errors::ConnectorError> {
self.build_headers(req, connectors)
}
@@ -760,8 +745,8 @@ impl ConnectorIntegration<api::RSync, types::RefundsData, types::RefundsResponse
fn get_url(
&self,
- req: &types::RefundSyncRouterData,
- connectors: &settings::Connectors,
+ req: &RefundSyncRouterData,
+ connectors: &Connectors,
) -> CustomResult<String, errors::ConnectorError> {
let _connector_payment_id = req.request.connector_transaction_id.clone();
let connector_refund_id = req.request.get_connector_refund_id()?;
@@ -774,12 +759,12 @@ impl ConnectorIntegration<api::RSync, types::RefundsData, types::RefundsResponse
fn build_request(
&self,
- req: &types::RefundSyncRouterData,
- connectors: &settings::Connectors,
- ) -> CustomResult<Option<services::Request>, errors::ConnectorError> {
+ req: &RefundSyncRouterData,
+ connectors: &Connectors,
+ ) -> CustomResult<Option<Request>, errors::ConnectorError> {
Ok(Some(
- services::RequestBuilder::new()
- .method(services::Method::Get)
+ RequestBuilder::new()
+ .method(Method::Get)
.url(&types::RefundSyncType::get_url(self, req, connectors)?)
.attach_default_headers()
.headers(types::RefundSyncType::get_headers(self, req, connectors)?)
@@ -789,10 +774,10 @@ impl ConnectorIntegration<api::RSync, types::RefundsData, types::RefundsResponse
fn handle_response(
&self,
- data: &types::RefundSyncRouterData,
+ data: &RefundSyncRouterData,
event_builder: Option<&mut ConnectorEvent>,
res: Response,
- ) -> CustomResult<types::RefundSyncRouterData, errors::ConnectorError> {
+ ) -> CustomResult<RefundSyncRouterData, errors::ConnectorError> {
let response: bambora::RefundResponse = res
.response
.parse_struct("bambora RefundResponse")
@@ -801,7 +786,7 @@ impl ConnectorIntegration<api::RSync, types::RefundsData, types::RefundsResponse
event_builder.map(|i| i.set_response_body(&response));
router_env::logger::info!(connector_response=?response);
- types::RouterData::try_from(types::ResponseRouterData {
+ RouterData::try_from(ResponseRouterData {
response,
data: data.clone(),
http_code: res.status_code,
@@ -819,24 +804,24 @@ impl ConnectorIntegration<api::RSync, types::RefundsData, types::RefundsResponse
}
#[async_trait::async_trait]
-impl api::IncomingWebhook for Bambora {
+impl webhooks::IncomingWebhook for Bambora {
fn get_webhook_object_reference_id(
&self,
- _request: &api::IncomingWebhookRequestDetails<'_>,
+ _request: &webhooks::IncomingWebhookRequestDetails<'_>,
) -> CustomResult<api_models::webhooks::ObjectReferenceId, errors::ConnectorError> {
Err(report!(errors::ConnectorError::WebhooksNotImplemented))
}
fn get_webhook_event_type(
&self,
- _request: &api::IncomingWebhookRequestDetails<'_>,
- ) -> CustomResult<api::IncomingWebhookEvent, errors::ConnectorError> {
- Ok(api::IncomingWebhookEvent::EventNotSupported)
+ _request: &webhooks::IncomingWebhookRequestDetails<'_>,
+ ) -> CustomResult<api_models::webhooks::IncomingWebhookEvent, errors::ConnectorError> {
+ Ok(api_models::webhooks::IncomingWebhookEvent::EventNotSupported)
}
fn get_webhook_resource_object(
&self,
- _request: &api::IncomingWebhookRequestDetails<'_>,
+ _request: &webhooks::IncomingWebhookRequestDetails<'_>,
) -> CustomResult<Box<dyn masking::ErasedMaskSerialize>, errors::ConnectorError> {
Err(report!(errors::ConnectorError::WebhooksNotImplemented))
}
diff --git a/crates/router/src/connector/bambora/transformers.rs b/crates/hyperswitch_connectors/src/connectors/bambora/transformers.rs
similarity index 79%
rename from crates/router/src/connector/bambora/transformers.rs
rename to crates/hyperswitch_connectors/src/connectors/bambora/transformers.rs
index b2e9b1a032e..bfa2da851f8 100644
--- a/crates/router/src/connector/bambora/transformers.rs
+++ b/crates/hyperswitch_connectors/src/connectors/bambora/transformers.rs
@@ -1,19 +1,29 @@
use base64::Engine;
+use common_enums::enums;
use common_utils::{ext_traits::ValueExt, pii::IpAddress};
use error_stack::ResultExt;
+use hyperswitch_domain_models::{
+ payment_method_data::PaymentMethodData,
+ router_data::{ConnectorAuthType, RouterData},
+ router_flow_types::refunds::{Execute, RSync},
+ router_request_types::{
+ CompleteAuthorizeData, PaymentsAuthorizeData, PaymentsCancelData, PaymentsCaptureData,
+ PaymentsSyncData, ResponseId,
+ },
+ router_response_types::{PaymentsResponseData, RedirectForm, RefundsResponseData},
+ types,
+};
+use hyperswitch_interfaces::{api, errors};
use masking::{ExposeInterface, PeekInterface, Secret};
use serde::{Deserialize, Deserializer, Serialize};
use crate::{
- connector::utils::{
- self, AddressDetailsData, BrowserInformationData, CardData as OtherCardData,
+ types::{RefundsResponseRouterData, ResponseRouterData},
+ utils::{
+ self, AddressDetailsData, BrowserInformationData, CardData as _,
PaymentsAuthorizeRequestData, PaymentsCompleteAuthorizeRequestData,
- PaymentsSyncRequestData, RouterData,
+ PaymentsSyncRequestData, RouterData as _,
},
- consts,
- core::errors,
- services,
- types::{self, api, domain, storage::enums},
};
pub struct BamboraRouterData<T> {
@@ -109,9 +119,9 @@ fn get_browser_info(
}
}
-impl TryFrom<&types::CompleteAuthorizeData> for BamboraThreedsContinueRequest {
+impl TryFrom<&CompleteAuthorizeData> for BamboraThreedsContinueRequest {
type Error = error_stack::Report<errors::ConnectorError>;
- fn try_from(value: &types::CompleteAuthorizeData) -> Result<Self, Self::Error> {
+ fn try_from(value: &CompleteAuthorizeData) -> Result<Self, Self::Error> {
let card_response: CardResponse = value
.redirect_response
.as_ref()
@@ -135,7 +145,7 @@ impl TryFrom<BamboraRouterData<&types::PaymentsAuthorizeRouterData>> for Bambora
item: BamboraRouterData<&types::PaymentsAuthorizeRouterData>,
) -> Result<Self, Self::Error> {
match item.router_data.request.payment_method_data.clone() {
- domain::PaymentMethodData::Card(req_card) => {
+ PaymentMethodData::Card(req_card) => {
let (three_ds, customer_ip) = match item.router_data.auth_type {
enums::AuthenticationType::ThreeDs => (
Some(ThreeDSecure {
@@ -172,26 +182,24 @@ impl TryFrom<BamboraRouterData<&types::PaymentsAuthorizeRouterData>> for Bambora
term_url: item.router_data.request.complete_authorize_url.clone(),
})
}
- domain::PaymentMethodData::CardRedirect(_)
- | domain::PaymentMethodData::Wallet(_)
- | domain::PaymentMethodData::PayLater(_)
- | domain::PaymentMethodData::BankRedirect(_)
- | domain::PaymentMethodData::BankDebit(_)
- | domain::PaymentMethodData::BankTransfer(_)
- | domain::PaymentMethodData::Crypto(_)
- | domain::PaymentMethodData::MandatePayment
- | domain::PaymentMethodData::Reward
- | domain::PaymentMethodData::RealTimePayment(_)
- | domain::PaymentMethodData::Upi(_)
- | domain::PaymentMethodData::Voucher(_)
- | domain::PaymentMethodData::GiftCard(_)
- | domain::PaymentMethodData::OpenBanking(_)
- | domain::PaymentMethodData::CardToken(_) => {
- Err(errors::ConnectorError::NotImplemented(
- utils::get_unimplemented_payment_method_error_message("bambora"),
- )
- .into())
- }
+ PaymentMethodData::CardRedirect(_)
+ | PaymentMethodData::Wallet(_)
+ | PaymentMethodData::PayLater(_)
+ | PaymentMethodData::BankRedirect(_)
+ | PaymentMethodData::BankDebit(_)
+ | PaymentMethodData::BankTransfer(_)
+ | PaymentMethodData::Crypto(_)
+ | PaymentMethodData::MandatePayment
+ | PaymentMethodData::Reward
+ | PaymentMethodData::RealTimePayment(_)
+ | PaymentMethodData::Upi(_)
+ | PaymentMethodData::Voucher(_)
+ | PaymentMethodData::GiftCard(_)
+ | PaymentMethodData::OpenBanking(_)
+ | PaymentMethodData::CardToken(_) => Err(errors::ConnectorError::NotImplemented(
+ utils::get_unimplemented_payment_method_error_message("bambora"),
+ )
+ .into()),
}
}
}
@@ -211,12 +219,15 @@ pub struct BamboraAuthType {
pub(super) api_key: Secret<String>,
}
-impl TryFrom<&types::ConnectorAuthType> for BamboraAuthType {
+impl TryFrom<&ConnectorAuthType> for BamboraAuthType {
type Error = error_stack::Report<errors::ConnectorError>;
- fn try_from(auth_type: &types::ConnectorAuthType) -> Result<Self, Self::Error> {
- if let types::ConnectorAuthType::BodyKey { api_key, key1 } = auth_type {
+ fn try_from(auth_type: &ConnectorAuthType) -> Result<Self, Self::Error> {
+ if let ConnectorAuthType::BodyKey { api_key, key1 } = auth_type {
let auth_key = format!("{}:{}", key1.peek(), api_key.peek());
- let auth_header = format!("Passcode {}", consts::BASE64_ENGINE.encode(auth_key));
+ let auth_header = format!(
+ "Passcode {}",
+ common_utils::consts::BASE64_ENGINE.encode(auth_key)
+ );
Ok(Self {
api_key: Secret::new(auth_header),
})
@@ -407,24 +418,12 @@ impl TryFrom<BamboraRouterData<&types::PaymentsCaptureRouterData>>
}
}
-impl<F>
- TryFrom<
- types::ResponseRouterData<
- F,
- BamboraResponse,
- types::PaymentsAuthorizeData,
- types::PaymentsResponseData,
- >,
- > for types::RouterData<F, types::PaymentsAuthorizeData, types::PaymentsResponseData>
+impl<F> TryFrom<ResponseRouterData<F, BamboraResponse, PaymentsAuthorizeData, PaymentsResponseData>>
+ for RouterData<F, PaymentsAuthorizeData, PaymentsResponseData>
{
type Error = error_stack::Report<errors::ConnectorError>;
fn try_from(
- item: types::ResponseRouterData<
- F,
- BamboraResponse,
- types::PaymentsAuthorizeData,
- types::PaymentsResponseData,
- >,
+ item: ResponseRouterData<F, BamboraResponse, PaymentsAuthorizeData, PaymentsResponseData>,
) -> Result<Self, Self::Error> {
match item.response {
BamboraResponse::NormalTransaction(pg_response) => Ok(Self {
@@ -439,10 +438,8 @@ impl<F>
false => enums::AttemptStatus::AuthorizationFailed,
}
},
- response: Ok(types::PaymentsResponseData::TransactionResponse {
- resource_id: types::ResponseId::ConnectorTransactionId(
- pg_response.id.to_string(),
- ),
+ response: Ok(PaymentsResponseData::TransactionResponse {
+ resource_id: ResponseId::ConnectorTransactionId(pg_response.id.to_string()),
redirection_data: None,
mandate_reference: None,
connector_metadata: None,
@@ -458,11 +455,11 @@ impl<F>
let value = url::form_urlencoded::parse(response.contents.as_bytes())
.map(|(key, val)| [key, val].concat())
.collect();
- let redirection_data = Some(services::RedirectForm::Html { html_data: value });
+ let redirection_data = Some(RedirectForm::Html { html_data: value });
Ok(Self {
status: enums::AttemptStatus::AuthenticationPending,
- response: Ok(types::PaymentsResponseData::TransactionResponse {
- resource_id: types::ResponseId::NoResponseId,
+ response: Ok(PaymentsResponseData::TransactionResponse {
+ resource_id: ResponseId::NoResponseId,
redirection_data,
mandate_reference: None,
connector_metadata: Some(
@@ -487,21 +484,16 @@ impl<F>
impl<F>
TryFrom<
- types::ResponseRouterData<
- F,
- BamboraPaymentsResponse,
- types::CompleteAuthorizeData,
- types::PaymentsResponseData,
- >,
- > for types::RouterData<F, types::CompleteAuthorizeData, types::PaymentsResponseData>
+ ResponseRouterData<F, BamboraPaymentsResponse, CompleteAuthorizeData, PaymentsResponseData>,
+ > for RouterData<F, CompleteAuthorizeData, PaymentsResponseData>
{
type Error = error_stack::Report<errors::ConnectorError>;
fn try_from(
- item: types::ResponseRouterData<
+ item: ResponseRouterData<
F,
BamboraPaymentsResponse,
- types::CompleteAuthorizeData,
- types::PaymentsResponseData,
+ CompleteAuthorizeData,
+ PaymentsResponseData,
>,
) -> Result<Self, Self::Error> {
Ok(Self {
@@ -516,10 +508,8 @@ impl<F>
false => enums::AttemptStatus::AuthorizationFailed,
}
},
- response: Ok(types::PaymentsResponseData::TransactionResponse {
- resource_id: types::ResponseId::ConnectorTransactionId(
- item.response.id.to_string(),
- ),
+ response: Ok(PaymentsResponseData::TransactionResponse {
+ resource_id: ResponseId::ConnectorTransactionId(item.response.id.to_string()),
redirection_data: None,
mandate_reference: None,
connector_metadata: None,
@@ -534,22 +524,16 @@ impl<F>
}
impl<F>
- TryFrom<
- types::ResponseRouterData<
- F,
- BamboraPaymentsResponse,
- types::PaymentsSyncData,
- types::PaymentsResponseData,
- >,
- > for types::RouterData<F, types::PaymentsSyncData, types::PaymentsResponseData>
+ TryFrom<ResponseRouterData<F, BamboraPaymentsResponse, PaymentsSyncData, PaymentsResponseData>>
+ for RouterData<F, PaymentsSyncData, PaymentsResponseData>
{
type Error = error_stack::Report<errors::ConnectorError>;
fn try_from(
- item: types::ResponseRouterData<
+ item: ResponseRouterData<
F,
BamboraPaymentsResponse,
- types::PaymentsSyncData,
- types::PaymentsResponseData,
+ PaymentsSyncData,
+ PaymentsResponseData,
>,
) -> Result<Self, Self::Error> {
Ok(Self {
@@ -569,10 +553,8 @@ impl<F>
}
}
},
- response: Ok(types::PaymentsResponseData::TransactionResponse {
- resource_id: types::ResponseId::ConnectorTransactionId(
- item.response.id.to_string(),
- ),
+ response: Ok(PaymentsResponseData::TransactionResponse {
+ resource_id: ResponseId::ConnectorTransactionId(item.response.id.to_string()),
redirection_data: None,
mandate_reference: None,
connector_metadata: None,
@@ -588,21 +570,16 @@ impl<F>
impl<F>
TryFrom<
- types::ResponseRouterData<
- F,
- BamboraPaymentsResponse,
- types::PaymentsCaptureData,
- types::PaymentsResponseData,
- >,
- > for types::RouterData<F, types::PaymentsCaptureData, types::PaymentsResponseData>
+ ResponseRouterData<F, BamboraPaymentsResponse, PaymentsCaptureData, PaymentsResponseData>,
+ > for RouterData<F, PaymentsCaptureData, PaymentsResponseData>
{
type Error = error_stack::Report<errors::ConnectorError>;
fn try_from(
- item: types::ResponseRouterData<
+ item: ResponseRouterData<
F,
BamboraPaymentsResponse,
- types::PaymentsCaptureData,
- types::PaymentsResponseData,
+ PaymentsCaptureData,
+ PaymentsResponseData,
>,
) -> Result<Self, Self::Error> {
Ok(Self {
@@ -611,10 +588,8 @@ impl<F>
} else {
enums::AttemptStatus::Failure
},
- response: Ok(types::PaymentsResponseData::TransactionResponse {
- resource_id: types::ResponseId::ConnectorTransactionId(
- item.response.id.to_string(),
- ),
+ response: Ok(PaymentsResponseData::TransactionResponse {
+ resource_id: ResponseId::ConnectorTransactionId(item.response.id.to_string()),
redirection_data: None,
mandate_reference: None,
connector_metadata: None,
@@ -630,21 +605,16 @@ impl<F>
impl<F>
TryFrom<
- types::ResponseRouterData<
- F,
- BamboraPaymentsResponse,
- types::PaymentsCancelData,
- types::PaymentsResponseData,
- >,
- > for types::RouterData<F, types::PaymentsCancelData, types::PaymentsResponseData>
+ ResponseRouterData<F, BamboraPaymentsResponse, PaymentsCancelData, PaymentsResponseData>,
+ > for RouterData<F, PaymentsCancelData, PaymentsResponseData>
{
type Error = error_stack::Report<errors::ConnectorError>;
fn try_from(
- item: types::ResponseRouterData<
+ item: ResponseRouterData<
F,
BamboraPaymentsResponse,
- types::PaymentsCancelData,
- types::PaymentsResponseData,
+ PaymentsCancelData,
+ PaymentsResponseData,
>,
) -> Result<Self, Self::Error> {
Ok(Self {
@@ -653,10 +623,8 @@ impl<F>
} else {
enums::AttemptStatus::VoidFailed
},
- response: Ok(types::PaymentsResponseData::TransactionResponse {
- resource_id: types::ResponseId::ConnectorTransactionId(
- item.response.id.to_string(),
- ),
+ response: Ok(PaymentsResponseData::TransactionResponse {
+ resource_id: ResponseId::ConnectorTransactionId(item.response.id.to_string()),
redirection_data: None,
mandate_reference: None,
connector_metadata: None,
@@ -738,12 +706,12 @@ pub struct RefundResponse {
pub risk_score: Option<f32>,
}
-impl TryFrom<types::RefundsResponseRouterData<api::Execute, RefundResponse>>
- for types::RefundsRouterData<api::Execute>
+impl TryFrom<RefundsResponseRouterData<Execute, RefundResponse>>
+ for types::RefundsRouterData<Execute>
{
type Error = error_stack::Report<errors::ConnectorError>;
fn try_from(
- item: types::RefundsResponseRouterData<api::Execute, RefundResponse>,
+ item: RefundsResponseRouterData<Execute, RefundResponse>,
) -> Result<Self, Self::Error> {
let refund_status = if item.response.approved.as_str() == "1" {
enums::RefundStatus::Success
@@ -751,7 +719,7 @@ impl TryFrom<types::RefundsResponseRouterData<api::Execute, RefundResponse>>
enums::RefundStatus::Failure
};
Ok(Self {
- response: Ok(types::RefundsResponseData {
+ response: Ok(RefundsResponseData {
connector_refund_id: item.response.id.to_string(),
refund_status,
}),
@@ -760,12 +728,10 @@ impl TryFrom<types::RefundsResponseRouterData<api::Execute, RefundResponse>>
}
}
-impl TryFrom<types::RefundsResponseRouterData<api::RSync, RefundResponse>>
- for types::RefundsRouterData<api::RSync>
-{
+impl TryFrom<RefundsResponseRouterData<RSync, RefundResponse>> for types::RefundsRouterData<RSync> {
type Error = error_stack::Report<errors::ConnectorError>;
fn try_from(
- item: types::RefundsResponseRouterData<api::RSync, RefundResponse>,
+ item: RefundsResponseRouterData<RSync, RefundResponse>,
) -> Result<Self, Self::Error> {
let refund_status = if item.response.approved.as_str() == "1" {
enums::RefundStatus::Success
@@ -773,7 +739,7 @@ impl TryFrom<types::RefundsResponseRouterData<api::RSync, RefundResponse>>
enums::RefundStatus::Failure
};
Ok(Self {
- response: Ok(types::RefundsResponseData {
+ response: Ok(RefundsResponseData {
connector_refund_id: item.response.id.to_string(),
refund_status,
}),
diff --git a/crates/router/src/connector/bitpay.rs b/crates/hyperswitch_connectors/src/connectors/bitpay.rs
similarity index 61%
rename from crates/router/src/connector/bitpay.rs
rename to crates/hyperswitch_connectors/src/connectors/bitpay.rs
index 445324dee3f..032b8cf051f 100644
--- a/crates/router/src/connector/bitpay.rs
+++ b/crates/hyperswitch_connectors/src/connectors/bitpay.rs
@@ -1,35 +1,44 @@
pub mod transformers;
+use api_models::webhooks::IncomingWebhookEvent;
use common_utils::{
- errors::ReportSwitchExt,
+ errors::{CustomResult, ReportSwitchExt},
ext_traits::ByteSliceExt,
- request::RequestContent,
+ request::{Method, Request, RequestBuilder, RequestContent},
types::{AmountConvertor, MinorUnit, MinorUnitForConnector},
};
use error_stack::ResultExt;
-use masking::PeekInterface;
-use transformers as bitpay;
-
-use self::bitpay::BitpayWebhookDetails;
-use super::utils as connector_utils;
-use crate::{
- configs::settings,
- consts,
- core::errors::{self, CustomResult},
- events::connector_api_logs::ConnectorEvent,
- headers,
- services::{
- self,
- request::{self, Mask},
- ConnectorIntegration, ConnectorValidation,
+use hyperswitch_domain_models::{
+ router_data::{AccessToken, ConnectorAuthType, ErrorResponse, RouterData},
+ router_flow_types::{
+ access_token_auth::AccessTokenAuth,
+ payments::{Authorize, Capture, PSync, PaymentMethodToken, Session, SetupMandate, Void},
+ refunds::{Execute, RSync},
},
+ router_request_types::{
+ AccessTokenRequestData, PaymentMethodTokenizationData, PaymentsAuthorizeData,
+ PaymentsCancelData, PaymentsCaptureData, PaymentsSessionData, PaymentsSyncData,
+ RefundsData, SetupMandateRequestData,
+ },
+ router_response_types::{PaymentsResponseData, RefundsResponseData},
types::{
- self,
- api::{self, ConnectorCommon, ConnectorCommonExt},
- ErrorResponse, Response,
+ PaymentsAuthorizeRouterData, PaymentsCaptureRouterData, PaymentsSyncRouterData,
+ RefundsRouterData,
},
- utils::BytesExt,
};
+use hyperswitch_interfaces::{
+ api::{self, ConnectorCommon, ConnectorCommonExt, ConnectorIntegration, ConnectorValidation},
+ configs::Connectors,
+ consts, errors,
+ events::connector_api_logs::ConnectorEvent,
+ types::{PaymentsAuthorizeType, PaymentsSyncType, Response},
+ webhooks,
+};
+use masking::{Mask, PeekInterface};
+use transformers as bitpay;
+
+use self::bitpay::BitpayWebhookDetails;
+use crate::{constants::headers, types::ResponseRouterData, utils};
#[derive(Clone)]
pub struct Bitpay {
@@ -57,12 +66,8 @@ impl api::Refund for Bitpay {}
impl api::RefundExecute for Bitpay {}
impl api::RefundSync for Bitpay {}
-impl
- ConnectorIntegration<
- api::PaymentMethodToken,
- types::PaymentMethodTokenizationData,
- types::PaymentsResponseData,
- > for Bitpay
+impl ConnectorIntegration<PaymentMethodToken, PaymentMethodTokenizationData, PaymentsResponseData>
+ for Bitpay
{
// Not Implemented (R)
}
@@ -73,13 +78,13 @@ where
{
fn build_headers(
&self,
- _req: &types::RouterData<Flow, Request, Response>,
- _connectors: &settings::Connectors,
- ) -> CustomResult<Vec<(String, request::Maskable<String>)>, errors::ConnectorError> {
+ _req: &RouterData<Flow, Request, Response>,
+ _connectors: &Connectors,
+ ) -> CustomResult<Vec<(String, masking::Maskable<String>)>, errors::ConnectorError> {
let header = vec![
(
headers::CONTENT_TYPE.to_string(),
- types::PaymentsAuthorizeType::get_content_type(self)
+ PaymentsAuthorizeType::get_content_type(self)
.to_string()
.into(),
),
@@ -105,14 +110,14 @@ impl ConnectorCommon for Bitpay {
"application/json"
}
- fn base_url<'a>(&self, connectors: &'a settings::Connectors) -> &'a str {
+ fn base_url<'a>(&self, connectors: &'a Connectors) -> &'a str {
connectors.bitpay.base_url.as_ref()
}
fn get_auth_header(
&self,
- auth_type: &types::ConnectorAuthType,
- ) -> CustomResult<Vec<(String, request::Maskable<String>)>, errors::ConnectorError> {
+ auth_type: &ConnectorAuthType,
+ ) -> CustomResult<Vec<(String, masking::Maskable<String>)>, errors::ConnectorError> {
let auth = bitpay::BitpayAuthType::try_from(auth_type)
.change_context(errors::ConnectorError::FailedToObtainAuthType)?;
Ok(vec![(
@@ -147,33 +152,18 @@ impl ConnectorCommon for Bitpay {
impl ConnectorValidation for Bitpay {}
-impl ConnectorIntegration<api::Session, types::PaymentsSessionData, types::PaymentsResponseData>
- for Bitpay
-{
+impl ConnectorIntegration<Session, PaymentsSessionData, PaymentsResponseData> for Bitpay {
//TODO: implement sessions flow
}
-impl ConnectorIntegration<api::AccessTokenAuth, types::AccessTokenRequestData, types::AccessToken>
- for Bitpay
-{
-}
+impl ConnectorIntegration<AccessTokenAuth, AccessTokenRequestData, AccessToken> for Bitpay {}
-impl
- ConnectorIntegration<
- api::SetupMandate,
- types::SetupMandateRequestData,
- types::PaymentsResponseData,
- > for Bitpay
-{
+impl ConnectorIntegration<SetupMandate, SetupMandateRequestData, PaymentsResponseData> for Bitpay {
fn build_request(
&self,
- _req: &types::RouterData<
- api::SetupMandate,
- types::SetupMandateRequestData,
- types::PaymentsResponseData,
- >,
- _connectors: &settings::Connectors,
- ) -> CustomResult<Option<services::Request>, errors::ConnectorError> {
+ _req: &RouterData<SetupMandate, SetupMandateRequestData, PaymentsResponseData>,
+ _connectors: &Connectors,
+ ) -> CustomResult<Option<Request>, errors::ConnectorError> {
Err(
errors::ConnectorError::NotImplemented("Setup Mandate flow for Bitpay".to_string())
.into(),
@@ -181,14 +171,12 @@ impl
}
}
-impl ConnectorIntegration<api::Authorize, types::PaymentsAuthorizeData, types::PaymentsResponseData>
- for Bitpay
-{
+impl ConnectorIntegration<Authorize, PaymentsAuthorizeData, PaymentsResponseData> for Bitpay {
fn get_headers(
&self,
- req: &types::PaymentsAuthorizeRouterData,
- connectors: &settings::Connectors,
- ) -> CustomResult<Vec<(String, request::Maskable<String>)>, errors::ConnectorError> {
+ req: &PaymentsAuthorizeRouterData,
+ connectors: &Connectors,
+ ) -> CustomResult<Vec<(String, masking::Maskable<String>)>, errors::ConnectorError> {
self.build_headers(req, connectors)
}
@@ -198,18 +186,18 @@ impl ConnectorIntegration<api::Authorize, types::PaymentsAuthorizeData, types::P
fn get_url(
&self,
- _req: &types::PaymentsAuthorizeRouterData,
- connectors: &settings::Connectors,
+ _req: &PaymentsAuthorizeRouterData,
+ connectors: &Connectors,
) -> CustomResult<String, errors::ConnectorError> {
Ok(format!("{}/invoices", self.base_url(connectors)))
}
fn get_request_body(
&self,
- req: &types::PaymentsAuthorizeRouterData,
- _connectors: &settings::Connectors,
+ req: &PaymentsAuthorizeRouterData,
+ _connectors: &Connectors,
) -> CustomResult<RequestContent, errors::ConnectorError> {
- let amount = connector_utils::convert_amount(
+ let amount = utils::convert_amount(
self.amount_converter,
req.request.minor_amount,
req.request.currency,
@@ -223,20 +211,16 @@ impl ConnectorIntegration<api::Authorize, types::PaymentsAuthorizeData, types::P
fn build_request(
&self,
- req: &types::PaymentsAuthorizeRouterData,
- connectors: &settings::Connectors,
- ) -> CustomResult<Option<services::Request>, errors::ConnectorError> {
+ req: &PaymentsAuthorizeRouterData,
+ connectors: &Connectors,
+ ) -> CustomResult<Option<Request>, errors::ConnectorError> {
Ok(Some(
- services::RequestBuilder::new()
- .method(services::Method::Post)
- .url(&types::PaymentsAuthorizeType::get_url(
- self, req, connectors,
- )?)
+ RequestBuilder::new()
+ .method(Method::Post)
+ .url(&PaymentsAuthorizeType::get_url(self, req, connectors)?)
.attach_default_headers()
- .headers(types::PaymentsAuthorizeType::get_headers(
- self, req, connectors,
- )?)
- .set_body(types::PaymentsAuthorizeType::get_request_body(
+ .headers(PaymentsAuthorizeType::get_headers(self, req, connectors)?)
+ .set_body(PaymentsAuthorizeType::get_request_body(
self, req, connectors,
)?)
.build(),
@@ -245,17 +229,17 @@ impl ConnectorIntegration<api::Authorize, types::PaymentsAuthorizeData, types::P
fn handle_response(
&self,
- data: &types::PaymentsAuthorizeRouterData,
+ data: &PaymentsAuthorizeRouterData,
event_builder: Option<&mut ConnectorEvent>,
res: Response,
- ) -> CustomResult<types::PaymentsAuthorizeRouterData, errors::ConnectorError> {
+ ) -> CustomResult<PaymentsAuthorizeRouterData, errors::ConnectorError> {
let response: bitpay::BitpayPaymentsResponse = res
.response
.parse_struct("Bitpay PaymentsAuthorizeResponse")
.switch()?;
event_builder.map(|i| i.set_response_body(&response));
router_env::logger::info!(connector_response=?response);
- types::RouterData::try_from(types::ResponseRouterData {
+ RouterData::try_from(ResponseRouterData {
response,
data: data.clone(),
http_code: res.status_code,
@@ -271,14 +255,12 @@ impl ConnectorIntegration<api::Authorize, types::PaymentsAuthorizeData, types::P
}
}
-impl ConnectorIntegration<api::PSync, types::PaymentsSyncData, types::PaymentsResponseData>
- for Bitpay
-{
+impl ConnectorIntegration<PSync, PaymentsSyncData, PaymentsResponseData> for Bitpay {
fn get_headers(
&self,
- req: &types::PaymentsSyncRouterData,
- connectors: &settings::Connectors,
- ) -> CustomResult<Vec<(String, request::Maskable<String>)>, errors::ConnectorError> {
+ req: &PaymentsSyncRouterData,
+ connectors: &Connectors,
+ ) -> CustomResult<Vec<(String, masking::Maskable<String>)>, errors::ConnectorError> {
self.build_headers(req, connectors)
}
@@ -288,8 +270,8 @@ impl ConnectorIntegration<api::PSync, types::PaymentsSyncData, types::PaymentsRe
fn get_url(
&self,
- req: &types::PaymentsSyncRouterData,
- connectors: &settings::Connectors,
+ req: &PaymentsSyncRouterData,
+ connectors: &Connectors,
) -> CustomResult<String, errors::ConnectorError> {
let auth = bitpay::BitpayAuthType::try_from(&req.connector_auth_type)
.change_context(errors::ConnectorError::FailedToObtainAuthType)?;
@@ -308,32 +290,32 @@ impl ConnectorIntegration<api::PSync, types::PaymentsSyncData, types::PaymentsRe
fn build_request(
&self,
- req: &types::PaymentsSyncRouterData,
- connectors: &settings::Connectors,
- ) -> CustomResult<Option<services::Request>, errors::ConnectorError> {
+ req: &PaymentsSyncRouterData,
+ connectors: &Connectors,
+ ) -> CustomResult<Option<Request>, errors::ConnectorError> {
Ok(Some(
- services::RequestBuilder::new()
- .method(services::Method::Get)
- .url(&types::PaymentsSyncType::get_url(self, req, connectors)?)
+ RequestBuilder::new()
+ .method(Method::Get)
+ .url(&PaymentsSyncType::get_url(self, req, connectors)?)
.attach_default_headers()
- .headers(types::PaymentsSyncType::get_headers(self, req, connectors)?)
+ .headers(PaymentsSyncType::get_headers(self, req, connectors)?)
.build(),
))
}
fn handle_response(
&self,
- data: &types::PaymentsSyncRouterData,
+ data: &PaymentsSyncRouterData,
event_builder: Option<&mut ConnectorEvent>,
res: Response,
- ) -> CustomResult<types::PaymentsSyncRouterData, errors::ConnectorError> {
+ ) -> CustomResult<PaymentsSyncRouterData, errors::ConnectorError> {
let response: bitpay::BitpayPaymentsResponse = res
.response
.parse_struct("bitpay PaymentsSyncResponse")
.switch()?;
event_builder.map(|i| i.set_response_body(&response));
router_env::logger::info!(connector_response=?response);
- types::RouterData::try_from(types::ResponseRouterData {
+ RouterData::try_from(ResponseRouterData {
response,
data: data.clone(),
http_code: res.status_code,
@@ -349,14 +331,12 @@ impl ConnectorIntegration<api::PSync, types::PaymentsSyncData, types::PaymentsRe
}
}
-impl ConnectorIntegration<api::Capture, types::PaymentsCaptureData, types::PaymentsResponseData>
- for Bitpay
-{
+impl ConnectorIntegration<Capture, PaymentsCaptureData, PaymentsResponseData> for Bitpay {
fn build_request(
&self,
- _req: &types::PaymentsCaptureRouterData,
- _connectors: &settings::Connectors,
- ) -> CustomResult<Option<services::Request>, errors::ConnectorError> {
+ _req: &PaymentsCaptureRouterData,
+ _connectors: &Connectors,
+ ) -> CustomResult<Option<Request>, errors::ConnectorError> {
Err(errors::ConnectorError::FlowNotSupported {
flow: "Capture".to_string(),
connector: "Bitpay".to_string(),
@@ -365,17 +345,14 @@ impl ConnectorIntegration<api::Capture, types::PaymentsCaptureData, types::Payme
}
}
-impl ConnectorIntegration<api::Void, types::PaymentsCancelData, types::PaymentsResponseData>
- for Bitpay
-{
-}
+impl ConnectorIntegration<Void, PaymentsCancelData, PaymentsResponseData> for Bitpay {}
-impl ConnectorIntegration<api::Execute, types::RefundsData, types::RefundsResponseData> for Bitpay {
+impl ConnectorIntegration<Execute, RefundsData, RefundsResponseData> for Bitpay {
fn build_request(
&self,
- _req: &types::RefundsRouterData<api::Execute>,
- _connectors: &settings::Connectors,
- ) -> CustomResult<Option<services::Request>, errors::ConnectorError> {
+ _req: &RefundsRouterData<Execute>,
+ _connectors: &Connectors,
+ ) -> CustomResult<Option<Request>, errors::ConnectorError> {
Err(
errors::ConnectorError::NotImplemented("Refund flow not Implemented".to_string())
.into(),
@@ -383,16 +360,16 @@ impl ConnectorIntegration<api::Execute, types::RefundsData, types::RefundsRespon
}
}
-impl ConnectorIntegration<api::RSync, types::RefundsData, types::RefundsResponseData> for Bitpay {
+impl ConnectorIntegration<RSync, RefundsData, RefundsResponseData> for Bitpay {
// default implementation of build_request method will be executed
}
#[async_trait::async_trait]
-impl api::IncomingWebhook for Bitpay {
+impl webhooks::IncomingWebhook for Bitpay {
fn get_webhook_object_reference_id(
&self,
- request: &api::IncomingWebhookRequestDetails<'_>,
- ) -> CustomResult<api::webhooks::ObjectReferenceId, errors::ConnectorError> {
+ request: &webhooks::IncomingWebhookRequestDetails<'_>,
+ ) -> CustomResult<api_models::webhooks::ObjectReferenceId, errors::ConnectorError> {
let notif: BitpayWebhookDetails = request
.body
.parse_struct("BitpayWebhookDetails")
@@ -404,33 +381,29 @@ impl api::IncomingWebhook for Bitpay {
fn get_webhook_event_type(
&self,
- request: &api::IncomingWebhookRequestDetails<'_>,
- ) -> CustomResult<api::IncomingWebhookEvent, errors::ConnectorError> {
+ request: &webhooks::IncomingWebhookRequestDetails<'_>,
+ ) -> CustomResult<IncomingWebhookEvent, errors::ConnectorError> {
let notif: BitpayWebhookDetails = request
.body
.parse_struct("BitpayWebhookDetails")
.change_context(errors::ConnectorError::WebhookEventTypeNotFound)?;
match notif.event.name {
bitpay::WebhookEventType::Confirmed | bitpay::WebhookEventType::Completed => {
- Ok(api::IncomingWebhookEvent::PaymentIntentSuccess)
- }
- bitpay::WebhookEventType::Paid => {
- Ok(api::IncomingWebhookEvent::PaymentIntentProcessing)
- }
- bitpay::WebhookEventType::Declined => {
- Ok(api::IncomingWebhookEvent::PaymentIntentFailure)
+ Ok(IncomingWebhookEvent::PaymentIntentSuccess)
}
+ bitpay::WebhookEventType::Paid => Ok(IncomingWebhookEvent::PaymentIntentProcessing),
+ bitpay::WebhookEventType::Declined => Ok(IncomingWebhookEvent::PaymentIntentFailure),
bitpay::WebhookEventType::Unknown
| bitpay::WebhookEventType::Expired
| bitpay::WebhookEventType::Invalid
| bitpay::WebhookEventType::Refunded
- | bitpay::WebhookEventType::Resent => Ok(api::IncomingWebhookEvent::EventNotSupported),
+ | bitpay::WebhookEventType::Resent => Ok(IncomingWebhookEvent::EventNotSupported),
}
}
fn get_webhook_resource_object(
&self,
- request: &api::IncomingWebhookRequestDetails<'_>,
+ request: &webhooks::IncomingWebhookRequestDetails<'_>,
) -> CustomResult<Box<dyn masking::ErasedMaskSerialize>, errors::ConnectorError> {
let notif: BitpayWebhookDetails = request
.body
diff --git a/crates/router/src/connector/bitpay/transformers.rs b/crates/hyperswitch_connectors/src/connectors/bitpay/transformers.rs
similarity index 85%
rename from crates/router/src/connector/bitpay/transformers.rs
rename to crates/hyperswitch_connectors/src/connectors/bitpay/transformers.rs
index ffce669dcaf..1c42bfd08c8 100644
--- a/crates/router/src/connector/bitpay/transformers.rs
+++ b/crates/hyperswitch_connectors/src/connectors/bitpay/transformers.rs
@@ -1,13 +1,19 @@
-use common_utils::types::MinorUnit;
+use common_enums::enums;
+use common_utils::{request::Method, types::MinorUnit};
+use hyperswitch_domain_models::{
+ router_data::{ConnectorAuthType, RouterData},
+ router_flow_types::refunds::{Execute, RSync},
+ router_request_types::ResponseId,
+ router_response_types::{PaymentsResponseData, RedirectForm, RefundsResponseData},
+ types,
+};
+use hyperswitch_interfaces::errors;
use masking::Secret;
-use reqwest::Url;
use serde::{Deserialize, Serialize};
use crate::{
- connector::utils::PaymentsAuthorizeRequestData,
- core::errors,
- services,
- types::{self, api, storage::enums, ConnectorAuthType},
+ types::{RefundsResponseRouterData, ResponseRouterData},
+ utils::PaymentsAuthorizeRequestData,
};
#[derive(Debug, Serialize)]
@@ -109,7 +115,7 @@ pub enum ExceptionStatus {
#[derive(Default, Debug, Clone, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct BitpayPaymentResponseData {
- pub url: Option<Url>,
+ pub url: Option<url::Url>,
pub status: BitpayPaymentStatus,
pub price: MinorUnit,
pub currency: String,
@@ -135,24 +141,23 @@ pub struct BitpayPaymentsResponse {
facade: Option<String>,
}
-impl<F, T>
- TryFrom<types::ResponseRouterData<F, BitpayPaymentsResponse, T, types::PaymentsResponseData>>
- for types::RouterData<F, T, types::PaymentsResponseData>
+impl<F, T> TryFrom<ResponseRouterData<F, BitpayPaymentsResponse, T, PaymentsResponseData>>
+ for RouterData<F, T, PaymentsResponseData>
{
type Error = error_stack::Report<errors::ConnectorError>;
fn try_from(
- item: types::ResponseRouterData<F, BitpayPaymentsResponse, T, types::PaymentsResponseData>,
+ item: ResponseRouterData<F, BitpayPaymentsResponse, T, PaymentsResponseData>,
) -> Result<Self, Self::Error> {
let redirection_data = item
.response
.data
.url
- .map(|x| services::RedirectForm::from((x, services::Method::Get)));
- let connector_id = types::ResponseId::ConnectorTransactionId(item.response.data.id.clone());
+ .map(|x| RedirectForm::from((x, Method::Get)));
+ let connector_id = ResponseId::ConnectorTransactionId(item.response.data.id.clone());
let attempt_status = item.response.data.status;
Ok(Self {
status: enums::AttemptStatus::from(attempt_status),
- response: Ok(types::PaymentsResponseData::TransactionResponse {
+ response: Ok(PaymentsResponseData::TransactionResponse {
resource_id: connector_id,
redirection_data,
mandate_reference: None,
@@ -218,15 +223,15 @@ pub struct RefundResponse {
status: RefundStatus,
}
-impl TryFrom<types::RefundsResponseRouterData<api::Execute, RefundResponse>>
- for types::RefundsRouterData<api::Execute>
+impl TryFrom<RefundsResponseRouterData<Execute, RefundResponse>>
+ for types::RefundsRouterData<Execute>
{
type Error = error_stack::Report<errors::ConnectorError>;
fn try_from(
- item: types::RefundsResponseRouterData<api::Execute, RefundResponse>,
+ item: RefundsResponseRouterData<Execute, RefundResponse>,
) -> Result<Self, Self::Error> {
Ok(Self {
- response: Ok(types::RefundsResponseData {
+ response: Ok(RefundsResponseData {
connector_refund_id: item.response.id.to_string(),
refund_status: enums::RefundStatus::from(item.response.status),
}),
@@ -235,15 +240,13 @@ impl TryFrom<types::RefundsResponseRouterData<api::Execute, RefundResponse>>
}
}
-impl TryFrom<types::RefundsResponseRouterData<api::RSync, RefundResponse>>
- for types::RefundsRouterData<api::RSync>
-{
+impl TryFrom<RefundsResponseRouterData<RSync, RefundResponse>> for types::RefundsRouterData<RSync> {
type Error = error_stack::Report<errors::ConnectorError>;
fn try_from(
- item: types::RefundsResponseRouterData<api::RSync, RefundResponse>,
+ item: RefundsResponseRouterData<RSync, RefundResponse>,
) -> Result<Self, Self::Error> {
Ok(Self {
- response: Ok(types::RefundsResponseData {
+ response: Ok(RefundsResponseData {
connector_refund_id: item.response.id.to_string(),
refund_status: enums::RefundStatus::from(item.response.status),
}),
diff --git a/crates/router/src/connector/stax.rs b/crates/hyperswitch_connectors/src/connectors/stax.rs
similarity index 69%
rename from crates/router/src/connector/stax.rs
rename to crates/hyperswitch_connectors/src/connectors/stax.rs
index 8524a19309d..8ca847327a4 100644
--- a/crates/router/src/connector/stax.rs
+++ b/crates/hyperswitch_connectors/src/connectors/stax.rs
@@ -2,33 +2,53 @@ pub mod transformers;
use std::fmt::Debug;
-use common_utils::{ext_traits::ByteSliceExt, request::RequestContent};
-use diesel_models::enums;
+use api_models::webhooks::IncomingWebhookEvent;
+use common_enums::enums;
+use common_utils::{
+ errors::CustomResult,
+ ext_traits::ByteSliceExt,
+ request::{Method, Request, RequestBuilder, RequestContent},
+};
use error_stack::ResultExt;
-use masking::{PeekInterface, Secret};
-use transformers as stax;
-
-use self::stax::StaxWebhookEventType;
-use super::utils::{self as connector_utils, to_connector_meta, RefundsRequestData};
-use crate::{
- configs::settings,
- consts,
- core::errors::{self, CustomResult},
- events::connector_api_logs::ConnectorEvent,
- headers,
- services::{
- self,
- request::{self, Mask},
- ConnectorIntegration, ConnectorValidation,
+use hyperswitch_domain_models::{
+ router_data::{AccessToken, ConnectorAuthType, ErrorResponse, RouterData},
+ router_flow_types::{
+ access_token_auth::AccessTokenAuth,
+ payments::{
+ Authorize, Capture, CreateConnectorCustomer, PSync, PaymentMethodToken, Session,
+ SetupMandate, Void,
+ },
+ refunds::{Execute, RSync},
},
+ router_request_types::{
+ AccessTokenRequestData, ConnectorCustomerData, PaymentMethodTokenizationData,
+ PaymentsAuthorizeData, PaymentsCancelData, PaymentsCaptureData, PaymentsSessionData,
+ PaymentsSyncData, RefundsData, SetupMandateRequestData,
+ },
+ router_response_types::{PaymentsResponseData, RefundsResponseData},
types::{
- self,
- api::{self, ConnectorCommon, ConnectorCommonExt},
- ErrorResponse, Response,
+ ConnectorCustomerRouterData, PaymentsAuthorizeRouterData, PaymentsCancelRouterData,
+ PaymentsCaptureRouterData, PaymentsSyncRouterData, RefundSyncRouterData, RefundsRouterData,
+ TokenizationRouterData,
},
- utils::BytesExt,
};
+use hyperswitch_interfaces::{
+ api::{self, ConnectorCommon, ConnectorCommonExt, ConnectorIntegration, ConnectorValidation},
+ configs::Connectors,
+ consts, errors,
+ events::connector_api_logs::ConnectorEvent,
+ types::{self, Response},
+ webhooks,
+};
+use masking::{Mask, PeekInterface, Secret};
+use transformers as stax;
+use self::stax::StaxWebhookEventType;
+use crate::{
+ constants::headers,
+ types::ResponseRouterData,
+ utils::{self, RefundsRequestData},
+};
#[derive(Debug, Clone)]
pub struct Stax;
@@ -51,9 +71,9 @@ where
{
fn build_headers(
&self,
- req: &types::RouterData<Flow, Request, Response>,
- _connectors: &settings::Connectors,
- ) -> CustomResult<Vec<(String, request::Maskable<String>)>, errors::ConnectorError> {
+ req: &RouterData<Flow, Request, Response>,
+ _connectors: &Connectors,
+ ) -> CustomResult<Vec<(String, masking::Maskable<String>)>, errors::ConnectorError> {
let mut header = vec![(
headers::CONTENT_TYPE.to_string(),
types::PaymentsAuthorizeType::get_content_type(self)
@@ -79,14 +99,14 @@ impl ConnectorCommon for Stax {
"application/json"
}
- fn base_url<'a>(&self, connectors: &'a settings::Connectors) -> &'a str {
+ fn base_url<'a>(&self, connectors: &'a Connectors) -> &'a str {
connectors.stax.base_url.as_ref()
}
fn get_auth_header(
&self,
- auth_type: &types::ConnectorAuthType,
- ) -> CustomResult<Vec<(String, request::Maskable<String>)>, errors::ConnectorError> {
+ auth_type: &ConnectorAuthType,
+ ) -> CustomResult<Vec<(String, masking::Maskable<String>)>, errors::ConnectorError> {
let auth = stax::StaxAuthType::try_from(auth_type)
.change_context(errors::ConnectorError::FailedToObtainAuthType)?;
@@ -126,7 +146,7 @@ impl ConnectorValidation for Stax {
match capture_method {
enums::CaptureMethod::Automatic | enums::CaptureMethod::Manual => Ok(()),
enums::CaptureMethod::ManualMultiple | enums::CaptureMethod::Scheduled => Err(
- connector_utils::construct_not_supported_error_report(capture_method, self.id()),
+ utils::construct_not_supported_error_report(capture_method, self.id()),
),
}
}
@@ -134,18 +154,14 @@ impl ConnectorValidation for Stax {
impl api::ConnectorCustomer for Stax {}
-impl
- ConnectorIntegration<
- api::CreateConnectorCustomer,
- types::ConnectorCustomerData,
- types::PaymentsResponseData,
- > for Stax
+impl ConnectorIntegration<CreateConnectorCustomer, ConnectorCustomerData, PaymentsResponseData>
+ for Stax
{
fn get_headers(
&self,
- req: &types::ConnectorCustomerRouterData,
- connectors: &settings::Connectors,
- ) -> CustomResult<Vec<(String, request::Maskable<String>)>, errors::ConnectorError> {
+ req: &ConnectorCustomerRouterData,
+ connectors: &Connectors,
+ ) -> CustomResult<Vec<(String, masking::Maskable<String>)>, errors::ConnectorError> {
self.build_headers(req, connectors)
}
@@ -155,16 +171,16 @@ impl
fn get_url(
&self,
- _req: &types::ConnectorCustomerRouterData,
- connectors: &settings::Connectors,
+ _req: &ConnectorCustomerRouterData,
+ connectors: &Connectors,
) -> CustomResult<String, errors::ConnectorError> {
Ok(format!("{}customer", self.base_url(connectors),))
}
fn get_request_body(
&self,
- req: &types::ConnectorCustomerRouterData,
- _connectors: &settings::Connectors,
+ req: &ConnectorCustomerRouterData,
+ _connectors: &Connectors,
) -> CustomResult<RequestContent, errors::ConnectorError> {
let connector_req = stax::StaxCustomerRequest::try_from(req)?;
@@ -173,12 +189,12 @@ impl
fn build_request(
&self,
- req: &types::ConnectorCustomerRouterData,
- connectors: &settings::Connectors,
- ) -> CustomResult<Option<services::Request>, errors::ConnectorError> {
+ req: &ConnectorCustomerRouterData,
+ connectors: &Connectors,
+ ) -> CustomResult<Option<Request>, errors::ConnectorError> {
Ok(Some(
- services::RequestBuilder::new()
- .method(services::Method::Post)
+ RequestBuilder::new()
+ .method(Method::Post)
.url(&types::ConnectorCustomerType::get_url(
self, req, connectors,
)?)
@@ -195,12 +211,12 @@ impl
fn handle_response(
&self,
- data: &types::ConnectorCustomerRouterData,
+ data: &ConnectorCustomerRouterData,
event_builder: Option<&mut ConnectorEvent>,
res: Response,
- ) -> CustomResult<types::ConnectorCustomerRouterData, errors::ConnectorError>
+ ) -> CustomResult<ConnectorCustomerRouterData, errors::ConnectorError>
where
- types::PaymentsResponseData: Clone,
+ PaymentsResponseData: Clone,
{
let response: stax::StaxCustomerResponse = res
.response
@@ -210,7 +226,7 @@ impl
event_builder.map(|i| i.set_response_body(&response));
router_env::logger::info!(connector_response=?response);
- types::RouterData::try_from(types::ResponseRouterData {
+ RouterData::try_from(ResponseRouterData {
response,
data: data.clone(),
http_code: res.status_code,
@@ -226,18 +242,14 @@ impl
}
}
-impl
- ConnectorIntegration<
- api::PaymentMethodToken,
- types::PaymentMethodTokenizationData,
- types::PaymentsResponseData,
- > for Stax
+impl ConnectorIntegration<PaymentMethodToken, PaymentMethodTokenizationData, PaymentsResponseData>
+ for Stax
{
fn get_headers(
&self,
- req: &types::TokenizationRouterData,
- connectors: &settings::Connectors,
- ) -> CustomResult<Vec<(String, request::Maskable<String>)>, errors::ConnectorError> {
+ req: &TokenizationRouterData,
+ connectors: &Connectors,
+ ) -> CustomResult<Vec<(String, masking::Maskable<String>)>, errors::ConnectorError> {
self.build_headers(req, connectors)
}
@@ -247,16 +259,16 @@ impl
fn get_url(
&self,
- _req: &types::TokenizationRouterData,
- connectors: &settings::Connectors,
+ _req: &TokenizationRouterData,
+ connectors: &Connectors,
) -> CustomResult<String, errors::ConnectorError> {
Ok(format!("{}payment-method/", self.base_url(connectors)))
}
fn get_request_body(
&self,
- req: &types::TokenizationRouterData,
- _connectors: &settings::Connectors,
+ req: &TokenizationRouterData,
+ _connectors: &Connectors,
) -> CustomResult<RequestContent, errors::ConnectorError> {
let connector_req = stax::StaxTokenRequest::try_from(req)?;
@@ -265,12 +277,12 @@ impl
fn build_request(
&self,
- req: &types::TokenizationRouterData,
- connectors: &settings::Connectors,
- ) -> CustomResult<Option<services::Request>, errors::ConnectorError> {
+ req: &TokenizationRouterData,
+ connectors: &Connectors,
+ ) -> CustomResult<Option<Request>, errors::ConnectorError> {
Ok(Some(
- services::RequestBuilder::new()
- .method(services::Method::Post)
+ RequestBuilder::new()
+ .method(Method::Post)
.url(&types::TokenizationType::get_url(self, req, connectors)?)
.attach_default_headers()
.headers(types::TokenizationType::get_headers(self, req, connectors)?)
@@ -283,12 +295,12 @@ impl
fn handle_response(
&self,
- data: &types::TokenizationRouterData,
+ data: &TokenizationRouterData,
event_builder: Option<&mut ConnectorEvent>,
res: Response,
- ) -> CustomResult<types::TokenizationRouterData, errors::ConnectorError>
+ ) -> CustomResult<TokenizationRouterData, errors::ConnectorError>
where
- types::PaymentsResponseData: Clone,
+ PaymentsResponseData: Clone,
{
let response: stax::StaxTokenResponse = res
.response
@@ -298,7 +310,7 @@ impl
event_builder.map(|i| i.set_response_body(&response));
router_env::logger::info!(connector_response=?response);
- types::RouterData::try_from(types::ResponseRouterData {
+ RouterData::try_from(ResponseRouterData {
response,
data: data.clone(),
http_code: res.status_code,
@@ -314,33 +326,18 @@ impl
}
}
-impl ConnectorIntegration<api::Session, types::PaymentsSessionData, types::PaymentsResponseData>
- for Stax
-{
+impl ConnectorIntegration<Session, PaymentsSessionData, PaymentsResponseData> for Stax {
//TODO: implement sessions flow
}
-impl ConnectorIntegration<api::AccessTokenAuth, types::AccessTokenRequestData, types::AccessToken>
- for Stax
-{
-}
+impl ConnectorIntegration<AccessTokenAuth, AccessTokenRequestData, AccessToken> for Stax {}
-impl
- ConnectorIntegration<
- api::SetupMandate,
- types::SetupMandateRequestData,
- types::PaymentsResponseData,
- > for Stax
-{
+impl ConnectorIntegration<SetupMandate, SetupMandateRequestData, PaymentsResponseData> for Stax {
fn build_request(
&self,
- _req: &types::RouterData<
- api::SetupMandate,
- types::SetupMandateRequestData,
- types::PaymentsResponseData,
- >,
- _connectors: &settings::Connectors,
- ) -> CustomResult<Option<services::Request>, errors::ConnectorError> {
+ _req: &RouterData<SetupMandate, SetupMandateRequestData, PaymentsResponseData>,
+ _connectors: &Connectors,
+ ) -> CustomResult<Option<Request>, errors::ConnectorError> {
Err(
errors::ConnectorError::NotImplemented("Setup Mandate flow for Stax".to_string())
.into(),
@@ -348,14 +345,12 @@ impl
}
}
-impl ConnectorIntegration<api::Authorize, types::PaymentsAuthorizeData, types::PaymentsResponseData>
- for Stax
-{
+impl ConnectorIntegration<Authorize, PaymentsAuthorizeData, PaymentsResponseData> for Stax {
fn get_headers(
&self,
- req: &types::PaymentsAuthorizeRouterData,
- connectors: &settings::Connectors,
- ) -> CustomResult<Vec<(String, request::Maskable<String>)>, errors::ConnectorError> {
+ req: &PaymentsAuthorizeRouterData,
+ connectors: &Connectors,
+ ) -> CustomResult<Vec<(String, masking::Maskable<String>)>, errors::ConnectorError> {
self.build_headers(req, connectors)
}
@@ -365,16 +360,16 @@ impl ConnectorIntegration<api::Authorize, types::PaymentsAuthorizeData, types::P
fn get_url(
&self,
- _req: &types::PaymentsAuthorizeRouterData,
- connectors: &settings::Connectors,
+ _req: &PaymentsAuthorizeRouterData,
+ connectors: &Connectors,
) -> CustomResult<String, errors::ConnectorError> {
Ok(format!("{}charge", self.base_url(connectors),))
}
fn get_request_body(
&self,
- req: &types::PaymentsAuthorizeRouterData,
- _connectors: &settings::Connectors,
+ req: &PaymentsAuthorizeRouterData,
+ _connectors: &Connectors,
) -> CustomResult<RequestContent, errors::ConnectorError> {
let connector_router_data = stax::StaxRouterData::try_from((
&self.get_currency_unit(),
@@ -389,12 +384,12 @@ impl ConnectorIntegration<api::Authorize, types::PaymentsAuthorizeData, types::P
fn build_request(
&self,
- req: &types::PaymentsAuthorizeRouterData,
- connectors: &settings::Connectors,
- ) -> CustomResult<Option<services::Request>, errors::ConnectorError> {
+ req: &PaymentsAuthorizeRouterData,
+ connectors: &Connectors,
+ ) -> CustomResult<Option<Request>, errors::ConnectorError> {
Ok(Some(
- services::RequestBuilder::new()
- .method(services::Method::Post)
+ RequestBuilder::new()
+ .method(Method::Post)
.url(&types::PaymentsAuthorizeType::get_url(
self, req, connectors,
)?)
@@ -411,10 +406,10 @@ impl ConnectorIntegration<api::Authorize, types::PaymentsAuthorizeData, types::P
fn handle_response(
&self,
- data: &types::PaymentsAuthorizeRouterData,
+ data: &PaymentsAuthorizeRouterData,
event_builder: Option<&mut ConnectorEvent>,
res: Response,
- ) -> CustomResult<types::PaymentsAuthorizeRouterData, errors::ConnectorError> {
+ ) -> CustomResult<PaymentsAuthorizeRouterData, errors::ConnectorError> {
let response: stax::StaxPaymentsResponse = res
.response
.parse_struct("StaxPaymentsAuthorizeResponse")
@@ -423,7 +418,7 @@ impl ConnectorIntegration<api::Authorize, types::PaymentsAuthorizeData, types::P
event_builder.map(|i| i.set_response_body(&response));
router_env::logger::info!(connector_response=?response);
- types::RouterData::try_from(types::ResponseRouterData {
+ RouterData::try_from(ResponseRouterData {
response,
data: data.clone(),
http_code: res.status_code,
@@ -439,14 +434,12 @@ impl ConnectorIntegration<api::Authorize, types::PaymentsAuthorizeData, types::P
}
}
-impl ConnectorIntegration<api::PSync, types::PaymentsSyncData, types::PaymentsResponseData>
- for Stax
-{
+impl ConnectorIntegration<PSync, PaymentsSyncData, PaymentsResponseData> for Stax {
fn get_headers(
&self,
- req: &types::PaymentsSyncRouterData,
- connectors: &settings::Connectors,
- ) -> CustomResult<Vec<(String, request::Maskable<String>)>, errors::ConnectorError> {
+ req: &PaymentsSyncRouterData,
+ connectors: &Connectors,
+ ) -> CustomResult<Vec<(String, masking::Maskable<String>)>, errors::ConnectorError> {
self.build_headers(req, connectors)
}
@@ -456,8 +449,8 @@ impl ConnectorIntegration<api::PSync, types::PaymentsSyncData, types::PaymentsRe
fn get_url(
&self,
- req: &types::PaymentsSyncRouterData,
- connectors: &settings::Connectors,
+ req: &PaymentsSyncRouterData,
+ connectors: &Connectors,
) -> CustomResult<String, errors::ConnectorError> {
let connector_payment_id = req
.request
@@ -473,12 +466,12 @@ impl ConnectorIntegration<api::PSync, types::PaymentsSyncData, types::PaymentsRe
fn build_request(
&self,
- req: &types::PaymentsSyncRouterData,
- connectors: &settings::Connectors,
- ) -> CustomResult<Option<services::Request>, errors::ConnectorError> {
+ req: &PaymentsSyncRouterData,
+ connectors: &Connectors,
+ ) -> CustomResult<Option<Request>, errors::ConnectorError> {
Ok(Some(
- services::RequestBuilder::new()
- .method(services::Method::Get)
+ RequestBuilder::new()
+ .method(Method::Get)
.url(&types::PaymentsSyncType::get_url(self, req, connectors)?)
.attach_default_headers()
.headers(types::PaymentsSyncType::get_headers(self, req, connectors)?)
@@ -488,10 +481,10 @@ impl ConnectorIntegration<api::PSync, types::PaymentsSyncData, types::PaymentsRe
fn handle_response(
&self,
- data: &types::PaymentsSyncRouterData,
+ data: &PaymentsSyncRouterData,
event_builder: Option<&mut ConnectorEvent>,
res: Response,
- ) -> CustomResult<types::PaymentsSyncRouterData, errors::ConnectorError> {
+ ) -> CustomResult<PaymentsSyncRouterData, errors::ConnectorError> {
let response: stax::StaxPaymentsResponse = res
.response
.parse_struct("StaxPaymentsSyncResponse")
@@ -500,7 +493,7 @@ impl ConnectorIntegration<api::PSync, types::PaymentsSyncData, types::PaymentsRe
event_builder.map(|i| i.set_response_body(&response));
router_env::logger::info!(connector_response=?response);
- types::RouterData::try_from(types::ResponseRouterData {
+ RouterData::try_from(ResponseRouterData {
response,
data: data.clone(),
http_code: res.status_code,
@@ -516,14 +509,12 @@ impl ConnectorIntegration<api::PSync, types::PaymentsSyncData, types::PaymentsRe
}
}
-impl ConnectorIntegration<api::Capture, types::PaymentsCaptureData, types::PaymentsResponseData>
- for Stax
-{
+impl ConnectorIntegration<Capture, PaymentsCaptureData, PaymentsResponseData> for Stax {
fn get_headers(
&self,
- req: &types::PaymentsCaptureRouterData,
- connectors: &settings::Connectors,
- ) -> CustomResult<Vec<(String, request::Maskable<String>)>, errors::ConnectorError> {
+ req: &PaymentsCaptureRouterData,
+ connectors: &Connectors,
+ ) -> CustomResult<Vec<(String, masking::Maskable<String>)>, errors::ConnectorError> {
self.build_headers(req, connectors)
}
@@ -533,8 +524,8 @@ impl ConnectorIntegration<api::Capture, types::PaymentsCaptureData, types::Payme
fn get_url(
&self,
- req: &types::PaymentsCaptureRouterData,
- connectors: &settings::Connectors,
+ req: &PaymentsCaptureRouterData,
+ connectors: &Connectors,
) -> CustomResult<String, errors::ConnectorError> {
Ok(format!(
"{}/transaction/{}/capture",
@@ -545,8 +536,8 @@ impl ConnectorIntegration<api::Capture, types::PaymentsCaptureData, types::Payme
fn get_request_body(
&self,
- req: &types::PaymentsCaptureRouterData,
- _connectors: &settings::Connectors,
+ req: &PaymentsCaptureRouterData,
+ _connectors: &Connectors,
) -> CustomResult<RequestContent, errors::ConnectorError> {
let connector_router_data = stax::StaxRouterData::try_from((
&self.get_currency_unit(),
@@ -560,12 +551,12 @@ impl ConnectorIntegration<api::Capture, types::PaymentsCaptureData, types::Payme
fn build_request(
&self,
- req: &types::PaymentsCaptureRouterData,
- connectors: &settings::Connectors,
- ) -> CustomResult<Option<services::Request>, errors::ConnectorError> {
+ req: &PaymentsCaptureRouterData,
+ connectors: &Connectors,
+ ) -> CustomResult<Option<Request>, errors::ConnectorError> {
Ok(Some(
- services::RequestBuilder::new()
- .method(services::Method::Post)
+ RequestBuilder::new()
+ .method(Method::Post)
.url(&types::PaymentsCaptureType::get_url(self, req, connectors)?)
.attach_default_headers()
.headers(types::PaymentsCaptureType::get_headers(
@@ -580,10 +571,10 @@ impl ConnectorIntegration<api::Capture, types::PaymentsCaptureData, types::Payme
fn handle_response(
&self,
- data: &types::PaymentsCaptureRouterData,
+ data: &PaymentsCaptureRouterData,
event_builder: Option<&mut ConnectorEvent>,
res: Response,
- ) -> CustomResult<types::PaymentsCaptureRouterData, errors::ConnectorError> {
+ ) -> CustomResult<PaymentsCaptureRouterData, errors::ConnectorError> {
let response: stax::StaxPaymentsResponse = res
.response
.parse_struct("StaxPaymentsCaptureResponse")
@@ -592,7 +583,7 @@ impl ConnectorIntegration<api::Capture, types::PaymentsCaptureData, types::Payme
event_builder.map(|i| i.set_response_body(&response));
router_env::logger::info!(connector_response=?response);
- types::RouterData::try_from(types::ResponseRouterData {
+ RouterData::try_from(ResponseRouterData {
response,
data: data.clone(),
http_code: res.status_code,
@@ -608,14 +599,12 @@ impl ConnectorIntegration<api::Capture, types::PaymentsCaptureData, types::Payme
}
}
-impl ConnectorIntegration<api::Void, types::PaymentsCancelData, types::PaymentsResponseData>
- for Stax
-{
+impl ConnectorIntegration<Void, PaymentsCancelData, PaymentsResponseData> for Stax {
fn get_headers(
&self,
- req: &types::PaymentsCancelRouterData,
- connectors: &settings::Connectors,
- ) -> CustomResult<Vec<(String, request::Maskable<String>)>, errors::ConnectorError> {
+ req: &PaymentsCancelRouterData,
+ connectors: &Connectors,
+ ) -> CustomResult<Vec<(String, masking::Maskable<String>)>, errors::ConnectorError> {
self.build_headers(req, connectors)
}
@@ -625,8 +614,8 @@ impl ConnectorIntegration<api::Void, types::PaymentsCancelData, types::PaymentsR
fn get_url(
&self,
- req: &types::PaymentsCancelRouterData,
- connectors: &settings::Connectors,
+ req: &PaymentsCancelRouterData,
+ connectors: &Connectors,
) -> CustomResult<String, errors::ConnectorError> {
Ok(format!(
"{}/transaction/{}/void-or-refund",
@@ -637,12 +626,12 @@ impl ConnectorIntegration<api::Void, types::PaymentsCancelData, types::PaymentsR
fn build_request(
&self,
- req: &types::PaymentsCancelRouterData,
- connectors: &settings::Connectors,
- ) -> CustomResult<Option<services::Request>, errors::ConnectorError> {
+ req: &PaymentsCancelRouterData,
+ connectors: &Connectors,
+ ) -> CustomResult<Option<Request>, errors::ConnectorError> {
Ok(Some(
- services::RequestBuilder::new()
- .method(services::Method::Post)
+ RequestBuilder::new()
+ .method(Method::Post)
.url(&types::PaymentsVoidType::get_url(self, req, connectors)?)
.attach_default_headers()
.headers(types::PaymentsVoidType::get_headers(self, req, connectors)?)
@@ -652,10 +641,10 @@ impl ConnectorIntegration<api::Void, types::PaymentsCancelData, types::PaymentsR
fn handle_response(
&self,
- data: &types::PaymentsCancelRouterData,
+ data: &PaymentsCancelRouterData,
event_builder: Option<&mut ConnectorEvent>,
res: Response,
- ) -> CustomResult<types::PaymentsCancelRouterData, errors::ConnectorError> {
+ ) -> CustomResult<PaymentsCancelRouterData, errors::ConnectorError> {
let response: stax::StaxPaymentsResponse = res
.response
.parse_struct("StaxPaymentsVoidResponse")
@@ -664,7 +653,7 @@ impl ConnectorIntegration<api::Void, types::PaymentsCancelData, types::PaymentsR
event_builder.map(|i| i.set_response_body(&response));
router_env::logger::info!(connector_response=?response);
- types::RouterData::try_from(types::ResponseRouterData {
+ RouterData::try_from(ResponseRouterData {
response,
data: data.clone(),
http_code: res.status_code,
@@ -680,12 +669,12 @@ impl ConnectorIntegration<api::Void, types::PaymentsCancelData, types::PaymentsR
}
}
-impl ConnectorIntegration<api::Execute, types::RefundsData, types::RefundsResponseData> for Stax {
+impl ConnectorIntegration<Execute, RefundsData, RefundsResponseData> for Stax {
fn get_headers(
&self,
- req: &types::RefundsRouterData<api::Execute>,
- connectors: &settings::Connectors,
- ) -> CustomResult<Vec<(String, request::Maskable<String>)>, errors::ConnectorError> {
+ req: &RefundsRouterData<Execute>,
+ connectors: &Connectors,
+ ) -> CustomResult<Vec<(String, masking::Maskable<String>)>, errors::ConnectorError> {
self.build_headers(req, connectors)
}
@@ -695,12 +684,12 @@ impl ConnectorIntegration<api::Execute, types::RefundsData, types::RefundsRespon
fn get_url(
&self,
- req: &types::RefundsRouterData<api::Execute>,
- connectors: &settings::Connectors,
+ req: &RefundsRouterData<Execute>,
+ connectors: &Connectors,
) -> CustomResult<String, errors::ConnectorError> {
let connector_transaction_id = if req.request.connector_metadata.is_some() {
let stax_capture: stax::StaxMetaData =
- to_connector_meta(req.request.connector_metadata.clone())?;
+ utils::to_connector_meta(req.request.connector_metadata.clone())?;
stax_capture.capture_id
} else {
req.request.connector_transaction_id.clone()
@@ -715,8 +704,8 @@ impl ConnectorIntegration<api::Execute, types::RefundsData, types::RefundsRespon
fn get_request_body(
&self,
- req: &types::RefundsRouterData<api::Execute>,
- _connectors: &settings::Connectors,
+ req: &RefundsRouterData<Execute>,
+ _connectors: &Connectors,
) -> CustomResult<RequestContent, errors::ConnectorError> {
let connector_router_data = stax::StaxRouterData::try_from((
&self.get_currency_unit(),
@@ -730,11 +719,11 @@ impl ConnectorIntegration<api::Execute, types::RefundsData, types::RefundsRespon
fn build_request(
&self,
- req: &types::RefundsRouterData<api::Execute>,
- connectors: &settings::Connectors,
- ) -> CustomResult<Option<services::Request>, errors::ConnectorError> {
- let request = services::RequestBuilder::new()
- .method(services::Method::Post)
+ req: &RefundsRouterData<Execute>,
+ connectors: &Connectors,
+ ) -> CustomResult<Option<Request>, errors::ConnectorError> {
+ let request = RequestBuilder::new()
+ .method(Method::Post)
.url(&types::RefundExecuteType::get_url(self, req, connectors)?)
.attach_default_headers()
.headers(types::RefundExecuteType::get_headers(
@@ -749,10 +738,10 @@ impl ConnectorIntegration<api::Execute, types::RefundsData, types::RefundsRespon
fn handle_response(
&self,
- data: &types::RefundsRouterData<api::Execute>,
+ data: &RefundsRouterData<Execute>,
event_builder: Option<&mut ConnectorEvent>,
res: Response,
- ) -> CustomResult<types::RefundsRouterData<api::Execute>, errors::ConnectorError> {
+ ) -> CustomResult<RefundsRouterData<Execute>, errors::ConnectorError> {
let response: stax::RefundResponse = res
.response
.parse_struct("StaxRefundResponse")
@@ -761,7 +750,7 @@ impl ConnectorIntegration<api::Execute, types::RefundsData, types::RefundsRespon
event_builder.map(|i| i.set_response_body(&response));
router_env::logger::info!(connector_response=?response);
- types::RouterData::try_from(types::ResponseRouterData {
+ RouterData::try_from(ResponseRouterData {
response,
data: data.clone(),
http_code: res.status_code,
@@ -777,12 +766,12 @@ impl ConnectorIntegration<api::Execute, types::RefundsData, types::RefundsRespon
}
}
-impl ConnectorIntegration<api::RSync, types::RefundsData, types::RefundsResponseData> for Stax {
+impl ConnectorIntegration<RSync, RefundsData, RefundsResponseData> for Stax {
fn get_headers(
&self,
- req: &types::RefundSyncRouterData,
- connectors: &settings::Connectors,
- ) -> CustomResult<Vec<(String, request::Maskable<String>)>, errors::ConnectorError> {
+ req: &RefundSyncRouterData,
+ connectors: &Connectors,
+ ) -> CustomResult<Vec<(String, masking::Maskable<String>)>, errors::ConnectorError> {
self.build_headers(req, connectors)
}
@@ -792,8 +781,8 @@ impl ConnectorIntegration<api::RSync, types::RefundsData, types::RefundsResponse
fn get_url(
&self,
- req: &types::RefundSyncRouterData,
- connectors: &settings::Connectors,
+ req: &RefundSyncRouterData,
+ connectors: &Connectors,
) -> CustomResult<String, errors::ConnectorError> {
Ok(format!(
"{}/transaction/{}",
@@ -804,12 +793,12 @@ impl ConnectorIntegration<api::RSync, types::RefundsData, types::RefundsResponse
fn build_request(
&self,
- req: &types::RefundSyncRouterData,
- connectors: &settings::Connectors,
- ) -> CustomResult<Option<services::Request>, errors::ConnectorError> {
+ req: &RefundSyncRouterData,
+ connectors: &Connectors,
+ ) -> CustomResult<Option<Request>, errors::ConnectorError> {
Ok(Some(
- services::RequestBuilder::new()
- .method(services::Method::Get)
+ RequestBuilder::new()
+ .method(Method::Get)
.url(&types::RefundSyncType::get_url(self, req, connectors)?)
.attach_default_headers()
.headers(types::RefundSyncType::get_headers(self, req, connectors)?)
@@ -819,10 +808,10 @@ impl ConnectorIntegration<api::RSync, types::RefundsData, types::RefundsResponse
fn handle_response(
&self,
- data: &types::RefundSyncRouterData,
+ data: &RefundSyncRouterData,
event_builder: Option<&mut ConnectorEvent>,
res: Response,
- ) -> CustomResult<types::RefundSyncRouterData, errors::ConnectorError> {
+ ) -> CustomResult<RefundSyncRouterData, errors::ConnectorError> {
let response: stax::RefundResponse = res
.response
.parse_struct("StaxRefundSyncResponse")
@@ -831,7 +820,7 @@ impl ConnectorIntegration<api::RSync, types::RefundsData, types::RefundsResponse
event_builder.map(|i| i.set_response_body(&response));
router_env::logger::info!(connector_response=?response);
- types::RouterData::try_from(types::ResponseRouterData {
+ RouterData::try_from(ResponseRouterData {
response,
data: data.clone(),
http_code: res.status_code,
@@ -848,10 +837,10 @@ impl ConnectorIntegration<api::RSync, types::RefundsData, types::RefundsResponse
}
#[async_trait::async_trait]
-impl api::IncomingWebhook for Stax {
+impl webhooks::IncomingWebhook for Stax {
async fn verify_webhook_source(
&self,
- _request: &api::IncomingWebhookRequestDetails<'_>,
+ _request: &webhooks::IncomingWebhookRequestDetails<'_>,
_merchant_id: &common_utils::id_type::MerchantId,
_connector_webhook_details: Option<common_utils::pii::SecretSerdeValue>,
_connector_account_details: common_utils::crypto::Encryptable<Secret<serde_json::Value>>,
@@ -862,8 +851,8 @@ impl api::IncomingWebhook for Stax {
fn get_webhook_object_reference_id(
&self,
- request: &api::IncomingWebhookRequestDetails<'_>,
- ) -> CustomResult<api::webhooks::ObjectReferenceId, errors::ConnectorError> {
+ request: &webhooks::IncomingWebhookRequestDetails<'_>,
+ ) -> CustomResult<api_models::webhooks::ObjectReferenceId, errors::ConnectorError> {
let webhook_body: stax::StaxWebhookBody = request
.body
.parse_struct("StaxWebhookBody")
@@ -894,8 +883,8 @@ impl api::IncomingWebhook for Stax {
fn get_webhook_event_type(
&self,
- request: &api::IncomingWebhookRequestDetails<'_>,
- ) -> CustomResult<api::IncomingWebhookEvent, errors::ConnectorError> {
+ request: &webhooks::IncomingWebhookRequestDetails<'_>,
+ ) -> CustomResult<IncomingWebhookEvent, errors::ConnectorError> {
let details: stax::StaxWebhookBody = request
.body
.parse_struct("StaxWebhookEventType")
@@ -903,24 +892,24 @@ impl api::IncomingWebhook for Stax {
Ok(match &details.transaction_type {
StaxWebhookEventType::Refund => match &details.success {
- true => api::IncomingWebhookEvent::RefundSuccess,
- false => api::IncomingWebhookEvent::RefundFailure,
+ true => IncomingWebhookEvent::RefundSuccess,
+ false => IncomingWebhookEvent::RefundFailure,
},
StaxWebhookEventType::Capture | StaxWebhookEventType::Charge => {
match &details.success {
- true => api::IncomingWebhookEvent::PaymentIntentSuccess,
- false => api::IncomingWebhookEvent::PaymentIntentFailure,
+ true => IncomingWebhookEvent::PaymentIntentSuccess,
+ false => IncomingWebhookEvent::PaymentIntentFailure,
}
}
StaxWebhookEventType::PreAuth
| StaxWebhookEventType::Void
- | StaxWebhookEventType::Unknown => api::IncomingWebhookEvent::EventNotSupported,
+ | StaxWebhookEventType::Unknown => IncomingWebhookEvent::EventNotSupported,
})
}
fn get_webhook_resource_object(
&self,
- request: &api::IncomingWebhookRequestDetails<'_>,
+ request: &webhooks::IncomingWebhookRequestDetails<'_>,
) -> CustomResult<Box<dyn masking::ErasedMaskSerialize>, errors::ConnectorError> {
let reference_object: serde_json::Value = serde_json::from_slice(request.body)
.change_context(errors::ConnectorError::WebhookResourceObjectNotFound)?;
diff --git a/crates/router/src/connector/stax/transformers.rs b/crates/hyperswitch_connectors/src/connectors/stax/transformers.rs
similarity index 73%
rename from crates/router/src/connector/stax/transformers.rs
rename to crates/hyperswitch_connectors/src/connectors/stax/transformers.rs
index d814deef264..8c767e848da 100644
--- a/crates/router/src/connector/stax/transformers.rs
+++ b/crates/hyperswitch_connectors/src/connectors/stax/transformers.rs
@@ -1,15 +1,25 @@
+use common_enums::enums;
use common_utils::pii::Email;
use error_stack::ResultExt;
+use hyperswitch_domain_models::{
+ payment_method_data::{BankDebitData, PaymentMethodData},
+ router_data::{ConnectorAuthType, PaymentMethodToken, RouterData},
+ router_flow_types::refunds::{Execute, RSync},
+ router_request_types::ResponseId,
+ router_response_types::{PaymentsResponseData, RefundsResponseData},
+ types,
+};
+use hyperswitch_interfaces::{api, errors};
use masking::{ExposeInterface, Secret};
use serde::{Deserialize, Serialize};
use crate::{
- connector::utils::{
- self, missing_field_err, CardData, PaymentsAuthorizeRequestData, RouterData,
- },
- core::errors,
- types::{self, api, domain, storage::enums},
+ types::{RefundsResponseRouterData, ResponseRouterData},
unimplemented_payment_method,
+ utils::{
+ self, missing_field_err, CardData as CardDataUtil, PaymentsAuthorizeRequestData,
+ RouterData as _,
+ },
};
#[derive(Debug, Serialize)]
@@ -59,7 +69,7 @@ impl TryFrom<&StaxRouterData<&types::PaymentsAuthorizeRouterData>> for StaxPayme
let total = item.amount;
match item.router_data.request.payment_method_data.clone() {
- domain::PaymentMethodData::Card(_) => {
+ PaymentMethodData::Card(_) => {
let pm_token = item.router_data.get_payment_method_token()?;
let pre_auth = !item.router_data.request.is_auto_capture()?;
Ok(Self {
@@ -68,17 +78,15 @@ impl TryFrom<&StaxRouterData<&types::PaymentsAuthorizeRouterData>> for StaxPayme
is_refundable: true,
pre_auth,
payment_method_id: match pm_token {
- types::PaymentMethodToken::Token(token) => token,
- types::PaymentMethodToken::ApplePayDecrypt(_) => Err(
+ PaymentMethodToken::Token(token) => token,
+ PaymentMethodToken::ApplePayDecrypt(_) => Err(
unimplemented_payment_method!("Apple Pay", "Simplified", "Stax"),
)?,
},
idempotency_id: Some(item.router_data.connector_request_reference_id.clone()),
})
}
- domain::PaymentMethodData::BankDebit(domain::BankDebitData::AchBankDebit {
- ..
- }) => {
+ PaymentMethodData::BankDebit(BankDebitData::AchBankDebit { .. }) => {
let pm_token = item.router_data.get_payment_method_token()?;
let pre_auth = !item.router_data.request.is_auto_capture()?;
Ok(Self {
@@ -87,33 +95,31 @@ impl TryFrom<&StaxRouterData<&types::PaymentsAuthorizeRouterData>> for StaxPayme
is_refundable: true,
pre_auth,
payment_method_id: match pm_token {
- types::PaymentMethodToken::Token(token) => token,
- types::PaymentMethodToken::ApplePayDecrypt(_) => Err(
+ PaymentMethodToken::Token(token) => token,
+ PaymentMethodToken::ApplePayDecrypt(_) => Err(
unimplemented_payment_method!("Apple Pay", "Simplified", "Stax"),
)?,
},
idempotency_id: Some(item.router_data.connector_request_reference_id.clone()),
})
}
- domain::PaymentMethodData::BankDebit(_)
- | domain::PaymentMethodData::Wallet(_)
- | domain::PaymentMethodData::PayLater(_)
- | domain::PaymentMethodData::BankRedirect(_)
- | domain::PaymentMethodData::BankTransfer(_)
- | domain::PaymentMethodData::Crypto(_)
- | domain::PaymentMethodData::MandatePayment
- | domain::PaymentMethodData::Reward
- | domain::PaymentMethodData::RealTimePayment(_)
- | domain::PaymentMethodData::Voucher(_)
- | domain::PaymentMethodData::GiftCard(_)
- | domain::PaymentMethodData::CardRedirect(_)
- | domain::PaymentMethodData::Upi(_)
- | domain::PaymentMethodData::OpenBanking(_)
- | domain::PaymentMethodData::CardToken(_) => {
- Err(errors::ConnectorError::NotImplemented(
- utils::get_unimplemented_payment_method_error_message("Stax"),
- ))?
- }
+ PaymentMethodData::BankDebit(_)
+ | PaymentMethodData::Wallet(_)
+ | PaymentMethodData::PayLater(_)
+ | PaymentMethodData::BankRedirect(_)
+ | PaymentMethodData::BankTransfer(_)
+ | PaymentMethodData::Crypto(_)
+ | PaymentMethodData::MandatePayment
+ | PaymentMethodData::Reward
+ | PaymentMethodData::RealTimePayment(_)
+ | PaymentMethodData::Voucher(_)
+ | PaymentMethodData::GiftCard(_)
+ | PaymentMethodData::CardRedirect(_)
+ | PaymentMethodData::Upi(_)
+ | PaymentMethodData::OpenBanking(_)
+ | PaymentMethodData::CardToken(_) => Err(errors::ConnectorError::NotImplemented(
+ utils::get_unimplemented_payment_method_error_message("Stax"),
+ ))?,
}
}
}
@@ -123,11 +129,11 @@ pub struct StaxAuthType {
pub(super) api_key: Secret<String>,
}
-impl TryFrom<&types::ConnectorAuthType> for StaxAuthType {
+impl TryFrom<&ConnectorAuthType> for StaxAuthType {
type Error = error_stack::Report<errors::ConnectorError>;
- fn try_from(auth_type: &types::ConnectorAuthType) -> Result<Self, Self::Error> {
+ fn try_from(auth_type: &ConnectorAuthType) -> Result<Self, Self::Error> {
match auth_type {
- types::ConnectorAuthType::HeaderKey { api_key } => Ok(Self {
+ ConnectorAuthType::HeaderKey { api_key } => Ok(Self {
api_key: api_key.to_owned(),
}),
_ => Err(errors::ConnectorError::FailedToObtainAuthType.into()),
@@ -165,16 +171,15 @@ pub struct StaxCustomerResponse {
id: Secret<String>,
}
-impl<F, T>
- TryFrom<types::ResponseRouterData<F, StaxCustomerResponse, T, types::PaymentsResponseData>>
- for types::RouterData<F, T, types::PaymentsResponseData>
+impl<F, T> TryFrom<ResponseRouterData<F, StaxCustomerResponse, T, PaymentsResponseData>>
+ for RouterData<F, T, PaymentsResponseData>
{
type Error = error_stack::Report<errors::ConnectorError>;
fn try_from(
- item: types::ResponseRouterData<F, StaxCustomerResponse, T, types::PaymentsResponseData>,
+ item: ResponseRouterData<F, StaxCustomerResponse, T, PaymentsResponseData>,
) -> Result<Self, Self::Error> {
Ok(Self {
- response: Ok(types::PaymentsResponseData::ConnectorCustomerResponse {
+ response: Ok(PaymentsResponseData::ConnectorCustomerResponse {
connector_customer_id: item.response.id.expose(),
}),
..item.data
@@ -215,7 +220,7 @@ impl TryFrom<&types::TokenizationRouterData> for StaxTokenRequest {
fn try_from(item: &types::TokenizationRouterData) -> Result<Self, Self::Error> {
let customer_id = item.get_connector_customer_id()?;
match item.request.payment_method_data.clone() {
- domain::PaymentMethodData::Card(card_data) => {
+ PaymentMethodData::Card(card_data) => {
let stax_card_data = StaxTokenizeData {
card_exp: card_data
.get_card_expiry_month_year_2_digit_with_delimiter("".to_string())?,
@@ -228,7 +233,7 @@ impl TryFrom<&types::TokenizationRouterData> for StaxTokenRequest {
};
Ok(Self::Card(stax_card_data))
}
- domain::PaymentMethodData::BankDebit(domain::BankDebitData::AchBankDebit {
+ PaymentMethodData::BankDebit(BankDebitData::AchBankDebit {
account_number,
routing_number,
bank_name,
@@ -248,25 +253,23 @@ impl TryFrom<&types::TokenizationRouterData> for StaxTokenRequest {
};
Ok(Self::Bank(stax_bank_data))
}
- domain::PaymentMethodData::BankDebit(_)
- | domain::PaymentMethodData::Wallet(_)
- | domain::PaymentMethodData::PayLater(_)
- | domain::PaymentMethodData::BankRedirect(_)
- | domain::PaymentMethodData::BankTransfer(_)
- | domain::PaymentMethodData::Crypto(_)
- | domain::PaymentMethodData::MandatePayment
- | domain::PaymentMethodData::Reward
- | domain::PaymentMethodData::RealTimePayment(_)
- | domain::PaymentMethodData::Voucher(_)
- | domain::PaymentMethodData::GiftCard(_)
- | domain::PaymentMethodData::CardRedirect(_)
- | domain::PaymentMethodData::Upi(_)
- | domain::PaymentMethodData::OpenBanking(_)
- | domain::PaymentMethodData::CardToken(_) => {
- Err(errors::ConnectorError::NotImplemented(
- utils::get_unimplemented_payment_method_error_message("Stax"),
- ))?
- }
+ PaymentMethodData::BankDebit(_)
+ | PaymentMethodData::Wallet(_)
+ | PaymentMethodData::PayLater(_)
+ | PaymentMethodData::BankRedirect(_)
+ | PaymentMethodData::BankTransfer(_)
+ | PaymentMethodData::Crypto(_)
+ | PaymentMethodData::MandatePayment
+ | PaymentMethodData::Reward
+ | PaymentMethodData::RealTimePayment(_)
+ | PaymentMethodData::Voucher(_)
+ | PaymentMethodData::GiftCard(_)
+ | PaymentMethodData::CardRedirect(_)
+ | PaymentMethodData::Upi(_)
+ | PaymentMethodData::OpenBanking(_)
+ | PaymentMethodData::CardToken(_) => Err(errors::ConnectorError::NotImplemented(
+ utils::get_unimplemented_payment_method_error_message("Stax"),
+ ))?,
}
}
}
@@ -276,15 +279,15 @@ pub struct StaxTokenResponse {
id: Secret<String>,
}
-impl<F, T> TryFrom<types::ResponseRouterData<F, StaxTokenResponse, T, types::PaymentsResponseData>>
- for types::RouterData<F, T, types::PaymentsResponseData>
+impl<F, T> TryFrom<ResponseRouterData<F, StaxTokenResponse, T, PaymentsResponseData>>
+ for RouterData<F, T, PaymentsResponseData>
{
type Error = error_stack::Report<errors::ConnectorError>;
fn try_from(
- item: types::ResponseRouterData<F, StaxTokenResponse, T, types::PaymentsResponseData>,
+ item: ResponseRouterData<F, StaxTokenResponse, T, PaymentsResponseData>,
) -> Result<Self, Self::Error> {
Ok(Self {
- response: Ok(types::PaymentsResponseData::TokenizationResponse {
+ response: Ok(PaymentsResponseData::TokenizationResponse {
token: item.response.id.expose(),
}),
..item.data
@@ -321,13 +324,12 @@ pub struct StaxMetaData {
pub capture_id: String,
}
-impl<F, T>
- TryFrom<types::ResponseRouterData<F, StaxPaymentsResponse, T, types::PaymentsResponseData>>
- for types::RouterData<F, T, types::PaymentsResponseData>
+impl<F, T> TryFrom<ResponseRouterData<F, StaxPaymentsResponse, T, PaymentsResponseData>>
+ for RouterData<F, T, PaymentsResponseData>
{
type Error = error_stack::Report<errors::ConnectorError>;
fn try_from(
- item: types::ResponseRouterData<F, StaxPaymentsResponse, T, types::PaymentsResponseData>,
+ item: ResponseRouterData<F, StaxPaymentsResponse, T, PaymentsResponseData>,
) -> Result<Self, Self::Error> {
let mut connector_metadata = None;
let mut status = match item.response.success {
@@ -354,8 +356,8 @@ impl<F, T>
Ok(Self {
status,
- response: Ok(types::PaymentsResponseData::TransactionResponse {
- resource_id: types::ResponseId::ConnectorTransactionId(item.response.id.clone()),
+ response: Ok(PaymentsResponseData::TransactionResponse {
+ resource_id: ResponseId::ConnectorTransactionId(item.response.id.clone()),
redirection_data: None,
mandate_reference: None,
connector_metadata,
@@ -415,12 +417,12 @@ pub struct RefundResponse {
child_transactions: Vec<ChildTransactionsInResponse>,
}
-impl TryFrom<types::RefundsResponseRouterData<api::Execute, RefundResponse>>
- for types::RefundsRouterData<api::Execute>
+impl TryFrom<RefundsResponseRouterData<Execute, RefundResponse>>
+ for types::RefundsRouterData<Execute>
{
type Error = error_stack::Report<errors::ConnectorError>;
fn try_from(
- item: types::RefundsResponseRouterData<api::Execute, RefundResponse>,
+ item: RefundsResponseRouterData<Execute, RefundResponse>,
) -> Result<Self, Self::Error> {
let refund_amount = utils::to_currency_base_unit_asf64(
item.data.request.refund_amount,
@@ -450,7 +452,7 @@ impl TryFrom<types::RefundsResponseRouterData<api::Execute, RefundResponse>>
};
Ok(Self {
- response: Ok(types::RefundsResponseData {
+ response: Ok(RefundsResponseData {
connector_refund_id: refund_txn.id.clone(),
refund_status,
}),
@@ -459,19 +461,17 @@ impl TryFrom<types::RefundsResponseRouterData<api::Execute, RefundResponse>>
}
}
-impl TryFrom<types::RefundsResponseRouterData<api::RSync, RefundResponse>>
- for types::RefundsRouterData<api::RSync>
-{
+impl TryFrom<RefundsResponseRouterData<RSync, RefundResponse>> for types::RefundsRouterData<RSync> {
type Error = error_stack::Report<errors::ConnectorError>;
fn try_from(
- item: types::RefundsResponseRouterData<api::RSync, RefundResponse>,
+ item: RefundsResponseRouterData<RSync, RefundResponse>,
) -> Result<Self, Self::Error> {
let refund_status = match item.response.success {
true => enums::RefundStatus::Success,
false => enums::RefundStatus::Failure,
};
Ok(Self {
- response: Ok(types::RefundsResponseData {
+ response: Ok(RefundsResponseData {
connector_refund_id: item.response.id,
refund_status,
}),
diff --git a/crates/hyperswitch_connectors/src/constants.rs b/crates/hyperswitch_connectors/src/constants.rs
index 8a5a2ff543a..a8d08424190 100644
--- a/crates/hyperswitch_connectors/src/constants.rs
+++ b/crates/hyperswitch_connectors/src/constants.rs
@@ -6,4 +6,5 @@ pub(crate) mod headers {
pub(crate) const CONTENT_TYPE: &str = "Content-Type";
pub(crate) const IDEMPOTENCY_KEY: &str = "Idempotency-Key";
pub(crate) const TIMESTAMP: &str = "Timestamp";
+ pub(crate) const X_ACCEPT_VERSION: &str = "X-Accept-Version";
}
diff --git a/crates/hyperswitch_connectors/src/default_implementations.rs b/crates/hyperswitch_connectors/src/default_implementations.rs
index d8e2e121318..dd3f2152cd8 100644
--- a/crates/hyperswitch_connectors/src/default_implementations.rs
+++ b/crates/hyperswitch_connectors/src/default_implementations.rs
@@ -3,6 +3,7 @@
// impl api::PaymentsPreProcessing for Helcim {}
// impl api::PaymentReject for Helcim {}
// impl api::PaymentApprove for Helcim {}
+use common_utils::errors::CustomResult;
#[cfg(feature = "frm")]
use hyperswitch_domain_models::{
router_flow_types::fraud_check::{Checkout, Fulfillment, RecordReturn, Sale, Transaction},
@@ -55,16 +56,19 @@ use hyperswitch_interfaces::api::payouts::{
PayoutCancel, PayoutCreate, PayoutEligibility, PayoutFulfill, PayoutQuote, PayoutRecipient,
PayoutRecipientAccount, PayoutSync,
};
-use hyperswitch_interfaces::api::{
- self,
- disputes::{AcceptDispute, DefendDispute, Dispute, SubmitEvidence},
- files::{FileUpload, RetrieveFile, UploadFile},
- payments::{
- ConnectorCustomer, PaymentApprove, PaymentAuthorizeSessionToken,
- PaymentIncrementalAuthorization, PaymentReject, PaymentsCompleteAuthorize,
- PaymentsPostProcessing, PaymentsPreProcessing,
+use hyperswitch_interfaces::{
+ api::{
+ self,
+ disputes::{AcceptDispute, DefendDispute, Dispute, SubmitEvidence},
+ files::{FileUpload, RetrieveFile, UploadFile},
+ payments::{
+ ConnectorCustomer, PaymentApprove, PaymentAuthorizeSessionToken,
+ PaymentIncrementalAuthorization, PaymentReject, PaymentsCompleteAuthorize,
+ PaymentsPostProcessing, PaymentsPreProcessing,
+ },
+ ConnectorIntegration, ConnectorMandateRevoke, ConnectorRedirectResponse,
},
- ConnectorIntegration, ConnectorMandateRevoke,
+ errors::ConnectorError,
};
macro_rules! default_imp_for_authorize_session_token {
@@ -81,7 +85,13 @@ macro_rules! default_imp_for_authorize_session_token {
};
}
-default_imp_for_authorize_session_token!(connectors::Fiserv, connectors::Helcim);
+default_imp_for_authorize_session_token!(
+ connectors::Bambora,
+ connectors::Bitpay,
+ connectors::Fiserv,
+ connectors::Helcim,
+ connectors::Stax
+);
use crate::connectors;
macro_rules! default_imp_for_complete_authorize {
@@ -99,7 +109,12 @@ macro_rules! default_imp_for_complete_authorize {
};
}
-default_imp_for_complete_authorize!(connectors::Fiserv, connectors::Helcim);
+default_imp_for_complete_authorize!(
+ connectors::Bitpay,
+ connectors::Fiserv,
+ connectors::Helcim,
+ connectors::Stax
+);
macro_rules! default_imp_for_incremental_authorization {
($($path:ident::$connector:ident),*) => {
@@ -116,7 +131,13 @@ macro_rules! default_imp_for_incremental_authorization {
};
}
-default_imp_for_incremental_authorization!(connectors::Fiserv, connectors::Helcim);
+default_imp_for_incremental_authorization!(
+ connectors::Bambora,
+ connectors::Bitpay,
+ connectors::Fiserv,
+ connectors::Helcim,
+ connectors::Stax
+);
macro_rules! default_imp_for_create_customer {
($($path:ident::$connector:ident),*) => {
@@ -133,7 +154,36 @@ macro_rules! default_imp_for_create_customer {
};
}
-default_imp_for_create_customer!(connectors::Fiserv, connectors::Helcim);
+default_imp_for_create_customer!(
+ connectors::Bambora,
+ connectors::Bitpay,
+ connectors::Fiserv,
+ connectors::Helcim
+);
+
+macro_rules! default_imp_for_connector_redirect_response {
+ ($($path:ident::$connector:ident),*) => {
+ $(
+ impl ConnectorRedirectResponse for $path::$connector {
+ fn get_flow_type(
+ &self,
+ _query_params: &str,
+ _json_payload: Option<serde_json::Value>,
+ _action: common_enums::enums::PaymentAction
+ ) -> CustomResult<common_enums::enums::CallConnectorAction, ConnectorError> {
+ Ok(common_enums::enums::CallConnectorAction::Trigger)
+ }
+ }
+ )*
+ };
+}
+
+default_imp_for_connector_redirect_response!(
+ connectors::Bitpay,
+ connectors::Fiserv,
+ connectors::Helcim,
+ connectors::Stax
+);
macro_rules! default_imp_for_pre_processing_steps{
($($path:ident::$connector:ident),*)=> {
@@ -150,7 +200,13 @@ macro_rules! default_imp_for_pre_processing_steps{
};
}
-default_imp_for_pre_processing_steps!(connectors::Fiserv, connectors::Helcim);
+default_imp_for_pre_processing_steps!(
+ connectors::Bambora,
+ connectors::Bitpay,
+ connectors::Fiserv,
+ connectors::Helcim,
+ connectors::Stax
+);
macro_rules! default_imp_for_post_processing_steps{
($($path:ident::$connector:ident),*)=> {
@@ -167,7 +223,13 @@ macro_rules! default_imp_for_post_processing_steps{
};
}
-default_imp_for_post_processing_steps!(connectors::Fiserv, connectors::Helcim);
+default_imp_for_post_processing_steps!(
+ connectors::Bambora,
+ connectors::Bitpay,
+ connectors::Fiserv,
+ connectors::Helcim,
+ connectors::Stax
+);
macro_rules! default_imp_for_approve {
($($path:ident::$connector:ident),*) => {
@@ -184,7 +246,13 @@ macro_rules! default_imp_for_approve {
};
}
-default_imp_for_approve!(connectors::Fiserv, connectors::Helcim);
+default_imp_for_approve!(
+ connectors::Bambora,
+ connectors::Bitpay,
+ connectors::Fiserv,
+ connectors::Helcim,
+ connectors::Stax
+);
macro_rules! default_imp_for_reject {
($($path:ident::$connector:ident),*) => {
@@ -201,7 +269,13 @@ macro_rules! default_imp_for_reject {
};
}
-default_imp_for_reject!(connectors::Fiserv, connectors::Helcim);
+default_imp_for_reject!(
+ connectors::Bambora,
+ connectors::Bitpay,
+ connectors::Fiserv,
+ connectors::Helcim,
+ connectors::Stax
+);
macro_rules! default_imp_for_webhook_source_verification {
($($path:ident::$connector:ident),*) => {
@@ -218,7 +292,13 @@ macro_rules! default_imp_for_webhook_source_verification {
};
}
-default_imp_for_webhook_source_verification!(connectors::Fiserv, connectors::Helcim);
+default_imp_for_webhook_source_verification!(
+ connectors::Bambora,
+ connectors::Bitpay,
+ connectors::Fiserv,
+ connectors::Helcim,
+ connectors::Stax
+);
macro_rules! default_imp_for_accept_dispute {
($($path:ident::$connector:ident),*) => {
@@ -236,7 +316,13 @@ macro_rules! default_imp_for_accept_dispute {
};
}
-default_imp_for_accept_dispute!(connectors::Fiserv, connectors::Helcim);
+default_imp_for_accept_dispute!(
+ connectors::Bambora,
+ connectors::Bitpay,
+ connectors::Fiserv,
+ connectors::Helcim,
+ connectors::Stax
+);
macro_rules! default_imp_for_submit_evidence {
($($path:ident::$connector:ident),*) => {
@@ -253,7 +339,13 @@ macro_rules! default_imp_for_submit_evidence {
};
}
-default_imp_for_submit_evidence!(connectors::Fiserv, connectors::Helcim);
+default_imp_for_submit_evidence!(
+ connectors::Bambora,
+ connectors::Bitpay,
+ connectors::Fiserv,
+ connectors::Helcim,
+ connectors::Stax
+);
macro_rules! default_imp_for_defend_dispute {
($($path:ident::$connector:ident),*) => {
@@ -270,7 +362,13 @@ macro_rules! default_imp_for_defend_dispute {
};
}
-default_imp_for_defend_dispute!(connectors::Fiserv, connectors::Helcim);
+default_imp_for_defend_dispute!(
+ connectors::Bambora,
+ connectors::Bitpay,
+ connectors::Fiserv,
+ connectors::Helcim,
+ connectors::Stax
+);
macro_rules! default_imp_for_file_upload {
($($path:ident::$connector:ident),*) => {
@@ -296,7 +394,13 @@ macro_rules! default_imp_for_file_upload {
};
}
-default_imp_for_file_upload!(connectors::Fiserv, connectors::Helcim);
+default_imp_for_file_upload!(
+ connectors::Bambora,
+ connectors::Bitpay,
+ connectors::Fiserv,
+ connectors::Helcim,
+ connectors::Stax
+);
#[cfg(feature = "payouts")]
macro_rules! default_imp_for_payouts_create {
@@ -315,7 +419,13 @@ macro_rules! default_imp_for_payouts_create {
}
#[cfg(feature = "payouts")]
-default_imp_for_payouts_create!(connectors::Fiserv, connectors::Helcim);
+default_imp_for_payouts_create!(
+ connectors::Bambora,
+ connectors::Bitpay,
+ connectors::Fiserv,
+ connectors::Helcim,
+ connectors::Stax
+);
#[cfg(feature = "payouts")]
macro_rules! default_imp_for_payouts_retrieve {
@@ -334,7 +444,13 @@ macro_rules! default_imp_for_payouts_retrieve {
}
#[cfg(feature = "payouts")]
-default_imp_for_payouts_retrieve!(connectors::Fiserv, connectors::Helcim);
+default_imp_for_payouts_retrieve!(
+ connectors::Bambora,
+ connectors::Bitpay,
+ connectors::Fiserv,
+ connectors::Helcim,
+ connectors::Stax
+);
#[cfg(feature = "payouts")]
macro_rules! default_imp_for_payouts_eligibility {
@@ -353,7 +469,13 @@ macro_rules! default_imp_for_payouts_eligibility {
}
#[cfg(feature = "payouts")]
-default_imp_for_payouts_eligibility!(connectors::Fiserv, connectors::Helcim);
+default_imp_for_payouts_eligibility!(
+ connectors::Bambora,
+ connectors::Bitpay,
+ connectors::Fiserv,
+ connectors::Helcim,
+ connectors::Stax
+);
#[cfg(feature = "payouts")]
macro_rules! default_imp_for_payouts_fulfill {
@@ -372,7 +494,13 @@ macro_rules! default_imp_for_payouts_fulfill {
}
#[cfg(feature = "payouts")]
-default_imp_for_payouts_fulfill!(connectors::Fiserv, connectors::Helcim);
+default_imp_for_payouts_fulfill!(
+ connectors::Bambora,
+ connectors::Bitpay,
+ connectors::Fiserv,
+ connectors::Helcim,
+ connectors::Stax
+);
#[cfg(feature = "payouts")]
macro_rules! default_imp_for_payouts_cancel {
@@ -391,7 +519,13 @@ macro_rules! default_imp_for_payouts_cancel {
}
#[cfg(feature = "payouts")]
-default_imp_for_payouts_cancel!(connectors::Fiserv, connectors::Helcim);
+default_imp_for_payouts_cancel!(
+ connectors::Bambora,
+ connectors::Bitpay,
+ connectors::Fiserv,
+ connectors::Helcim,
+ connectors::Stax
+);
#[cfg(feature = "payouts")]
macro_rules! default_imp_for_payouts_quote {
@@ -410,7 +544,13 @@ macro_rules! default_imp_for_payouts_quote {
}
#[cfg(feature = "payouts")]
-default_imp_for_payouts_quote!(connectors::Fiserv, connectors::Helcim);
+default_imp_for_payouts_quote!(
+ connectors::Bambora,
+ connectors::Bitpay,
+ connectors::Fiserv,
+ connectors::Helcim,
+ connectors::Stax
+);
#[cfg(feature = "payouts")]
macro_rules! default_imp_for_payouts_recipient {
@@ -429,7 +569,13 @@ macro_rules! default_imp_for_payouts_recipient {
}
#[cfg(feature = "payouts")]
-default_imp_for_payouts_recipient!(connectors::Fiserv, connectors::Helcim);
+default_imp_for_payouts_recipient!(
+ connectors::Bambora,
+ connectors::Bitpay,
+ connectors::Fiserv,
+ connectors::Helcim,
+ connectors::Stax
+);
#[cfg(feature = "payouts")]
macro_rules! default_imp_for_payouts_recipient_account {
@@ -448,7 +594,13 @@ macro_rules! default_imp_for_payouts_recipient_account {
}
#[cfg(feature = "payouts")]
-default_imp_for_payouts_recipient_account!(connectors::Fiserv, connectors::Helcim);
+default_imp_for_payouts_recipient_account!(
+ connectors::Bambora,
+ connectors::Bitpay,
+ connectors::Fiserv,
+ connectors::Helcim,
+ connectors::Stax
+);
#[cfg(feature = "frm")]
macro_rules! default_imp_for_frm_sale {
@@ -467,7 +619,13 @@ macro_rules! default_imp_for_frm_sale {
}
#[cfg(feature = "frm")]
-default_imp_for_frm_sale!(connectors::Fiserv, connectors::Helcim);
+default_imp_for_frm_sale!(
+ connectors::Bambora,
+ connectors::Bitpay,
+ connectors::Fiserv,
+ connectors::Helcim,
+ connectors::Stax
+);
#[cfg(feature = "frm")]
macro_rules! default_imp_for_frm_checkout {
@@ -486,7 +644,13 @@ macro_rules! default_imp_for_frm_checkout {
}
#[cfg(feature = "frm")]
-default_imp_for_frm_checkout!(connectors::Fiserv, connectors::Helcim);
+default_imp_for_frm_checkout!(
+ connectors::Bambora,
+ connectors::Bitpay,
+ connectors::Fiserv,
+ connectors::Helcim,
+ connectors::Stax
+);
#[cfg(feature = "frm")]
macro_rules! default_imp_for_frm_transaction {
@@ -505,7 +669,13 @@ macro_rules! default_imp_for_frm_transaction {
}
#[cfg(feature = "frm")]
-default_imp_for_frm_transaction!(connectors::Fiserv, connectors::Helcim);
+default_imp_for_frm_transaction!(
+ connectors::Bambora,
+ connectors::Bitpay,
+ connectors::Fiserv,
+ connectors::Helcim,
+ connectors::Stax
+);
#[cfg(feature = "frm")]
macro_rules! default_imp_for_frm_fulfillment {
@@ -524,7 +694,13 @@ macro_rules! default_imp_for_frm_fulfillment {
}
#[cfg(feature = "frm")]
-default_imp_for_frm_fulfillment!(connectors::Fiserv, connectors::Helcim);
+default_imp_for_frm_fulfillment!(
+ connectors::Bambora,
+ connectors::Bitpay,
+ connectors::Fiserv,
+ connectors::Helcim,
+ connectors::Stax
+);
#[cfg(feature = "frm")]
macro_rules! default_imp_for_frm_record_return {
@@ -543,7 +719,13 @@ macro_rules! default_imp_for_frm_record_return {
}
#[cfg(feature = "frm")]
-default_imp_for_frm_record_return!(connectors::Fiserv, connectors::Helcim);
+default_imp_for_frm_record_return!(
+ connectors::Bambora,
+ connectors::Bitpay,
+ connectors::Fiserv,
+ connectors::Helcim,
+ connectors::Stax
+);
macro_rules! default_imp_for_revoking_mandates {
($($path:ident::$connector:ident),*) => {
@@ -559,4 +741,10 @@ macro_rules! default_imp_for_revoking_mandates {
};
}
-default_imp_for_revoking_mandates!(connectors::Fiserv, connectors::Helcim);
+default_imp_for_revoking_mandates!(
+ connectors::Bambora,
+ connectors::Bitpay,
+ connectors::Fiserv,
+ connectors::Helcim,
+ connectors::Stax
+);
diff --git a/crates/hyperswitch_connectors/src/default_implementations_v2.rs b/crates/hyperswitch_connectors/src/default_implementations_v2.rs
index f420447fd74..050c8687d89 100644
--- a/crates/hyperswitch_connectors/src/default_implementations_v2.rs
+++ b/crates/hyperswitch_connectors/src/default_implementations_v2.rs
@@ -180,7 +180,13 @@ macro_rules! default_imp_for_new_connector_integration_payment {
};
}
-default_imp_for_new_connector_integration_payment!(connectors::Fiserv, connectors::Helcim);
+default_imp_for_new_connector_integration_payment!(
+ connectors::Bambora,
+ connectors::Bitpay,
+ connectors::Fiserv,
+ connectors::Helcim,
+ connectors::Stax
+);
macro_rules! default_imp_for_new_connector_integration_refund {
($($path:ident::$connector:ident),*) => {
@@ -198,7 +204,13 @@ macro_rules! default_imp_for_new_connector_integration_refund {
};
}
-default_imp_for_new_connector_integration_refund!(connectors::Fiserv, connectors::Helcim);
+default_imp_for_new_connector_integration_refund!(
+ connectors::Bambora,
+ connectors::Bitpay,
+ connectors::Fiserv,
+ connectors::Helcim,
+ connectors::Stax
+);
macro_rules! default_imp_for_new_connector_integration_connector_access_token {
($($path:ident::$connector:ident),*) => {
@@ -212,8 +224,11 @@ macro_rules! default_imp_for_new_connector_integration_connector_access_token {
}
default_imp_for_new_connector_integration_connector_access_token!(
+ connectors::Bambora,
+ connectors::Bitpay,
connectors::Fiserv,
- connectors::Helcim
+ connectors::Helcim,
+ connectors::Stax
);
macro_rules! default_imp_for_new_connector_integration_accept_dispute {
@@ -233,7 +248,13 @@ macro_rules! default_imp_for_new_connector_integration_accept_dispute {
};
}
-default_imp_for_new_connector_integration_accept_dispute!(connectors::Fiserv, connectors::Helcim);
+default_imp_for_new_connector_integration_accept_dispute!(
+ connectors::Bambora,
+ connectors::Bitpay,
+ connectors::Fiserv,
+ connectors::Helcim,
+ connectors::Stax
+);
macro_rules! default_imp_for_new_connector_integration_submit_evidence {
($($path:ident::$connector:ident),*) => {
@@ -251,7 +272,13 @@ macro_rules! default_imp_for_new_connector_integration_submit_evidence {
};
}
-default_imp_for_new_connector_integration_submit_evidence!(connectors::Fiserv, connectors::Helcim);
+default_imp_for_new_connector_integration_submit_evidence!(
+ connectors::Bambora,
+ connectors::Bitpay,
+ connectors::Fiserv,
+ connectors::Helcim,
+ connectors::Stax
+);
macro_rules! default_imp_for_new_connector_integration_defend_dispute {
($($path:ident::$connector:ident),*) => {
@@ -269,7 +296,13 @@ macro_rules! default_imp_for_new_connector_integration_defend_dispute {
};
}
-default_imp_for_new_connector_integration_defend_dispute!(connectors::Fiserv, connectors::Helcim);
+default_imp_for_new_connector_integration_defend_dispute!(
+ connectors::Bambora,
+ connectors::Bitpay,
+ connectors::Fiserv,
+ connectors::Helcim,
+ connectors::Stax
+);
macro_rules! default_imp_for_new_connector_integration_file_upload {
($($path:ident::$connector:ident),*) => {
@@ -297,7 +330,13 @@ macro_rules! default_imp_for_new_connector_integration_file_upload {
};
}
-default_imp_for_new_connector_integration_file_upload!(connectors::Fiserv, connectors::Helcim);
+default_imp_for_new_connector_integration_file_upload!(
+ connectors::Bambora,
+ connectors::Bitpay,
+ connectors::Fiserv,
+ connectors::Helcim,
+ connectors::Stax
+);
#[cfg(feature = "payouts")]
macro_rules! default_imp_for_new_connector_integration_payouts_create {
@@ -317,7 +356,13 @@ macro_rules! default_imp_for_new_connector_integration_payouts_create {
}
#[cfg(feature = "payouts")]
-default_imp_for_new_connector_integration_payouts_create!(connectors::Fiserv, connectors::Helcim);
+default_imp_for_new_connector_integration_payouts_create!(
+ connectors::Bambora,
+ connectors::Bitpay,
+ connectors::Fiserv,
+ connectors::Helcim,
+ connectors::Stax
+);
#[cfg(feature = "payouts")]
macro_rules! default_imp_for_new_connector_integration_payouts_eligibility {
@@ -338,8 +383,11 @@ macro_rules! default_imp_for_new_connector_integration_payouts_eligibility {
#[cfg(feature = "payouts")]
default_imp_for_new_connector_integration_payouts_eligibility!(
+ connectors::Bambora,
+ connectors::Bitpay,
connectors::Fiserv,
- connectors::Helcim
+ connectors::Helcim,
+ connectors::Stax
);
#[cfg(feature = "payouts")]
@@ -360,7 +408,13 @@ macro_rules! default_imp_for_new_connector_integration_payouts_fulfill {
}
#[cfg(feature = "payouts")]
-default_imp_for_new_connector_integration_payouts_fulfill!(connectors::Fiserv, connectors::Helcim);
+default_imp_for_new_connector_integration_payouts_fulfill!(
+ connectors::Bambora,
+ connectors::Bitpay,
+ connectors::Fiserv,
+ connectors::Helcim,
+ connectors::Stax
+);
#[cfg(feature = "payouts")]
macro_rules! default_imp_for_new_connector_integration_payouts_cancel {
@@ -380,7 +434,13 @@ macro_rules! default_imp_for_new_connector_integration_payouts_cancel {
}
#[cfg(feature = "payouts")]
-default_imp_for_new_connector_integration_payouts_cancel!(connectors::Fiserv, connectors::Helcim);
+default_imp_for_new_connector_integration_payouts_cancel!(
+ connectors::Bambora,
+ connectors::Bitpay,
+ connectors::Fiserv,
+ connectors::Helcim,
+ connectors::Stax
+);
#[cfg(feature = "payouts")]
macro_rules! default_imp_for_new_connector_integration_payouts_quote {
@@ -400,7 +460,13 @@ macro_rules! default_imp_for_new_connector_integration_payouts_quote {
}
#[cfg(feature = "payouts")]
-default_imp_for_new_connector_integration_payouts_quote!(connectors::Fiserv, connectors::Helcim);
+default_imp_for_new_connector_integration_payouts_quote!(
+ connectors::Bambora,
+ connectors::Bitpay,
+ connectors::Fiserv,
+ connectors::Helcim,
+ connectors::Stax
+);
#[cfg(feature = "payouts")]
macro_rules! default_imp_for_new_connector_integration_payouts_recipient {
@@ -421,8 +487,11 @@ macro_rules! default_imp_for_new_connector_integration_payouts_recipient {
#[cfg(feature = "payouts")]
default_imp_for_new_connector_integration_payouts_recipient!(
+ connectors::Bambora,
+ connectors::Bitpay,
connectors::Fiserv,
- connectors::Helcim
+ connectors::Helcim,
+ connectors::Stax
);
#[cfg(feature = "payouts")]
@@ -443,7 +512,13 @@ macro_rules! default_imp_for_new_connector_integration_payouts_sync {
}
#[cfg(feature = "payouts")]
-default_imp_for_new_connector_integration_payouts_sync!(connectors::Fiserv, connectors::Helcim);
+default_imp_for_new_connector_integration_payouts_sync!(
+ connectors::Bambora,
+ connectors::Bitpay,
+ connectors::Fiserv,
+ connectors::Helcim,
+ connectors::Stax
+);
#[cfg(feature = "payouts")]
macro_rules! default_imp_for_new_connector_integration_payouts_recipient_account {
@@ -464,8 +539,11 @@ macro_rules! default_imp_for_new_connector_integration_payouts_recipient_account
#[cfg(feature = "payouts")]
default_imp_for_new_connector_integration_payouts_recipient_account!(
+ connectors::Bambora,
+ connectors::Bitpay,
connectors::Fiserv,
- connectors::Helcim
+ connectors::Helcim,
+ connectors::Stax
);
macro_rules! default_imp_for_new_connector_integration_webhook_source_verification {
@@ -485,8 +563,11 @@ macro_rules! default_imp_for_new_connector_integration_webhook_source_verificati
}
default_imp_for_new_connector_integration_webhook_source_verification!(
+ connectors::Bambora,
+ connectors::Bitpay,
connectors::Fiserv,
- connectors::Helcim
+ connectors::Helcim,
+ connectors::Stax
);
#[cfg(feature = "frm")]
@@ -507,7 +588,13 @@ macro_rules! default_imp_for_new_connector_integration_frm_sale {
}
#[cfg(feature = "frm")]
-default_imp_for_new_connector_integration_frm_sale!(connectors::Fiserv, connectors::Helcim);
+default_imp_for_new_connector_integration_frm_sale!(
+ connectors::Bambora,
+ connectors::Bitpay,
+ connectors::Fiserv,
+ connectors::Helcim,
+ connectors::Stax
+);
#[cfg(feature = "frm")]
macro_rules! default_imp_for_new_connector_integration_frm_checkout {
@@ -527,7 +614,13 @@ macro_rules! default_imp_for_new_connector_integration_frm_checkout {
}
#[cfg(feature = "frm")]
-default_imp_for_new_connector_integration_frm_checkout!(connectors::Fiserv, connectors::Helcim);
+default_imp_for_new_connector_integration_frm_checkout!(
+ connectors::Bambora,
+ connectors::Bitpay,
+ connectors::Fiserv,
+ connectors::Helcim,
+ connectors::Stax
+);
#[cfg(feature = "frm")]
macro_rules! default_imp_for_new_connector_integration_frm_transaction {
@@ -547,7 +640,13 @@ macro_rules! default_imp_for_new_connector_integration_frm_transaction {
}
#[cfg(feature = "frm")]
-default_imp_for_new_connector_integration_frm_transaction!(connectors::Fiserv, connectors::Helcim);
+default_imp_for_new_connector_integration_frm_transaction!(
+ connectors::Bambora,
+ connectors::Bitpay,
+ connectors::Fiserv,
+ connectors::Helcim,
+ connectors::Stax
+);
#[cfg(feature = "frm")]
macro_rules! default_imp_for_new_connector_integration_frm_fulfillment {
@@ -567,7 +666,13 @@ macro_rules! default_imp_for_new_connector_integration_frm_fulfillment {
}
#[cfg(feature = "frm")]
-default_imp_for_new_connector_integration_frm_fulfillment!(connectors::Fiserv, connectors::Helcim);
+default_imp_for_new_connector_integration_frm_fulfillment!(
+ connectors::Bambora,
+ connectors::Bitpay,
+ connectors::Fiserv,
+ connectors::Helcim,
+ connectors::Stax
+);
#[cfg(feature = "frm")]
macro_rules! default_imp_for_new_connector_integration_frm_record_return {
@@ -588,8 +693,11 @@ macro_rules! default_imp_for_new_connector_integration_frm_record_return {
#[cfg(feature = "frm")]
default_imp_for_new_connector_integration_frm_record_return!(
+ connectors::Bambora,
+ connectors::Bitpay,
connectors::Fiserv,
- connectors::Helcim
+ connectors::Helcim,
+ connectors::Stax
);
macro_rules! default_imp_for_new_connector_integration_revoking_mandates {
@@ -608,6 +716,9 @@ macro_rules! default_imp_for_new_connector_integration_revoking_mandates {
}
default_imp_for_new_connector_integration_revoking_mandates!(
+ connectors::Bambora,
+ connectors::Bitpay,
connectors::Fiserv,
- connectors::Helcim
+ connectors::Helcim,
+ connectors::Stax
);
diff --git a/crates/hyperswitch_connectors/src/utils.rs b/crates/hyperswitch_connectors/src/utils.rs
index 40f98b6efdb..ebd3ff34704 100644
--- a/crates/hyperswitch_connectors/src/utils.rs
+++ b/crates/hyperswitch_connectors/src/utils.rs
@@ -5,14 +5,16 @@ use common_utils::{
ext_traits::{OptionExt, ValueExt},
id_type,
pii::{self, Email, IpAddress},
+ types::{AmountConvertor, MinorUnit},
};
use error_stack::ResultExt;
use hyperswitch_domain_models::{
payment_method_data::{Card, PaymentMethodData},
router_data::{PaymentMethodToken, RecurringMandatePaymentData},
router_request_types::{
- AuthenticationData, BrowserInformation, PaymentsAuthorizeData, PaymentsCancelData,
- PaymentsCaptureData, PaymentsSyncData, RefundsData, ResponseId, SetupMandateRequestData,
+ AuthenticationData, BrowserInformation, CompleteAuthorizeData, PaymentsAuthorizeData,
+ PaymentsCancelData, PaymentsCaptureData, PaymentsSyncData, RefundsData, ResponseId,
+ SetupMandateRequestData,
},
};
use hyperswitch_interfaces::{api, errors};
@@ -131,6 +133,16 @@ where
json.parse_value(std::any::type_name::<T>()).switch()
}
+pub(crate) fn convert_amount<T>(
+ amount_convertor: &dyn AmountConvertor<Output = T>,
+ amount: MinorUnit,
+ currency: enums::Currency,
+) -> Result<T, error_stack::Report<errors::ConnectorError>> {
+ amount_convertor
+ .convert(amount, currency)
+ .change_context(errors::ConnectorError::AmountConversionFailed)
+}
+
// TODO: Make all traits as `pub(crate) trait` once all connectors are moved.
pub trait RouterData {
fn get_billing(&self) -> Result<&Address, Error>;
@@ -1094,6 +1106,54 @@ impl PaymentsSetupMandateRequestData for SetupMandateRequestData {
}
}
+pub trait PaymentsCompleteAuthorizeRequestData {
+ fn is_auto_capture(&self) -> Result<bool, Error>;
+ fn get_email(&self) -> Result<Email, Error>;
+ fn get_redirect_response_payload(&self) -> Result<pii::SecretSerdeValue, Error>;
+ fn get_complete_authorize_url(&self) -> Result<String, Error>;
+ fn is_mandate_payment(&self) -> bool;
+}
+
+impl PaymentsCompleteAuthorizeRequestData for CompleteAuthorizeData {
+ fn is_auto_capture(&self) -> Result<bool, Error> {
+ match self.capture_method {
+ Some(enums::CaptureMethod::Automatic) | None => Ok(true),
+ Some(enums::CaptureMethod::Manual) => Ok(false),
+ Some(_) => Err(errors::ConnectorError::CaptureMethodNotSupported.into()),
+ }
+ }
+ fn get_email(&self) -> Result<Email, Error> {
+ self.email.clone().ok_or_else(missing_field_err("email"))
+ }
+ 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 get_complete_authorize_url(&self) -> Result<String, Error> {
+ self.complete_authorize_url
+ .clone()
+ .ok_or_else(missing_field_err("complete_authorize_url"))
+ }
+ fn is_mandate_payment(&self) -> bool {
+ ((self.customer_acceptance.is_some() || self.setup_mandate_details.is_some())
+ && self.setup_future_usage.map_or(false, |setup_future_usage| {
+ setup_future_usage == FutureUsage::OffSession
+ }))
+ || self
+ .mandate_id
+ .as_ref()
+ .and_then(|mandate_ids| mandate_ids.mandate_reference_id.as_ref())
+ .is_some()
+ }
+}
+
pub trait BrowserInformationData {
fn get_accept_header(&self) -> Result<String, Error>;
fn get_language(&self) -> Result<String, Error>;
@@ -1154,3 +1214,19 @@ impl BrowserInformationData for BrowserInformation {
.ok_or_else(missing_field_err("browser_info.java_script_enabled"))
}
}
+
+#[macro_export]
+macro_rules! unimplemented_payment_method {
+ ($payment_method:expr, $connector:expr) => {
+ errors::ConnectorError::NotImplemented(format!(
+ "{} through {}",
+ $payment_method, $connector
+ ))
+ };
+ ($payment_method:expr, $flow:expr, $connector:expr) => {
+ errors::ConnectorError::NotImplemented(format!(
+ "{} {} through {}",
+ $payment_method, $flow, $connector
+ ))
+ };
+}
diff --git a/crates/hyperswitch_domain_models/src/types.rs b/crates/hyperswitch_domain_models/src/types.rs
index 814d235e6f0..e425fc7fcc6 100644
--- a/crates/hyperswitch_domain_models/src/types.rs
+++ b/crates/hyperswitch_domain_models/src/types.rs
@@ -1,7 +1,11 @@
use crate::{
router_data::RouterData,
- router_flow_types::{Authorize, Capture, PSync, RSync, SetupMandate, Void},
+ router_flow_types::{
+ Authorize, Capture, CompleteAuthorize, CreateConnectorCustomer, PSync, PaymentMethodToken,
+ RSync, SetupMandate, Void,
+ },
router_request_types::{
+ CompleteAuthorizeData, ConnectorCustomerData, PaymentMethodTokenizationData,
PaymentsAuthorizeData, PaymentsCancelData, PaymentsCaptureData, PaymentsSyncData,
RefundsData, SetupMandateRequestData,
},
@@ -17,3 +21,9 @@ pub type SetupMandateRouterData =
RouterData<SetupMandate, SetupMandateRequestData, PaymentsResponseData>;
pub type RefundsRouterData<F> = RouterData<F, RefundsData, RefundsResponseData>;
pub type RefundSyncRouterData = RouterData<RSync, RefundsData, RefundsResponseData>;
+pub type TokenizationRouterData =
+ RouterData<PaymentMethodToken, PaymentMethodTokenizationData, PaymentsResponseData>;
+pub type ConnectorCustomerRouterData =
+ RouterData<CreateConnectorCustomer, ConnectorCustomerData, PaymentsResponseData>;
+pub type PaymentsCompleteAuthorizeRouterData =
+ RouterData<CompleteAuthorize, CompleteAuthorizeData, PaymentsResponseData>;
diff --git a/crates/hyperswitch_interfaces/src/api.rs b/crates/hyperswitch_interfaces/src/api.rs
index 82ae0d141d7..0b4545a33d7 100644
--- a/crates/hyperswitch_interfaces/src/api.rs
+++ b/crates/hyperswitch_interfaces/src/api.rs
@@ -17,7 +17,7 @@ pub mod payouts_v2;
pub mod refunds;
pub mod refunds_v2;
-use common_enums::enums::{CaptureMethod, PaymentMethodType};
+use common_enums::enums::{CallConnectorAction, CaptureMethod, PaymentAction, PaymentMethodType};
use common_utils::{
errors::CustomResult,
request::{Method, Request, RequestContent},
@@ -398,3 +398,16 @@ pub trait ConnectorValidation: ConnectorCommon {
false
}
}
+
+/// trait ConnectorRedirectResponse
+pub trait ConnectorRedirectResponse {
+ /// fn get_flow_type
+ fn get_flow_type(
+ &self,
+ _query_params: &str,
+ _json_payload: Option<serde_json::Value>,
+ _action: PaymentAction,
+ ) -> CustomResult<CallConnectorAction, errors::ConnectorError> {
+ Ok(CallConnectorAction::Avoid)
+ }
+}
diff --git a/crates/router/src/connector.rs b/crates/router/src/connector.rs
index a421c931203..7d5fc28e2ba 100644
--- a/crates/router/src/connector.rs
+++ b/crates/router/src/connector.rs
@@ -3,11 +3,9 @@ pub mod adyen;
pub mod adyenplatform;
pub mod airwallex;
pub mod authorizedotnet;
-pub mod bambora;
pub mod bamboraapac;
pub mod bankofamerica;
pub mod billwerk;
-pub mod bitpay;
pub mod bluesnap;
pub mod boku;
pub mod braintree;
@@ -54,7 +52,6 @@ pub mod riskified;
pub mod shift4;
pub mod signifyd;
pub mod square;
-pub mod stax;
pub mod stripe;
pub mod threedsecureio;
pub mod trustpay;
@@ -68,24 +65,26 @@ pub mod worldpay;
pub mod zen;
pub mod zsl;
-pub use hyperswitch_connectors::connectors::{fiserv, fiserv::Fiserv, helcim, helcim::Helcim};
+pub use hyperswitch_connectors::connectors::{
+ bambora, bambora::Bambora, bitpay, bitpay::Bitpay, fiserv, fiserv::Fiserv, helcim,
+ helcim::Helcim, stax, stax::Stax,
+};
#[cfg(feature = "dummy_connector")]
pub use self::dummyconnector::DummyConnector;
pub use self::{
aci::Aci, adyen::Adyen, adyenplatform::Adyenplatform, airwallex::Airwallex,
- authorizedotnet::Authorizedotnet, bambora::Bambora, bamboraapac::Bamboraapac,
- bankofamerica::Bankofamerica, billwerk::Billwerk, bitpay::Bitpay, bluesnap::Bluesnap,
- boku::Boku, braintree::Braintree, cashtocode::Cashtocode, checkout::Checkout,
- coinbase::Coinbase, cryptopay::Cryptopay, cybersource::Cybersource, datatrans::Datatrans,
- dlocal::Dlocal, ebanx::Ebanx, forte::Forte, globalpay::Globalpay, globepay::Globepay,
- gocardless::Gocardless, gpayments::Gpayments, iatapay::Iatapay, itaubank::Itaubank,
- klarna::Klarna, mifinity::Mifinity, mollie::Mollie, multisafepay::Multisafepay,
- netcetera::Netcetera, nexinets::Nexinets, nmi::Nmi, noon::Noon, nuvei::Nuvei, opayo::Opayo,
- opennode::Opennode, payeezy::Payeezy, payme::Payme, payone::Payone, paypal::Paypal, payu::Payu,
- placetopay::Placetopay, plaid::Plaid, powertranz::Powertranz, prophetpay::Prophetpay,
- rapyd::Rapyd, razorpay::Razorpay, riskified::Riskified, shift4::Shift4, signifyd::Signifyd,
- square::Square, stax::Stax, stripe::Stripe, threedsecureio::Threedsecureio, trustpay::Trustpay,
- tsys::Tsys, volt::Volt, wellsfargo::Wellsfargo, wise::Wise, worldline::Worldline,
- worldpay::Worldpay, zen::Zen, zsl::Zsl,
+ authorizedotnet::Authorizedotnet, bamboraapac::Bamboraapac, bankofamerica::Bankofamerica,
+ billwerk::Billwerk, bluesnap::Bluesnap, boku::Boku, braintree::Braintree,
+ cashtocode::Cashtocode, checkout::Checkout, coinbase::Coinbase, cryptopay::Cryptopay,
+ cybersource::Cybersource, datatrans::Datatrans, dlocal::Dlocal, ebanx::Ebanx, forte::Forte,
+ globalpay::Globalpay, globepay::Globepay, gocardless::Gocardless, gpayments::Gpayments,
+ iatapay::Iatapay, itaubank::Itaubank, klarna::Klarna, mifinity::Mifinity, mollie::Mollie,
+ multisafepay::Multisafepay, netcetera::Netcetera, nexinets::Nexinets, nmi::Nmi, noon::Noon,
+ nuvei::Nuvei, opayo::Opayo, opennode::Opennode, payeezy::Payeezy, payme::Payme, payone::Payone,
+ paypal::Paypal, payu::Payu, placetopay::Placetopay, plaid::Plaid, powertranz::Powertranz,
+ prophetpay::Prophetpay, rapyd::Rapyd, razorpay::Razorpay, riskified::Riskified, shift4::Shift4,
+ signifyd::Signifyd, square::Square, stripe::Stripe, threedsecureio::Threedsecureio,
+ trustpay::Trustpay, tsys::Tsys, volt::Volt, wellsfargo::Wellsfargo, wise::Wise,
+ worldline::Worldline, worldpay::Worldpay, zen::Zen, zsl::Zsl,
};
diff --git a/crates/router/src/core/payments.rs b/crates/router/src/core/payments.rs
index 003c9561094..a165264117a 100644
--- a/crates/router/src/core/payments.rs
+++ b/crates/router/src/core/payments.rs
@@ -25,6 +25,7 @@ use api_models::{
mandates::RecurringDetails,
payments::{self as payments_api, HeaderPayload},
};
+pub use common_enums::enums::CallConnectorAction;
use common_utils::{
ext_traits::{AsyncExt, StringExt},
id_type, pii,
@@ -2661,18 +2662,6 @@ where
Ok(payment_data.to_owned())
}
-#[derive(Clone, PartialEq)]
-pub enum CallConnectorAction {
- Trigger,
- Avoid,
- StatusUpdate {
- status: storage_enums::AttemptStatus,
- error_code: Option<String>,
- error_message: Option<String>,
- },
- HandleResponse(Vec<u8>),
-}
-
#[derive(Clone)]
pub struct MandateConnectorDetails {
pub connector: String,
diff --git a/crates/router/src/core/payments/connector_integration_v2_impls.rs b/crates/router/src/core/payments/connector_integration_v2_impls.rs
index 019020b0b52..4090dc40462 100644
--- a/crates/router/src/core/payments/connector_integration_v2_impls.rs
+++ b/crates/router/src/core/payments/connector_integration_v2_impls.rs
@@ -639,11 +639,9 @@ default_imp_for_new_connector_integration_payment!(
connector::Adyenplatform,
connector::Airwallex,
connector::Authorizedotnet,
- connector::Bambora,
connector::Bamboraapac,
connector::Bankofamerica,
connector::Billwerk,
- connector::Bitpay,
connector::Bluesnap,
connector::Boku,
connector::Braintree,
@@ -686,7 +684,6 @@ default_imp_for_new_connector_integration_payment!(
connector::Riskified,
connector::Signifyd,
connector::Square,
- connector::Stax,
connector::Stripe,
connector::Shift4,
connector::Trustpay,
@@ -724,11 +721,9 @@ default_imp_for_new_connector_integration_refund!(
connector::Adyenplatform,
connector::Airwallex,
connector::Authorizedotnet,
- connector::Bambora,
connector::Bamboraapac,
connector::Bankofamerica,
connector::Billwerk,
- connector::Bitpay,
connector::Bluesnap,
connector::Boku,
connector::Braintree,
@@ -771,7 +766,6 @@ default_imp_for_new_connector_integration_refund!(
connector::Riskified,
connector::Signifyd,
connector::Square,
- connector::Stax,
connector::Stripe,
connector::Shift4,
connector::Trustpay,
@@ -804,11 +798,9 @@ default_imp_for_new_connector_integration_connector_access_token!(
connector::Adyenplatform,
connector::Airwallex,
connector::Authorizedotnet,
- connector::Bambora,
connector::Bamboraapac,
connector::Bankofamerica,
connector::Billwerk,
- connector::Bitpay,
connector::Bluesnap,
connector::Boku,
connector::Braintree,
@@ -851,7 +843,6 @@ default_imp_for_new_connector_integration_connector_access_token!(
connector::Riskified,
connector::Signifyd,
connector::Square,
- connector::Stax,
connector::Stripe,
connector::Shift4,
connector::Trustpay,
@@ -906,11 +897,9 @@ default_imp_for_new_connector_integration_accept_dispute!(
connector::Adyenplatform,
connector::Airwallex,
connector::Authorizedotnet,
- connector::Bambora,
connector::Bamboraapac,
connector::Bankofamerica,
connector::Billwerk,
- connector::Bitpay,
connector::Bluesnap,
connector::Boku,
connector::Braintree,
@@ -953,7 +942,6 @@ default_imp_for_new_connector_integration_accept_dispute!(
connector::Riskified,
connector::Signifyd,
connector::Square,
- connector::Stax,
connector::Stripe,
connector::Shift4,
connector::Trustpay,
@@ -990,11 +978,9 @@ default_imp_for_new_connector_integration_defend_dispute!(
connector::Adyenplatform,
connector::Airwallex,
connector::Authorizedotnet,
- connector::Bambora,
connector::Bamboraapac,
connector::Bankofamerica,
connector::Billwerk,
- connector::Bitpay,
connector::Bluesnap,
connector::Boku,
connector::Braintree,
@@ -1037,7 +1023,6 @@ default_imp_for_new_connector_integration_defend_dispute!(
connector::Riskified,
connector::Signifyd,
connector::Square,
- connector::Stax,
connector::Stripe,
connector::Shift4,
connector::Trustpay,
@@ -1058,11 +1043,9 @@ default_imp_for_new_connector_integration_submit_evidence!(
connector::Adyenplatform,
connector::Airwallex,
connector::Authorizedotnet,
- connector::Bambora,
connector::Bamboraapac,
connector::Bankofamerica,
connector::Billwerk,
- connector::Bitpay,
connector::Bluesnap,
connector::Boku,
connector::Braintree,
@@ -1105,7 +1088,6 @@ default_imp_for_new_connector_integration_submit_evidence!(
connector::Riskified,
connector::Signifyd,
connector::Square,
- connector::Stax,
connector::Stripe,
connector::Shift4,
connector::Trustpay,
@@ -1153,11 +1135,9 @@ default_imp_for_new_connector_integration_file_upload!(
connector::Adyenplatform,
connector::Airwallex,
connector::Authorizedotnet,
- connector::Bambora,
connector::Bamboraapac,
connector::Bankofamerica,
connector::Billwerk,
- connector::Bitpay,
connector::Bluesnap,
connector::Boku,
connector::Braintree,
@@ -1200,7 +1180,6 @@ default_imp_for_new_connector_integration_file_upload!(
connector::Riskified,
connector::Signifyd,
connector::Square,
- connector::Stax,
connector::Stripe,
connector::Shift4,
connector::Trustpay,
@@ -1319,11 +1298,9 @@ default_imp_for_new_connector_integration_payouts_create!(
connector::Adyenplatform,
connector::Airwallex,
connector::Authorizedotnet,
- connector::Bambora,
connector::Bamboraapac,
connector::Bankofamerica,
connector::Billwerk,
- connector::Bitpay,
connector::Bluesnap,
connector::Boku,
connector::Braintree,
@@ -1366,7 +1343,6 @@ default_imp_for_new_connector_integration_payouts_create!(
connector::Riskified,
connector::Signifyd,
connector::Square,
- connector::Stax,
connector::Stripe,
connector::Shift4,
connector::Trustpay,
@@ -1406,11 +1382,9 @@ default_imp_for_new_connector_integration_payouts_eligibility!(
connector::Adyenplatform,
connector::Airwallex,
connector::Authorizedotnet,
- connector::Bambora,
connector::Bamboraapac,
connector::Bankofamerica,
connector::Billwerk,
- connector::Bitpay,
connector::Bluesnap,
connector::Boku,
connector::Braintree,
@@ -1453,7 +1427,6 @@ default_imp_for_new_connector_integration_payouts_eligibility!(
connector::Riskified,
connector::Signifyd,
connector::Square,
- connector::Stax,
connector::Stripe,
connector::Shift4,
connector::Trustpay,
@@ -1493,11 +1466,9 @@ default_imp_for_new_connector_integration_payouts_fulfill!(
connector::Adyenplatform,
connector::Airwallex,
connector::Authorizedotnet,
- connector::Bambora,
connector::Bamboraapac,
connector::Bankofamerica,
connector::Billwerk,
- connector::Bitpay,
connector::Bluesnap,
connector::Boku,
connector::Braintree,
@@ -1540,7 +1511,6 @@ default_imp_for_new_connector_integration_payouts_fulfill!(
connector::Riskified,
connector::Signifyd,
connector::Square,
- connector::Stax,
connector::Stripe,
connector::Shift4,
connector::Trustpay,
@@ -1580,11 +1550,9 @@ default_imp_for_new_connector_integration_payouts_cancel!(
connector::Adyenplatform,
connector::Airwallex,
connector::Authorizedotnet,
- connector::Bambora,
connector::Bamboraapac,
connector::Bankofamerica,
connector::Billwerk,
- connector::Bitpay,
connector::Bluesnap,
connector::Boku,
connector::Braintree,
@@ -1627,7 +1595,6 @@ default_imp_for_new_connector_integration_payouts_cancel!(
connector::Riskified,
connector::Signifyd,
connector::Square,
- connector::Stax,
connector::Stripe,
connector::Shift4,
connector::Trustpay,
@@ -1667,11 +1634,9 @@ default_imp_for_new_connector_integration_payouts_quote!(
connector::Adyenplatform,
connector::Airwallex,
connector::Authorizedotnet,
- connector::Bambora,
connector::Bamboraapac,
connector::Bankofamerica,
connector::Billwerk,
- connector::Bitpay,
connector::Bluesnap,
connector::Boku,
connector::Braintree,
@@ -1714,7 +1679,6 @@ default_imp_for_new_connector_integration_payouts_quote!(
connector::Riskified,
connector::Signifyd,
connector::Square,
- connector::Stax,
connector::Stripe,
connector::Shift4,
connector::Trustpay,
@@ -1754,11 +1718,9 @@ default_imp_for_new_connector_integration_payouts_recipient!(
connector::Adyenplatform,
connector::Airwallex,
connector::Authorizedotnet,
- connector::Bambora,
connector::Bamboraapac,
connector::Bankofamerica,
connector::Billwerk,
- connector::Bitpay,
connector::Bluesnap,
connector::Boku,
connector::Braintree,
@@ -1801,7 +1763,6 @@ default_imp_for_new_connector_integration_payouts_recipient!(
connector::Riskified,
connector::Signifyd,
connector::Square,
- connector::Stax,
connector::Stripe,
connector::Shift4,
connector::Trustpay,
@@ -1841,11 +1802,9 @@ default_imp_for_new_connector_integration_payouts_sync!(
connector::Adyen,
connector::Airwallex,
connector::Authorizedotnet,
- connector::Bambora,
connector::Bamboraapac,
connector::Bankofamerica,
connector::Billwerk,
- connector::Bitpay,
connector::Bluesnap,
connector::Boku,
connector::Braintree,
@@ -1889,7 +1848,6 @@ default_imp_for_new_connector_integration_payouts_sync!(
connector::Signifyd,
connector::Stripe,
connector::Square,
- connector::Stax,
connector::Shift4,
connector::Threedsecureio,
connector::Trustpay,
@@ -1928,11 +1886,9 @@ default_imp_for_new_connector_integration_payouts_recipient_account!(
connector::Adyenplatform,
connector::Airwallex,
connector::Authorizedotnet,
- connector::Bambora,
connector::Bamboraapac,
connector::Bankofamerica,
connector::Billwerk,
- connector::Bitpay,
connector::Bluesnap,
connector::Boku,
connector::Braintree,
@@ -1975,7 +1931,6 @@ default_imp_for_new_connector_integration_payouts_recipient_account!(
connector::Riskified,
connector::Signifyd,
connector::Square,
- connector::Stax,
connector::Stripe,
connector::Shift4,
connector::Trustpay,
@@ -2013,11 +1968,9 @@ default_imp_for_new_connector_integration_webhook_source_verification!(
connector::Adyenplatform,
connector::Airwallex,
connector::Authorizedotnet,
- connector::Bambora,
connector::Bamboraapac,
connector::Bankofamerica,
connector::Billwerk,
- connector::Bitpay,
connector::Bluesnap,
connector::Boku,
connector::Braintree,
@@ -2060,7 +2013,6 @@ default_imp_for_new_connector_integration_webhook_source_verification!(
connector::Riskified,
connector::Signifyd,
connector::Square,
- connector::Stax,
connector::Stripe,
connector::Shift4,
connector::Trustpay,
@@ -2179,11 +2131,9 @@ default_imp_for_new_connector_integration_frm_sale!(
connector::Adyenplatform,
connector::Airwallex,
connector::Authorizedotnet,
- connector::Bambora,
connector::Bamboraapac,
connector::Bankofamerica,
connector::Billwerk,
- connector::Bitpay,
connector::Bluesnap,
connector::Boku,
connector::Braintree,
@@ -2226,7 +2176,6 @@ default_imp_for_new_connector_integration_frm_sale!(
connector::Riskified,
connector::Signifyd,
connector::Square,
- connector::Stax,
connector::Stripe,
connector::Shift4,
connector::Trustpay,
@@ -2266,11 +2215,9 @@ default_imp_for_new_connector_integration_frm_checkout!(
connector::Adyenplatform,
connector::Airwallex,
connector::Authorizedotnet,
- connector::Bambora,
connector::Bamboraapac,
connector::Bankofamerica,
connector::Billwerk,
- connector::Bitpay,
connector::Bluesnap,
connector::Boku,
connector::Braintree,
@@ -2313,7 +2260,6 @@ default_imp_for_new_connector_integration_frm_checkout!(
connector::Riskified,
connector::Signifyd,
connector::Square,
- connector::Stax,
connector::Stripe,
connector::Shift4,
connector::Trustpay,
@@ -2353,11 +2299,9 @@ default_imp_for_new_connector_integration_frm_transaction!(
connector::Adyenplatform,
connector::Airwallex,
connector::Authorizedotnet,
- connector::Bambora,
connector::Bamboraapac,
connector::Bankofamerica,
connector::Billwerk,
- connector::Bitpay,
connector::Bluesnap,
connector::Boku,
connector::Braintree,
@@ -2400,7 +2344,6 @@ default_imp_for_new_connector_integration_frm_transaction!(
connector::Riskified,
connector::Signifyd,
connector::Square,
- connector::Stax,
connector::Stripe,
connector::Shift4,
connector::Trustpay,
@@ -2440,11 +2383,9 @@ default_imp_for_new_connector_integration_frm_fulfillment!(
connector::Adyenplatform,
connector::Airwallex,
connector::Authorizedotnet,
- connector::Bambora,
connector::Bamboraapac,
connector::Bankofamerica,
connector::Billwerk,
- connector::Bitpay,
connector::Bluesnap,
connector::Boku,
connector::Braintree,
@@ -2487,7 +2428,6 @@ default_imp_for_new_connector_integration_frm_fulfillment!(
connector::Riskified,
connector::Signifyd,
connector::Square,
- connector::Stax,
connector::Stripe,
connector::Shift4,
connector::Trustpay,
@@ -2527,11 +2467,9 @@ default_imp_for_new_connector_integration_frm_record_return!(
connector::Adyenplatform,
connector::Airwallex,
connector::Authorizedotnet,
- connector::Bambora,
connector::Bamboraapac,
connector::Bankofamerica,
connector::Billwerk,
- connector::Bitpay,
connector::Bluesnap,
connector::Boku,
connector::Braintree,
@@ -2574,7 +2512,6 @@ default_imp_for_new_connector_integration_frm_record_return!(
connector::Riskified,
connector::Signifyd,
connector::Square,
- connector::Stax,
connector::Stripe,
connector::Shift4,
connector::Trustpay,
@@ -2611,11 +2548,9 @@ default_imp_for_new_connector_integration_revoking_mandates!(
connector::Adyenplatform,
connector::Airwallex,
connector::Authorizedotnet,
- connector::Bambora,
connector::Bamboraapac,
connector::Bankofamerica,
connector::Billwerk,
- connector::Bitpay,
connector::Bluesnap,
connector::Boku,
connector::Braintree,
@@ -2658,7 +2593,6 @@ default_imp_for_new_connector_integration_revoking_mandates!(
connector::Riskified,
connector::Signifyd,
connector::Square,
- connector::Stax,
connector::Stripe,
connector::Shift4,
connector::Trustpay,
diff --git a/crates/router/src/core/payments/flows.rs b/crates/router/src/core/payments/flows.rs
index 6756b9ff5dc..af56c7e4ba6 100644
--- a/crates/router/src/core/payments/flows.rs
+++ b/crates/router/src/core/payments/flows.rs
@@ -192,7 +192,6 @@ default_imp_for_complete_authorize!(
connector::Bamboraapac,
connector::Bankofamerica,
connector::Billwerk,
- connector::Bitpay,
connector::Boku,
connector::Cashtocode,
connector::Checkout,
@@ -225,7 +224,6 @@ default_imp_for_complete_authorize!(
connector::Riskified,
connector::Signifyd,
connector::Square,
- connector::Stax,
connector::Stripe,
connector::Threedsecureio,
connector::Trustpay,
@@ -270,11 +268,9 @@ default_imp_for_webhook_source_verification!(
connector::Adyen,
connector::Airwallex,
connector::Authorizedotnet,
- connector::Bambora,
connector::Bamboraapac,
connector::Bankofamerica,
connector::Billwerk,
- connector::Bitpay,
connector::Bluesnap,
connector::Braintree,
connector::Boku,
@@ -318,7 +314,6 @@ default_imp_for_webhook_source_verification!(
connector::Shift4,
connector::Signifyd,
connector::Square,
- connector::Stax,
connector::Stripe,
connector::Threedsecureio,
connector::Trustpay,
@@ -365,11 +360,9 @@ default_imp_for_create_customer!(
connector::Adyen,
connector::Airwallex,
connector::Authorizedotnet,
- connector::Bambora,
connector::Bamboraapac,
connector::Bankofamerica,
connector::Billwerk,
- connector::Bitpay,
connector::Bluesnap,
connector::Boku,
connector::Braintree,
@@ -459,7 +452,6 @@ default_imp_for_connector_redirect_response!(
connector::Aci,
connector::Adyen,
connector::Bamboraapac,
- connector::Bitpay,
connector::Bankofamerica,
connector::Billwerk,
connector::Boku,
@@ -470,12 +462,10 @@ default_imp_for_connector_redirect_response!(
connector::Datatrans,
connector::Dlocal,
connector::Ebanx,
- connector::Fiserv,
connector::Forte,
connector::Globepay,
connector::Gocardless,
connector::Gpayments,
- connector::Helcim,
connector::Iatapay,
connector::Itaubank,
connector::Klarna,
@@ -498,7 +488,6 @@ default_imp_for_connector_redirect_response!(
connector::Shift4,
connector::Signifyd,
connector::Square,
- connector::Stax,
connector::Threedsecureio,
connector::Tsys,
connector::Volt,
@@ -625,11 +614,9 @@ default_imp_for_accept_dispute!(
connector::Adyen,
connector::Airwallex,
connector::Authorizedotnet,
- connector::Bambora,
connector::Bamboraapac,
connector::Bankofamerica,
connector::Billwerk,
- connector::Bitpay,
connector::Bluesnap,
connector::Boku,
connector::Braintree,
@@ -673,7 +660,6 @@ default_imp_for_accept_dispute!(
connector::Shift4,
connector::Signifyd,
connector::Square,
- connector::Stax,
connector::Stripe,
connector::Threedsecureio,
connector::Trustpay,
@@ -742,11 +728,9 @@ default_imp_for_file_upload!(
connector::Adyen,
connector::Airwallex,
connector::Authorizedotnet,
- connector::Bambora,
connector::Bamboraapac,
connector::Bankofamerica,
connector::Billwerk,
- connector::Bitpay,
connector::Bluesnap,
connector::Boku,
connector::Braintree,
@@ -789,7 +773,6 @@ default_imp_for_file_upload!(
connector::Shift4,
connector::Signifyd,
connector::Square,
- connector::Stax,
connector::Threedsecureio,
connector::Trustpay,
connector::Tsys,
@@ -836,11 +819,9 @@ default_imp_for_submit_evidence!(
connector::Adyen,
connector::Airwallex,
connector::Authorizedotnet,
- connector::Bambora,
connector::Bamboraapac,
connector::Bankofamerica,
connector::Billwerk,
- connector::Bitpay,
connector::Bluesnap,
connector::Boku,
connector::Braintree,
@@ -883,7 +864,6 @@ default_imp_for_submit_evidence!(
connector::Shift4,
connector::Signifyd,
connector::Square,
- connector::Stax,
connector::Threedsecureio,
connector::Trustpay,
connector::Tsys,
@@ -930,11 +910,9 @@ default_imp_for_defend_dispute!(
connector::Adyen,
connector::Airwallex,
connector::Authorizedotnet,
- connector::Bambora,
connector::Bamboraapac,
connector::Bankofamerica,
connector::Billwerk,
- connector::Bitpay,
connector::Bluesnap,
connector::Boku,
connector::Braintree,
@@ -977,7 +955,6 @@ default_imp_for_defend_dispute!(
connector::Shift4,
connector::Signifyd,
connector::Square,
- connector::Stax,
connector::Stripe,
connector::Threedsecureio,
connector::Trustpay,
@@ -1038,11 +1015,9 @@ default_imp_for_pre_processing_steps!(
connector::Adyenplatform,
connector::Aci,
connector::Authorizedotnet,
- connector::Bambora,
connector::Bamboraapac,
connector::Bankofamerica,
connector::Billwerk,
- connector::Bitpay,
connector::Bluesnap,
connector::Boku,
connector::Braintree,
@@ -1080,7 +1055,6 @@ default_imp_for_pre_processing_steps!(
connector::Riskified,
connector::Signifyd,
connector::Square,
- connector::Stax,
connector::Threedsecureio,
connector::Tsys,
connector::Volt,
@@ -1120,10 +1094,8 @@ default_imp_for_post_processing_steps!(
connector::Trustpay,
connector::Aci,
connector::Authorizedotnet,
- connector::Bambora,
connector::Bamboraapac,
connector::Billwerk,
- connector::Bitpay,
connector::Bluesnap,
connector::Boku,
connector::Braintree,
@@ -1159,7 +1131,6 @@ default_imp_for_post_processing_steps!(
connector::Riskified,
connector::Signifyd,
connector::Square,
- connector::Stax,
connector::Threedsecureio,
connector::Tsys,
connector::Volt,
@@ -1279,11 +1250,9 @@ default_imp_for_payouts_create!(
connector::Aci,
connector::Airwallex,
connector::Authorizedotnet,
- connector::Bambora,
connector::Bamboraapac,
connector::Bankofamerica,
connector::Billwerk,
- connector::Bitpay,
connector::Bluesnap,
connector::Boku,
connector::Braintree,
@@ -1325,7 +1294,6 @@ default_imp_for_payouts_create!(
connector::Riskified,
connector::Signifyd,
connector::Square,
- connector::Stax,
connector::Shift4,
connector::Threedsecureio,
connector::Trustpay,
@@ -1372,11 +1340,9 @@ default_imp_for_payouts_retrieve!(
connector::Adyen,
connector::Airwallex,
connector::Authorizedotnet,
- connector::Bambora,
connector::Bamboraapac,
connector::Bankofamerica,
connector::Billwerk,
- connector::Bitpay,
connector::Bluesnap,
connector::Boku,
connector::Braintree,
@@ -1420,7 +1386,6 @@ default_imp_for_payouts_retrieve!(
connector::Signifyd,
connector::Stripe,
connector::Square,
- connector::Stax,
connector::Shift4,
connector::Threedsecureio,
connector::Trustpay,
@@ -1470,11 +1435,9 @@ default_imp_for_payouts_eligibility!(
connector::Aci,
connector::Airwallex,
connector::Authorizedotnet,
- connector::Bambora,
connector::Bamboraapac,
connector::Bankofamerica,
connector::Billwerk,
- connector::Bitpay,
connector::Bluesnap,
connector::Boku,
connector::Braintree,
@@ -1517,7 +1480,6 @@ default_imp_for_payouts_eligibility!(
connector::Riskified,
connector::Signifyd,
connector::Square,
- connector::Stax,
connector::Stripe,
connector::Shift4,
connector::Threedsecureio,
@@ -1563,11 +1525,9 @@ default_imp_for_payouts_fulfill!(
connector::Aci,
connector::Airwallex,
connector::Authorizedotnet,
- connector::Bambora,
connector::Bamboraapac,
connector::Bankofamerica,
connector::Billwerk,
- connector::Bitpay,
connector::Bluesnap,
connector::Boku,
connector::Braintree,
@@ -1607,7 +1567,6 @@ default_imp_for_payouts_fulfill!(
connector::Riskified,
connector::Signifyd,
connector::Square,
- connector::Stax,
connector::Shift4,
connector::Threedsecureio,
connector::Trustpay,
@@ -1653,11 +1612,9 @@ default_imp_for_payouts_cancel!(
connector::Aci,
connector::Airwallex,
connector::Authorizedotnet,
- connector::Bambora,
connector::Bamboraapac,
connector::Bankofamerica,
connector::Billwerk,
- connector::Bitpay,
connector::Bluesnap,
connector::Boku,
connector::Braintree,
@@ -1700,7 +1657,6 @@ default_imp_for_payouts_cancel!(
connector::Riskified,
connector::Signifyd,
connector::Square,
- connector::Stax,
connector::Shift4,
connector::Threedsecureio,
connector::Trustpay,
@@ -1747,11 +1703,9 @@ default_imp_for_payouts_quote!(
connector::Adyen,
connector::Airwallex,
connector::Authorizedotnet,
- connector::Bambora,
connector::Bamboraapac,
connector::Bankofamerica,
connector::Billwerk,
- connector::Bitpay,
connector::Bluesnap,
connector::Boku,
connector::Braintree,
@@ -1794,7 +1748,6 @@ default_imp_for_payouts_quote!(
connector::Riskified,
connector::Signifyd,
connector::Square,
- connector::Stax,
connector::Stripe,
connector::Shift4,
connector::Threedsecureio,
@@ -1842,11 +1795,9 @@ default_imp_for_payouts_recipient!(
connector::Adyen,
connector::Airwallex,
connector::Authorizedotnet,
- connector::Bambora,
connector::Bamboraapac,
connector::Bankofamerica,
connector::Billwerk,
- connector::Bitpay,
connector::Bluesnap,
connector::Boku,
connector::Braintree,
@@ -1889,7 +1840,6 @@ default_imp_for_payouts_recipient!(
connector::Riskified,
connector::Signifyd,
connector::Square,
- connector::Stax,
connector::Shift4,
connector::Threedsecureio,
connector::Trustpay,
@@ -1939,11 +1889,9 @@ default_imp_for_payouts_recipient_account!(
connector::Adyen,
connector::Airwallex,
connector::Authorizedotnet,
- connector::Bambora,
connector::Bamboraapac,
connector::Bankofamerica,
connector::Billwerk,
- connector::Bitpay,
connector::Bluesnap,
connector::Boku,
connector::Braintree,
@@ -1987,7 +1935,6 @@ default_imp_for_payouts_recipient_account!(
connector::Riskified,
connector::Signifyd,
connector::Square,
- connector::Stax,
connector::Shift4,
connector::Threedsecureio,
connector::Trustpay,
@@ -2034,11 +1981,9 @@ default_imp_for_approve!(
connector::Adyen,
connector::Airwallex,
connector::Authorizedotnet,
- connector::Bambora,
connector::Bamboraapac,
connector::Bankofamerica,
connector::Billwerk,
- connector::Bitpay,
connector::Bluesnap,
connector::Boku,
connector::Braintree,
@@ -2082,7 +2027,6 @@ default_imp_for_approve!(
connector::Riskified,
connector::Signifyd,
connector::Square,
- connector::Stax,
connector::Stripe,
connector::Shift4,
connector::Threedsecureio,
@@ -2130,11 +2074,9 @@ default_imp_for_reject!(
connector::Adyen,
connector::Airwallex,
connector::Authorizedotnet,
- connector::Bambora,
connector::Bamboraapac,
connector::Bankofamerica,
connector::Billwerk,
- connector::Bitpay,
connector::Bluesnap,
connector::Boku,
connector::Braintree,
@@ -2178,7 +2120,6 @@ default_imp_for_reject!(
connector::Riskified,
connector::Signifyd,
connector::Square,
- connector::Stax,
connector::Stripe,
connector::Shift4,
connector::Threedsecureio,
@@ -2308,11 +2249,9 @@ default_imp_for_frm_sale!(
connector::Adyen,
connector::Airwallex,
connector::Authorizedotnet,
- connector::Bambora,
connector::Bamboraapac,
connector::Bankofamerica,
connector::Billwerk,
- connector::Bitpay,
connector::Bluesnap,
connector::Boku,
connector::Braintree,
@@ -2354,7 +2293,6 @@ default_imp_for_frm_sale!(
connector::Rapyd,
connector::Razorpay,
connector::Square,
- connector::Stax,
connector::Stripe,
connector::Shift4,
connector::Threedsecureio,
@@ -2404,11 +2342,9 @@ default_imp_for_frm_checkout!(
connector::Adyen,
connector::Airwallex,
connector::Authorizedotnet,
- connector::Bambora,
connector::Bamboraapac,
connector::Bankofamerica,
connector::Billwerk,
- connector::Bitpay,
connector::Bluesnap,
connector::Boku,
connector::Braintree,
@@ -2450,7 +2386,6 @@ default_imp_for_frm_checkout!(
connector::Rapyd,
connector::Razorpay,
connector::Square,
- connector::Stax,
connector::Stripe,
connector::Shift4,
connector::Threedsecureio,
@@ -2500,11 +2435,9 @@ default_imp_for_frm_transaction!(
connector::Adyen,
connector::Airwallex,
connector::Authorizedotnet,
- connector::Bambora,
connector::Bamboraapac,
connector::Bankofamerica,
connector::Billwerk,
- connector::Bitpay,
connector::Bluesnap,
connector::Boku,
connector::Braintree,
@@ -2546,7 +2479,6 @@ default_imp_for_frm_transaction!(
connector::Rapyd,
connector::Razorpay,
connector::Square,
- connector::Stax,
connector::Stripe,
connector::Shift4,
connector::Threedsecureio,
@@ -2596,11 +2528,9 @@ default_imp_for_frm_fulfillment!(
connector::Adyen,
connector::Airwallex,
connector::Authorizedotnet,
- connector::Bambora,
connector::Bamboraapac,
connector::Bankofamerica,
connector::Billwerk,
- connector::Bitpay,
connector::Bluesnap,
connector::Boku,
connector::Braintree,
@@ -2642,7 +2572,6 @@ default_imp_for_frm_fulfillment!(
connector::Rapyd,
connector::Razorpay,
connector::Square,
- connector::Stax,
connector::Stripe,
connector::Shift4,
connector::Threedsecureio,
@@ -2692,11 +2621,9 @@ default_imp_for_frm_record_return!(
connector::Adyen,
connector::Airwallex,
connector::Authorizedotnet,
- connector::Bambora,
connector::Bamboraapac,
connector::Bankofamerica,
connector::Billwerk,
- connector::Bitpay,
connector::Bluesnap,
connector::Boku,
connector::Braintree,
@@ -2738,7 +2665,6 @@ default_imp_for_frm_record_return!(
connector::Rapyd,
connector::Razorpay,
connector::Square,
- connector::Stax,
connector::Stripe,
connector::Shift4,
connector::Threedsecureio,
@@ -2786,11 +2712,9 @@ default_imp_for_incremental_authorization!(
connector::Adyen,
connector::Airwallex,
connector::Authorizedotnet,
- connector::Bambora,
connector::Bamboraapac,
connector::Bankofamerica,
connector::Billwerk,
- connector::Bitpay,
connector::Bluesnap,
connector::Boku,
connector::Braintree,
@@ -2833,7 +2757,6 @@ default_imp_for_incremental_authorization!(
connector::Riskified,
connector::Signifyd,
connector::Square,
- connector::Stax,
connector::Stripe,
connector::Shift4,
connector::Threedsecureio,
@@ -2879,11 +2802,9 @@ default_imp_for_revoking_mandates!(
connector::Adyen,
connector::Airwallex,
connector::Authorizedotnet,
- connector::Bambora,
connector::Bamboraapac,
connector::Bankofamerica,
connector::Billwerk,
- connector::Bitpay,
connector::Bluesnap,
connector::Boku,
connector::Braintree,
@@ -2925,7 +2846,6 @@ default_imp_for_revoking_mandates!(
connector::Riskified,
connector::Signifyd,
connector::Square,
- connector::Stax,
connector::Stripe,
connector::Shift4,
connector::Threedsecureio,
@@ -3124,11 +3044,9 @@ default_imp_for_authorize_session_token!(
connector::Adyenplatform,
connector::Airwallex,
connector::Authorizedotnet,
- connector::Bambora,
connector::Bamboraapac,
connector::Bankofamerica,
connector::Billwerk,
- connector::Bitpay,
connector::Bluesnap,
connector::Boku,
connector::Braintree,
@@ -3170,7 +3088,6 @@ default_imp_for_authorize_session_token!(
connector::Razorpay,
connector::Riskified,
connector::Signifyd,
- connector::Stax,
connector::Stripe,
connector::Shift4,
connector::Threedsecureio,
diff --git a/crates/router/src/services/api.rs b/crates/router/src/services/api.rs
index 795d6dd9eff..322478da295 100644
--- a/crates/router/src/services/api.rs
+++ b/crates/router/src/services/api.rs
@@ -18,6 +18,7 @@ use actix_web::{
web, FromRequest, HttpRequest, HttpResponse, Responder, ResponseError,
};
pub use client::{proxy_bypass_urls, ApiClient, MockApiClient, ProxyClient};
+pub use common_enums::enums::PaymentAction;
pub use common_utils::request::{ContentType, Method, Request, RequestBuilder};
use common_utils::{
consts::{DEFAULT_TENANT, TENANT_HEADER, X_HS_LATENCY},
@@ -37,7 +38,7 @@ pub use hyperswitch_domain_models::{
pub use hyperswitch_interfaces::{
api::{
BoxedConnectorIntegration, CaptureSyncMethod, ConnectorIntegration,
- ConnectorIntegrationAny, ConnectorValidation,
+ ConnectorIntegrationAny, ConnectorRedirectResponse, ConnectorValidation,
},
connector_integration_v2::{
BoxedConnectorIntegrationV2, ConnectorIntegrationAnyV2, ConnectorIntegrationV2,
@@ -672,13 +673,6 @@ async fn handle_response(
.await
}
-#[derive(Debug, Eq, PartialEq)]
-pub enum PaymentAction {
- PSync,
- CompleteAuthorize,
- PaymentAuthenticateCompleteAuthorize,
-}
-
#[derive(Debug, Eq, PartialEq, Serialize)]
pub struct ApplicationRedirectResponse {
pub url: String,
@@ -1219,17 +1213,6 @@ pub fn http_response_err<T: body::MessageBody + 'static>(response: T) -> HttpRes
.body(response)
}
-pub trait ConnectorRedirectResponse {
- fn get_flow_type(
- &self,
- _query_params: &str,
- _json_payload: Option<serde_json::Value>,
- _action: PaymentAction,
- ) -> CustomResult<payments::CallConnectorAction, errors::ConnectorError> {
- Ok(payments::CallConnectorAction::Avoid)
- }
-}
-
pub trait Authenticate {
fn get_client_secret(&self) -> Option<&String> {
None
|
2024-07-26T10:09:10Z
|
## Type of Change
<!-- Put an `x` in the boxes that apply -->
- [ ] Bugfix
- [x] New feature
- [ ] Enhancement
- [ ] Refactoring
- [ ] Dependency updates
- [ ] Documentation
- [ ] CI/CD
## Description
<!-- Describe your changes in detail -->
Move connector code for `bambora, bitpay and stax` from crate `router` to crate `hyperswitch_connectors`.
### Additional Changes
- [ ] This PR modifies the API contract
- [ ] This PR modifies the database schema
- [ ] This PR modifies application configuration/environment variables
<!--
Provide links to the files with corresponding changes.
Following are the paths where you can find config files:
1. `config`
2. `crates/router/src/configs`
3. `loadtest/config`
-->
## Motivation and Context
<!--
Why is this change required? What problem does it solve?
If it fixes an open issue, please link to the issue here.
If you don't have an issue, we'd recommend starting with one first so the PR
can focus on the implementation (unless it is an obvious bug or documentation fix
that will have little conversation).
-->
https://github.com/juspay/hyperswitch/issues/5451
## How did you test it?
<!--
Did you write an integration/unit/API test to verify the code changes?
Or did you test this change manually (provide relevant screenshots)?
-->
The following flows need to be tested for connector `Bambora`:
1. Authorize(Auto Capture):
Request:
```
curl --location 'http://localhost:8080/payments' \
--header 'Content-Type: application/json' \
--header 'Accept: application/json' \
--header 'api-key: dev_cNgJBniCHyPWijpb73YRpH06jVNPFSU8B8oZl9yJCa1tK9wO3kru8HXSeYfvREpD' \
--data '{
"amount": 2000,
"currency": "USD",
"confirm": true,
"customer_id": "assdre1v",
"authentication_type": "no_three_ds",
"payment_method": "card",
"payment_method_type": "credit",
"payment_method_data": {
"card": {
"card_number": "4030000010001234",
"card_exp_month": "10",
"card_exp_year": "24",
"card_holder_name": "Sundari KK",
"card_cvc": "123"
}
}
}'
```
Response:
```
{
"payment_id": "pay_9iF0FWAx4IczBe6lfjqN",
"merchant_id": "merchant_1722320361",
"status": "succeeded",
"amount": 2000,
"net_amount": 2000,
"amount_capturable": 0,
"amount_received": 2000,
"connector": "bambora",
"client_secret": "pay_9iF0FWAx4IczBe6lfjqN_secret_4AqBHdIhtcaLfUgaASFu",
"created": "2024-07-30T06:22:16.297Z",
"currency": "USD",
"customer_id": "assdre1v",
"customer": {
"id": "assdre1v",
"name": null,
"email": null,
"phone": null,
"phone_country_code": null
},
"description": null,
"refunds": null,
"disputes": null,
"mandate_id": null,
"mandate_data": null,
"setup_future_usage": null,
"off_session": null,
"capture_on": null,
"capture_method": null,
"payment_method": "card",
"payment_method_data": {
"card": {
"last4": "1234",
"card_type": null,
"card_network": null,
"card_issuer": null,
"card_issuing_country": null,
"card_isin": "403000",
"card_extended_bin": null,
"card_exp_month": "10",
"card_exp_year": "24",
"card_holder_name": "Sundari KK",
"payment_checks": null,
"authentication_data": null
},
"billing": null
},
"payment_token": null,
"shipping": null,
"billing": null,
"order_details": null,
"email": null,
"name": null,
"phone": null,
"return_url": null,
"authentication_type": "no_three_ds",
"statement_descriptor_name": null,
"statement_descriptor_suffix": null,
"next_action": null,
"cancellation_reason": null,
"error_code": null,
"error_message": null,
"unified_code": null,
"unified_message": null,
"payment_experience": null,
"payment_method_type": "credit",
"connector_label": null,
"business_country": null,
"business_label": "default",
"business_sub_label": null,
"allowed_payment_method_types": null,
"ephemeral_key": {
"customer_id": "assdre1v",
"created_at": 1722320536,
"expires": 1722324136,
"secret": "epk_54a280472ee5468d9153d58fe3681776"
},
"manual_retry_allowed": false,
"connector_transaction_id": "10005121",
"frm_message": null,
"metadata": null,
"connector_metadata": null,
"feature_metadata": null,
"reference_id": "pay_9iF0FWAx4IczBe6lfjqN_1",
"payment_link": null,
"profile_id": "pro_sUtV9MeXG0JSXuSGISfQ",
"surcharge_details": null,
"attempt_count": 1,
"merchant_decision": null,
"merchant_connector_id": "mca_iMJkO4jVosAfhRagvx0w",
"incremental_authorization_allowed": null,
"authorization_count": null,
"incremental_authorizations": null,
"external_authentication_details": null,
"external_3ds_authentication_attempted": false,
"expires_on": "2024-07-30T06:37:16.297Z",
"fingerprint": null,
"browser_info": null,
"payment_method_id": null,
"payment_method_status": null,
"updated": "2024-07-30T06:22:18.261Z",
"charges": null,
"frm_metadata": null,
"merchant_order_reference_id": null
}
```
2. Authorize(Manual Capture):
Request:
```
curl --location 'http://localhost:8080/payments' \
--header 'Content-Type: application/json' \
--header 'Accept: application/json' \
--header 'api-key: dev_cNgJBniCHyPWijpb73YRpH06jVNPFSU8B8oZl9yJCa1tK9wO3kru8HXSeYfvREpD' \
--data '{
"amount": 2000,
"currency": "USD",
"confirm": true,
"customer_id": "assdre1v",
"capture_method": "manual",
"authentication_type": "no_three_ds",
"payment_method": "card",
"payment_method_type": "credit",
"payment_method_data": {
"card": {
"card_number": "4030000010001234",
"card_exp_month": "10",
"card_exp_year": "24",
"card_holder_name": "Sundari KK",
"card_cvc": "123"
}
}
}'
```
Response:
```
{
"payment_id": "pay_qFIbwvRbf3PMDPiCrCR6",
"merchant_id": "merchant_1722320361",
"status": "requires_capture",
"amount": 2000,
"net_amount": 2000,
"amount_capturable": 2000,
"amount_received": null,
"connector": "bambora",
"client_secret": "pay_qFIbwvRbf3PMDPiCrCR6_secret_95Ls5eHUAZGfw90y0Thr",
"created": "2024-07-30T06:19:31.883Z",
"currency": "USD",
"customer_id": "assdre1v",
"customer": {
"id": "assdre1v",
"name": null,
"email": null,
"phone": null,
"phone_country_code": null
},
"description": null,
"refunds": null,
"disputes": null,
"mandate_id": null,
"mandate_data": null,
"setup_future_usage": null,
"off_session": null,
"capture_on": null,
"capture_method": "manual",
"payment_method": "card",
"payment_method_data": {
"card": {
"last4": "1234",
"card_type": null,
"card_network": null,
"card_issuer": null,
"card_issuing_country": null,
"card_isin": "403000",
"card_extended_bin": null,
"card_exp_month": "10",
"card_exp_year": "24",
"card_holder_name": "Sundari KK",
"payment_checks": null,
"authentication_data": null
},
"billing": null
},
"payment_token": null,
"shipping": null,
"billing": null,
"order_details": null,
"email": null,
"name": null,
"phone": null,
"return_url": null,
"authentication_type": "no_three_ds",
"statement_descriptor_name": null,
"statement_descriptor_suffix": null,
"next_action": null,
"cancellation_reason": null,
"error_code": null,
"error_message": null,
"unified_code": null,
"unified_message": null,
"payment_experience": null,
"payment_method_type": "credit",
"connector_label": null,
"business_country": null,
"business_label": "default",
"business_sub_label": null,
"allowed_payment_method_types": null,
"ephemeral_key": {
"customer_id": "assdre1v",
"created_at": 1722320371,
"expires": 1722323971,
"secret": "epk_ed3c8ac50159491791de640213f46b60"
},
"manual_retry_allowed": false,
"connector_transaction_id": "10005119",
"frm_message": null,
"metadata": null,
"connector_metadata": null,
"feature_metadata": null,
"reference_id": "pay_qFIbwvRbf3PMDPiCrCR6_1",
"payment_link": null,
"profile_id": "pro_sUtV9MeXG0JSXuSGISfQ",
"surcharge_details": null,
"attempt_count": 1,
"merchant_decision": null,
"merchant_connector_id": "mca_iMJkO4jVosAfhRagvx0w",
"incremental_authorization_allowed": null,
"authorization_count": null,
"incremental_authorizations": null,
"external_authentication_details": null,
"external_3ds_authentication_attempted": false,
"expires_on": "2024-07-30T06:34:31.883Z",
"fingerprint": null,
"browser_info": null,
"payment_method_id": null,
"payment_method_status": null,
"updated": "2024-07-30T06:19:34.580Z",
"charges": null,
"frm_metadata": null,
"merchant_order_reference_id": null
}
```
3. Capture:
Request:
```
curl --location 'http://localhost:8080/payments/pay_qFIbwvRbf3PMDPiCrCR6/capture' \
--header 'Content-Type: application/json' \
--header 'Accept: application/json' \
--header 'api-key: dev_cNgJBniCHyPWijpb73YRpH06jVNPFSU8B8oZl9yJCa1tK9wO3kru8HXSeYfvREpD' \
--data '{
"amount_to_capture": 200,
"statement_descriptor_name": "Joseph",
"statement_descriptor_suffix": "JS"
}'
```
Response:
```
{
"payment_id": "pay_qFIbwvRbf3PMDPiCrCR6",
"merchant_id": "merchant_1722320361",
"status": "partially_captured",
"amount": 2000,
"net_amount": 2000,
"amount_capturable": 0,
"amount_received": 200,
"connector": "bambora",
"client_secret": "pay_qFIbwvRbf3PMDPiCrCR6_secret_95Ls5eHUAZGfw90y0Thr",
"created": "2024-07-30T06:19:31.883Z",
"currency": "USD",
"customer_id": "assdre1v",
"customer": {
"id": "assdre1v",
"name": null,
"email": null,
"phone": null,
"phone_country_code": null
},
"description": null,
"refunds": null,
"disputes": null,
"mandate_id": null,
"mandate_data": null,
"setup_future_usage": null,
"off_session": null,
"capture_on": null,
"capture_method": "manual",
"payment_method": "card",
"payment_method_data": {
"card": {
"last4": "1234",
"card_type": null,
"card_network": null,
"card_issuer": null,
"card_issuing_country": null,
"card_isin": "403000",
"card_extended_bin": null,
"card_exp_month": "10",
"card_exp_year": "24",
"card_holder_name": "Sundari KK",
"payment_checks": null,
"authentication_data": null
},
"billing": null
},
"payment_token": null,
"shipping": null,
"billing": null,
"order_details": null,
"email": null,
"name": null,
"phone": null,
"return_url": null,
"authentication_type": "no_three_ds",
"statement_descriptor_name": null,
"statement_descriptor_suffix": null,
"next_action": null,
"cancellation_reason": null,
"error_code": null,
"error_message": null,
"unified_code": null,
"unified_message": null,
"payment_experience": null,
"payment_method_type": "credit",
"connector_label": null,
"business_country": null,
"business_label": "default",
"business_sub_label": null,
"allowed_payment_method_types": null,
"ephemeral_key": null,
"manual_retry_allowed": false,
"connector_transaction_id": "10005120",
"frm_message": null,
"metadata": null,
"connector_metadata": null,
"feature_metadata": null,
"reference_id": "pay_qFIbwvRbf3PMDPiCrCR6_1",
"payment_link": null,
"profile_id": "pro_sUtV9MeXG0JSXuSGISfQ",
"surcharge_details": null,
"attempt_count": 1,
"merchant_decision": null,
"merchant_connector_id": "mca_iMJkO4jVosAfhRagvx0w",
"incremental_authorization_allowed": null,
"authorization_count": null,
"incremental_authorizations": null,
"external_authentication_details": null,
"external_3ds_authentication_attempted": false,
"expires_on": "2024-07-30T06:34:31.883Z",
"fingerprint": null,
"browser_info": null,
"payment_method_id": null,
"payment_method_status": null,
"updated": "2024-07-30T06:19:48.869Z",
"charges": null,
"frm_metadata": null,
"merchant_order_reference_id": null
}
```
4. Refunds:
Request:
```
curl --location 'http://localhost:8080/refunds' \
--header 'Content-Type: application/json' \
--header 'Accept: application/json' \
--header 'api-key: dev_cNgJBniCHyPWijpb73YRpH06jVNPFSU8B8oZl9yJCa1tK9wO3kru8HXSeYfvREpD' \
--data '{
"amount": 1800,
"payment_id": "pay_9iF0FWAx4IczBe6lfjqN",
"reason": "Customer returned product",
"refund_type": "instant",
"metadata": {
"udf1": "value1",
"new_customer": "true",
"login_date": "2019-09-10T10:11:12Z"
}
}'
```
Response:
```
{
"refund_id": "ref_sNXFUu2iIv7W6YnkCMBI",
"payment_id": "pay_9iF0FWAx4IczBe6lfjqN",
"amount": 1800,
"currency": "USD",
"status": "succeeded",
"reason": "Customer returned product",
"metadata": {
"udf1": "value1",
"new_customer": "true",
"login_date": "2019-09-10T10:11:12Z"
},
"error_message": null,
"error_code": null,
"created_at": "2024-07-30T06:23:22.914Z",
"updated_at": "2024-07-30T06:23:24.894Z",
"connector": "bambora",
"profile_id": "pro_sUtV9MeXG0JSXuSGISfQ",
"merchant_connector_id": "mca_iMJkO4jVosAfhRagvx0w",
"charges": null
}
```
The following flows need to be tested for connector `Bitpay`:
1. Crypto Payments
Request:
```
curl --location 'http://localhost:8080/payments' \
--header 'Content-Type: application/json' \
--header 'Accept: application/json' \
--header 'api-key: dev_99Sx4JP34jZH3nIuLGozMU5eK4ZJ7QfuE0tN1Rw5O6k9aQSyolBElNku3AFGfxgb' \
--data-raw '{
"amount": 300,
"currency": "USD",
"confirm": true,
"email": "guest@example.com",
"return_url": "https://google.com",
"payment_method": "crypto",
"payment_method_type": "crypto_currency",
"payment_experience": "redirect_to_url",
"payment_method_data": {
"crypto": {
}
}
}'
```
Response:
```
{
"payment_id": "pay_DPBpI5I90ikPO8CTJp1Y",
"merchant_id": "merchant_1722321516",
"status": "requires_customer_action",
"amount": 300,
"net_amount": 300,
"amount_capturable": 300,
"amount_received": null,
"connector": "bitpay",
"client_secret": "pay_DPBpI5I90ikPO8CTJp1Y_secret_nMreir9mEcGy13gQSmMe",
"created": "2024-07-30T06:43:30.792Z",
"currency": "USD",
"customer_id": null,
"customer": {
"id": null,
"name": null,
"email": "guest@example.com",
"phone": null,
"phone_country_code": null
},
"description": null,
"refunds": null,
"disputes": null,
"mandate_id": null,
"mandate_data": null,
"setup_future_usage": null,
"off_session": null,
"capture_on": null,
"capture_method": null,
"payment_method": "crypto",
"payment_method_data": {
"crypto": {},
"billing": null
},
"payment_token": null,
"shipping": null,
"billing": null,
"order_details": null,
"email": null,
"name": null,
"phone": null,
"return_url": "https://google.com/",
"authentication_type": "no_three_ds",
"statement_descriptor_name": null,
"statement_descriptor_suffix": null,
"next_action": {
"type": "redirect_to_url",
"redirect_to_url": "http://localhost:8080/payments/redirect/pay_DPBpI5I90ikPO8CTJp1Y/merchant_1722321516/pay_DPBpI5I90ikPO8CTJp1Y_1"
},
"cancellation_reason": null,
"error_code": null,
"error_message": null,
"unified_code": null,
"unified_message": null,
"payment_experience": "redirect_to_url",
"payment_method_type": "crypto_currency",
"connector_label": null,
"business_country": null,
"business_label": "default",
"business_sub_label": null,
"allowed_payment_method_types": null,
"ephemeral_key": null,
"manual_retry_allowed": null,
"connector_transaction_id": "JyqXeDMKQRAmVBCXBd2aEc",
"frm_message": null,
"metadata": null,
"connector_metadata": null,
"feature_metadata": null,
"reference_id": "pay_DPBpI5I90ikPO8CTJp1Y_1",
"payment_link": null,
"profile_id": "pro_BUr4X7qL5JQnl1U9FFZs",
"surcharge_details": null,
"attempt_count": 1,
"merchant_decision": null,
"merchant_connector_id": "mca_x8QTHQaO14QhJ91e69Sz",
"incremental_authorization_allowed": null,
"authorization_count": null,
"incremental_authorizations": null,
"external_authentication_details": null,
"external_3ds_authentication_attempted": false,
"expires_on": "2024-07-30T06:58:30.791Z",
"fingerprint": null,
"browser_info": null,
"payment_method_id": null,
"payment_method_status": null,
"updated": "2024-07-30T06:43:32.508Z",
"charges": null,
"frm_metadata": null,
"merchant_order_reference_id": null
}
```
The following flows need to be tested for connector `Stax`:
1. Authorize(Automatic):
Request:
```
curl --location 'http://localhost:8080/payments' \
--header 'Content-Type: application/json' \
--header 'Accept: application/json' \
--header 'api-key: dev_BtwJUODc6bNNM5ySoCmUS4p6JCSpPHnddRpnm8kx1oKi6WQgNkxTKZGXNaVKvtSG' \
--data-raw '{
"amount": 2222,
"currency": "USD",
"confirm": true,
"capture_method": "automatic",
"customer_id": "cust444",
"email": "guest@example.com",
"payment_method": "card",
"payment_method_type": "credit",
"payment_method_data": {
"card": {
"card_number": "4111111111111111",
"card_exp_month": "10",
"card_exp_year": "25",
"card_holder_name": "joseph Doe",
"card_cvc": "123"
}
}
}'
```
Response:
```
{
"payment_id": "pay_a0eHRq2zOMFJBmpmznQ8",
"merchant_id": "merchant_1722322392",
"status": "succeeded",
"amount": 2222,
"net_amount": 2222,
"amount_capturable": 0,
"amount_received": 2222,
"connector": "stax",
"client_secret": "pay_a0eHRq2zOMFJBmpmznQ8_secret_iijSwRexoORYfIHmwpVK",
"created": "2024-07-30T07:02:35.652Z",
"currency": "USD",
"customer_id": "cust444",
"customer": {
"id": "cust444",
"name": null,
"email": "guest@example.com",
"phone": null,
"phone_country_code": null
},
"description": null,
"refunds": null,
"disputes": null,
"mandate_id": null,
"mandate_data": null,
"setup_future_usage": null,
"off_session": null,
"capture_on": null,
"capture_method": "automatic",
"payment_method": "card",
"payment_method_data": {
"card": {
"last4": "1111",
"card_type": null,
"card_network": null,
"card_issuer": null,
"card_issuing_country": null,
"card_isin": "411111",
"card_extended_bin": null,
"card_exp_month": "10",
"card_exp_year": "25",
"card_holder_name": "joseph Doe",
"payment_checks": null,
"authentication_data": null
},
"billing": null
},
"payment_token": null,
"shipping": null,
"billing": null,
"order_details": null,
"email": "guest@example.com",
"name": null,
"phone": null,
"return_url": null,
"authentication_type": "no_three_ds",
"statement_descriptor_name": null,
"statement_descriptor_suffix": null,
"next_action": null,
"cancellation_reason": null,
"error_code": null,
"error_message": null,
"unified_code": null,
"unified_message": null,
"payment_experience": null,
"payment_method_type": "credit",
"connector_label": null,
"business_country": null,
"business_label": "default",
"business_sub_label": null,
"allowed_payment_method_types": null,
"ephemeral_key": {
"customer_id": "cust444",
"created_at": 1722322955,
"expires": 1722326555,
"secret": "epk_a28c3e61f16f4a5da93b9fa942e2fffc"
},
"manual_retry_allowed": false,
"connector_transaction_id": "3a476321-bb19-46f0-b9b6-8eab5d661f2a",
"frm_message": null,
"metadata": null,
"connector_metadata": null,
"feature_metadata": null,
"reference_id": "pay_a0eHRq2zOMFJBmpmznQ8_1",
"payment_link": null,
"profile_id": "pro_dFvHY1XCf6cD4QOSyBtM",
"surcharge_details": null,
"attempt_count": 1,
"merchant_decision": null,
"merchant_connector_id": "mca_0o3x3l2iNNeSlCyNuLDF",
"incremental_authorization_allowed": null,
"authorization_count": null,
"incremental_authorizations": null,
"external_authentication_details": null,
"external_3ds_authentication_attempted": false,
"expires_on": "2024-07-30T07:17:35.652Z",
"fingerprint": null,
"browser_info": null,
"payment_method_id": null,
"payment_method_status": null,
"updated": "2024-07-30T07:02:39.845Z",
"charges": null,
"frm_metadata": null,
"merchant_order_reference_id": null
}
```
2. Authorize(Manual Capture):
Request:
```
curl --location 'http://localhost:8080/payments' \
--header 'Content-Type: application/json' \
--header 'Accept: application/json' \
--header 'api-key: dev_BtwJUODc6bNNM5ySoCmUS4p6JCSpPHnddRpnm8kx1oKi6WQgNkxTKZGXNaVKvtSG' \
--data-raw '{
"amount": 2222,
"currency": "USD",
"confirm": true,
"capture_method": "manual",
"customer_id": "cust444",
"email": "guest@example.com",
"payment_method": "card",
"payment_method_type": "credit",
"payment_method_data": {
"card": {
"card_number": "4111111111111111",
"card_exp_month": "10",
"card_exp_year": "25",
"card_holder_name": "joseph Doe",
"card_cvc": "123"
}
}
}'
```
Response:
```
{
"payment_id": "pay_TdofYbOgeNyCaV3QRVTP",
"merchant_id": "merchant_1722322392",
"status": "requires_capture",
"amount": 2222,
"net_amount": 2222,
"amount_capturable": 2222,
"amount_received": null,
"connector": "stax",
"client_secret": "pay_TdofYbOgeNyCaV3QRVTP_secret_iysfBGEuMiMQv1CAu28o",
"created": "2024-07-30T07:03:01.825Z",
"currency": "USD",
"customer_id": "cust444",
"customer": {
"id": "cust444",
"name": null,
"email": "guest@example.com",
"phone": null,
"phone_country_code": null
},
"description": null,
"refunds": null,
"disputes": null,
"mandate_id": null,
"mandate_data": null,
"setup_future_usage": null,
"off_session": null,
"capture_on": null,
"capture_method": "manual",
"payment_method": "card",
"payment_method_data": {
"card": {
"last4": "1111",
"card_type": null,
"card_network": null,
"card_issuer": null,
"card_issuing_country": null,
"card_isin": "411111",
"card_extended_bin": null,
"card_exp_month": "10",
"card_exp_year": "25",
"card_holder_name": "joseph Doe",
"payment_checks": null,
"authentication_data": null
},
"billing": null
},
"payment_token": null,
"shipping": null,
"billing": null,
"order_details": null,
"email": "guest@example.com",
"name": null,
"phone": null,
"return_url": null,
"authentication_type": "no_three_ds",
"statement_descriptor_name": null,
"statement_descriptor_suffix": null,
"next_action": null,
"cancellation_reason": null,
"error_code": null,
"error_message": null,
"unified_code": null,
"unified_message": null,
"payment_experience": null,
"payment_method_type": "credit",
"connector_label": null,
"business_country": null,
"business_label": "default",
"business_sub_label": null,
"allowed_payment_method_types": null,
"ephemeral_key": {
"customer_id": "cust444",
"created_at": 1722322981,
"expires": 1722326581,
"secret": "epk_d9a8b2f7caf74bf587dec7d9de2092a2"
},
"manual_retry_allowed": false,
"connector_transaction_id": "786f8ff4-8a5f-4f3d-a0a3-b21a555a383e",
"frm_message": null,
"metadata": null,
"connector_metadata": null,
"feature_metadata": null,
"reference_id": "pay_TdofYbOgeNyCaV3QRVTP_1",
"payment_link": null,
"profile_id": "pro_dFvHY1XCf6cD4QOSyBtM",
"surcharge_details": null,
"attempt_count": 1,
"merchant_decision": null,
"merchant_connector_id": "mca_0o3x3l2iNNeSlCyNuLDF",
"incremental_authorization_allowed": null,
"authorization_count": null,
"incremental_authorizations": null,
"external_authentication_details": null,
"external_3ds_authentication_attempted": false,
"expires_on": "2024-07-30T07:18:01.825Z",
"fingerprint": null,
"browser_info": null,
"payment_method_id": null,
"payment_method_status": null,
"updated": "2024-07-30T07:03:04.575Z",
"charges": null,
"frm_metadata": null,
"merchant_order_reference_id": null
}
```
3. Capture:
Request:
```
curl --location 'http://localhost:8080/payments/pay_TdofYbOgeNyCaV3QRVTP/capture' \
--header 'Content-Type: application/json' \
--header 'Accept: application/json' \
--header 'api-key: dev_BtwJUODc6bNNM5ySoCmUS4p6JCSpPHnddRpnm8kx1oKi6WQgNkxTKZGXNaVKvtSG' \
--data '{
"statement_descriptor_name": "Joseph",
"statement_descriptor_suffix": "JS"
}'
```
Response:
```
{
"payment_id": "pay_TdofYbOgeNyCaV3QRVTP",
"merchant_id": "merchant_1722322392",
"status": "succeeded",
"amount": 2222,
"net_amount": 2222,
"amount_capturable": 0,
"amount_received": 2222,
"connector": "stax",
"client_secret": "pay_TdofYbOgeNyCaV3QRVTP_secret_iysfBGEuMiMQv1CAu28o",
"created": "2024-07-30T07:03:01.825Z",
"currency": "USD",
"customer_id": "cust444",
"customer": {
"id": "cust444",
"name": null,
"email": "guest@example.com",
"phone": null,
"phone_country_code": null
},
"description": null,
"refunds": null,
"disputes": null,
"mandate_id": null,
"mandate_data": null,
"setup_future_usage": null,
"off_session": null,
"capture_on": null,
"capture_method": "manual",
"payment_method": "card",
"payment_method_data": {
"card": {
"last4": "1111",
"card_type": null,
"card_network": null,
"card_issuer": null,
"card_issuing_country": null,
"card_isin": "411111",
"card_extended_bin": null,
"card_exp_month": "10",
"card_exp_year": "25",
"card_holder_name": "joseph Doe",
"payment_checks": null,
"authentication_data": null
},
"billing": null
},
"payment_token": null,
"shipping": null,
"billing": null,
"order_details": null,
"email": "guest@example.com",
"name": null,
"phone": null,
"return_url": null,
"authentication_type": "no_three_ds",
"statement_descriptor_name": null,
"statement_descriptor_suffix": null,
"next_action": null,
"cancellation_reason": null,
"error_code": null,
"error_message": null,
"unified_code": null,
"unified_message": null,
"payment_experience": null,
"payment_method_type": "credit",
"connector_label": null,
"business_country": null,
"business_label": "default",
"business_sub_label": null,
"allowed_payment_method_types": null,
"ephemeral_key": null,
"manual_retry_allowed": false,
"connector_transaction_id": "786f8ff4-8a5f-4f3d-a0a3-b21a555a383e",
"frm_message": null,
"metadata": null,
"connector_metadata": null,
"feature_metadata": null,
"reference_id": "pay_TdofYbOgeNyCaV3QRVTP_1",
"payment_link": null,
"profile_id": "pro_dFvHY1XCf6cD4QOSyBtM",
"surcharge_details": null,
"attempt_count": 1,
"merchant_decision": null,
"merchant_connector_id": "mca_0o3x3l2iNNeSlCyNuLDF",
"incremental_authorization_allowed": null,
"authorization_count": null,
"incremental_authorizations": null,
"external_authentication_details": null,
"external_3ds_authentication_attempted": false,
"expires_on": "2024-07-30T07:18:01.825Z",
"fingerprint": null,
"browser_info": null,
"payment_method_id": null,
"payment_method_status": null,
"updated": "2024-07-30T07:03:30.629Z",
"charges": null,
"frm_metadata": null,
"merchant_order_reference_id": null
}
```
4. Refunds:
Request:
```
curl --location 'http://localhost:8080/refunds' \
--header 'Content-Type: application/json' \
--header 'Accept: application/json' \
--header 'api-key: dev_BtwJUODc6bNNM5ySoCmUS4p6JCSpPHnddRpnm8kx1oKi6WQgNkxTKZGXNaVKvtSG' \
--data '{
"payment_id": "pay_TdofYbOgeNyCaV3QRVTP",
"reason": "Customer returned product",
"refund_type": "instant",
"metadata": {
"udf1": "value1",
"new_customer": "true",
"login_date": "2019-09-10T10:11:12Z"
}
}'
```
Response:
```
{
"refund_id": "ref_cTaclSt8LdumcOvNvIbB",
"payment_id": "pay_TdofYbOgeNyCaV3QRVTP",
"amount": 2222,
"currency": "USD",
"status": "succeeded",
"reason": "Customer returned product",
"metadata": {
"udf1": "value1",
"new_customer": "true",
"login_date": "2019-09-10T10:11:12Z"
},
"error_message": null,
"error_code": null,
"created_at": "2024-07-30T07:04:54.998Z",
"updated_at": "2024-07-30T07:04:56.594Z",
"connector": "stax",
"profile_id": "pro_dFvHY1XCf6cD4QOSyBtM",
"merchant_connector_id": "mca_0o3x3l2iNNeSlCyNuLDF",
"charges": null
}
```
## Checklist
<!-- Put an `x` in the boxes that apply -->
- [x] I formatted the code `cargo +nightly fmt --all`
- [x] I addressed lints thrown by `cargo clippy`
- [x] I reviewed the submitted code
- [ ] I added unit tests for my changes where possible
|
46f3f6132aa667c29bea063ad1b04a880ae377d3
|
|
juspay/hyperswitch
|
juspay__hyperswitch-5446
|
Bug: chore: address Rust 1.80 clippy lints
Address the clippy lints occurring due to new rust version 1.80
See https://github.com/juspay/hyperswitch/issues/3391 for more information.
|
diff --git a/crates/api_models/src/events.rs b/crates/api_models/src/events.rs
index 8289a320d01..a0808c0c24b 100644
--- a/crates/api_models/src/events.rs
+++ b/crates/api_models/src/events.rs
@@ -145,20 +145,6 @@ impl_api_event_type!(
)
);
-#[cfg(feature = "stripe")]
-impl_api_event_type!(
- Miscellaneous,
- (
- StripeSetupIntentResponse,
- StripeRefundResponse,
- StripePaymentIntentListResponse,
- StripePaymentIntentResponse,
- CustomerDeleteResponse,
- CustomerPaymentMethodListResponse,
- CreateCustomerResponse
- )
-);
-
impl<T> ApiEventMetric for MetricsResponse<T> {
fn get_api_event_type(&self) -> Option<ApiEventsType> {
Some(ApiEventsType::Miscellaneous)
diff --git a/crates/external_services/src/file_storage/file_system.rs b/crates/external_services/src/file_storage/file_system.rs
index 2c1ec287f5f..e3986abf0f8 100644
--- a/crates/external_services/src/file_storage/file_system.rs
+++ b/crates/external_services/src/file_storage/file_system.rs
@@ -17,9 +17,6 @@ use crate::file_storage::{FileStorageError, FileStorageInterface};
/// The file path is generated based on the workspace path and the provided file key.
fn get_file_path(file_key: impl AsRef<str>) -> PathBuf {
let mut file_path = PathBuf::new();
- #[cfg(feature = "logs")]
- file_path.push(router_env::env::workspace_path());
- #[cfg(not(feature = "logs"))]
file_path.push(std::env::current_dir().unwrap_or(".".into()));
file_path.push("files");
diff --git a/crates/router/src/compatibility/stripe/payment_intents.rs b/crates/router/src/compatibility/stripe/payment_intents.rs
index 79b6b0fc008..fa6b02e499d 100644
--- a/crates/router/src/compatibility/stripe/payment_intents.rs
+++ b/crates/router/src/compatibility/stripe/payment_intents.rs
@@ -28,7 +28,7 @@ pub async fn payment_intents_create(
Err(err) => return api::log_and_return_error_response(err),
};
- tracing::Span::current().record("payment_id", &payload.id.clone().unwrap_or_default());
+ tracing::Span::current().record("payment_id", payload.id.clone().unwrap_or_default());
logger::info!(tag = ?Tag::CompatibilityLayerRequest, payload = ?payload);
@@ -170,7 +170,7 @@ pub async fn payment_intents_retrieve_with_gateway_creds(
_ => Flow::PaymentsRetrieve,
};
- tracing::Span::current().record("flow", &flow.to_string());
+ tracing::Span::current().record("flow", flow.to_string());
let locking_action = payload.get_locking_input(flow.clone());
Box::pin(wrap::compatibility_api_wrap::<
@@ -361,7 +361,7 @@ pub async fn payment_intents_capture(
}
};
- tracing::Span::current().record("payment_id", &stripe_payload.payment_id.clone());
+ tracing::Span::current().record("payment_id", stripe_payload.payment_id.clone());
logger::info!(tag = ?Tag::CompatibilityLayerRequest, payload = ?stripe_payload);
@@ -423,7 +423,7 @@ pub async fn payment_intents_cancel(
}
};
- tracing::Span::current().record("payment_id", &payment_id.clone());
+ tracing::Span::current().record("payment_id", payment_id.clone());
logger::info!(tag = ?Tag::CompatibilityLayerRequest, payload = ?stripe_payload);
diff --git a/crates/router/src/compatibility/stripe/refunds.rs b/crates/router/src/compatibility/stripe/refunds.rs
index da68e79e422..52d5230cfc8 100644
--- a/crates/router/src/compatibility/stripe/refunds.rs
+++ b/crates/router/src/compatibility/stripe/refunds.rs
@@ -26,7 +26,7 @@ pub async fn refund_create(
Err(err) => return api::log_and_return_error_response(err),
};
- tracing::Span::current().record("payment_id", &payload.payment_intent.clone());
+ tracing::Span::current().record("payment_id", payload.payment_intent.clone());
logger::info!(tag = ?Tag::CompatibilityLayerRequest, payload = ?payload);
@@ -76,7 +76,7 @@ pub async fn refund_retrieve_with_gateway_creds(
_ => Flow::RefundsRetrieve,
};
- tracing::Span::current().record("flow", &flow.to_string());
+ tracing::Span::current().record("flow", flow.to_string());
Box::pin(wrap::compatibility_api_wrap::<
_,
diff --git a/crates/router/src/configs/settings.rs b/crates/router/src/configs/settings.rs
index 8ccc97c73f4..2fe484b8fbc 100644
--- a/crates/router/src/configs/settings.rs
+++ b/crates/router/src/configs/settings.rs
@@ -45,16 +45,6 @@ pub struct CmdLineConf {
/// Application will look for "config/config.toml" if this option isn't specified.
#[arg(short = 'f', long, value_name = "FILE")]
pub config_path: Option<PathBuf>,
-
- #[command(subcommand)]
- pub subcommand: Option<Subcommand>,
-}
-
-#[derive(clap::Parser)]
-pub enum Subcommand {
- #[cfg(feature = "openapi")]
- /// Generate the OpenAPI specification file from code.
- GenerateOpenapiSpec,
}
#[derive(Debug, Deserialize, Clone, Default)]
diff --git a/crates/router/src/connector/adyen/transformers.rs b/crates/router/src/connector/adyen/transformers.rs
index 27189aab996..b1f14e8305b 100644
--- a/crates/router/src/connector/adyen/transformers.rs
+++ b/crates/router/src/connector/adyen/transformers.rs
@@ -688,12 +688,6 @@ pub struct MbwayData {
telephone_number: Secret<String>,
}
-#[derive(Debug, Clone, Serialize)]
-pub struct WalleyData {
- #[serde(rename = "type")]
- payment_type: PaymentType,
-}
-
#[derive(Debug, Clone, Serialize)]
pub struct SamsungPayPmData {
#[serde(rename = "type")]
@@ -702,12 +696,6 @@ pub struct SamsungPayPmData {
samsung_pay_token: Secret<String>,
}
-#[derive(Debug, Clone, Serialize)]
-pub struct PayBrightData {
- #[serde(rename = "type")]
- payment_type: PaymentType,
-}
-
#[derive(Debug, Clone, Serialize)]
pub struct OnlineBankingCzechRepublicData {
#[serde(rename = "type")]
diff --git a/crates/router/src/connector/bluesnap/transformers.rs b/crates/router/src/connector/bluesnap/transformers.rs
index 2f4670ccdcf..dc67c1961be 100644
--- a/crates/router/src/connector/bluesnap/transformers.rs
+++ b/crates/router/src/connector/bluesnap/transformers.rs
@@ -133,12 +133,6 @@ pub struct BluesnapGooglePayObject {
payment_method_data: utils::GooglePayWalletData,
}
-#[derive(Debug, Serialize)]
-#[serde(rename_all = "camelCase")]
-pub struct BluesnapApplePayObject {
- token: payments::ApplePayWalletData,
-}
-
#[derive(Debug, Serialize)]
#[serde(rename_all = "SCREAMING_SNAKE_CASE")]
pub enum BluesnapWalletTypes {
diff --git a/crates/router/src/connector/boku/transformers.rs b/crates/router/src/connector/boku/transformers.rs
index a8b4d8c0ec2..e6c6e3b8239 100644
--- a/crates/router/src/connector/boku/transformers.rs
+++ b/crates/router/src/connector/boku/transformers.rs
@@ -459,11 +459,6 @@ pub struct BokuErrorResponse {
pub reason: Option<String>,
}
-#[derive(Debug, Serialize)]
-pub struct BokuConnMetaData {
- country: String,
-}
-
fn get_hosted_data(item: &types::PaymentsAuthorizeRouterData) -> Option<BokuHostedData> {
item.return_url
.clone()
diff --git a/crates/router/src/connector/globalpay/response.rs b/crates/router/src/connector/globalpay/response.rs
index 228562a1bc2..a5f905d0e70 100644
--- a/crates/router/src/connector/globalpay/response.rs
+++ b/crates/router/src/connector/globalpay/response.rs
@@ -123,9 +123,9 @@ pub struct PaymentMethod {
/// If enabled, this field indicates whether the payment method has been seen before or is
/// new.
/// * EXISTS - Indicates that the payment method was seen on the platform before by this
- /// merchant.
+ /// merchant.
/// * NEW - Indicates that the payment method was not seen on the platform before by this
- /// merchant.
+ /// merchant.
pub fingerprint_presence_indicator: Option<String>,
/// Unique Global Payments generated id used to reference a stored payment method on the
/// Global Payments system. Often referred to as the payment method token. This value can be
diff --git a/crates/router/src/connector/mollie/transformers.rs b/crates/router/src/connector/mollie/transformers.rs
index 9320aee8d7a..f755ca6029b 100644
--- a/crates/router/src/connector/mollie/transformers.rs
+++ b/crates/router/src/connector/mollie/transformers.rs
@@ -462,12 +462,6 @@ pub struct CardDetails {
pub card_cvv: Secret<String>,
}
-#[derive(Debug, Serialize, Eq, PartialEq)]
-#[serde(rename_all = "camelCase")]
-pub struct BankDetails {
- billing_email: Email,
-}
-
pub struct MollieAuthType {
pub(super) api_key: Secret<String>,
pub(super) profile_token: Option<Secret<String>>,
diff --git a/crates/router/src/connector/netcetera/netcetera_types.rs b/crates/router/src/connector/netcetera/netcetera_types.rs
index 2a7758fe55d..2718fb3b238 100644
--- a/crates/router/src/connector/netcetera/netcetera_types.rs
+++ b/crates/router/src/connector/netcetera/netcetera_types.rs
@@ -91,7 +91,7 @@ pub struct ThreeDSRequestor {
/// Format of this field was changed with EMV 3DS 2.3.1 version:
/// In versions prior to 2.3.1, this field is a single object.
/// Starting from EMVCo version 2.3.1, this field is now an array of objects. Accepted value length is 1-3 elements.
- ///
+ ///
/// This field is optional, but recommended to include.
#[serde(rename = "threeDSRequestorAuthenticationInfo")]
pub three_ds_requestor_authentication_info:
@@ -206,16 +206,16 @@ pub struct ThreeDSRequestorAuthenticationInformation {
/// Indicates whether a challenge is requested for this transaction. For example: For 01-PA, a 3DS Requestor may have
/// concerns about the transaction, and request a challenge. For 02-NPA, a challenge may be necessary when adding a new
/// card to a wallet.
-///
+///
/// This field is optional. The accepted values are:
///
/// - 01 -> No preference
/// - 02 -> No challenge requested
/// - 03 -> Challenge requested: 3DS Requestor Preference
/// - 04 -> Challenge requested: Mandate.
-/// The next values are accepted as well if 3DS Server initiates authentication with EMV 3DS 2.2.0 version
-/// or greater (required protocol version can be set in
-/// ThreeDSServerAuthenticationRequest#preferredProtocolVersion field):
+/// The next values are accepted as well if 3DS Server initiates authentication with EMV 3DS 2.2.0 version
+/// or greater (required protocol version can be set in
+/// ThreeDSServerAuthenticationRequest#preferredProtocolVersion field):
///
/// - 05 -> No challenge requested (transactional risk analysis is already performed)
/// - 06 -> No challenge requested (Data share only)
@@ -223,9 +223,9 @@ pub struct ThreeDSRequestorAuthenticationInformation {
/// - 08 -> No challenge requested (utilise whitelist exemption if no challenge required)
/// - 09 -> Challenge requested (whitelist prompt requested if challenge required).
/// - Additionally, 80-99 can be used for PS-specific values, regardless of protocol version.
-///
+///
/// If the element is not provided, the expected action is that the ACS would interpret as 01 -> No preference.
-///
+///
/// Format of this field was changed with EMV 3DS 2.3.1 version:
/// In versions prior to 2.3.1, this field is a String.
/// Starting from EMVCo version 2.3.1, this field is now an array of objects. Accepted value length is 1-2 elements.
@@ -257,7 +257,7 @@ pub enum ThreeDSRequestorChallengeIndicator {
/// Format of this field was changed with EMV 3DS 2.3.1 version:
/// In versions prior to 2.3.1, this field is a single object.
/// Starting from EMVCo version 2.3.1, this field is now an array of objects. Accepted value length is 1-3 elements.
-///
+///
/// This field is optional, but recommended to include for versions prior to 2.3.1. From 2.3.1,
/// it is required for 3RI in the case of Decoupled Authentication Fallback or for SPC.
#[derive(Serialize, Deserialize, Debug, Clone)]
diff --git a/crates/router/src/connector/powertranz/transformers.rs b/crates/router/src/connector/powertranz/transformers.rs
index 40fe8235956..fedaabb5e75 100644
--- a/crates/router/src/connector/powertranz/transformers.rs
+++ b/crates/router/src/connector/powertranz/transformers.rs
@@ -1,4 +1,4 @@
-use common_utils::pii::{Email, IpAddress};
+use common_utils::pii::IpAddress;
use diesel_models::enums::RefundStatus;
use masking::{ExposeInterface, Secret};
use serde::{Deserialize, Serialize};
@@ -74,20 +74,20 @@ pub struct PowertranzCard {
card_cvv: Secret<String>,
}
-#[derive(Debug, Serialize)]
-#[serde(rename_all = "PascalCase")]
-pub struct PowertranzAddressDetails {
- first_name: Option<Secret<String>>,
- last_name: Option<Secret<String>>,
- line1: Option<Secret<String>>,
- line2: Option<Secret<String>>,
- city: Option<String>,
- country: Option<enums::CountryAlpha2>,
- state: Option<Secret<String>>,
- postal_code: Option<Secret<String>>,
- email_address: Option<Email>,
- phone_number: Option<Secret<String>>,
-}
+// #[derive(Debug, Serialize)]
+// #[serde(rename_all = "PascalCase")]
+// pub struct PowertranzAddressDetails {
+// first_name: Option<Secret<String>>,
+// last_name: Option<Secret<String>>,
+// line1: Option<Secret<String>>,
+// line2: Option<Secret<String>>,
+// city: Option<String>,
+// country: Option<enums::CountryAlpha2>,
+// state: Option<Secret<String>>,
+// postal_code: Option<Secret<String>>,
+// email_address: Option<Email>,
+// phone_number: Option<Secret<String>>,
+// }
#[derive(Debug, Deserialize)]
#[serde(rename_all = "PascalCase")]
diff --git a/crates/router/src/db/user_role.rs b/crates/router/src/db/user_role.rs
index cc3e2460967..8689dfc6533 100644
--- a/crates/router/src/db/user_role.rs
+++ b/crates/router/src/db/user_role.rs
@@ -634,56 +634,3 @@ impl UserRoleInterface for MockDb {
Ok(filtered_roles)
}
}
-
-#[cfg(feature = "kafka_events")]
-#[async_trait::async_trait]
-impl UserRoleInterface for super::KafkaStore {
- async fn insert_user_role(
- &self,
- user_role: storage::UserRoleNew,
- ) -> CustomResult<storage::UserRole, errors::StorageError> {
- self.diesel_store.insert_user_role(user_role).await
- }
- async fn update_user_role_by_user_id_merchant_id(
- &self,
- user_id: &str,
- merchant_id: &common_utils::id_type::MerchantId,
- update: storage::UserRoleUpdate,
- ) -> CustomResult<storage::UserRole, errors::StorageError> {
- self.diesel_store
- .update_user_role_by_user_id_merchant_id(user_id, merchant_id, update)
- .await
- }
- async fn find_user_role_by_user_id(
- &self,
- user_id: &str,
- version: enums::UserRoleVersion,
- ) -> CustomResult<storage::UserRole, errors::StorageError> {
- self.diesel_store
- .find_user_role_by_user_id(user_id, version)
- .await
- }
- async fn delete_user_role_by_user_id_merchant_id(
- &self,
- user_id: &str,
- merchant_id: &common_utils::id_type::MerchantId,
- ) -> CustomResult<storage::UserRole, errors::StorageError> {
- self.diesel_store
- .delete_user_role_by_user_id_merchant_id(user_id, merchant_id)
- .await
- }
- async fn list_user_roles_by_user_id(
- &self,
- user_id: &str,
- ) -> CustomResult<Vec<storage::UserRole>, errors::StorageError> {
- self.diesel_store.list_user_roles_by_user_id(user_id).await
- }
- async fn list_user_roles_by_merchant_id(
- &self,
- merchant_id: &common_utils::id_type::MerchantId,
- ) -> CustomResult<Vec<storage::UserRole>, errors::StorageError> {
- self.diesel_store
- .list_user_roles_by_merchant_id(merchant_id)
- .await
- }
-}
diff --git a/crates/router/src/routes/payments.rs b/crates/router/src/routes/payments.rs
index 2bac740d377..956909f9e5a 100644
--- a/crates/router/src/routes/payments.rs
+++ b/crates/router/src/routes/payments.rs
@@ -108,7 +108,7 @@ pub async fn payments_create(
tracing::Span::current().record(
"payment_id",
- &payload
+ payload
.payment_id
.as_ref()
.map(|payment_id_type| payment_id_type.get_payment_intent_id())
@@ -254,8 +254,8 @@ pub async fn payments_retrieve(
..Default::default()
};
- tracing::Span::current().record("payment_id", &path.to_string());
- tracing::Span::current().record("flow", &flow.to_string());
+ tracing::Span::current().record("payment_id", path.to_string());
+ tracing::Span::current().record("flow", flow.to_string());
let (auth_type, auth_flow) =
match auth::check_client_secret_and_get_auth(req.headers(), &payload) {
@@ -334,7 +334,7 @@ pub async fn payments_retrieve_with_gateway_creds(
};
tracing::Span::current().record("payment_id", &json_payload.payment_id);
- tracing::Span::current().record("flow", &flow.to_string());
+ tracing::Span::current().record("flow", flow.to_string());
let locking_action = payload.get_locking_input(flow.clone());
diff --git a/crates/router/src/routes/refunds.rs b/crates/router/src/routes/refunds.rs
index 6c7af7496ed..46ff0dce2ae 100644
--- a/crates/router/src/routes/refunds.rs
+++ b/crates/router/src/routes/refunds.rs
@@ -81,7 +81,7 @@ pub async fn refunds_retrieve(
_ => Flow::RefundsRetrieve,
};
- tracing::Span::current().record("flow", &flow.to_string());
+ tracing::Span::current().record("flow", flow.to_string());
Box::pin(api::server_wrap(
flow,
@@ -132,7 +132,7 @@ pub async fn refunds_retrieve_with_body(
_ => Flow::RefundsRetrieve,
};
- tracing::Span::current().record("flow", &flow.to_string());
+ tracing::Span::current().record("flow", flow.to_string());
Box::pin(api::server_wrap(
flow,
diff --git a/crates/router/src/services/api.rs b/crates/router/src/services/api.rs
index bee82d8935d..795d6dd9eff 100644
--- a/crates/router/src/services/api.rs
+++ b/crates/router/src/services/api.rs
@@ -126,7 +126,7 @@ where
// If needed add an error stack as follows
// connector_integration.build_request(req).attach_printable("Failed to build request");
tracing::Span::current().record("connector_name", &req.connector);
- tracing::Span::current().record("payment_method", &req.payment_method.to_string());
+ tracing::Span::current().record("payment_method", req.payment_method.to_string());
logger::debug!(connector_request=?connector_request);
let mut router_data = req.clone();
match call_connector_action {
diff --git a/crates/router_derive/src/lib.rs b/crates/router_derive/src/lib.rs
index ff407deb093..31e28a2aaad 100644
--- a/crates/router_derive/src/lib.rs
+++ b/crates/router_derive/src/lib.rs
@@ -292,7 +292,7 @@ fn check_if_auth_based_attr_is_present(f: &syn::Field, ident: &str) -> bool {
/// # The Generated `Serialize` Implementation
///
/// - For a simple enum variant with no fields, the generated [`Serialize`][Serialize]
-/// implementation has only three fields, `type`, `code` and `message`:
+/// implementation has only three fields, `type`, `code` and `message`:
///
/// ```
/// # use router_derive::ApiError;
@@ -322,8 +322,8 @@ fn check_if_auth_based_attr_is_present(f: &syn::Field, ident: &str) -> bool {
/// ```
///
/// - For an enum variant with named fields, the generated [`Serialize`][Serialize] implementation
-/// includes three mandatory fields, `type`, `code` and `message`, and any other fields not
-/// included in the message:
+/// includes three mandatory fields, `type`, `code` and `message`, and any other fields not
+/// included in the message:
///
/// ```
/// # use router_derive::ApiError;
|
2024-07-26T07:51:31Z
|
## Type of Change
<!-- Put an `x` in the boxes that apply -->
- [ ] Bugfix
- [ ] New feature
- [ ] Enhancement
- [ ] Refactoring
- [x] Dependency updates
- [ ] Documentation
- [ ] CI/CD
## Description
<!-- Describe your changes in detail -->
This PR addresses the clippy lints occurring due to new rust version 1.80
### Additional Changes
- [ ] This PR modifies the API contract
- [ ] This PR modifies the database schema
- [ ] This PR modifies application configuration/environment variables
<!--
Provide links to the files with corresponding changes.
Following are the paths where you can find config files:
1. `config`
2. `crates/router/src/configs`
3. `loadtest/config`
-->
## Motivation and Context
<!--
Why is this change required? What problem does it solve?
If it fixes an open issue, please link to the issue here.
If you don't have an issue, we'd recommend starting with one first so the PR
can focus on the implementation (unless it is an obvious bug or documentation fix
that will have little conversation).
-->
## How did you test it?
<!--
Did you write an integration/unit/API test to verify the code changes?
Or did you test this change manually (provide relevant screenshots)?
-->
Basic sanity testing should suffice
## Checklist
<!-- Put an `x` in the boxes that apply -->
- [x] I formatted the code `cargo +nightly fmt --all`
- [x] I addressed lints thrown by `cargo clippy`
- [x] I reviewed the submitted code
- [ ] I added unit tests for my changes where possible
|
93976db30a91b3e67d854681fb4b9db8eea7e295
|
|
juspay/hyperswitch
|
juspay__hyperswitch-5443
|
Bug: [FEATURE] : Create env variable for enabling keymanager service
### Feature Description
Application changes for encryption service is not backward compatible, so encryption service has to be enabled with runtime config once the build is deployed and certified stable..
### Possible Implementation
Introduce the env variable key_manager.enabled flag which enables the encryption service after the build is deployed and certified stable. Since the changes are not backward compatible once the feature is enabled it can't disabled.
### Have you spent some time checking if this feature request has been raised before?
- [X] I checked and didn't find a similar issue
### Have you read the Contributing Guidelines?
- [X] I have read the [Contributing Guidelines](https://github.com/juspay/hyperswitch/blob/main/docs/CONTRIBUTING.md)
### Are you willing to submit a PR?
Yes, I am willing to submit a PR!
|
diff --git a/crates/common_utils/src/types/keymanager.rs b/crates/common_utils/src/types/keymanager.rs
index f4b671abcd7..e263f3d5789 100644
--- a/crates/common_utils/src/types/keymanager.rs
+++ b/crates/common_utils/src/types/keymanager.rs
@@ -23,6 +23,7 @@ use crate::{
#[derive(Debug)]
pub struct KeyManagerState {
+ pub enabled: Option<bool>,
pub url: String,
pub client_idle_timeout: Option<u64>,
#[cfg(feature = "keymanager_mtls")]
diff --git a/crates/hyperswitch_domain_models/src/type_encryption.rs b/crates/hyperswitch_domain_models/src/type_encryption.rs
index ba739079169..a36969478d1 100644
--- a/crates/hyperswitch_domain_models/src/type_encryption.rs
+++ b/crates/hyperswitch_domain_models/src/type_encryption.rs
@@ -17,26 +17,19 @@ mod encrypt {
crypto,
encryption::Encryption,
errors::{self, CustomResult},
- types::keymanager::{Identifier, KeyManagerState},
+ keymanager::call_encryption_service,
+ transformers::{ForeignFrom, ForeignTryFrom},
+ types::keymanager::{
+ BatchDecryptDataResponse, BatchEncryptDataRequest, BatchEncryptDataResponse,
+ DecryptDataResponse, EncryptDataRequest, EncryptDataResponse, Identifier,
+ KeyManagerState, TransientBatchDecryptDataRequest, TransientDecryptDataRequest,
+ },
};
use error_stack::ResultExt;
+ use http::Method;
use masking::{PeekInterface, Secret};
- use router_env::{instrument, tracing};
+ use router_env::{instrument, logger, tracing};
use rustc_hash::FxHashMap;
- #[cfg(feature = "encryption_service")]
- use {
- common_utils::{
- keymanager::call_encryption_service,
- transformers::{ForeignFrom, ForeignTryFrom},
- types::keymanager::{
- BatchDecryptDataResponse, BatchEncryptDataRequest, BatchEncryptDataResponse,
- DecryptDataResponse, EncryptDataRequest, EncryptDataResponse,
- TransientBatchDecryptDataRequest, TransientDecryptDataRequest,
- },
- },
- http::Method,
- router_env::logger,
- };
use super::metrics;
@@ -104,6 +97,17 @@ mod encrypt {
) -> CustomResult<FxHashMap<String, Self>, errors::CryptoError>;
}
+ fn is_encryption_service_enabled(_state: &KeyManagerState) -> bool {
+ #[cfg(feature = "encryption_service")]
+ {
+ _state.enabled.unwrap_or_default()
+ }
+ #[cfg(not(feature = "encryption_service"))]
+ {
+ false
+ }
+ }
+
#[async_trait]
impl<
V: crypto::DecodeMessage + crypto::EncodeMessage + Send + 'static,
@@ -119,12 +123,10 @@ mod encrypt {
key: &[u8],
crypt_algo: V,
) -> CustomResult<Self, errors::CryptoError> {
- #[cfg(not(feature = "encryption_service"))]
- {
+ // If encryption service is not enabled, fall back to application encryption or else call encryption service
+ if !is_encryption_service_enabled(state) {
Self::encrypt(masked_data, key, crypt_algo).await
- }
- #[cfg(feature = "encryption_service")]
- {
+ } else {
let result: Result<
EncryptDataResponse,
error_stack::Report<errors::KeyManagerClientError>,
@@ -156,12 +158,10 @@ mod encrypt {
key: &[u8],
crypt_algo: V,
) -> CustomResult<Self, errors::CryptoError> {
- #[cfg(not(feature = "encryption_service"))]
- {
+ // If encryption service is not enabled, fall back to application encryption or else call encryption service
+ if !is_encryption_service_enabled(state) {
Self::decrypt(encrypted_data, key, crypt_algo).await
- }
- #[cfg(feature = "encryption_service")]
- {
+ } else {
let result: Result<
DecryptDataResponse,
error_stack::Report<errors::KeyManagerClientError>,
@@ -227,13 +227,10 @@ mod encrypt {
key: &[u8],
crypt_algo: V,
) -> CustomResult<FxHashMap<String, Self>, errors::CryptoError> {
- #[cfg(not(feature = "encryption_service"))]
- {
+ // If encryption service is not enabled, fall back to application encryption or else call encryption service
+ if !is_encryption_service_enabled(state) {
Self::batch_encrypt(masked_data, key, crypt_algo).await
- }
-
- #[cfg(feature = "encryption_service")]
- {
+ } else {
let result: Result<
BatchEncryptDataResponse,
error_stack::Report<errors::KeyManagerClientError>,
@@ -264,13 +261,10 @@ mod encrypt {
key: &[u8],
crypt_algo: V,
) -> CustomResult<FxHashMap<String, Self>, errors::CryptoError> {
- #[cfg(not(feature = "encryption_service"))]
- {
+ // If encryption service is not enabled, fall back to application encryption or else call encryption service
+ if !is_encryption_service_enabled(state) {
Self::batch_decrypt(encrypted_data, key, crypt_algo).await
- }
-
- #[cfg(feature = "encryption_service")]
- {
+ } else {
let result: Result<
BatchDecryptDataResponse,
error_stack::Report<errors::KeyManagerClientError>,
@@ -356,12 +350,10 @@ mod encrypt {
key: &[u8],
crypt_algo: V,
) -> CustomResult<Self, errors::CryptoError> {
- #[cfg(not(feature = "encryption_service"))]
- {
+ // If encryption service is not enabled, fall back to application encryption or else call encryption service
+ if !is_encryption_service_enabled(state) {
Self::encrypt(masked_data, key, crypt_algo).await
- }
- #[cfg(feature = "encryption_service")]
- {
+ } else {
let result: Result<
EncryptDataResponse,
error_stack::Report<errors::KeyManagerClientError>,
@@ -393,12 +385,10 @@ mod encrypt {
key: &[u8],
crypt_algo: V,
) -> CustomResult<Self, errors::CryptoError> {
- #[cfg(not(feature = "encryption_service"))]
- {
+ // If encryption service is not enabled, fall back to application encryption or else call encryption service
+ if !is_encryption_service_enabled(state) {
Self::decrypt(encrypted_data, key, crypt_algo).await
- }
- #[cfg(feature = "encryption_service")]
- {
+ } else {
let result: Result<
DecryptDataResponse,
error_stack::Report<errors::KeyManagerClientError>,
@@ -465,12 +455,10 @@ mod encrypt {
key: &[u8],
crypt_algo: V,
) -> CustomResult<FxHashMap<String, Self>, errors::CryptoError> {
- #[cfg(not(feature = "encryption_service"))]
- {
+ // If encryption service is not enabled, fall back to application encryption or else call encryption service
+ if !is_encryption_service_enabled(state) {
Self::batch_encrypt(masked_data, key, crypt_algo).await
- }
- #[cfg(feature = "encryption_service")]
- {
+ } else {
let result: Result<
BatchEncryptDataResponse,
error_stack::Report<errors::KeyManagerClientError>,
@@ -501,12 +489,10 @@ mod encrypt {
key: &[u8],
crypt_algo: V,
) -> CustomResult<FxHashMap<String, Self>, errors::CryptoError> {
- #[cfg(not(feature = "encryption_service"))]
- {
+ // If encryption service is not enabled, fall back to application encryption or else call encryption service
+ if !is_encryption_service_enabled(state) {
Self::batch_decrypt(encrypted_data, key, crypt_algo).await
- }
- #[cfg(feature = "encryption_service")]
- {
+ } else {
let result: Result<
BatchDecryptDataResponse,
error_stack::Report<errors::KeyManagerClientError>,
@@ -590,12 +576,10 @@ mod encrypt {
key: &[u8],
crypt_algo: V,
) -> CustomResult<Self, errors::CryptoError> {
- #[cfg(not(feature = "encryption_service"))]
- {
+ // If encryption service is not enabled, fall back to application encryption or else call encryption service
+ if !is_encryption_service_enabled(state) {
Self::encrypt(masked_data, key, crypt_algo).await
- }
- #[cfg(feature = "encryption_service")]
- {
+ } else {
let result: Result<
EncryptDataResponse,
error_stack::Report<errors::KeyManagerClientError>,
@@ -627,12 +611,10 @@ mod encrypt {
key: &[u8],
crypt_algo: V,
) -> CustomResult<Self, errors::CryptoError> {
- #[cfg(not(feature = "encryption_service"))]
- {
+ // If encryption service is not enabled, fall back to application encryption or else call encryption service
+ if !is_encryption_service_enabled(state) {
Self::decrypt(encrypted_data, key, crypt_algo).await
- }
- #[cfg(feature = "encryption_service")]
- {
+ } else {
let result: Result<
DecryptDataResponse,
error_stack::Report<errors::KeyManagerClientError>,
@@ -694,13 +676,10 @@ mod encrypt {
key: &[u8],
crypt_algo: V,
) -> CustomResult<FxHashMap<String, Self>, errors::CryptoError> {
- #[cfg(not(feature = "encryption_service"))]
- {
+ // If encryption service is not enabled, fall back to application encryption or else call encryption service
+ if !is_encryption_service_enabled(state) {
Self::batch_encrypt(masked_data, key, crypt_algo).await
- }
-
- #[cfg(feature = "encryption_service")]
- {
+ } else {
let result: Result<
BatchEncryptDataResponse,
error_stack::Report<errors::KeyManagerClientError>,
@@ -731,12 +710,10 @@ mod encrypt {
key: &[u8],
crypt_algo: V,
) -> CustomResult<FxHashMap<String, Self>, errors::CryptoError> {
- #[cfg(not(feature = "encryption_service"))]
- {
+ // If encryption service is not enabled, fall back to application encryption or else call encryption service
+ if !is_encryption_service_enabled(state) {
Self::batch_decrypt(encrypted_data, key, crypt_algo).await
- }
- #[cfg(feature = "encryption_service")]
- {
+ } else {
let result: Result<
BatchDecryptDataResponse,
error_stack::Report<errors::KeyManagerClientError>,
diff --git a/crates/router/Cargo.toml b/crates/router/Cargo.toml
index 90774ed0df3..e01be51a68c 100644
--- a/crates/router/Cargo.toml
+++ b/crates/router/Cargo.toml
@@ -12,10 +12,11 @@ license.workspace = true
default = ["kv_store", "stripe", "oltp", "olap", "accounts_cache", "dummy_connector", "payouts", "payout_retry", "retry", "frm", "tls", "v1"]
olap = ["hyperswitch_domain_models/olap", "storage_impl/olap", "scheduler/olap", "api_models/olap", "dep:analytics"]
tls = ["actix-web/rustls-0_22"]
-keymanager_mtls = ["reqwest/rustls-tls", "common_utils/keymanager_mtls"]
-encryption_service = ["hyperswitch_domain_models/encryption_service", "common_utils/encryption_service"]
email = ["external_services/email", "scheduler/email", "olap"]
+# keymanager_create, keymanager_mtls, encryption_service should not be removed or added to default feature. Once this features were enabled it can't be disabled as these are breaking changes.
keymanager_create = []
+keymanager_mtls = ["reqwest/rustls-tls", "common_utils/keymanager_mtls"]
+encryption_service = ["hyperswitch_domain_models/encryption_service", "common_utils/encryption_service"]
frm = ["api_models/frm", "hyperswitch_domain_models/frm", "hyperswitch_connectors/frm", "hyperswitch_interfaces/frm"]
stripe = ["dep:serde_qs"]
release = ["stripe", "email", "accounts_cache", "kv_store", "vergen", "recon", "external_services/aws_kms", "external_services/aws_s3", "keymanager_mtls", "keymanager_create", "encryption_service"]
diff --git a/crates/router/src/configs/defaults.rs b/crates/router/src/configs/defaults.rs
index ffa3d81edea..c7125770fff 100644
--- a/crates/router/src/configs/defaults.rs
+++ b/crates/router/src/configs/defaults.rs
@@ -8936,6 +8936,7 @@ impl Default for super::settings::ApiKeys {
impl Default for super::settings::KeyManagerConfig {
fn default() -> Self {
Self {
+ enabled: None,
url: String::from("localhost:5000"),
#[cfg(feature = "keymanager_mtls")]
ca: String::default().into(),
diff --git a/crates/router/src/configs/settings.rs b/crates/router/src/configs/settings.rs
index 2fe484b8fbc..a210b86baf1 100644
--- a/crates/router/src/configs/settings.rs
+++ b/crates/router/src/configs/settings.rs
@@ -210,6 +210,7 @@ pub struct KvConfig {
#[derive(Debug, Deserialize, Clone)]
pub struct KeyManagerConfig {
+ pub enabled: Option<bool>,
pub url: String,
#[cfg(feature = "keymanager_mtls")]
pub cert: Secret<String>,
diff --git a/crates/router/src/routes/admin.rs b/crates/router/src/routes/admin.rs
index 5044070037f..c9cb9dac908 100644
--- a/crates/router/src/routes/admin.rs
+++ b/crates/router/src/routes/admin.rs
@@ -772,7 +772,7 @@ pub async fn merchant_account_transfer_keys(
payload: web::Json<api_models::admin::MerchantKeyTransferRequest>,
) -> HttpResponse {
let flow = Flow::ConfigKeyFetch;
- api::server_wrap(
+ Box::pin(api::server_wrap(
flow,
state,
&req,
@@ -780,7 +780,7 @@ pub async fn merchant_account_transfer_keys(
|state, _, req, _| transfer_key_store_to_key_manager(state, req),
&auth::AdminApiAuth,
api_locking::LockAction::NotApplicable,
- )
+ ))
.await
}
diff --git a/crates/router/src/types/domain/types.rs b/crates/router/src/types/domain/types.rs
index fa9053a096f..e105b2eba09 100644
--- a/crates/router/src/types/domain/types.rs
+++ b/crates/router/src/types/domain/types.rs
@@ -8,6 +8,7 @@ impl From<&crate::SessionState> for KeyManagerState {
fn from(state: &crate::SessionState) -> Self {
let conf = state.conf.key_manager.get_inner();
Self {
+ enabled: conf.enabled,
url: conf.url.clone(),
client_idle_timeout: state.conf.proxy.idle_pool_connection_timeout,
#[cfg(feature = "keymanager_mtls")]
|
2024-07-25T11:50:32Z
|
## Type of Change
<!-- Put an `x` in the boxes that apply -->
- [ ] Bugfix
- [x] New feature
- [ ] Enhancement
- [ ] Refactoring
- [ ] Dependency updates
- [ ] Documentation
- [ ] CI/CD
## Description
This PR adds env variable for enabling encryption service. Application changes for encryption service is not backward compatible, so once the build is deployed and certified stable this feature will be enabled by setting up "true" to key_manager.enabled flag. Later only application starts using encryption service for encryption and decryption. Once the config is enabled it shouldn't be disabled.
### Additional Changes
- [ ] This PR modifies the API contract
- [ ] This PR modifies the database schema
- [x] This PR modifies application configuration/environment variables
## Motivation and Context
This PR adds env variable for enabling encryption service. Application changes for encryption service is not backward compatible, so once the build is deployed and certified stable this feature will be enabled by setting up "true" to key_manager.enabled flag. Later only application starts using encryption service for encryption and decryption.
## How did you test it?
**This can't be tested in Test environment, since it is already enabled in both**
1. key_manager.enabled: false and feature "encryption_service" disabled. Encryption and decryption happens within the application
2. key_manager.enabled: true and feature "encryption_service" disabled. Encryption and decryption happens within the application
3. key_manager.enabled: false and feature "encryption_service" enabled. Encryption and decryption happens within the application
4. key_manager.enabled: true and feature "encryption_service" enabled. Encryption and decryption happens with encryption service. Once this is enabled can't be disabled.
## Checklist
<!-- Put an `x` in the boxes that apply -->
- [x] I formatted the code `cargo +nightly fmt --all`
- [x] I addressed lints thrown by `cargo clippy`
- [x] I reviewed the submitted code
|
043ea6d8dc9fe8108e0b7eb8113217bc37fa488a
|
|
juspay/hyperswitch
|
juspay__hyperswitch-5433
|
Bug: refactor(opensearch): Add Error Handling for Empty Query and Filters in Request
**Description:**
> **Problem:**
> Currently, there is no validation to check whether both the `query` and `filters` in the request are empty. This can lead to the processing of invalid requests, which may cause unexpected behavior or errors in the application.
>
> **Recommended Solution:**
> Implement a validation check that ensures the `query` field is not empty or consisting only of whitespace, and that the `filters` field is not entirely `None` or containing only `None` values for all its fields. If both conditions are true, an error should be returned.
|
diff --git a/crates/analytics/src/opensearch.rs b/crates/analytics/src/opensearch.rs
index 05f89b655cf..1031c815448 100644
--- a/crates/analytics/src/opensearch.rs
+++ b/crates/analytics/src/opensearch.rs
@@ -71,6 +71,8 @@ pub enum OpenSearchError {
ConnectionError,
#[error("Opensearch NON-200 response content: '{0}'")]
ResponseNotOK(String),
+ #[error("Opensearch bad request error")]
+ BadRequestError(String),
#[error("Opensearch response error")]
ResponseError,
#[error("Opensearch query building error")]
@@ -98,6 +100,9 @@ impl ErrorSwitch<ApiErrorResponse> for OpenSearchError {
"Connection error",
None,
)),
+ Self::BadRequestError(response) => {
+ ApiErrorResponse::BadRequest(ApiError::new("IR", 1, response.to_string(), None))
+ }
Self::ResponseNotOK(response) => ApiErrorResponse::InternalServerError(ApiError::new(
"IR",
1,
diff --git a/crates/analytics/src/search.rs b/crates/analytics/src/search.rs
index a5bd117bd63..68285afc8bb 100644
--- a/crates/analytics/src/search.rs
+++ b/crates/analytics/src/search.rs
@@ -16,6 +16,17 @@ pub async fn msearch_results(
merchant_id: &String,
indexes: Vec<SearchIndex>,
) -> CustomResult<Vec<GetSearchResponse>, OpenSearchError> {
+ if req.query.trim().is_empty()
+ && req
+ .filters
+ .as_ref()
+ .map_or(true, |filters| filters.is_all_none())
+ {
+ return Err(OpenSearchError::BadRequestError(
+ "Both query and filters are empty".to_string(),
+ )
+ .into());
+ }
let mut query_builder =
OpenSearchQueryBuilder::new(OpenSearchQuery::Msearch(indexes.clone()), req.query);
diff --git a/crates/api_models/src/analytics/search.rs b/crates/api_models/src/analytics/search.rs
index d1af00de569..f27af75936d 100644
--- a/crates/api_models/src/analytics/search.rs
+++ b/crates/api_models/src/analytics/search.rs
@@ -10,6 +10,15 @@ pub struct SearchFilters {
pub customer_email: Option<Vec<HashedString<common_utils::pii::EmailStrategy>>>,
pub search_tags: Option<Vec<HashedString<WithType>>>,
}
+impl SearchFilters {
+ pub fn is_all_none(&self) -> bool {
+ self.payment_method.is_none()
+ && self.currency.is_none()
+ && self.status.is_none()
+ && self.customer_email.is_none()
+ && self.search_tags.is_none()
+ }
+}
#[derive(Clone, Debug, serde::Deserialize, serde::Serialize)]
#[serde(rename_all = "camelCase")]
|
2024-07-24T13:34:26Z
|
## Type of Change
<!-- Put an `x` in the boxes that apply -->
- [ ] Bugfix
- [ ] New feature
- [ ] Enhancement
- [x] Refactoring
- [ ] Dependency updates
- [ ] Documentation
- [ ] CI/CD
## Description
<!-- Describe your changes in detail -->
> Implement a validation check that ensures the `query` field is not empty or consisting only of whitespace, and that the `filters` field is not entirely `None` or containing only `None` values for all its fields. If both conditions are true, an error should be returned.
### Additional Changes
- [ ] This PR modifies the API contract
- [ ] This PR modifies the database schema
- [ ] This PR modifies application configuration/environment variables
<!--
Provide links to the files with corresponding changes.
Following are the paths where you can find config files:
1. `config`
2. `crates/router/src/configs`
3. `loadtest/config`
-->
## Motivation and Context
<!--
Why is this change required? What problem does it solve?
If it fixes an open issue, please link to the issue here.
If you don't have an issue, we'd recommend starting with one first so the PR
can focus on the implementation (unless it is an obvious bug or documentation fix
that will have little conversation).
-->
## How did you test it?
<!--
Did you write an integration/unit/API test to verify the code changes?
Or did you test this change manually (provide relevant screenshots)?
-->
```bash
curl 'http://localhost:8080/analytics/v1/search' \
-H 'sec-ch-ua: "Not/A)Brand";v="8", "Chromium";v="126", "Google Chrome";v="126"' \
-H 'sec-ch-ua-mobile: ?0' \
-H 'authorization: Bearer eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJ1c2VyX2lkIjoiNTEzYWUyODItN2I1NS00MGMwLWFiZGMtYjdiMGYzNDNkMTQ2IiwibWVyY2hhbnRfaWQiOiJtZXJjaGFudF8xNzIxNjQyOTczIiwicm9sZV9pZCI6Im9yZ19hZG1pbiIsImV4cCI6MTcyMjE1NzQ0Miwib3JnX2lkIjoib3JnX2drZHNlNDBIdGx6RkNob2NpU0NzIn0.Fmrxsp-emKQ-67EpcJolMf7EyeDdjl4DcwbmnVSprMU' \
-H 'User-Agent: Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/126.0.0.0 Safari/537.36' \
-H 'Content-Type: application/json' \
-H 'Referer: http://localhost:9000/' \
-H 'api-key: hyperswitch' \
-H 'sec-ch-ua-platform: "macOS"' \
--data-raw '{"query":"dvs"}'
```
- An empty query with an unknown filter produces an error.
- An empty filter with whitespaces in the query produces an error.
- An empty query with a known filter should give results.
<img width="1304" alt="image" src="https://github.com/user-attachments/assets/013b397e-72f8-489d-af94-b04441708946">
## Checklist
<!-- Put an `x` in the boxes that apply -->
- [ ] I formatted the code `cargo +nightly fmt --all`
- [ ] I addressed lints thrown by `cargo clippy`
- [ ] I reviewed the submitted code
- [ ] I added unit tests for my changes where possible
|
e18ea7a7bab257a6082639e84da8d9e44f31168f
|
|
juspay/hyperswitch
|
juspay__hyperswitch-5455
|
Bug: [ENHANCEMENT] update API schema for payouts
### Bug Description
API request / response structure for payouts API hasn't kept up the development pace w payments API. Overtime, some of the fields in payouts API request have been obsoleted, whereas some of the new fields / objects are added for consuming different features.
On top of this, the auto-generated API docs are not well maintained.
### Expected Behavior
Loose fields like email, name etc. (revolving around customer's context) are to be moved to the `customer` object
Generated API reference + docs are to be reviewed and updated as necessary.
### Have you spent some time checking if this bug has been raised before?
- [X] I checked and didn't find a similar issue
### Have you read the Contributing Guidelines?
- [X] I have read the [Contributing Guidelines](https://github.com/juspay/hyperswitch/blob/main/docs/CONTRIBUTING.md)
### Are you willing to submit a PR?
Yes, I am willing to submit a PR!
|
diff --git a/crates/api_models/src/payouts.rs b/crates/api_models/src/payouts.rs
index c3ae760215b..3333fb6f546 100644
--- a/crates/api_models/src/payouts.rs
+++ b/crates/api_models/src/payouts.rs
@@ -18,7 +18,10 @@ pub enum PayoutRequest {
PayoutRetrieveRequest(PayoutRetrieveRequest),
}
-#[derive(Default, Debug, Deserialize, Serialize, Clone, ToSchema)]
+#[derive(
+ Default, Debug, Deserialize, Serialize, Clone, ToSchema, router_derive::PolymorphicSchema,
+)]
+#[generate_schemas(PayoutsCreateRequest, PayoutUpdateRequest, PayoutConfirmRequest)]
#[serde(deny_unknown_fields)]
pub struct PayoutCreateRequest {
/// Unique identifier for the payout. This ensures idempotency for multiple payouts that have been done by a single merchant. This field is auto generated and is returned in the API response, **not required to be included in the Payout Create/Update Request.**
@@ -26,21 +29,27 @@ pub struct PayoutCreateRequest {
value_type = Option<String>,
min_length = 30,
max_length = 30,
- example = "payout_mbabizu24mvu3mela5njyhpit4"
+ example = "187282ab-40ef-47a9-9206-5099ba31e432"
)]
+ #[remove_in(PayoutsCreateRequest, PayoutUpdateRequest, PayoutConfirmRequest)]
pub payout_id: Option<String>, // TODO: #1321 https://github.com/juspay/hyperswitch/issues/1321
/// This is an identifier for the merchant account. This is inferred from the API key provided during the request, **not required to be included in the Payout Create/Update Request.**
#[schema(max_length = 255, value_type = Option<String>, example = "merchant_1668273825")]
+ #[remove_in(PayoutsCreateRequest, PayoutUpdateRequest, PayoutConfirmRequest)]
pub merchant_id: Option<id_type::MerchantId>,
/// The payout amount. Amount for the payout in lowest denomination of the currency. (i.e) in cents for USD denomination, in paisa for INR denomination etc.,
- #[schema(value_type = i64, example = 1000)]
+ #[schema(value_type = Option<u64>, example = 1000)]
+ #[mandatory_in(PayoutsCreateRequest = u64)]
+ #[remove_in(PayoutsConfirmRequest)]
#[serde(default, deserialize_with = "payments::amount::deserialize_option")]
pub amount: Option<payments::Amount>,
/// The currency of the payout request can be specified here
- #[schema(value_type = Currency, example = "USD")]
+ #[schema(value_type = Option<Currency>, example = "USD")]
+ #[mandatory_in(PayoutsCreateRequest = Currency)]
+ #[remove_in(PayoutsConfirmRequest)]
pub currency: Option<api_enums::Currency>,
/// Specifies routing algorithm for selecting a connector
@@ -55,11 +64,12 @@ pub struct PayoutCreateRequest {
pub connector: Option<Vec<api_enums::PayoutConnectors>>,
/// This field is used when merchant wants to confirm the payout, thus useful for the payout _Confirm_ request. Ideally merchants should _Create_ a payout, _Update_ it (if required), then _Confirm_ it.
- #[schema(value_type = bool, example = true, default = false)]
+ #[schema(value_type = Option<bool>, example = true, default = false)]
+ #[remove_in(PayoutConfirmRequest)]
pub confirm: Option<bool>,
/// The payout_type of the payout request can be specified here, this is a mandatory field to _Confirm_ the payout, i.e., should be passed in _Create_ request, if not then should be updated in the payout _Update_ request, then only it can be confirmed.
- #[schema(value_type = PayoutType, example = "card")]
+ #[schema(value_type = Option<PayoutType>, example = "card")]
pub payout_type: Option<api_enums::PayoutType>,
/// The payout method information required for carrying out a payout
@@ -67,7 +77,7 @@ pub struct PayoutCreateRequest {
pub payout_method_data: Option<PayoutMethodData>,
/// The billing address for the payout
- #[schema(value_type = Option<Object>, example = json!(r#"{
+ #[schema(value_type = Option<Address>, example = json!(r#"{
"address": {
"line1": "1467",
"line2": "Harrison Street",
@@ -83,52 +93,42 @@ pub struct PayoutCreateRequest {
}"#))]
pub billing: Option<payments::Address>,
- /// The identifier for the customer object. If not provided the customer ID will be autogenerated.
- #[schema(value_type = Option<String>, max_length = 255, example = "cus_y3oqhf46pyzuxjbcn2giaqnb44")]
- pub customer_id: Option<id_type::CustomerId>,
-
/// Set to true to confirm the payout without review, no further action required
- #[schema(value_type = bool, example = true, default = false)]
+ #[schema(value_type = Option<bool>, example = true, default = false)]
pub auto_fulfill: Option<bool>,
- /// description: The customer's email address
- #[schema(max_length = 255, value_type = Option<String>, example = "johntest@test.com")]
- pub email: Option<Email>,
-
- /// description: The customer's name
- #[schema(value_type = Option<String>, max_length = 255, example = "John Test")]
- pub name: Option<Secret<String>>,
-
- /// The customer's phone number
- #[schema(value_type = Option<String>, max_length = 255, example = "9123456789")]
- pub phone: Option<Secret<String>>,
+ /// The identifier for the customer object. If not provided the customer ID will be autogenerated. _Deprecated: Use customer_id instead._
+ #[schema(deprecated, value_type = Option<String>, max_length = 255, example = "cus_y3oqhf46pyzuxjbcn2giaqnb44")]
+ pub customer_id: Option<id_type::CustomerId>,
- /// The country code for the customer phone number
- #[schema(max_length = 255, example = "+1")]
- pub phone_country_code: Option<String>,
+ /// Passing this object creates a new customer or attaches an existing customer to the payout
+ #[schema(value_type = Option<CustomerDetails>)]
+ pub customer: Option<payments::CustomerDetails>,
/// It's a token used for client side verification.
- #[schema(value_type = String, example = "pay_U42c409qyHwOkWo3vK60_secret_el9ksDkiB8hi6j9N78yo")]
+ #[schema(value_type = Option<String>, example = "pay_U42c409qyHwOkWo3vK60_secret_el9ksDkiB8hi6j9N78yo")]
+ #[remove_in(PayoutsCreateRequest)]
+ #[mandatory_in(PayoutConfirmRequest = String)]
pub client_secret: Option<String>,
/// The URL to redirect after the completion of the operation
- #[schema(value_type = String, example = "https://hyperswitch.io")]
+ #[schema(value_type = Option<String>, example = "https://hyperswitch.io")]
pub return_url: Option<String>,
- /// Business country of the merchant for this payout
- #[schema(example = "US", value_type = CountryAlpha2)]
+ /// Business country of the merchant for this payout. _Deprecated: Use profile_id instead._
+ #[schema(deprecated, example = "US", value_type = Option<CountryAlpha2>)]
pub business_country: Option<api_enums::CountryAlpha2>,
- /// Business label of the merchant for this payout
- #[schema(example = "food", value_type = Option<String>)]
+ /// Business label of the merchant for this payout. _Deprecated: Use profile_id instead._
+ #[schema(deprecated, example = "food", value_type = Option<String>)]
pub business_label: Option<String>,
/// A description of the payout
- #[schema(example = "It's my first payout request", value_type = String)]
+ #[schema(example = "It's my first payout request", value_type = Option<String>)]
pub description: Option<String>,
/// Type of entity to whom the payout is being carried out to, select from the given list of options
- #[schema(value_type = PayoutEntityType, example = "Individual")]
+ #[schema(value_type = Option<PayoutEntityType>, example = "Individual")]
pub entity_type: Option<api_enums::PayoutEntityType>,
/// Specifies whether or not the payout request is recurring
@@ -140,18 +140,18 @@ pub struct PayoutCreateRequest {
pub metadata: Option<pii::SecretSerdeValue>,
/// Provide a reference to a stored payout method, used to process the payout.
- #[schema(example = "187282ab-40ef-47a9-9206-5099ba31e432")]
+ #[schema(example = "187282ab-40ef-47a9-9206-5099ba31e432", value_type = Option<String>)]
pub payout_token: Option<String>,
/// The business profile to use for this payout, especially if there are multiple business profiles associated with the account, otherwise default business profile associated with the merchant account will be used.
pub profile_id: Option<String>,
/// The send method which will be required for processing payouts, check options for better understanding.
- #[schema(value_type = PayoutSendPriority, example = "instant")]
+ #[schema(value_type = Option<PayoutSendPriority>, example = "instant")]
pub priority: Option<api_enums::PayoutSendPriority>,
/// Whether to get the payout link (if applicable). Merchant need to specify this during the Payout _Create_, this field can not be updated during Payout _Update_.
- #[schema(default = false, example = true)]
+ #[schema(default = false, example = true, value_type = Option<bool>)]
pub payout_link: Option<bool>,
/// Custom payout link config for the particular payout, if payout link is to be generated.
@@ -162,6 +162,30 @@ pub struct PayoutCreateRequest {
/// (900) for 15 mins
#[schema(value_type = Option<u32>, example = 900)]
pub session_expiry: Option<u32>,
+
+ /// Customer's email. _Deprecated: Use customer object instead._
+ #[schema(deprecated, max_length = 255, value_type = Option<String>, example = "johntest@test.com")]
+ pub email: Option<Email>,
+
+ /// Customer's name. _Deprecated: Use customer object instead._
+ #[schema(deprecated, value_type = Option<String>, max_length = 255, example = "John Test")]
+ pub name: Option<Secret<String>>,
+
+ /// Customer's phone. _Deprecated: Use customer object instead._
+ #[schema(deprecated, value_type = Option<String>, max_length = 255, example = "9123456789")]
+ pub phone: Option<Secret<String>>,
+
+ /// Customer's phone country code. _Deprecated: Use customer object instead._
+ #[schema(deprecated, max_length = 255, example = "+1")]
+ pub phone_country_code: Option<String>,
+}
+
+impl PayoutCreateRequest {
+ pub fn get_customer_id(&self) -> Option<&id_type::CustomerId> {
+ self.customer_id
+ .as_ref()
+ .or(self.customer.as_ref().map(|customer| &customer.id))
+ }
}
/// Custom payout link config for the particular payout, if payout link is to be generated.
@@ -354,7 +378,7 @@ pub struct PayoutCreateResponse {
value_type = String,
min_length = 30,
max_length = 30,
- example = "payout_mbabizu24mvu3mela5njyhpit4"
+ example = "187282ab-40ef-47a9-9206-5099ba31e432"
)]
pub payout_id: String, // TODO: Update this to PayoutIdType similar to PaymentIdType
@@ -396,29 +420,17 @@ pub struct PayoutCreateResponse {
}"#))]
pub billing: Option<payments::Address>,
- /// The identifier for the customer object. If not provided the customer ID will be autogenerated.
- #[schema(value_type = String, max_length = 255, example = "cus_y3oqhf46pyzuxjbcn2giaqnb44")]
- pub customer_id: id_type::CustomerId,
-
/// Set to true to confirm the payout without review, no further action required
#[schema(value_type = bool, example = true, default = false)]
pub auto_fulfill: bool,
- /// description: The customer's email address
- #[schema(max_length = 255, value_type = Option<String>, example = "johntest@test.com")]
- pub email: crypto::OptionalEncryptableEmail,
-
- /// description: The customer's name
- #[schema(value_type = Option<String>, max_length = 255, example = "John Test")]
- pub name: crypto::OptionalEncryptableName,
-
- /// The customer's phone number
- #[schema(value_type = Option<String>, max_length = 255, example = "9123456789")]
- pub phone: crypto::OptionalEncryptablePhone,
+ /// The identifier for the customer object. If not provided the customer ID will be autogenerated.
+ #[schema(value_type = String, max_length = 255, example = "cus_y3oqhf46pyzuxjbcn2giaqnb44")]
+ pub customer_id: Option<id_type::CustomerId>,
- /// The country code for the customer phone number
- #[schema(max_length = 255, example = "+1")]
- pub phone_country_code: Option<String>,
+ /// Passing this object creates a new customer or attaches an existing customer to the payout
+ #[schema(value_type = Option<CustomerDetailsResponse>)]
+ pub customer: Option<payments::CustomerDetailsResponse>,
/// It's a token used for client side verification.
#[schema(value_type = String, example = "pay_U42c409qyHwOkWo3vK60_secret_el9ksDkiB8hi6j9N78yo")]
@@ -437,7 +449,7 @@ pub struct PayoutCreateResponse {
pub business_label: Option<String>,
/// A description of the payout
- #[schema(example = "It's my first payout request", value_type = String)]
+ #[schema(example = "It's my first payout request", value_type = Option<String>)]
pub description: Option<String>,
/// Type of entity to whom the payout is being carried out to
@@ -445,7 +457,7 @@ pub struct PayoutCreateResponse {
pub entity_type: api_enums::PayoutEntityType,
/// Specifies whether or not the payout request is recurring
- #[schema(value_type = Option<bool>, default = false)]
+ #[schema(value_type = bool, default = false)]
pub recurring: bool,
/// You can specify up to 50 keys, with key names up to 40 characters long and values up to 500 characters long. Metadata is useful for storing additional, structured information on an object.
@@ -453,15 +465,15 @@ pub struct PayoutCreateResponse {
pub metadata: Option<pii::SecretSerdeValue>,
/// Current status of the Payout
- #[schema(value_type = PayoutStatus, example = Pending)]
+ #[schema(value_type = PayoutStatus, example = RequiresConfirmation)]
pub status: api_enums::PayoutStatus,
/// If there was an error while calling the connector the error message is received here
- #[schema(value_type = String, example = "Failed while verifying the card")]
+ #[schema(value_type = Option<String>, example = "Failed while verifying the card")]
pub error_message: Option<String>,
/// If there was an error while calling the connectors the code is received here
- #[schema(value_type = String, example = "E0001")]
+ #[schema(value_type = Option<String>, example = "E0001")]
pub error_code: Option<String>,
/// The business profile that is associated with this payout
@@ -488,6 +500,22 @@ pub struct PayoutCreateResponse {
/// If payout link was requested, this contains the link's ID and the URL to render the payout widget
#[schema(value_type = Option<PayoutLinkResponse>)]
pub payout_link: Option<PayoutLinkResponse>,
+
+ /// Customer's email. _Deprecated: Use customer object instead._
+ #[schema(deprecated, max_length = 255, value_type = Option<String>, example = "johntest@test.com")]
+ pub email: crypto::OptionalEncryptableEmail,
+
+ /// Customer's name. _Deprecated: Use customer object instead._
+ #[schema(deprecated, value_type = Option<String>, max_length = 255, example = "John Test")]
+ pub name: crypto::OptionalEncryptableName,
+
+ /// Customer's phone. _Deprecated: Use customer object instead._
+ #[schema(deprecated, value_type = Option<String>, max_length = 255, example = "9123456789")]
+ pub phone: crypto::OptionalEncryptablePhone,
+
+ /// Customer's phone country code. _Deprecated: Use customer object instead._
+ #[schema(deprecated, max_length = 255, example = "+1")]
+ pub phone_country_code: Option<String>,
}
#[derive(
@@ -542,7 +570,7 @@ pub struct PayoutRetrieveRequest {
value_type = String,
min_length = 30,
max_length = 30,
- example = "payout_mbabizu24mvu3mela5njyhpit4"
+ example = "187282ab-40ef-47a9-9206-5099ba31e432"
)]
pub payout_id: String,
@@ -556,7 +584,10 @@ pub struct PayoutRetrieveRequest {
pub merchant_id: Option<id_type::MerchantId>,
}
-#[derive(Default, Debug, Serialize, ToSchema, Clone, Deserialize)]
+#[derive(
+ Default, Debug, Deserialize, Serialize, Clone, ToSchema, router_derive::PolymorphicSchema,
+)]
+#[generate_schemas(PayoutCancelRequest, PayoutFulfillRequest)]
pub struct PayoutActionRequest {
/// Unique identifier for the payout. This ensures idempotency for multiple payouts
/// that have been done by a single merchant. This field is auto generated and is returned in the API response.
@@ -564,8 +595,9 @@ pub struct PayoutActionRequest {
value_type = String,
min_length = 30,
max_length = 30,
- example = "payout_mbabizu24mvu3mela5njyhpit4"
+ example = "187282ab-40ef-47a9-9206-5099ba31e432"
)]
+ #[serde(skip_deserializing)]
pub payout_id: String,
}
@@ -645,7 +677,7 @@ pub struct PayoutListFilterConstraints {
value_type = Option<String>,
min_length = 30,
max_length = 30,
- example = "payout_mbabizu24mvu3mela5njyhpit4"
+ example = "187282ab-40ef-47a9-9206-5099ba31e432"
)]
pub payout_id: Option<String>,
/// The identifier for business profile
@@ -687,15 +719,19 @@ pub struct PayoutListResponse {
pub data: Vec<PayoutCreateResponse>,
}
-#[derive(Clone, Debug, serde::Serialize)]
+#[derive(Clone, Debug, serde::Serialize, ToSchema)]
pub struct PayoutListFilters {
/// The list of available connector filters
+ #[schema(value_type = Vec<PayoutConnectors>)]
pub connector: Vec<api_enums::PayoutConnectors>,
/// The list of available currency filters
+ #[schema(value_type = Vec<Currency>)]
pub currency: Vec<common_enums::Currency>,
/// The list of available payout status filters
+ #[schema(value_type = Vec<PayoutStatus>)]
pub status: Vec<common_enums::PayoutStatus>,
/// The list of available payout method filters
+ #[schema(value_type = Vec<PayoutType>)]
pub payout_method: Vec<common_enums::PayoutType>,
}
diff --git a/crates/diesel_models/src/payout_attempt.rs b/crates/diesel_models/src/payout_attempt.rs
index d8e5af55ccc..fe8bbd77a38 100644
--- a/crates/diesel_models/src/payout_attempt.rs
+++ b/crates/diesel_models/src/payout_attempt.rs
@@ -11,9 +11,9 @@ use crate::{enums as storage_enums, schema::payout_attempt};
pub struct PayoutAttempt {
pub payout_attempt_id: String,
pub payout_id: String,
- pub customer_id: common_utils::id_type::CustomerId,
+ pub customer_id: Option<common_utils::id_type::CustomerId>,
pub merchant_id: common_utils::id_type::MerchantId,
- pub address_id: String,
+ pub address_id: Option<String>,
pub connector: Option<String>,
pub connector_payout_id: Option<String>,
pub payout_token: Option<String>,
@@ -47,9 +47,9 @@ pub struct PayoutAttempt {
pub struct PayoutAttemptNew {
pub payout_attempt_id: String,
pub payout_id: String,
- pub customer_id: common_utils::id_type::CustomerId,
+ pub customer_id: Option<common_utils::id_type::CustomerId>,
pub merchant_id: common_utils::id_type::MerchantId,
- pub address_id: String,
+ pub address_id: Option<String>,
pub connector: Option<String>,
pub connector_payout_id: Option<String>,
pub payout_token: Option<String>,
@@ -83,6 +83,8 @@ pub enum PayoutAttemptUpdate {
BusinessUpdate {
business_country: Option<storage_enums::CountryAlpha2>,
business_label: Option<String>,
+ address_id: Option<String>,
+ customer_id: Option<common_utils::id_type::CustomerId>,
},
UpdateRouting {
connector: String,
@@ -104,6 +106,8 @@ pub struct PayoutAttemptUpdateInternal {
pub connector: Option<String>,
pub routing_info: Option<serde_json::Value>,
pub last_modified_at: PrimitiveDateTime,
+ pub address_id: Option<String>,
+ pub customer_id: Option<common_utils::id_type::CustomerId>,
}
impl Default for PayoutAttemptUpdateInternal {
@@ -120,6 +124,8 @@ impl Default for PayoutAttemptUpdateInternal {
connector: None,
routing_info: None,
last_modified_at: common_utils::date_time::now(),
+ address_id: None,
+ customer_id: None,
}
}
}
@@ -148,9 +154,13 @@ impl From<PayoutAttemptUpdate> for PayoutAttemptUpdateInternal {
PayoutAttemptUpdate::BusinessUpdate {
business_country,
business_label,
+ address_id,
+ customer_id,
} => Self {
business_country,
business_label,
+ address_id,
+ customer_id,
..Default::default()
},
PayoutAttemptUpdate::UpdateRouting {
@@ -179,6 +189,8 @@ impl PayoutAttemptUpdate {
connector,
routing_info,
last_modified_at,
+ address_id,
+ customer_id,
} = self.into();
PayoutAttempt {
payout_token: payout_token.or(source.payout_token),
@@ -192,6 +204,8 @@ impl PayoutAttemptUpdate {
connector: connector.or(source.connector),
routing_info: routing_info.or(source.routing_info),
last_modified_at,
+ address_id: address_id.or(source.address_id),
+ customer_id: customer_id.or(source.customer_id),
..source
}
}
diff --git a/crates/diesel_models/src/payouts.rs b/crates/diesel_models/src/payouts.rs
index 9573d056641..cb8f6f9a884 100644
--- a/crates/diesel_models/src/payouts.rs
+++ b/crates/diesel_models/src/payouts.rs
@@ -13,8 +13,8 @@ use crate::{enums as storage_enums, schema::payouts};
pub struct Payouts {
pub payout_id: String,
pub merchant_id: common_utils::id_type::MerchantId,
- pub customer_id: common_utils::id_type::CustomerId,
- pub address_id: String,
+ pub customer_id: Option<common_utils::id_type::CustomerId>,
+ pub address_id: Option<String>,
pub payout_type: Option<storage_enums::PayoutType>,
pub payout_method_id: Option<String>,
pub amount: MinorUnit,
@@ -54,8 +54,8 @@ pub struct Payouts {
pub struct PayoutsNew {
pub payout_id: String,
pub merchant_id: common_utils::id_type::MerchantId,
- pub customer_id: common_utils::id_type::CustomerId,
- pub address_id: String,
+ pub customer_id: Option<common_utils::id_type::CustomerId>,
+ pub address_id: Option<String>,
pub payout_type: Option<storage_enums::PayoutType>,
pub payout_method_id: Option<String>,
pub amount: MinorUnit,
@@ -96,6 +96,8 @@ pub enum PayoutsUpdate {
status: Option<storage_enums::PayoutStatus>,
confirm: Option<bool>,
payout_type: Option<storage_enums::PayoutType>,
+ address_id: Option<String>,
+ customer_id: Option<common_utils::id_type::CustomerId>,
},
PayoutMethodIdUpdate {
payout_method_id: String,
@@ -130,6 +132,8 @@ pub struct PayoutsUpdateInternal {
pub attempt_count: Option<i16>,
pub confirm: Option<bool>,
pub payout_type: Option<common_enums::PayoutType>,
+ pub address_id: Option<String>,
+ pub customer_id: Option<common_utils::id_type::CustomerId>,
}
impl Default for PayoutsUpdateInternal {
@@ -151,6 +155,8 @@ impl Default for PayoutsUpdateInternal {
attempt_count: None,
confirm: None,
payout_type: None,
+ address_id: None,
+ customer_id: None,
}
}
}
@@ -172,6 +178,8 @@ impl From<PayoutsUpdate> for PayoutsUpdateInternal {
status,
confirm,
payout_type,
+ address_id,
+ customer_id,
} => Self {
amount: Some(amount),
destination_currency: Some(destination_currency),
@@ -186,6 +194,8 @@ impl From<PayoutsUpdate> for PayoutsUpdateInternal {
status,
confirm,
payout_type,
+ address_id,
+ customer_id,
..Default::default()
},
PayoutsUpdate::PayoutMethodIdUpdate { payout_method_id } => Self {
@@ -227,6 +237,8 @@ impl PayoutsUpdate {
attempt_count,
confirm,
payout_type,
+ address_id,
+ customer_id,
} = self.into();
Payouts {
amount: amount.unwrap_or(source.amount),
@@ -245,6 +257,8 @@ impl PayoutsUpdate {
attempt_count: attempt_count.unwrap_or(source.attempt_count),
confirm: confirm.or(source.confirm),
payout_type: payout_type.or(source.payout_type),
+ address_id: address_id.or(source.address_id),
+ customer_id: customer_id.or(source.customer_id),
..source
}
}
diff --git a/crates/diesel_models/src/schema.rs b/crates/diesel_models/src/schema.rs
index ebeff9c97f3..08a4e68c883 100644
--- a/crates/diesel_models/src/schema.rs
+++ b/crates/diesel_models/src/schema.rs
@@ -997,11 +997,11 @@ diesel::table! {
#[max_length = 64]
payout_id -> Varchar,
#[max_length = 64]
- customer_id -> Varchar,
+ customer_id -> Nullable<Varchar>,
#[max_length = 64]
merchant_id -> Varchar,
#[max_length = 64]
- address_id -> Varchar,
+ address_id -> Nullable<Varchar>,
#[max_length = 64]
connector -> Nullable<Varchar>,
#[max_length = 128]
@@ -1036,9 +1036,9 @@ diesel::table! {
#[max_length = 64]
merchant_id -> Varchar,
#[max_length = 64]
- customer_id -> Varchar,
+ customer_id -> Nullable<Varchar>,
#[max_length = 64]
- address_id -> Varchar,
+ address_id -> Nullable<Varchar>,
payout_type -> Nullable<PayoutType>,
#[max_length = 64]
payout_method_id -> Nullable<Varchar>,
diff --git a/crates/diesel_models/src/schema_v2.rs b/crates/diesel_models/src/schema_v2.rs
index 68c066288fd..b5cfc00ae18 100644
--- a/crates/diesel_models/src/schema_v2.rs
+++ b/crates/diesel_models/src/schema_v2.rs
@@ -980,11 +980,11 @@ diesel::table! {
#[max_length = 64]
payout_id -> Varchar,
#[max_length = 64]
- customer_id -> Varchar,
+ customer_id -> Nullable<Varchar>,
#[max_length = 64]
merchant_id -> Varchar,
#[max_length = 64]
- address_id -> Varchar,
+ address_id -> Nullable<Varchar>,
#[max_length = 64]
connector -> Nullable<Varchar>,
#[max_length = 128]
@@ -1019,9 +1019,9 @@ diesel::table! {
#[max_length = 64]
merchant_id -> Varchar,
#[max_length = 64]
- customer_id -> Varchar,
+ customer_id -> Nullable<Varchar>,
#[max_length = 64]
- address_id -> Varchar,
+ address_id -> Nullable<Varchar>,
payout_type -> Nullable<PayoutType>,
#[max_length = 64]
payout_method_id -> Nullable<Varchar>,
diff --git a/crates/hyperswitch_domain_models/src/payouts/payout_attempt.rs b/crates/hyperswitch_domain_models/src/payouts/payout_attempt.rs
index fe1cf4c9bdf..adba454c798 100644
--- a/crates/hyperswitch_domain_models/src/payouts/payout_attempt.rs
+++ b/crates/hyperswitch_domain_models/src/payouts/payout_attempt.rs
@@ -1,6 +1,6 @@
use api_models::enums::PayoutConnectors;
use common_enums as storage_enums;
-use common_utils::{generate_customer_id_of_default_length, id_type};
+use common_utils::id_type;
use serde::{Deserialize, Serialize};
use storage_enums::MerchantStorageScheme;
use time::PrimitiveDateTime;
@@ -59,9 +59,9 @@ pub struct PayoutListFilters {
pub struct PayoutAttempt {
pub payout_attempt_id: String,
pub payout_id: String,
- pub customer_id: id_type::CustomerId,
+ pub customer_id: Option<id_type::CustomerId>,
pub merchant_id: id_type::MerchantId,
- pub address_id: String,
+ pub address_id: Option<String>,
pub connector: Option<String>,
pub connector_payout_id: Option<String>,
pub payout_token: Option<String>,
@@ -84,9 +84,9 @@ pub struct PayoutAttempt {
pub struct PayoutAttemptNew {
pub payout_attempt_id: String,
pub payout_id: String,
- pub customer_id: id_type::CustomerId,
+ pub customer_id: Option<id_type::CustomerId>,
pub merchant_id: id_type::MerchantId,
- pub address_id: String,
+ pub address_id: Option<String>,
pub connector: Option<String>,
pub connector_payout_id: Option<String>,
pub payout_token: Option<String>,
@@ -110,17 +110,17 @@ impl Default for PayoutAttemptNew {
Self {
payout_attempt_id: String::default(),
payout_id: String::default(),
- customer_id: generate_customer_id_of_default_length(),
+ customer_id: None,
merchant_id: id_type::MerchantId::default(),
- address_id: String::default(),
+ address_id: None,
connector: None,
- connector_payout_id: Some(String::default()),
+ connector_payout_id: None,
payout_token: None,
status: storage_enums::PayoutStatus::default(),
is_eligible: None,
error_message: None,
error_code: None,
- business_country: Some(storage_enums::CountryAlpha2::default()),
+ business_country: None,
business_label: None,
created_at: Some(now),
last_modified_at: Some(now),
@@ -146,6 +146,8 @@ pub enum PayoutAttemptUpdate {
BusinessUpdate {
business_country: Option<storage_enums::CountryAlpha2>,
business_label: Option<String>,
+ address_id: Option<String>,
+ customer_id: Option<id_type::CustomerId>,
},
UpdateRouting {
connector: String,
@@ -165,6 +167,8 @@ pub struct PayoutAttemptUpdateInternal {
pub business_label: Option<String>,
pub connector: Option<String>,
pub routing_info: Option<serde_json::Value>,
+ pub address_id: Option<String>,
+ pub customer_id: Option<id_type::CustomerId>,
}
impl From<PayoutAttemptUpdate> for PayoutAttemptUpdateInternal {
@@ -191,9 +195,13 @@ impl From<PayoutAttemptUpdate> for PayoutAttemptUpdateInternal {
PayoutAttemptUpdate::BusinessUpdate {
business_country,
business_label,
+ address_id,
+ customer_id,
} => Self {
business_country,
business_label,
+ address_id,
+ customer_id,
..Default::default()
},
PayoutAttemptUpdate::UpdateRouting {
diff --git a/crates/hyperswitch_domain_models/src/payouts/payouts.rs b/crates/hyperswitch_domain_models/src/payouts/payouts.rs
index 16b4bf7f912..0c0fbe8ae28 100644
--- a/crates/hyperswitch_domain_models/src/payouts/payouts.rs
+++ b/crates/hyperswitch_domain_models/src/payouts/payouts.rs
@@ -54,7 +54,7 @@ pub trait PayoutsInterface {
_filters: &PayoutFetchConstraints,
_storage_scheme: MerchantStorageScheme,
) -> error_stack::Result<
- Vec<(Payouts, PayoutAttempt, diesel_models::Customer)>,
+ Vec<(Payouts, PayoutAttempt, Option<diesel_models::Customer>)>,
errors::StorageError,
>;
@@ -71,8 +71,8 @@ pub trait PayoutsInterface {
pub struct Payouts {
pub payout_id: String,
pub merchant_id: id_type::MerchantId,
- pub customer_id: id_type::CustomerId,
- pub address_id: String,
+ pub customer_id: Option<id_type::CustomerId>,
+ pub address_id: Option<String>,
pub payout_type: Option<storage_enums::PayoutType>,
pub payout_method_id: Option<String>,
pub amount: MinorUnit,
@@ -99,8 +99,8 @@ pub struct Payouts {
pub struct PayoutsNew {
pub payout_id: String,
pub merchant_id: id_type::MerchantId,
- pub customer_id: id_type::CustomerId,
- pub address_id: String,
+ pub customer_id: Option<id_type::CustomerId>,
+ pub address_id: Option<String>,
pub payout_type: Option<storage_enums::PayoutType>,
pub payout_method_id: Option<String>,
pub amount: MinorUnit,
@@ -130,27 +130,27 @@ impl Default for PayoutsNew {
Self {
payout_id: String::default(),
merchant_id: id_type::MerchantId::default(),
- customer_id: common_utils::generate_customer_id_of_default_length(),
- address_id: String::default(),
- payout_type: Some(storage_enums::PayoutType::default()),
- payout_method_id: Option::default(),
+ customer_id: None,
+ address_id: None,
+ payout_type: None,
+ payout_method_id: None,
amount: MinorUnit::new(i64::default()),
destination_currency: storage_enums::Currency::default(),
source_currency: storage_enums::Currency::default(),
- description: Option::default(),
+ description: None,
recurring: bool::default(),
auto_fulfill: bool::default(),
return_url: None,
entity_type: storage_enums::PayoutEntityType::default(),
- metadata: Option::default(),
+ metadata: None,
created_at: Some(now),
last_modified_at: Some(now),
attempt_count: 1,
profile_id: String::default(),
status: storage_enums::PayoutStatus::default(),
confirm: None,
- payout_link_id: Option::default(),
- client_secret: Option::default(),
+ payout_link_id: None,
+ client_secret: None,
priority: None,
}
}
@@ -172,6 +172,8 @@ pub enum PayoutsUpdate {
status: Option<storage_enums::PayoutStatus>,
confirm: Option<bool>,
payout_type: Option<storage_enums::PayoutType>,
+ address_id: Option<String>,
+ customer_id: Option<id_type::CustomerId>,
},
PayoutMethodIdUpdate {
payout_method_id: String,
@@ -204,6 +206,8 @@ pub struct PayoutsUpdateInternal {
pub attempt_count: Option<i16>,
pub confirm: Option<bool>,
pub payout_type: Option<common_enums::PayoutType>,
+ pub address_id: Option<String>,
+ pub customer_id: Option<id_type::CustomerId>,
}
impl From<PayoutsUpdate> for PayoutsUpdateInternal {
@@ -223,6 +227,8 @@ impl From<PayoutsUpdate> for PayoutsUpdateInternal {
status,
confirm,
payout_type,
+ address_id,
+ customer_id,
} => Self {
amount: Some(amount),
destination_currency: Some(destination_currency),
@@ -237,6 +243,8 @@ impl From<PayoutsUpdate> for PayoutsUpdateInternal {
status,
confirm,
payout_type,
+ address_id,
+ customer_id,
..Default::default()
},
PayoutsUpdate::PayoutMethodIdUpdate { payout_method_id } => Self {
diff --git a/crates/openapi/src/openapi.rs b/crates/openapi/src/openapi.rs
index 50bbd797051..cd51a44edf7 100644
--- a/crates/openapi/src/openapi.rs
+++ b/crates/openapi/src/openapi.rs
@@ -172,8 +172,9 @@ Never share your secret api keys. Keep them guarded and secure.
routes::payouts::payouts_cancel,
routes::payouts::payouts_fulfill,
routes::payouts::payouts_list,
- routes::payouts::payouts_filter,
routes::payouts::payouts_confirm,
+ routes::payouts::payouts_list_filters,
+ routes::payouts::payouts_list_by_filter,
// Routes for api keys
routes::api_keys::api_key_create,
@@ -479,16 +480,19 @@ Never share your secret api keys. Keep them guarded and secure.
api_models::payouts::BacsBankTransfer,
api_models::payouts::SepaBankTransfer,
api_models::payouts::PixBankTransfer,
- api_models::payouts::PayoutRequest,
+ api_models::payouts::PayoutsCreateRequest,
+ api_models::payouts::PayoutUpdateRequest,
+ api_models::payouts::PayoutConfirmRequest,
+ api_models::payouts::PayoutCancelRequest,
+ api_models::payouts::PayoutFulfillRequest,
+ api_models::payouts::PayoutRetrieveRequest,
api_models::payouts::PayoutAttemptResponse,
- api_models::payouts::PayoutActionRequest,
- api_models::payouts::PayoutCreateRequest,
api_models::payouts::PayoutCreateResponse,
api_models::payouts::PayoutListConstraints,
+ api_models::payouts::PayoutListFilters,
api_models::payouts::PayoutListFilterConstraints,
api_models::payouts::PayoutListResponse,
api_models::payouts::PayoutRetrieveBody,
- api_models::payouts::PayoutRetrieveRequest,
api_models::payouts::PayoutMethodData,
api_models::payouts::PayoutLinkResponse,
api_models::payouts::Bank,
diff --git a/crates/openapi/src/routes/payouts.rs b/crates/openapi/src/routes/payouts.rs
index 63daa85226a..0a429041afe 100644
--- a/crates/openapi/src/routes/payouts.rs
+++ b/crates/openapi/src/routes/payouts.rs
@@ -2,7 +2,7 @@
#[utoipa::path(
post,
path = "/payouts/create",
- request_body=PayoutCreateRequest,
+ request_body=PayoutsCreateRequest,
responses(
(status = 200, description = "Payout created", body = PayoutCreateResponse),
(status = 400, description = "Missing Mandatory fields")
@@ -18,7 +18,8 @@ pub async fn payouts_create() {}
get,
path = "/payouts/{payout_id}",
params(
- ("payout_id" = String, Path, description = "The identifier for payout]")
+ ("payout_id" = String, Path, description = "The identifier for payout"),
+ ("force_sync" = Option<bool>, Query, description = "Sync with the connector to get the payout details (defaults to false)")
),
responses(
(status = 200, description = "Payout retrieved", body = PayoutCreateResponse),
@@ -35,9 +36,9 @@ pub async fn payouts_retrieve() {}
post,
path = "/payouts/{payout_id}",
params(
- ("payout_id" = String, Path, description = "The identifier for payout]")
+ ("payout_id" = String, Path, description = "The identifier for payout")
),
- request_body=PayoutCreateRequest,
+ request_body=PayoutUpdateRequest,
responses(
(status = 200, description = "Payout updated", body = PayoutCreateResponse),
(status = 400, description = "Missing Mandatory fields")
@@ -55,7 +56,7 @@ pub async fn payouts_update() {}
params(
("payout_id" = String, Path, description = "The identifier for payout")
),
- request_body=PayoutActionRequest,
+ request_body=PayoutCancelRequest,
responses(
(status = 200, description = "Payout cancelled", body = PayoutCreateResponse),
(status = 400, description = "Missing Mandatory fields")
@@ -73,7 +74,7 @@ pub async fn payouts_cancel() {}
params(
("payout_id" = String, Path, description = "The identifier for payout")
),
- request_body=PayoutActionRequest,
+ request_body=PayoutFulfillRequest,
responses(
(status = 200, description = "Payout fulfilled", body = PayoutCreateResponse),
(status = 400, description = "Missing Mandatory fields")
@@ -88,38 +89,61 @@ pub async fn payouts_fulfill() {}
#[utoipa::path(
get,
path = "/payouts/list",
+ params(
+ ("customer_id" = String, Query, description = "The identifier for customer"),
+ ("starting_after" = String, Query, description = "A cursor for use in pagination, fetch the next list after some object"),
+ ("ending_before" = String, Query, description = "A cursor for use in pagination, fetch the previous list before some object"),
+ ("limit" = String, Query, description = "limit on the number of objects to return"),
+ ("created" = String, Query, description = "The time at which payout is created"),
+ ("time_range" = String, Query, description = "The time range for which objects are needed. TimeRange has two fields start_time and end_time from which objects can be filtered as per required scenarios (created_at, time less than, greater than etc).")
+ ),
responses(
(status = 200, description = "Payouts listed", body = PayoutListResponse),
(status = 404, description = "Payout not found")
),
tag = "Payouts",
- operation_id = "List payouts",
+ operation_id = "List payouts using generic constraints",
security(("api_key" = []))
)]
pub async fn payouts_list() {}
-/// Payouts - Filter
+/// Payouts - List available filters
+#[utoipa::path(
+ post,
+ path = "/payouts/filter",
+ request_body=TimeRange,
+ responses(
+ (status = 200, description = "Filters listed", body = PayoutListFilters)
+ ),
+ tag = "Payouts",
+ operation_id = "List available payout filters",
+ security(("api_key" = []))
+)]
+pub async fn payouts_list_filters() {}
+
+/// Payouts - List using filters
#[utoipa::path(
post,
path = "/payouts/list",
+ request_body=PayoutListFilterConstraints,
responses(
(status = 200, description = "Payouts filtered", body = PayoutListResponse),
(status = 404, description = "Payout not found")
),
tag = "Payouts",
- operation_id = "Filter payouts",
+ operation_id = "Filter payouts using specific constraints",
security(("api_key" = []))
)]
-pub async fn payouts_filter() {}
+pub async fn payouts_list_by_filter() {}
/// Payouts - Confirm
#[utoipa::path(
post,
path = "/payouts/{payout_id}/confirm",
params(
- ("payout_id" = String, Path, description = "The identifier for payout]")
+ ("payout_id" = String, Path, description = "The identifier for payout")
),
- request_body=PayoutCreateRequest,
+ request_body=PayoutConfirmRequest,
responses(
(status = 200, description = "Payout updated", body = PayoutCreateResponse),
(status = 400, description = "Missing Mandatory fields")
diff --git a/crates/router/src/compatibility/stripe/webhooks.rs b/crates/router/src/compatibility/stripe/webhooks.rs
index 4b08b0d36e8..998702b5de1 100644
--- a/crates/router/src/compatibility/stripe/webhooks.rs
+++ b/crates/router/src/compatibility/stripe/webhooks.rs
@@ -5,10 +5,7 @@ use api_models::{
webhooks::{self as api},
};
#[cfg(feature = "payouts")]
-use common_utils::{
- crypto::Encryptable,
- pii::{self, Email},
-};
+use common_utils::pii::{self, Email};
use common_utils::{crypto::SignMessage, date_time, ext_traits::Encode};
use error_stack::ResultExt;
use router_env::logger;
@@ -167,16 +164,25 @@ impl From<common_enums::PayoutStatus> for StripePayoutStatus {
#[cfg(feature = "payouts")]
impl From<payout_models::PayoutCreateResponse> for StripePayoutResponse {
fn from(res: payout_models::PayoutCreateResponse) -> Self {
+ let (name, email, phone, phone_country_code) = match res.customer {
+ Some(customer) => (
+ customer.name,
+ customer.email,
+ customer.phone,
+ customer.phone_country_code,
+ ),
+ None => (None, None, None, None),
+ };
Self {
id: res.payout_id,
amount: res.amount.get_amount_as_i64(),
currency: res.currency.to_string(),
payout_type: res.payout_type,
status: StripePayoutStatus::from(res.status),
- name: res.name.map(Encryptable::into_inner),
- email: res.email.map(|inner| inner.into()),
- phone: res.phone.map(Encryptable::into_inner),
- phone_country_code: res.phone_country_code,
+ name,
+ email,
+ phone,
+ phone_country_code,
created: res.created.map(|t| t.assume_utc().unix_timestamp()),
metadata: res.metadata,
entity_type: res.entity_type,
diff --git a/crates/router/src/core/payments/transformers.rs b/crates/router/src/core/payments/transformers.rs
index 298106cfc76..9182bf93606 100644
--- a/crates/router/src/core/payments/transformers.rs
+++ b/crates/router/src/core/payments/transformers.rs
@@ -1,16 +1,14 @@
use std::{fmt::Debug, marker::PhantomData, str::FromStr};
use api_models::payments::{
- Address, CustomerDetailsResponse, FrmMessage, PaymentChargeRequest, PaymentChargeResponse,
- RequestSurchargeDetails,
+ Address, CustomerDetails, CustomerDetailsResponse, FrmMessage, PaymentChargeRequest,
+ PaymentChargeResponse, RequestSurchargeDetails,
};
-#[cfg(feature = "payouts")]
-use api_models::payouts::PayoutAttemptResponse;
use common_enums::RequestIncrementalAuthorization;
use common_utils::{consts::X_HS_LATENCY, fp_utils, pii::Email, types::MinorUnit};
use diesel_models::ephemeral_key;
use error_stack::{report, ResultExt};
-use hyperswitch_domain_models::payments::payment_intent::CustomerData;
+use hyperswitch_domain_models::{payments::payment_intent::CustomerData, router_request_types};
use masking::{ExposeInterface, Maskable, PeekInterface, Secret};
use router_env::{instrument, metrics::add_attributes, tracing};
@@ -1094,62 +1092,6 @@ impl ForeignFrom<(storage::PaymentIntent, storage::PaymentAttempt)> for api::Pay
}
}
-#[cfg(feature = "payouts")]
-impl ForeignFrom<(storage::Payouts, storage::PayoutAttempt, domain::Customer)>
- for api::PayoutCreateResponse
-{
- fn foreign_from(item: (storage::Payouts, storage::PayoutAttempt, domain::Customer)) -> Self {
- let (payout, payout_attempt, customer) = item;
- let attempt = PayoutAttemptResponse {
- attempt_id: payout_attempt.payout_attempt_id,
- status: payout_attempt.status,
- amount: payout.amount,
- currency: Some(payout.destination_currency),
- connector: payout_attempt.connector.clone(),
- error_code: payout_attempt.error_code.clone(),
- error_message: payout_attempt.error_message.clone(),
- payment_method: payout.payout_type,
- payout_method_type: None,
- connector_transaction_id: payout_attempt.connector_payout_id,
- cancellation_reason: None,
- unified_code: None,
- unified_message: None,
- };
- Self {
- payout_id: payout.payout_id,
- merchant_id: payout.merchant_id,
- amount: payout.amount,
- currency: payout.destination_currency,
- connector: payout_attempt.connector,
- payout_type: payout.payout_type,
- customer_id: customer.get_customer_id(),
- auto_fulfill: payout.auto_fulfill,
- email: customer.email,
- name: customer.name,
- phone: customer.phone,
- phone_country_code: customer.phone_country_code,
- return_url: payout.return_url,
- business_country: payout_attempt.business_country,
- business_label: payout_attempt.business_label,
- description: payout.description,
- entity_type: payout.entity_type,
- recurring: payout.recurring,
- metadata: payout.metadata,
- status: payout_attempt.status,
- error_message: payout_attempt.error_message,
- error_code: payout_attempt.error_code,
- profile_id: payout.profile_id,
- created: Some(payout.created_at),
- connector_transaction_id: attempt.connector_transaction_id.clone(),
- priority: payout.priority,
- attempts: Some(vec![attempt]),
- billing: None,
- client_secret: None,
- payout_link: None,
- }
- }
-}
-
impl ForeignFrom<ephemeral_key::EphemeralKey> for api::ephemeral_key::EphemeralKeyCreateResponse {
fn foreign_from(from: ephemeral_key::EphemeralKey) -> Self {
Self {
@@ -1962,3 +1904,15 @@ impl ForeignFrom<payments::FraudCheck> for FrmMessage {
}
}
}
+
+impl ForeignFrom<CustomerDetails> for router_request_types::CustomerDetails {
+ fn foreign_from(customer: CustomerDetails) -> Self {
+ Self {
+ customer_id: Some(customer.id),
+ name: customer.name,
+ email: customer.email,
+ phone: customer.phone,
+ phone_country_code: customer.phone_country_code,
+ }
+ }
+}
diff --git a/crates/router/src/core/payout_link.rs b/crates/router/src/core/payout_link.rs
index e20f373fd1d..da34a82a854 100644
--- a/crates/router/src/core/payout_link.rs
+++ b/crates/router/src/core/payout_link.rs
@@ -6,7 +6,7 @@ use std::{
use actix_web::http::header;
use api_models::payouts;
use common_utils::{
- ext_traits::{Encode, OptionExt},
+ ext_traits::{AsyncExt, Encode, OptionExt},
link_utils,
types::{AmountConvertor, StringMajorUnitForConnector},
};
@@ -284,14 +284,20 @@ pub async fn filter_payout_methods(
Some(&payout.profile_id),
common_enums::ConnectorType::PayoutProcessor,
);
- let address = db
- .find_address_by_address_id(key_manager_state, &payout.address_id.clone(), key_store)
+ let address = payout
+ .address_id
+ .as_ref()
+ .async_map(|address_id| async {
+ db.find_address_by_address_id(key_manager_state, address_id, key_store)
+ .await
+ })
.await
+ .transpose()
.change_context(errors::ApiErrorResponse::InternalServerError)
.attach_printable_lazy(|| {
format!(
- "Failed while fetching address with address id {}",
- payout.address_id.clone()
+ "Failed while fetching address [id - {:?}] for payout [id - {}]",
+ payout.address_id, payout.payout_id
)
})?;
@@ -326,7 +332,10 @@ pub async fn filter_payout_methods(
payout_filter,
request_payout_method_type,
&payout.destination_currency,
- &address.country,
+ address
+ .as_ref()
+ .and_then(|address| address.country)
+ .as_ref(),
)?;
if currency_country_filter.unwrap_or(true) {
match payment_method {
@@ -381,7 +390,7 @@ pub fn check_currency_country_filters(
payout_method_filter: Option<&PaymentMethodFilters>,
request_payout_method_type: &api_models::payment_methods::RequestPaymentMethodTypes,
currency: &common_enums::Currency,
- country: &Option<common_enums::CountryAlpha2>,
+ country: Option<&common_enums::CountryAlpha2>,
) -> errors::RouterResult<Option<bool>> {
if matches!(
request_payout_method_type.payment_method_type,
diff --git a/crates/router/src/core/payouts.rs b/crates/router/src/core/payouts.rs
index b0819f4a5f8..2debb492ada 100644
--- a/crates/router/src/core/payouts.rs
+++ b/crates/router/src/core/payouts.rs
@@ -2,6 +2,7 @@ pub mod access_token;
pub mod helpers;
#[cfg(feature = "payout_retry")]
pub mod retry;
+pub mod transformers;
pub mod validator;
use std::vec::IntoIter;
@@ -24,8 +25,6 @@ use diesel_models::{
use error_stack::{report, ResultExt};
#[cfg(feature = "olap")]
use futures::future::join_all;
-#[cfg(feature = "olap")]
-use hyperswitch_domain_models::errors::StorageError;
use masking::{PeekInterface, Secret};
#[cfg(feature = "payout_retry")]
use retry::GsmValidation;
@@ -49,7 +48,7 @@ use crate::{
services,
types::{
self,
- api::{self, payouts},
+ api::{self, payments as payment_api_types, payouts},
domain,
storage::{self, PaymentRoutingInfo},
transformers::ForeignFrom,
@@ -90,7 +89,7 @@ pub async fn get_connector_choice(
connector: Option<String>,
routing_algorithm: Option<serde_json::Value>,
payout_data: &mut PayoutData,
- eligible_connectors: Option<Vec<api_models::enums::PayoutConnectors>>,
+ eligible_connectors: Option<Vec<api_enums::PayoutConnectors>>,
) -> RouterResult<api::ConnectorCallType> {
let eligible_routable_connectors = eligible_connectors.map(|connectors| {
connectors
@@ -255,7 +254,9 @@ pub async fn make_connector_decision(
Ok(())
}
- _ => Err(errors::ApiErrorResponse::InternalServerError)?,
+ _ => Err(errors::ApiErrorResponse::InternalServerError).attach_printable({
+ "only PreDetermined and Retryable ConnectorCallTypes are supported".to_string()
+ })?,
}
}
@@ -266,7 +267,7 @@ pub async fn payouts_core(
key_store: &domain::MerchantKeyStore,
payout_data: &mut PayoutData,
routing_algorithm: Option<serde_json::Value>,
- eligible_connectors: Option<Vec<api_models::enums::PayoutConnectors>>,
+ eligible_connectors: Option<Vec<api_enums::PayoutConnectors>>,
) -> RouterResult<()> {
let payout_attempt = &payout_data.payout_attempt;
@@ -301,7 +302,7 @@ pub async fn payouts_create_core(
req: payouts::PayoutCreateRequest,
) -> RouterResponse<payouts::PayoutCreateResponse> {
// Validate create request
- let (payout_id, payout_method_data, profile_id) =
+ let (payout_id, payout_method_data, profile_id, customer) =
validator::validate_create_request(&state, &merchant_account, &req, &key_store).await?;
// Create DB entries
@@ -313,6 +314,7 @@ pub async fn payouts_create_core(
&payout_id,
&profile_id,
payout_method_data.as_ref(),
+ customer.as_ref(),
)
.await?;
@@ -320,18 +322,25 @@ pub async fn payouts_create_core(
let payout_type = payout_data.payouts.payout_type.to_owned();
// Persist payout method data in temp locker
- payout_data.payout_method_data = helpers::make_payout_method_data(
- &state,
- req.payout_method_data.as_ref(),
- payout_attempt.payout_token.as_deref(),
- &payout_attempt.customer_id,
- &payout_attempt.merchant_id,
- payout_type,
- &key_store,
- Some(&mut payout_data),
- merchant_account.storage_scheme,
- )
- .await?;
+ if req.payout_method_data.is_some() {
+ let customer_id = payout_data
+ .payouts
+ .customer_id
+ .clone()
+ .get_required_value("customer_id when payout_method_data is provided")?;
+ payout_data.payout_method_data = helpers::make_payout_method_data(
+ &state,
+ req.payout_method_data.as_ref(),
+ payout_attempt.payout_token.as_deref(),
+ &customer_id,
+ &payout_attempt.merchant_id,
+ payout_type,
+ &key_store,
+ Some(&mut payout_data),
+ merchant_account.storage_scheme,
+ )
+ .await?;
+ }
if let Some(true) = payout_data.payouts.confirm {
payouts_core(
@@ -380,8 +389,14 @@ pub async fn payouts_confirm_core(
"confirm",
)?;
- helpers::update_payouts_and_payout_attempt(&mut payout_data, &merchant_account, &req, &state)
- .await?;
+ helpers::update_payouts_and_payout_attempt(
+ &mut payout_data,
+ &merchant_account,
+ &req,
+ &state,
+ &key_store,
+ )
+ .await?;
let db = &*state.store;
@@ -441,8 +456,14 @@ pub async fn payouts_update_core(
),
}));
}
- helpers::update_payouts_and_payout_attempt(&mut payout_data, &merchant_account, &req, &state)
- .await?;
+ helpers::update_payouts_and_payout_attempt(
+ &mut payout_data,
+ &merchant_account,
+ &req,
+ &state,
+ &key_store,
+ )
+ .await?;
let payout_attempt = payout_data.payout_attempt.to_owned();
if (req.connector.is_none(), payout_attempt.connector.is_some()) != (true, true) {
@@ -452,18 +473,25 @@ pub async fn payouts_update_core(
};
// Update payout method data in temp locker
- payout_data.payout_method_data = helpers::make_payout_method_data(
- &state,
- req.payout_method_data.as_ref(),
- payout_attempt.payout_token.as_deref(),
- &payout_attempt.customer_id,
- &payout_attempt.merchant_id,
- payout_data.payouts.payout_type,
- &key_store,
- Some(&mut payout_data),
- merchant_account.storage_scheme,
- )
- .await?;
+ if req.payout_method_data.is_some() {
+ let customer_id = payout_data
+ .payouts
+ .customer_id
+ .clone()
+ .get_required_value("customer_id when payout_method_data is provided")?;
+ payout_data.payout_method_data = helpers::make_payout_method_data(
+ &state,
+ req.payout_method_data.as_ref(),
+ payout_attempt.payout_token.as_deref(),
+ &customer_id,
+ &payout_attempt.merchant_id,
+ payout_data.payouts.payout_type,
+ &key_store,
+ Some(&mut payout_data),
+ merchant_account.storage_scheme,
+ )
+ .await?;
+ }
if let Some(true) = payout_data.payouts.confirm {
payouts_core(
@@ -672,12 +700,17 @@ pub async fn payouts_fulfill_core(
};
// Trigger fulfillment
+ let customer_id = payout_data
+ .payouts
+ .customer_id
+ .clone()
+ .get_required_value("customer_id")?;
payout_data.payout_method_data = Some(
helpers::make_payout_method_data(
&state,
None,
payout_attempt.payout_token.as_deref(),
- &payout_attempt.customer_id,
+ &customer_id,
&payout_attempt.merchant_id,
payout_data.payouts.payout_type,
&key_store,
@@ -729,70 +762,77 @@ pub async fn payouts_list_core(
.to_not_found_response(errors::ApiErrorResponse::PayoutNotFound)?;
let payouts = core_utils::filter_objects_based_on_profile_id_list(profile_id_list, payouts);
- let collected_futures = payouts.into_iter().map(|payouts| async {
+ let collected_futures = payouts.into_iter().map(|payout| async {
match db
.find_payout_attempt_by_merchant_id_payout_attempt_id(
merchant_id,
- &utils::get_payment_attempt_id(payouts.payout_id.clone(), payouts.attempt_count),
+ &utils::get_payment_attempt_id(payout.payout_id.clone(), payout.attempt_count),
storage_enums::MerchantStorageScheme::PostgresOnly,
)
.await
{
- Ok(payout_attempt) => {
- match db
- .find_customer_by_customer_id_merchant_id(
- &(&state).into(),
- &payouts.customer_id,
- merchant_id,
- &key_store,
- merchant_account.storage_scheme,
- )
- .await
- {
- Ok(customer) => Some(Ok((payouts, payout_attempt, customer))),
- Err(error) => {
- if matches!(
- error.current_context(),
- storage_impl::errors::StorageError::ValueNotFound(_)
- ) {
- logger::warn!(
- ?error,
- "customer missing for customer_id : {:?}",
- payouts.customer_id,
+ Ok(ref payout_attempt) => match payout.customer_id.clone() {
+ Some(ref customer_id) => {
+ match db
+ .find_customer_by_customer_id_merchant_id(
+ &(&state).into(),
+ customer_id,
+ merchant_id,
+ &key_store,
+ merchant_account.storage_scheme,
+ )
+ .await
+ {
+ Ok(customer) => Ok((payout, payout_attempt.to_owned(), Some(customer))),
+ Err(err) => {
+ let err_msg = format!(
+ "failed while fetching customer for customer_id - {:?}",
+ customer_id
);
- return None;
+ logger::warn!(?err, err_msg);
+ if err.current_context().is_db_not_found() {
+ Ok((payout, payout_attempt.to_owned(), None))
+ } else {
+ Err(err
+ .change_context(errors::ApiErrorResponse::InternalServerError)
+ .attach_printable(err_msg))
+ }
}
- Some(Err(error.change_context(StorageError::ValueNotFound(
- format!(
- "customer missing for customer_id : {:?}",
- payouts.customer_id
- ),
- ))))
}
}
- }
- Err(error) => {
- if matches!(error.current_context(), StorageError::ValueNotFound(_)) {
- logger::warn!(
- ?error,
- "payout_attempt missing for payout_id : {}",
- payouts.payout_id,
- );
- return None;
- }
- Some(Err(error))
+ None => Ok((payout.to_owned(), payout_attempt.to_owned(), None)),
+ },
+ Err(err) => {
+ let err_msg = format!(
+ "failed while fetching payout_attempt for payout_id - {}",
+ payout.payout_id.clone(),
+ );
+ logger::warn!(?err, err_msg);
+ Err(err
+ .change_context(errors::ApiErrorResponse::InternalServerError)
+ .attach_printable(err_msg))
}
}
});
let pi_pa_tuple_vec: Result<
- Vec<(storage::Payouts, storage::PayoutAttempt, domain::Customer)>,
+ Vec<(
+ storage::Payouts,
+ storage::PayoutAttempt,
+ Option<domain::Customer>,
+ )>,
_,
> = join_all(collected_futures)
.await
.into_iter()
- .flatten()
- .collect::<Result<Vec<(storage::Payouts, storage::PayoutAttempt, domain::Customer)>, _>>();
+ .collect::<Result<
+ Vec<(
+ storage::Payouts,
+ storage::PayoutAttempt,
+ Option<domain::Customer>,
+ )>,
+ _,
+ >>();
let data: Vec<api::PayoutCreateResponse> = pi_pa_tuple_vec
.change_context(errors::ApiErrorResponse::InternalServerError)?
@@ -822,7 +862,7 @@ pub async fn payouts_filtered_list_core(
let list: Vec<(
storage::Payouts,
storage::PayoutAttempt,
- diesel_models::Customer,
+ Option<diesel_models::Customer>,
)> = db
.filter_payouts_and_attempts(
merchant_account.get_id(),
@@ -833,24 +873,23 @@ pub async fn payouts_filtered_list_core(
.to_not_found_response(errors::ApiErrorResponse::PayoutNotFound)?;
let list = core_utils::filter_objects_based_on_profile_id_list(profile_id_list, list);
let data: Vec<api::PayoutCreateResponse> = join_all(list.into_iter().map(|(p, pa, c)| async {
- match domain::Customer::convert_back(
- &(&state).into(),
- c,
- &key_store.key,
- key_store.merchant_id.clone().into(),
- )
- .await
- {
- Ok(domain_cust) => Some((p, pa, domain_cust)),
- Err(err) => {
- logger::warn!(
- ?err,
- "failed to convert customer for id: {:?}",
- p.customer_id
- );
- None
- }
- }
+ let domain_cust = c
+ .async_and_then(|cust| async {
+ domain::Customer::convert_back(
+ &(&state).into(),
+ cust,
+ &key_store.key,
+ key_store.merchant_id.clone().into(),
+ )
+ .await
+ .map_err(|err| {
+ let msg = format!("failed to convert customer for id: {:?}", p.customer_id);
+ logger::warn!(?err, msg);
+ })
+ .ok()
+ })
+ .await;
+ Some((p, pa, domain_cust))
}))
.await
.into_iter()
@@ -936,12 +975,16 @@ pub async fn call_connector_payout(
// Fetch / store payout_method_data
if payout_data.payout_method_data.is_none() || payout_attempt.payout_token.is_none() {
+ let customer_id = payouts
+ .customer_id
+ .clone()
+ .get_required_value("customer_id")?;
payout_data.payout_method_data = Some(
helpers::make_payout_method_data(
state,
payout_data.payout_method_data.to_owned().as_ref(),
payout_attempt.payout_token.as_deref(),
- &payout_attempt.customer_id,
+ &customer_id,
&payout_attempt.merchant_id,
payouts.payout_type,
key_store,
@@ -1975,22 +2018,6 @@ pub async fn fulfill_payout(
.status
.unwrap_or(payout_data.payout_attempt.status.to_owned());
payout_data.payouts.status = status;
- if payout_data.payouts.recurring
- && payout_data.payouts.payout_method_id.clone().is_none()
- && !helpers::is_payout_err_state(status)
- {
- helpers::save_payout_data_to_locker(
- state,
- payout_data,
- &payout_data
- .payout_method_data
- .clone()
- .get_required_value("payout_method_data")?,
- merchant_account,
- key_store,
- )
- .await?;
- }
let updated_payout_attempt = storage::PayoutAttemptUpdate::StatusUpdate {
connector_payout_id: payout_response_data.connector_payout_id,
status,
@@ -2024,6 +2051,31 @@ pub async fn fulfill_payout(
serde_json::json!({"payout_status": status.to_string(), "error_message": payout_data.payout_attempt.error_message.as_ref(), "error_code": payout_data.payout_attempt.error_code.as_ref()})
),
}));
+ } else if payout_data.payouts.recurring
+ && payout_data.payouts.payout_method_id.clone().is_none()
+ {
+ let payout_method_data = payout_data
+ .payout_method_data
+ .clone()
+ .get_required_value("payout_method_data")?;
+ payout_data
+ .payouts
+ .customer_id
+ .clone()
+ .async_map(|customer_id| async move {
+ helpers::save_payout_data_to_locker(
+ state,
+ payout_data,
+ &customer_id,
+ &payout_method_data,
+ merchant_account,
+ key_store,
+ )
+ .await
+ })
+ .await
+ .transpose()
+ .attach_printable("Failed to save payout data to locker")?;
}
}
Err(err) => {
@@ -2072,17 +2124,12 @@ pub async fn response_handler(
let customer_details = payout_data.customer_details.to_owned();
let customer_id = payouts.customer_id;
- let (email, name, phone, phone_country_code) = customer_details
- .map_or((None, None, None, None), |c| {
- (c.email, c.name, c.phone, c.phone_country_code)
- });
-
let address = billing_address.as_ref().map(|a| {
- let phone_details = api_models::payments::PhoneDetails {
+ let phone_details = payment_api_types::PhoneDetails {
number: a.phone_number.to_owned().map(Encryptable::into_inner),
country_code: a.country_code.to_owned(),
};
- let address_details = api_models::payments::AddressDetails {
+ let address_details = payment_api_types::AddressDetails {
city: a.city.to_owned(),
country: a.country.to_owned(),
line1: a.line1.to_owned().map(Encryptable::into_inner),
@@ -2108,12 +2155,17 @@ pub async fn response_handler(
connector: payout_attempt.connector.to_owned(),
payout_type: payouts.payout_type.to_owned(),
billing: address,
- customer_id,
auto_fulfill: payouts.auto_fulfill,
- email,
- name,
- phone,
- phone_country_code,
+ customer_id,
+ email: customer_details.as_ref().and_then(|c| c.email.clone()),
+ name: customer_details.as_ref().and_then(|c| c.name.clone()),
+ phone: customer_details.as_ref().and_then(|c| c.phone.clone()),
+ phone_country_code: customer_details
+ .as_ref()
+ .and_then(|c| c.phone_country_code.clone()),
+ customer: customer_details
+ .as_ref()
+ .map(payment_api_types::CustomerDetailsResponse::foreign_from),
client_secret: payouts.client_secret.to_owned(),
return_url: payouts.return_url.to_owned(),
business_country: payout_attempt.business_country,
@@ -2154,33 +2206,11 @@ pub async fn payout_create_db_entries(
payout_id: &String,
profile_id: &String,
stored_payout_method_data: Option<&payouts::PayoutMethodData>,
+ customer: Option<&domain::Customer>,
) -> RouterResult<PayoutData> {
let db = &*state.store;
let merchant_id = merchant_account.get_id();
-
- // Get or create customer
- let customer_details = payments::CustomerDetails {
- customer_id: req.customer_id.to_owned(),
- name: req.name.to_owned(),
- email: req.email.to_owned(),
- phone: req.phone.to_owned(),
- phone_country_code: req.phone_country_code.to_owned(),
- };
- let customer = helpers::get_or_create_customer_details(
- state,
- &customer_details,
- merchant_account,
- key_store,
- )
- .await?;
- let customer_id = customer
- .to_owned()
- .ok_or_else(|| {
- report!(errors::ApiErrorResponse::MissingRequiredField {
- field_name: "customer_id",
- })
- })?
- .get_customer_id();
+ let customer_id = customer.map(|cust| cust.get_customer_id());
// Validate whether profile_id passed in request is valid and is linked to the merchant
let business_profile =
@@ -2191,8 +2221,10 @@ pub async fn payout_create_db_entries(
create_payout_link(
state,
&business_profile,
- &customer_id,
- merchant_account.get_id(),
+ &customer_id
+ .clone()
+ .get_required_value("customer.id when payout_link is true")?,
+ merchant_id,
req,
payout_id,
)
@@ -2207,20 +2239,13 @@ pub async fn payout_create_db_entries(
req.billing.as_ref(),
None,
merchant_id,
- Some(&customer_id.to_owned()),
+ customer_id.as_ref(),
key_store,
payout_id,
merchant_account.storage_scheme,
)
.await?;
- let address_id = billing_address
- .to_owned()
- .ok_or_else(|| {
- report!(errors::ApiErrorResponse::MissingRequiredField {
- field_name: "billing.address",
- })
- })?
- .address_id;
+ let address_id = billing_address.to_owned().map(|address| address.address_id);
// Make payouts entry
let currency = req.currency.to_owned().get_required_value("currency")?;
@@ -2251,7 +2276,7 @@ pub async fn payout_create_db_entries(
let payouts_req = storage::PayoutsNew {
payout_id: payout_id.to_string(),
merchant_id: merchant_id.to_owned(),
- customer_id: customer_id.to_owned(),
+ customer_id,
address_id: address_id.to_owned(),
payout_type,
amount,
@@ -2288,9 +2313,7 @@ pub async fn payout_create_db_entries(
let payout_attempt_req = storage::PayoutAttemptNew {
payout_attempt_id: payout_attempt_id.to_string(),
payout_id: payout_id.to_owned(),
- customer_id: customer_id.to_owned(),
merchant_id: merchant_id.to_owned(),
- address_id: address_id.to_owned(),
status,
business_country: req.business_country.to_owned(),
business_label: req.business_label.to_owned(),
@@ -2314,7 +2337,7 @@ pub async fn payout_create_db_entries(
Ok(PayoutData {
billing_address,
business_profile,
- customer_details: customer,
+ customer_details: customer.map(ToOwned::to_owned),
merchant_connector_account: None,
payouts,
payout_attempt,
@@ -2365,28 +2388,41 @@ pub async fn make_payout_data(
.await
.to_not_found_response(errors::ApiErrorResponse::PayoutNotFound)?;
+ let customer_id = payouts.customer_id.as_ref();
+ let payout_id = &payouts.payout_id;
let billing_address = payment_helpers::create_or_find_address_for_payment_by_request(
state,
None,
- Some(&payouts.address_id.to_owned()),
+ payouts.address_id.as_deref(),
merchant_id,
- Some(&payouts.customer_id.to_owned()),
+ customer_id,
key_store,
- &payouts.payout_id,
+ payout_id,
merchant_account.storage_scheme,
)
.await?;
- let customer_details = db
- .find_customer_optional_by_customer_id_merchant_id(
- &state.into(),
- &payouts.customer_id.to_owned(),
- merchant_id,
- key_store,
- merchant_account.storage_scheme,
- )
+ let customer_details = customer_id
+ .async_map(|customer_id| async move {
+ db.find_customer_optional_by_customer_id_merchant_id(
+ &state.into(),
+ customer_id,
+ merchant_id,
+ key_store,
+ merchant_account.storage_scheme,
+ )
+ .await
+ .map_err(|err| err.change_context(errors::ApiErrorResponse::InternalServerError))
+ .attach_printable_lazy(|| {
+ format!(
+ "Failed while fetching optional customer [id - {:?}] for payout [id - {}]",
+ customer_id, payout_id
+ )
+ })
+ })
.await
- .map_or(None, |c| c);
+ .transpose()?
+ .and_then(|c| c);
let profile_id = payout_attempt.profile_id.clone();
@@ -2401,7 +2437,7 @@ pub async fn make_payout_data(
let customer_id = customer_details
.as_ref()
.map(|cd| cd.get_customer_id().to_owned())
- .get_required_value("customer")?;
+ .get_required_value("customer_id when payout_token is sent")?;
helpers::make_payout_method_data(
state,
None,
diff --git a/crates/router/src/core/payouts/helpers.rs b/crates/router/src/core/payouts/helpers.rs
index b17ea437560..4714992799a 100644
--- a/crates/router/src/core/payouts/helpers.rs
+++ b/crates/router/src/core/payouts/helpers.rs
@@ -20,6 +20,7 @@ use router_env::logger;
use super::PayoutData;
use crate::{
+ consts,
core::{
errors::{self, RouterResult, StorageErrorExt},
payment_methods::{
@@ -28,8 +29,8 @@ use crate::{
vault,
},
payments::{
- customers::get_connector_customer_details_if_present, route_connector_v1, routing,
- CustomerDetails,
+ customers::get_connector_customer_details_if_present, helpers as payment_helpers,
+ route_connector_v1, routing, CustomerDetails,
},
routing::TransactionData,
},
@@ -194,11 +195,12 @@ pub async fn make_payout_method_data<'a>(
pub async fn save_payout_data_to_locker(
state: &SessionState,
payout_data: &mut PayoutData,
+ customer_id: &id_type::CustomerId,
payout_method_data: &api::PayoutMethodData,
merchant_account: &domain::MerchantAccount,
key_store: &domain::MerchantKeyStore,
) -> RouterResult<()> {
- let payout_attempt = &payout_data.payout_attempt;
+ let payouts = &payout_data.payouts;
let (mut locker_req, card_details, bank_details, wallet_details, payment_method_type) =
match payout_method_data {
payouts::PayoutMethodData::Card(card) => {
@@ -215,7 +217,7 @@ pub async fn save_payout_data_to_locker(
};
let payload = StoreLockerReq::LockerCard(StoreCardReq {
merchant_id: merchant_account.get_id().clone(),
- merchant_customer_id: payout_attempt.customer_id.to_owned(),
+ merchant_customer_id: customer_id.to_owned(),
card: Card {
card_number: card.card_number.to_owned(),
name_on_card: card.card_holder_name.to_owned(),
@@ -271,7 +273,7 @@ pub async fn save_payout_data_to_locker(
})?;
let payload = StoreLockerReq::LockerGeneric(StoreGenericReq {
merchant_id: merchant_account.get_id().to_owned(),
- merchant_customer_id: payout_attempt.customer_id.to_owned(),
+ merchant_customer_id: customer_id.to_owned(),
enc_data,
ttl: state.conf.locker.ttl_for_storage_in_secs,
});
@@ -301,7 +303,7 @@ pub async fn save_payout_data_to_locker(
let stored_resp = cards::call_to_locker_hs(
state,
&locker_req,
- &payout_attempt.customer_id,
+ customer_id,
api_enums::LockerChoice::HyperswitchCardVault,
)
.await
@@ -403,7 +405,7 @@ pub async fn save_payout_data_to_locker(
card: card_details.clone(),
wallet: None,
metadata: None,
- customer_id: Some(payout_attempt.customer_id.to_owned()),
+ customer_id: Some(customer_id.to_owned()),
card_network: None,
client_secret: None,
payment_method_data: None,
@@ -490,7 +492,7 @@ pub async fn save_payout_data_to_locker(
card: None,
wallet: wallet_details,
metadata: None,
- customer_id: Some(payout_attempt.customer_id.to_owned()),
+ customer_id: Some(customer_id.to_owned()),
card_network: None,
client_secret: None,
payment_method_data: None,
@@ -503,11 +505,11 @@ pub async fn save_payout_data_to_locker(
// Insert new entry in payment_methods table
if should_insert_in_pm_table {
- let payment_method_id = common_utils::generate_id(crate::consts::ID_LENGTH, "pm");
+ let payment_method_id = common_utils::generate_id(consts::ID_LENGTH, "pm");
cards::create_payment_method(
state,
&new_payment_method,
- &payout_attempt.customer_id,
+ customer_id,
&payment_method_id,
Some(stored_resp.card_reference.clone()),
merchant_account.get_id(),
@@ -538,7 +540,7 @@ pub async fn save_payout_data_to_locker(
// Delete from locker
cards::delete_card_from_hs_locker(
state,
- &payout_attempt.customer_id,
+ customer_id,
merchant_account.get_id(),
card_reference,
)
@@ -553,7 +555,7 @@ pub async fn save_payout_data_to_locker(
let stored_resp = cards::call_to_locker_hs(
state,
&locker_req,
- &payout_attempt.customer_id,
+ customer_id,
api_enums::LockerChoice::HyperswitchCardVault,
)
.await
@@ -590,9 +592,9 @@ pub async fn save_payout_data_to_locker(
};
payout_data.payouts = db
.update_payout(
- &payout_data.payouts,
+ payouts,
updated_payout,
- payout_attempt,
+ &payout_data.payout_attempt,
merchant_account.storage_scheme,
)
.await
@@ -603,7 +605,7 @@ pub async fn save_payout_data_to_locker(
}
#[cfg(all(feature = "v2", feature = "customer_v2"))]
-pub async fn get_or_create_customer_details(
+pub(super) async fn get_or_create_customer_details(
_state: &SessionState,
_customer_details: &CustomerDetails,
_merchant_account: &domain::MerchantAccount,
@@ -613,7 +615,7 @@ pub async fn get_or_create_customer_details(
}
#[cfg(all(any(feature = "v1", feature = "v2"), not(feature = "customer_v2")))]
-pub async fn get_or_create_customer_details(
+pub(super) async fn get_or_create_customer_details(
state: &SessionState,
customer_details: &CustomerDetails,
merchant_account: &domain::MerchantAccount,
@@ -641,56 +643,78 @@ pub async fn get_or_create_customer_details(
.await
.change_context(errors::ApiErrorResponse::InternalServerError)?
{
+ // Customer found
Some(customer) => Ok(Some(customer)),
- None => {
- let encrypted_data = crypto_operation(
- &state.into(),
- type_name!(domain::Customer),
- CryptoOperation::BatchEncrypt(CustomerRequestWithEmail::to_encryptable(
- CustomerRequestWithEmail {
- name: customer_details.name.clone(),
- email: customer_details.email.clone(),
- phone: customer_details.phone.clone(),
- },
- )),
- Identifier::Merchant(key_store.merchant_id.clone()),
- key,
- )
- .await
- .and_then(|val| val.try_into_batchoperation())
- .change_context(errors::ApiErrorResponse::InternalServerError)?;
- let encryptable_customer =
- CustomerRequestWithEmail::from_encryptable(encrypted_data)
- .change_context(errors::ApiErrorResponse::InternalServerError)?;
-
- let customer = domain::Customer {
- customer_id,
- merchant_id: merchant_id.to_owned().clone(),
- name: encryptable_customer.name,
- email: encryptable_customer.email,
- phone: encryptable_customer.phone,
- description: None,
- phone_country_code: customer_details.phone_country_code.to_owned(),
- metadata: None,
- connector_customer: None,
- created_at: common_utils::date_time::now(),
- modified_at: common_utils::date_time::now(),
- address_id: None,
- default_payment_method_id: None,
- updated_by: None,
- version: common_enums::ApiVersion::V1,
- };
- Ok(Some(
- db.insert_customer(
- customer,
- key_manager_state,
- key_store,
- merchant_account.storage_scheme,
+ // Customer not found
+ // create only if atleast one of the fields were provided for customer creation or else throw error
+ None => {
+ if customer_details.name.is_some()
+ || customer_details.email.is_some()
+ || customer_details.phone.is_some()
+ || customer_details.phone_country_code.is_some()
+ {
+ let encrypted_data = crypto_operation(
+ &state.into(),
+ type_name!(domain::Customer),
+ CryptoOperation::BatchEncrypt(CustomerRequestWithEmail::to_encryptable(
+ CustomerRequestWithEmail {
+ name: customer_details.name.clone(),
+ email: customer_details.email.clone(),
+ phone: customer_details.phone.clone(),
+ },
+ )),
+ Identifier::Merchant(key_store.merchant_id.clone()),
+ key,
)
.await
- .change_context(errors::ApiErrorResponse::InternalServerError)?,
- ))
+ .and_then(|val| val.try_into_batchoperation())
+ .change_context(errors::ApiErrorResponse::InternalServerError)
+ .attach_printable("Failed to encrypt customer")?;
+ let encryptable_customer =
+ CustomerRequestWithEmail::from_encryptable(encrypted_data)
+ .change_context(errors::ApiErrorResponse::InternalServerError)
+ .attach_printable("Failed to form EncryptableCustomer")?;
+
+ let customer = domain::Customer {
+ customer_id: customer_id.clone(),
+ merchant_id: merchant_id.to_owned().clone(),
+ name: encryptable_customer.name,
+ email: encryptable_customer.email,
+ phone: encryptable_customer.phone,
+ description: None,
+ phone_country_code: customer_details.phone_country_code.to_owned(),
+ metadata: None,
+ connector_customer: None,
+ created_at: common_utils::date_time::now(),
+ modified_at: common_utils::date_time::now(),
+ address_id: None,
+ default_payment_method_id: None,
+ updated_by: None,
+ version: consts::API_VERSION,
+ };
+
+ Ok(Some(
+ db.insert_customer(
+ customer,
+ key_manager_state,
+ key_store,
+ merchant_account.storage_scheme,
+ )
+ .await
+ .change_context(errors::ApiErrorResponse::InternalServerError)
+ .attach_printable_lazy(|| {
+ format!(
+ "Failed to insert customer [id - {:?}] for merchant [id - {:?}]",
+ customer_id, merchant_id
+ )
+ })?,
+ ))
+ } else {
+ Err(report!(errors::ApiErrorResponse::InvalidRequestData {
+ message: format!("customer for id - {:?} not found", customer_id),
+ }))
+ }
}
}
}
@@ -997,6 +1021,7 @@ pub async fn update_payouts_and_payout_attempt(
merchant_account: &domain::MerchantAccount,
req: &payouts::PayoutCreateRequest,
state: &SessionState,
+ merchant_key_store: &domain::MerchantKeyStore,
) -> CustomResult<(), errors::ApiErrorResponse> {
let payout_attempt = payout_data.payout_attempt.to_owned();
let status = payout_attempt.status;
@@ -1011,6 +1036,47 @@ pub async fn update_payouts_and_payout_attempt(
}));
}
+ // Fetch customer details from request and create new or else use existing customer that was attached
+ let customer = get_customer_details_from_request(req);
+ let customer_id = if customer.customer_id.is_some()
+ || customer.name.is_some()
+ || customer.email.is_some()
+ || customer.phone.is_some()
+ || customer.phone_country_code.is_some()
+ {
+ payout_data.customer_details =
+ get_or_create_customer_details(state, &customer, merchant_account, merchant_key_store)
+ .await?;
+ payout_data
+ .customer_details
+ .as_ref()
+ .map(|customer| customer.get_customer_id())
+ } else {
+ payout_data.payouts.customer_id.clone()
+ };
+
+ // Fetch address details from request and create new or else use existing address that was attached
+ let billing_address = payment_helpers::create_or_find_address_for_payment_by_request(
+ state,
+ req.billing.as_ref(),
+ None,
+ merchant_account.get_id(),
+ customer_id.as_ref(),
+ merchant_key_store,
+ &payout_id,
+ merchant_account.storage_scheme,
+ )
+ .await?;
+ let address_id = if billing_address.is_some() {
+ payout_data.billing_address = billing_address;
+ payout_data
+ .billing_address
+ .as_ref()
+ .map(|address| address.address_id.clone())
+ } else {
+ payout_data.payouts.address_id.clone()
+ };
+
// Update DB with new data
let payouts = payout_data.payouts.to_owned();
let amount = MinorUnit::from(req.amount.unwrap_or(payouts.amount.into()));
@@ -1042,6 +1108,8 @@ pub async fn update_payouts_and_payout_attempt(
.payout_type
.to_owned()
.or(payouts.payout_type.to_owned()),
+ address_id: address_id.clone(),
+ customer_id: customer_id.clone(),
};
let db = &*state.store;
payout_data.payouts = db
@@ -1070,25 +1138,66 @@ pub async fn update_payouts_and_payout_attempt(
.to_owned()
.and_then(|nl| if nl != l { Some(nl) } else { None })
});
- match (updated_business_country, updated_business_label) {
- (None, None) => Ok(()),
- (business_country, business_label) => {
- let payout_attempt = &payout_data.payout_attempt;
- let updated_payout_attempt = storage::PayoutAttemptUpdate::BusinessUpdate {
- business_country,
- business_label,
- };
- payout_data.payout_attempt = db
- .update_payout_attempt(
- payout_attempt,
- updated_payout_attempt,
- &payout_data.payouts,
- merchant_account.storage_scheme,
- )
- .await
- .change_context(errors::ApiErrorResponse::InternalServerError)
- .attach_printable("Error updating payout_attempt")?;
- Ok(())
- }
+ if updated_business_country.is_some()
+ || updated_business_label.is_some()
+ || customer_id.is_some()
+ || address_id.is_some()
+ {
+ let payout_attempt = &payout_data.payout_attempt;
+ let updated_payout_attempt = storage::PayoutAttemptUpdate::BusinessUpdate {
+ business_country: updated_business_country,
+ business_label: updated_business_label,
+ address_id,
+ customer_id,
+ };
+ payout_data.payout_attempt = db
+ .update_payout_attempt(
+ payout_attempt,
+ updated_payout_attempt,
+ &payout_data.payouts,
+ merchant_account.storage_scheme,
+ )
+ .await
+ .change_context(errors::ApiErrorResponse::InternalServerError)
+ .attach_printable("Error updating payout_attempt")?;
+ }
+ Ok(())
+}
+
+pub(super) fn get_customer_details_from_request(
+ request: &payouts::PayoutCreateRequest,
+) -> CustomerDetails {
+ let customer_id = request.get_customer_id().map(ToOwned::to_owned);
+
+ let customer_name = request
+ .customer
+ .as_ref()
+ .and_then(|customer_details| customer_details.name.clone())
+ .or(request.name.clone());
+
+ let customer_email = request
+ .customer
+ .as_ref()
+ .and_then(|customer_details| customer_details.email.clone())
+ .or(request.email.clone());
+
+ let customer_phone = request
+ .customer
+ .as_ref()
+ .and_then(|customer_details| customer_details.phone.clone())
+ .or(request.phone.clone());
+
+ let customer_phone_code = request
+ .customer
+ .as_ref()
+ .and_then(|customer_details| customer_details.phone_country_code.clone())
+ .or(request.phone_country_code.clone());
+
+ CustomerDetails {
+ customer_id,
+ name: customer_name,
+ email: customer_email,
+ phone: customer_phone,
+ phone_country_code: customer_phone_code,
}
}
diff --git a/crates/router/src/core/payouts/transformers.rs b/crates/router/src/core/payouts/transformers.rs
new file mode 100644
index 00000000000..d8df7271b71
--- /dev/null
+++ b/crates/router/src/core/payouts/transformers.rs
@@ -0,0 +1,76 @@
+use crate::types::{
+ api, domain, storage,
+ transformers::{ForeignFrom, ForeignInto},
+};
+
+impl
+ ForeignFrom<(
+ storage::Payouts,
+ storage::PayoutAttempt,
+ Option<domain::Customer>,
+ )> for api::PayoutCreateResponse
+{
+ fn foreign_from(
+ item: (
+ storage::Payouts,
+ storage::PayoutAttempt,
+ Option<domain::Customer>,
+ ),
+ ) -> Self {
+ let (payout, payout_attempt, customer) = item;
+ let attempt = api::PayoutAttemptResponse {
+ attempt_id: payout_attempt.payout_attempt_id,
+ status: payout_attempt.status,
+ amount: payout.amount,
+ currency: Some(payout.destination_currency),
+ connector: payout_attempt.connector.clone(),
+ error_code: payout_attempt.error_code.clone(),
+ error_message: payout_attempt.error_message.clone(),
+ payment_method: payout.payout_type,
+ payout_method_type: None,
+ connector_transaction_id: payout_attempt.connector_payout_id,
+ cancellation_reason: None,
+ unified_code: None,
+ unified_message: None,
+ };
+ Self {
+ payout_id: payout.payout_id,
+ merchant_id: payout.merchant_id,
+ amount: payout.amount,
+ currency: payout.destination_currency,
+ connector: payout_attempt.connector,
+ payout_type: payout.payout_type,
+ auto_fulfill: payout.auto_fulfill,
+ customer_id: customer.as_ref().map(|cust| cust.get_customer_id()),
+ customer: customer.as_ref().map(|cust| cust.foreign_into()),
+ return_url: payout.return_url,
+ business_country: payout_attempt.business_country,
+ business_label: payout_attempt.business_label,
+ description: payout.description,
+ entity_type: payout.entity_type,
+ recurring: payout.recurring,
+ metadata: payout.metadata,
+ status: payout_attempt.status,
+ error_message: payout_attempt.error_message,
+ error_code: payout_attempt.error_code,
+ profile_id: payout.profile_id,
+ created: Some(payout.created_at),
+ connector_transaction_id: attempt.connector_transaction_id.clone(),
+ priority: payout.priority,
+ attempts: Some(vec![attempt]),
+ billing: None,
+ client_secret: None,
+ payout_link: None,
+ email: customer
+ .as_ref()
+ .and_then(|customer| customer.email.clone()),
+ name: customer.as_ref().and_then(|customer| customer.name.clone()),
+ phone: customer
+ .as_ref()
+ .and_then(|customer| customer.phone.clone()),
+ phone_country_code: customer
+ .as_ref()
+ .and_then(|customer| customer.phone_country_code.clone()),
+ }
+ }
+}
diff --git a/crates/router/src/core/payouts/validator.rs b/crates/router/src/core/payouts/validator.rs
index d8cb20aac05..c73c3907d51 100644
--- a/crates/router/src/core/payouts/validator.rs
+++ b/crates/router/src/core/payouts/validator.rs
@@ -53,12 +53,17 @@ pub async fn validate_create_request(
merchant_account: &domain::MerchantAccount,
req: &payouts::PayoutCreateRequest,
merchant_key_store: &domain::MerchantKeyStore,
-) -> RouterResult<(String, Option<payouts::PayoutMethodData>, String)> {
+) -> RouterResult<(
+ String,
+ Option<payouts::PayoutMethodData>,
+ String,
+ Option<domain::Customer>,
+)> {
let merchant_id = merchant_account.get_id();
if let Some(payout_link) = &req.payout_link {
if *payout_link {
- validate_payout_link_request(req.confirm)?;
+ validate_payout_link_request(req)?;
}
};
@@ -96,28 +101,46 @@ pub async fn validate_create_request(
None => Ok(()),
}?;
- // Payout token
- let payout_method_data = match req.payout_token.to_owned() {
- Some(payout_token) => {
- let customer_id = req
- .customer_id
- .to_owned()
- .unwrap_or_else(common_utils::generate_customer_id_of_default_length);
+ // Fetch customer details (merge of loose fields + customer object) and create DB entry
+ let customer_in_request = helpers::get_customer_details_from_request(req);
+ let customer = if customer_in_request.customer_id.is_some()
+ || customer_in_request.name.is_some()
+ || customer_in_request.email.is_some()
+ || customer_in_request.phone.is_some()
+ || customer_in_request.phone_country_code.is_some()
+ {
+ helpers::get_or_create_customer_details(
+ state,
+ &customer_in_request,
+ merchant_account,
+ merchant_key_store,
+ )
+ .await?
+ } else {
+ None
+ };
+
+ // payout_token
+ let payout_method_data = match (req.payout_token.as_ref(), customer.as_ref()) {
+ (Some(_), None) => Err(report!(errors::ApiErrorResponse::MissingRequiredField {
+ field_name: "customer or customer_id when payout_token is provided"
+ })),
+ (Some(payout_token), Some(customer)) => {
helpers::make_payout_method_data(
state,
req.payout_method_data.as_ref(),
- Some(&payout_token),
- &customer_id,
+ Some(payout_token),
+ &customer.customer_id,
merchant_account.get_id(),
req.payout_type,
merchant_key_store,
None,
merchant_account.storage_scheme,
)
- .await?
+ .await
}
- None => None,
- };
+ _ => Ok(None),
+ }?;
#[cfg(all(
any(feature = "v1", feature = "v2"),
@@ -145,19 +168,24 @@ pub async fn validate_create_request(
})
.attach_printable("Profile id is a mandatory parameter")?;
- Ok((payout_id, payout_method_data, profile_id))
+ Ok((payout_id, payout_method_data, profile_id, customer))
}
-pub fn validate_payout_link_request(confirm: Option<bool>) -> Result<(), errors::ApiErrorResponse> {
- if let Some(cnf) = confirm {
- if cnf {
- return Err(errors::ApiErrorResponse::InvalidRequestData {
- message: "cannot confirm a payout while creating a payout link".to_string(),
- });
- } else {
- return Ok(());
- }
+pub fn validate_payout_link_request(
+ req: &payouts::PayoutCreateRequest,
+) -> Result<(), errors::ApiErrorResponse> {
+ if req.confirm.unwrap_or(false) {
+ return Err(errors::ApiErrorResponse::InvalidRequestData {
+ message: "cannot confirm a payout while creating a payout link".to_string(),
+ });
}
+
+ if req.customer_id.is_none() {
+ return Err(errors::ApiErrorResponse::MissingRequiredField {
+ field_name: "customer or customer_id when payout_link is true",
+ });
+ }
+
Ok(())
}
diff --git a/crates/router/src/db/kafka_store.rs b/crates/router/src/db/kafka_store.rs
index 9e102e61e16..b997aad1080 100644
--- a/crates/router/src/db/kafka_store.rs
+++ b/crates/router/src/db/kafka_store.rs
@@ -1889,7 +1889,7 @@ impl PayoutsInterface for KafkaStore {
Vec<(
storage::Payouts,
storage::PayoutAttempt,
- diesel_models::Customer,
+ Option<diesel_models::Customer>,
)>,
errors::DataStorageError,
> {
diff --git a/crates/router/src/routes/payouts.rs b/crates/router/src/routes/payouts.rs
index 02e67e66c81..3c3d0f0a16b 100644
--- a/crates/router/src/routes/payouts.rs
+++ b/crates/router/src/routes/payouts.rs
@@ -14,18 +14,6 @@ use crate::{
};
/// Payouts - Create
-#[utoipa::path(
- post,
- path = "/payouts/create",
- request_body=PayoutCreateRequest,
- responses(
- (status = 200, description = "Payout created", body = PayoutCreateResponse),
- (status = 400, description = "Missing Mandatory fields")
- ),
- tag = "Payouts",
- operation_id = "Create a Payout",
- security(("api_key" = []))
-)]
#[instrument(skip_all, fields(flow = ?Flow::PayoutsCreate))]
pub async fn payouts_create(
state: web::Data<AppState>,
@@ -47,20 +35,6 @@ pub async fn payouts_create(
.await
}
/// Payouts - Retrieve
-#[utoipa::path(
- get,
- path = "/payouts/{payout_id}",
- params(
- ("payout_id" = String, Path, description = "The identifier for payout]")
- ),
- responses(
- (status = 200, description = "Payout retrieved", body = PayoutCreateResponse),
- (status = 404, description = "Payout does not exist in our records")
- ),
- tag = "Payouts",
- operation_id = "Retrieve a Payout",
- security(("api_key" = []))
-)]
#[instrument(skip_all, fields(flow = ?Flow::PayoutsRetrieve))]
pub async fn payouts_retrieve(
state: web::Data<AppState>,
@@ -98,21 +72,6 @@ pub async fn payouts_retrieve(
.await
}
/// Payouts - Update
-#[utoipa::path(
- post,
- path = "/payouts/{payout_id}",
- params(
- ("payout_id" = String, Path, description = "The identifier for payout]")
- ),
- request_body=PayoutCreateRequest,
- responses(
- (status = 200, description = "Payout updated", body = PayoutCreateResponse),
- (status = 400, description = "Missing Mandatory fields")
- ),
- tag = "Payouts",
- operation_id = "Update a Payout",
- security(("api_key" = []))
-)]
#[instrument(skip_all, fields(flow = ?Flow::PayoutsUpdate))]
pub async fn payouts_update(
state: web::Data<AppState>,
@@ -170,22 +129,8 @@ pub async fn payouts_confirm(
))
.await
}
+
/// Payouts - Cancel
-#[utoipa::path(
- post,
- path = "/payouts/{payout_id}/cancel",
- params(
- ("payout_id" = String, Path, description = "The identifier for payout")
- ),
- request_body=PayoutActionRequest,
- responses(
- (status = 200, description = "Payout cancelled", body = PayoutCreateResponse),
- (status = 400, description = "Missing Mandatory fields")
- ),
- tag = "Payouts",
- operation_id = "Cancel a Payout",
- security(("api_key" = []))
-)]
#[instrument(skip_all, fields(flow = ?Flow::PayoutsCancel))]
pub async fn payouts_cancel(
state: web::Data<AppState>,
@@ -211,21 +156,6 @@ pub async fn payouts_cancel(
.await
}
/// Payouts - Fulfill
-#[utoipa::path(
- post,
- path = "/payouts/{payout_id}/fulfill",
- params(
- ("payout_id" = String, Path, description = "The identifier for payout")
- ),
- request_body=PayoutActionRequest,
- responses(
- (status = 200, description = "Payout fulfilled", body = PayoutCreateResponse),
- (status = 400, description = "Missing Mandatory fields")
- ),
- tag = "Payouts",
- operation_id = "Fulfill a Payout",
- security(("api_key" = []))
-)]
#[instrument(skip_all, fields(flow = ?Flow::PayoutsFulfill))]
pub async fn payouts_fulfill(
state: web::Data<AppState>,
@@ -253,17 +183,6 @@ pub async fn payouts_fulfill(
/// Payouts - List
#[cfg(feature = "olap")]
-#[utoipa::path(
- get,
- path = "/payouts/list",
- responses(
- (status = 200, description = "Payouts listed", body = PayoutListResponse),
- (status = 404, description = "Payout not found")
- ),
- tag = "Payouts",
- operation_id = "List payouts",
- security(("api_key" = []))
-)]
#[instrument(skip_all, fields(flow = ?Flow::PayoutsList))]
pub async fn payouts_list(
state: web::Data<AppState>,
@@ -293,17 +212,6 @@ pub async fn payouts_list(
/// Payouts - Filtered list
#[cfg(feature = "olap")]
-#[utoipa::path(
- post,
- path = "/payouts/list",
- responses(
- (status = 200, description = "Payouts filtered", body = PayoutListResponse),
- (status = 404, description = "Payout not found")
- ),
- tag = "Payouts",
- operation_id = "Filter payouts",
- security(("api_key" = []))
-)]
#[instrument(skip_all, fields(flow = ?Flow::PayoutsList))]
pub async fn payouts_list_by_filter(
state: web::Data<AppState>,
@@ -333,17 +241,6 @@ pub async fn payouts_list_by_filter(
/// Payouts - Available filters
#[cfg(feature = "olap")]
-#[utoipa::path(
- post,
- path = "/payouts/filter",
- responses(
- (status = 200, description = "Payouts filtered", body = PayoutListFilters),
- (status = 404, description = "Payout not found")
- ),
- tag = "Payouts",
- operation_id = "Filter payouts",
- security(("api_key" = []))
-)]
#[instrument(skip_all, fields(flow = ?Flow::PayoutsFilter))]
pub async fn payouts_list_available_filters(
state: web::Data<AppState>,
diff --git a/crates/router/src/services/kafka/payout.rs b/crates/router/src/services/kafka/payout.rs
index 655639ed913..ca89a34f18d 100644
--- a/crates/router/src/services/kafka/payout.rs
+++ b/crates/router/src/services/kafka/payout.rs
@@ -8,8 +8,8 @@ pub struct KafkaPayout<'a> {
pub payout_id: &'a String,
pub payout_attempt_id: &'a String,
pub merchant_id: &'a id_type::MerchantId,
- pub customer_id: &'a id_type::CustomerId,
- pub address_id: &'a String,
+ pub customer_id: Option<&'a id_type::CustomerId>,
+ pub address_id: Option<&'a String>,
pub profile_id: &'a String,
pub payout_method_id: Option<&'a String>,
pub payout_type: Option<storage_enums::PayoutType>,
@@ -46,8 +46,8 @@ impl<'a> KafkaPayout<'a> {
payout_id: &payouts.payout_id,
payout_attempt_id: &payout_attempt.payout_attempt_id,
merchant_id: &payouts.merchant_id,
- customer_id: &payouts.customer_id,
- address_id: &payouts.address_id,
+ customer_id: payouts.customer_id.as_ref(),
+ address_id: payouts.address_id.as_ref(),
profile_id: &payouts.profile_id,
payout_method_id: payouts.payout_method_id.as_ref(),
payout_type: payouts.payout_type,
diff --git a/crates/router/src/types/api/payments.rs b/crates/router/src/types/api/payments.rs
index 04889e191b1..6b156098d5e 100644
--- a/crates/router/src/types/api/payments.rs
+++ b/crates/router/src/types/api/payments.rs
@@ -1,8 +1,8 @@
pub use api_models::payments::{
AcceptanceType, Address, AddressDetails, Amount, AuthenticationForStartResponse, Card,
- CryptoData, CustomerAcceptance, HeaderPayload, MandateAmountData, MandateData,
- MandateTransactionType, MandateType, MandateValidationFields, NextActionType, OnlineMandate,
- OpenBankingSessionToken, PayLaterData, PaymentIdType, PaymentListConstraints,
+ CryptoData, CustomerAcceptance, CustomerDetailsResponse, HeaderPayload, MandateAmountData,
+ MandateData, MandateTransactionType, MandateType, MandateValidationFields, NextActionType,
+ OnlineMandate, OpenBankingSessionToken, PayLaterData, PaymentIdType, PaymentListConstraints,
PaymentListFilterConstraints, PaymentListFilters, PaymentListFiltersV2, PaymentListResponse,
PaymentListResponseV2, PaymentMethodData, PaymentMethodDataRequest, PaymentMethodDataResponse,
PaymentOp, PaymentRetrieveBody, PaymentRetrieveBodyWithCredentials, PaymentsApproveRequest,
diff --git a/crates/router/src/types/api/payouts.rs b/crates/router/src/types/api/payouts.rs
index 0e89950d69e..84b7d93d68a 100644
--- a/crates/router/src/types/api/payouts.rs
+++ b/crates/router/src/types/api/payouts.rs
@@ -1,8 +1,9 @@
pub use api_models::payouts::{
AchBankTransfer, BacsBankTransfer, Bank as BankPayout, CardPayout, PayoutActionRequest,
- PayoutCreateRequest, PayoutCreateResponse, PayoutListConstraints, PayoutListFilterConstraints,
- PayoutListFilters, PayoutListResponse, PayoutMethodData, PayoutRequest, PayoutRetrieveBody,
- PayoutRetrieveRequest, PixBankTransfer, SepaBankTransfer, Wallet as WalletPayout,
+ PayoutAttemptResponse, PayoutCreateRequest, PayoutCreateResponse, PayoutLinkResponse,
+ PayoutListConstraints, PayoutListFilterConstraints, PayoutListFilters, PayoutListResponse,
+ PayoutMethodData, PayoutRequest, PayoutRetrieveBody, PayoutRetrieveRequest, PixBankTransfer,
+ SepaBankTransfer, Wallet as WalletPayout,
};
pub use hyperswitch_domain_models::router_flow_types::payouts::{
PoCancel, PoCreate, PoEligibility, PoFulfill, PoQuote, PoRecipient, PoRecipientAccount, PoSync,
diff --git a/crates/router/src/types/api/payouts_v2.rs b/crates/router/src/types/api/payouts_v2.rs
index 00a451e772b..8db2b1692b3 100644
--- a/crates/router/src/types/api/payouts_v2.rs
+++ b/crates/router/src/types/api/payouts_v2.rs
@@ -1,8 +1,9 @@
pub use api_models::payouts::{
AchBankTransfer, BacsBankTransfer, Bank as BankPayout, CardPayout, PayoutActionRequest,
- PayoutCreateRequest, PayoutCreateResponse, PayoutListConstraints, PayoutListFilterConstraints,
- PayoutListFilters, PayoutListResponse, PayoutMethodData, PayoutRequest, PayoutRetrieveBody,
- PayoutRetrieveRequest, PixBankTransfer, SepaBankTransfer, Wallet as WalletPayout,
+ PayoutAttemptResponse, PayoutCreateRequest, PayoutCreateResponse, PayoutListConstraints,
+ PayoutListFilterConstraints, PayoutListFilters, PayoutListResponse, PayoutMethodData,
+ PayoutRequest, PayoutRetrieveBody, PayoutRetrieveRequest, PixBankTransfer, SepaBankTransfer,
+ Wallet as WalletPayout,
};
pub use hyperswitch_domain_models::router_flow_types::payouts::{
PoCancel, PoCreate, PoEligibility, PoFulfill, PoQuote, PoRecipient, PoRecipientAccount, PoSync,
diff --git a/crates/storage_impl/src/mock_db/payouts.rs b/crates/storage_impl/src/mock_db/payouts.rs
index 53d34a39a28..835f73c62de 100644
--- a/crates/storage_impl/src/mock_db/payouts.rs
+++ b/crates/storage_impl/src/mock_db/payouts.rs
@@ -69,7 +69,8 @@ impl PayoutsInterface for MockDb {
_merchant_id: &common_utils::id_type::MerchantId,
_filters: &hyperswitch_domain_models::payouts::PayoutFetchConstraints,
_storage_scheme: storage_enums::MerchantStorageScheme,
- ) -> CustomResult<Vec<(Payouts, PayoutAttempt, diesel_models::Customer)>, StorageError> {
+ ) -> CustomResult<Vec<(Payouts, PayoutAttempt, Option<diesel_models::Customer>)>, StorageError>
+ {
// TODO: Implement function for `MockDb`
Err(StorageError::MockDbError)?
}
diff --git a/crates/storage_impl/src/payouts/payout_attempt.rs b/crates/storage_impl/src/payouts/payout_attempt.rs
index b17ba1b6d7f..8d2d62f2d37 100644
--- a/crates/storage_impl/src/payouts/payout_attempt.rs
+++ b/crates/storage_impl/src/payouts/payout_attempt.rs
@@ -619,9 +619,13 @@ impl DataModelExt for PayoutAttemptUpdate {
Self::BusinessUpdate {
business_country,
business_label,
+ address_id,
+ customer_id,
} => DieselPayoutAttemptUpdate::BusinessUpdate {
business_country,
business_label,
+ address_id,
+ customer_id,
},
Self::UpdateRouting {
connector,
diff --git a/crates/storage_impl/src/payouts/payouts.rs b/crates/storage_impl/src/payouts/payouts.rs
index c72965f0106..87433006f22 100644
--- a/crates/storage_impl/src/payouts/payouts.rs
+++ b/crates/storage_impl/src/payouts/payouts.rs
@@ -8,7 +8,7 @@ use common_utils::ext_traits::Encode;
))]
use diesel::JoinOnDsl;
#[cfg(feature = "olap")]
-use diesel::{associations::HasTable, ExpressionMethods, QueryDsl};
+use diesel::{associations::HasTable, ExpressionMethods, NullableExpressionMethods, QueryDsl};
#[cfg(feature = "olap")]
use diesel_models::{
customers::Customer as DieselCustomer, query::generics::db_metrics,
@@ -47,7 +47,13 @@ use router_env::logger;
use router_env::{instrument, tracing};
#[cfg(feature = "olap")]
-use crate::connection;
+use crate::{
+ connection,
+ store::schema::{
+ customers::all_columns as cust_all_columns, payout_attempt::all_columns as poa_all_columns,
+ payouts::all_columns as po_all_columns,
+ },
+};
use crate::{
diesel_error_to_data_error,
errors::RedisErrorExt,
@@ -320,7 +326,7 @@ impl<T: DatabaseStore> PayoutsInterface for KVRouterStore<T> {
merchant_id: &common_utils::id_type::MerchantId,
filters: &PayoutFetchConstraints,
storage_scheme: MerchantStorageScheme,
- ) -> error_stack::Result<Vec<(Payouts, PayoutAttempt, diesel_models::Customer)>, StorageError>
+ ) -> error_stack::Result<Vec<(Payouts, PayoutAttempt, Option<DieselCustomer>)>, StorageError>
{
self.router_store
.filter_payouts_and_attempts(merchant_id, filters, storage_scheme)
@@ -541,7 +547,8 @@ impl<T: DatabaseStore> PayoutsInterface for crate::RouterStore<T> {
merchant_id: &common_utils::id_type::MerchantId,
filters: &PayoutFetchConstraints,
storage_scheme: MerchantStorageScheme,
- ) -> error_stack::Result<Vec<(Payouts, PayoutAttempt, DieselCustomer)>, StorageError> {
+ ) -> error_stack::Result<Vec<(Payouts, PayoutAttempt, Option<DieselCustomer>)>, StorageError>
+ {
use common_utils::errors::ReportSwitchExt;
let conn = connection::pg_connection_read(self).await.switch()?;
@@ -553,7 +560,7 @@ impl<T: DatabaseStore> PayoutsInterface for crate::RouterStore<T> {
)
.inner_join(
diesel_models::schema::customers::table
- .on(cust_dsl::customer_id.eq(po_dsl::customer_id)),
+ .on(cust_dsl::customer_id.nullable().eq(po_dsl::customer_id)),
)
.filter(po_dsl::merchant_id.eq(merchant_id.to_owned()))
.order(po_dsl::created_at.desc())
@@ -645,7 +652,8 @@ impl<T: DatabaseStore> PayoutsInterface for crate::RouterStore<T> {
logger::debug!(filter = %diesel::debug_query::<diesel::pg::Pg,_>(&query).to_string());
query
- .get_results_async::<(DieselPayouts, DieselPayoutAttempt, DieselCustomer)>(conn)
+ .select((po_all_columns, poa_all_columns, cust_all_columns.nullable()))
+ .get_results_async::<(DieselPayouts, DieselPayoutAttempt, Option<DieselCustomer>)>(conn)
.await
.map(|results| {
results
@@ -836,6 +844,8 @@ impl DataModelExt for PayoutsUpdate {
status,
confirm,
payout_type,
+ address_id,
+ customer_id,
} => DieselPayoutsUpdate::Update {
amount,
destination_currency,
@@ -850,6 +860,8 @@ impl DataModelExt for PayoutsUpdate {
status,
confirm,
payout_type,
+ address_id,
+ customer_id,
},
Self::PayoutMethodIdUpdate { payout_method_id } => {
DieselPayoutsUpdate::PayoutMethodIdUpdate { payout_method_id }
diff --git a/migrations/2024-07-31-063531_alter_customer_id_in_payouts/down.sql b/migrations/2024-07-31-063531_alter_customer_id_in_payouts/down.sql
new file mode 100644
index 00000000000..41672976078
--- /dev/null
+++ b/migrations/2024-07-31-063531_alter_customer_id_in_payouts/down.sql
@@ -0,0 +1,15 @@
+ALTER TABLE payouts
+ALTER COLUMN customer_id
+SET
+ NOT NULL,
+ALTER COLUMN address_id
+SET
+ NOT NULL;
+
+ALTER TABLE payout_attempt
+ALTER COLUMN customer_id
+SET
+ NOT NULL,
+ALTER COLUMN address_id
+SET
+ NOT NULL;
\ No newline at end of file
diff --git a/migrations/2024-07-31-063531_alter_customer_id_in_payouts/up.sql b/migrations/2024-07-31-063531_alter_customer_id_in_payouts/up.sql
new file mode 100644
index 00000000000..310989a5160
--- /dev/null
+++ b/migrations/2024-07-31-063531_alter_customer_id_in_payouts/up.sql
@@ -0,0 +1,11 @@
+ALTER TABLE payouts
+ALTER COLUMN customer_id
+DROP NOT NULL,
+ALTER COLUMN address_id
+DROP NOT NULL;
+
+ALTER TABLE payout_attempt
+ALTER COLUMN customer_id
+DROP NOT NULL,
+ALTER COLUMN address_id
+DROP NOT NULL;
\ No newline at end of file
|
2024-07-11T08:17:38Z
|
## Type of Change
<!-- Put an `x` in the boxes that apply -->
- [ ] Bugfix
- [ ] New feature
- [x] Enhancement
- [x] Refactoring
- [ ] Dependency updates
- [ ] Documentation
- [ ] CI/CD
## Description
This PR includes below set of changes
- move customer specific fields to `customer` object for payout creation (backwards compatible)
- `customer` to be used when creating new customers
- `customer_id` to be used to specify details of an already onboarded customer
- update API reference docs - `PolymorphicSchema` derivation for payout APIs
- `billing_address` made optional for payout creation
### Additional Changes
- [x] This PR modifies the API contract
- [ ] This PR modifies the database schema
- [ ] This PR modifies application configuration/environment variables
<!--
Provide links to the files with corresponding changes.
Following are the paths where you can find config files:
1. `config`
2. `crates/router/src/configs`
3. `loadtest/config`
-->
## How did you test it?
*Backward comptability for customer fields*
<details>
<summary>1. Create a new customer (without passing customer_id)</summary>
curl --location 'http://localhost:8080/payouts/create' \
--header 'Content-Type: application/json' \
--header 'api-key: dev_OkApivBrWlFwhoXRY6Iulr3QONuGY9ZcGrBkXu2T9P0RijlIkM4ch0Xa1iuWQXQO' \
--data-raw '{
"amount": 100,
"currency": "EUR",
"profile_id": "pro_oVAk8tgH9W7ffFnsZqe0",
"email": "new_cust@example.com",
"name": "John Doe",
"phone": "999999999",
"phone_country_code": "+65",
"connector": [
"adyen"
],
"description": "Its my first payout request",
"payout_type": "card",
"payout_method_data": {
"card": {
"card_number": "4111111111111111",
"expiry_month": "3",
"expiry_year": "2030",
"card_holder_name": "John Doe"
}
},
"billing": {
"address": {
"line1": "1467",
"line2": "Harrison Street",
"line3": "Harrison Street",
"city": "San Fransico",
"state": "CA",
"zip": "94122",
"country": "US",
"first_name": "John",
"last_name": "Doe"
},
"phone": {
"number": "8056594427",
"country_code": "+91"
}
},
"entity_type": "Individual",
"recurring": true,
"metadata": {
"ref": "123"
},
"confirm": true,
"auto_fulfill": true
}'

</details>
<details>
<summary>2. Create a new customer (pass customer_id)</summary>
curl --location 'http://localhost:8080/payouts/create' \
--header 'Content-Type: application/json' \
--header 'api-key: dev_OkApivBrWlFwhoXRY6Iulr3QONuGY9ZcGrBkXu2T9P0RijlIkM4ch0Xa1iuWQXQO' \
--data-raw '{
"amount": 100,
"currency": "EUR",
"profile_id": "pro_oVAk8tgH9W7ffFnsZqe0",
"email": "new_cust@example.com",
"customer_id": "mycustomer_id",
"name": "John Doe",
"phone": "999999999",
"phone_country_code": "+65",
"connector": [
"adyen"
],
"description": "Its my first payout request",
"payout_type": "card",
"payout_method_data": {
"card": {
"card_number": "4111111111111111",
"expiry_month": "3",
"expiry_year": "2030",
"card_holder_name": "John Doe"
}
},
"billing": {
"address": {
"line1": "1467",
"line2": "Harrison Street",
"line3": "Harrison Street",
"city": "San Fransico",
"state": "CA",
"zip": "94122",
"country": "US",
"first_name": "John",
"last_name": "Doe"
},
"phone": {
"number": "8056594427",
"country_code": "+91"
}
},
"entity_type": "Individual",
"recurring": true,
"metadata": {
"ref": "123"
},
"confirm": true,
"auto_fulfill": true
}'

</details>
<details>
<summary>3. Attach existing customer (using customer_id)</summary>
curl --location 'http://localhost:8080/payouts/create' \
--header 'Content-Type: application/json' \
--header 'api-key: dev_OkApivBrWlFwhoXRY6Iulr3QONuGY9ZcGrBkXu2T9P0RijlIkM4ch0Xa1iuWQXQO' \
--data '{
"amount": 100,
"currency": "EUR",
"profile_id": "pro_oVAk8tgH9W7ffFnsZqe0",
"customer_id": "mycustomer_id",
"connector": [
"adyen"
],
"description": "Its my first payout request",
"payout_type": "card",
"payout_method_data": {
"card": {
"card_number": "4111111111111111",
"expiry_month": "3",
"expiry_year": "2030",
"card_holder_name": "John Doe"
}
},
"billing": {
"address": {
"line1": "1467",
"line2": "Harrison Street",
"line3": "Harrison Street",
"city": "San Fransico",
"state": "CA",
"zip": "94122",
"country": "US",
"first_name": "John",
"last_name": "Doe"
},
"phone": {
"number": "8056594427",
"country_code": "+91"
}
},
"entity_type": "Individual",
"recurring": true,
"metadata": {
"ref": "123"
},
"confirm": true,
"auto_fulfill": true
}'

</details>
*Updated consumption of customer*
<details>
<summary>1. Create a new customer</summary>
curl --location 'http://localhost:8080/payouts/create' \
--header 'Content-Type: application/json' \
--header 'api-key: dev_OkApivBrWlFwhoXRY6Iulr3QONuGY9ZcGrBkXu2T9P0RijlIkM4ch0Xa1iuWQXQO' \
--data-raw '{
"amount": 100,
"currency": "EUR",
"profile_id": "pro_oVAk8tgH9W7ffFnsZqe0",
"customer": {
"id": "updated_customer_id",
"email": "new_cust@example.com",
"name": "John Doe",
"phone": "999999999",
"phone_country_code": "+65"
},
"connector": [
"adyen"
],
"description": "Its my first payout request",
"payout_type": "card",
"payout_method_data": {
"card": {
"card_number": "4111111111111111",
"expiry_month": "3",
"expiry_year": "2030",
"card_holder_name": "John Doe"
}
},
"billing": {
"address": {
"line1": "1467",
"line2": "Harrison Street",
"line3": "Harrison Street",
"city": "San Fransico",
"state": "CA",
"zip": "94122",
"country": "US",
"first_name": "John",
"last_name": "Doe"
},
"phone": {
"number": "8056594427",
"country_code": "+91"
}
},
"entity_type": "Individual",
"recurring": true,
"metadata": {
"ref": "123"
},
"confirm": true,
"auto_fulfill": true
}'

</details>
<details>
<summary>2. Use existing customer</summary>
curl --location 'http://localhost:8080/payouts/create' \
--header 'Content-Type: application/json' \
--header 'api-key: dev_OkApivBrWlFwhoXRY6Iulr3QONuGY9ZcGrBkXu2T9P0RijlIkM4ch0Xa1iuWQXQO' \
--data '{
"amount": 100,
"currency": "EUR",
"profile_id": "pro_oVAk8tgH9W7ffFnsZqe0",
"customer_id": "updated_customer_id",
"connector": [
"adyen"
],
"description": "Its my first payout request",
"payout_type": "card",
"payout_method_data": {
"card": {
"card_number": "4111111111111111",
"expiry_month": "3",
"expiry_year": "2030",
"card_holder_name": "John Doe"
}
},
"billing": {
"address": {
"line1": "1467",
"line2": "Harrison Street",
"line3": "Harrison Street",
"city": "San Fransico",
"state": "CA",
"zip": "94122",
"country": "US",
"first_name": "John",
"last_name": "Doe"
},
"phone": {
"number": "8056594427",
"country_code": "+91"
}
},
"entity_type": "Individual",
"recurring": true,
"metadata": {
"ref": "123"
},
"confirm": true,
"auto_fulfill": true
}'
</details>
*Billing address consumption*
<details>
<summary>1. Create a payout without billing.address and customer</summary>
curl --location 'http://localhost:8080/payouts/create' \
--header 'x-feature: integ-custom' \
--header 'Content-Type: application/json' \
--header 'api-key: dev_OkApivBrWlFwhoXRY6Iulr3QONuGY9ZcGrBkXu2T9P0RijlIkM4ch0Xa1iuWQXQO' \
--data '{
"amount": 1,
"currency": "EUR",
"description": "Its my first payout request",
"payout_type": "bank",
"entity_type": "NaturalPerson",
"recurring": true,
"metadata": {
"ref": "123"
},
"confirm": false,
"auto_fulfill": false
}'

</details>
<details>
<summary>2. Update payout with billing.address and customer details</summary>
curl --location --request PUT 'http://localhost:8080/payouts/e682bd59-3a12-4a8f-9a74-29f07055fb2c' \
--header 'Content-Type: application/json' \
--header 'api-key: dev_OkApivBrWlFwhoXRY6Iulr3QONuGY9ZcGrBkXu2T9P0RijlIkM4ch0Xa1iuWQXQO' \
--data '{
"billing": {
"address": {
"line1": "1467",
"line2": "Harrison Street",
"line3": "Harrison Street",
"city": "San Fransico",
"state": "CA",
"zip": "94122",
"country": "US",
"first_name": "John",
"last_name": "Doe"
},
"phone": {
"number": "8056594427",
"country_code": "+91"
}
},
"customer_id": "cus_05845u0qSuOENDnHLqTl"
}'

</details>
<details>
<summary>3. Confirm / fulfill payout</summary>
curl --location 'http://localhost:8080/payouts/e2f0e7c8-1b23-47b6-959b-7fe8c4c938dc/confirm' \
--header 'Content-Type: application/json' \
--header 'api-key: dev_OkApivBrWlFwhoXRY6Iulr3QONuGY9ZcGrBkXu2T9P0RijlIkM4ch0Xa1iuWQXQO' \
--data '{
"payout_method_data": {
"bank": {
"iban": "NL46TEST0136169112",
"bic": "ABNANL2A",
"bank_name": "Deutsche Bank",
"bank_country_code": "NL",
"bank_city": "Amsterdam"
}
}
}'

</details>
## Checklist
<!-- Put an `x` in the boxes that apply -->
- [x] I formatted the code `cargo +nightly fmt --all`
- [x] I addressed lints thrown by `cargo clippy`
- [x] I reviewed the submitted code
- [ ] I added unit tests for my changes where possible
|
f81416e4df6fa430fd7f6eb910b55464cd72f3f0
|
|
juspay/hyperswitch
|
juspay__hyperswitch-5458
|
Bug: Update Schema and domain models for Payment Methods v2
### Feature Description
Have to change the schema for corresponding DB changes in `payment_methods` table for v2
### Possible Implementation
Will need to irun separate migrations for v2
Based on need, can implement domain models for Payment Methods as well
|
diff --git a/crates/diesel_models/Cargo.toml b/crates/diesel_models/Cargo.toml
index 45582cc0ad9..6b288899778 100644
--- a/crates/diesel_models/Cargo.toml
+++ b/crates/diesel_models/Cargo.toml
@@ -14,6 +14,7 @@ v1 = []
v2 = []
customer_v2 = []
payment_v2 = []
+payment_methods_v2 = []
[dependencies]
async-bb8-diesel = { git = "https://github.com/jarnura/async-bb8-diesel", rev = "53b4ab901aab7635c8215fd1c2d542c8db443094" }
diff --git a/crates/diesel_models/src/kv.rs b/crates/diesel_models/src/kv.rs
index 3361b82f89e..c8940c4c6b2 100644
--- a/crates/diesel_models/src/kv.rs
+++ b/crates/diesel_models/src/kv.rs
@@ -124,11 +124,19 @@ impl DBOperation {
Updateable::PayoutAttemptUpdate(a) => DBResult::PayoutAttempt(Box::new(
a.orig.update_with_attempt_id(conn, a.update_data).await?,
)),
+ #[cfg(all(
+ any(feature = "v1", feature = "v2"),
+ not(feature = "payment_methods_v2")
+ ))]
Updateable::PaymentMethodUpdate(v) => DBResult::PaymentMethod(Box::new(
v.orig
.update_with_payment_method_id(conn, v.update_data)
.await?,
)),
+ #[cfg(all(feature = "v2", feature = "payment_methods_v2"))]
+ Updateable::PaymentMethodUpdate(v) => DBResult::PaymentMethod(Box::new(
+ v.orig.update_with_id(conn, v.update_data).await?,
+ )),
Updateable::MandateUpdate(m) => DBResult::Mandate(Box::new(
Mandate::update_by_merchant_id_mandate_id(
conn,
diff --git a/crates/diesel_models/src/payment_method.rs b/crates/diesel_models/src/payment_method.rs
index b54824ad935..c56ab8a0b2b 100644
--- a/crates/diesel_models/src/payment_method.rs
+++ b/crates/diesel_models/src/payment_method.rs
@@ -1,12 +1,26 @@
use common_enums::MerchantStorageScheme;
use common_utils::{encryption::Encryption, pii};
use diesel::{AsChangeset, Identifiable, Insertable, Queryable, Selectable};
+#[cfg(all(
+ any(feature = "v1", feature = "v2"),
+ not(feature = "payment_methods_v2")
+))]
use masking::Secret;
use serde::{Deserialize, Serialize};
use time::PrimitiveDateTime;
+#[cfg(all(
+ any(feature = "v1", feature = "v2"),
+ not(feature = "payment_methods_v2")
+))]
use crate::{enums as storage_enums, schema::payment_methods};
+#[cfg(all(feature = "v2", feature = "payment_methods_v2"))]
+use crate::{enums as storage_enums, schema_v2::payment_methods};
+#[cfg(all(
+ any(feature = "v1", feature = "v2"),
+ not(feature = "payment_methods_v2")
+))]
#[derive(
Clone, Debug, Eq, PartialEq, Identifiable, Queryable, Selectable, Serialize, Deserialize,
)]
@@ -44,8 +58,56 @@ pub struct PaymentMethod {
pub client_secret: Option<String>,
pub payment_method_billing_address: Option<Encryption>,
pub updated_by: Option<String>,
+ pub version: common_enums::ApiVersion,
}
+#[cfg(all(feature = "v2", feature = "payment_methods_v2"))]
+#[derive(
+ Clone, Debug, Eq, PartialEq, Identifiable, Queryable, Selectable, Serialize, Deserialize,
+)]
+#[diesel(table_name = payment_methods, primary_key(id), check_for_backend(diesel::pg::Pg))]
+pub struct PaymentMethod {
+ pub customer_id: common_utils::id_type::CustomerId,
+ pub merchant_id: common_utils::id_type::MerchantId,
+ pub created_at: PrimitiveDateTime,
+ pub last_modified: PrimitiveDateTime,
+ pub payment_method: Option<storage_enums::PaymentMethod>,
+ pub payment_method_type: Option<storage_enums::PaymentMethodType>,
+ pub metadata: Option<pii::SecretSerdeValue>,
+ pub payment_method_data: Option<Encryption>,
+ pub locker_id: Option<String>,
+ pub last_used_at: PrimitiveDateTime,
+ pub connector_mandate_details: Option<pii::SecretSerdeValue>,
+ pub customer_acceptance: Option<pii::SecretSerdeValue>,
+ pub status: storage_enums::PaymentMethodStatus,
+ pub network_transaction_id: Option<String>,
+ pub client_secret: Option<String>,
+ pub payment_method_billing_address: Option<Encryption>,
+ pub updated_by: Option<String>,
+ pub locker_fingerprint_id: Option<String>,
+ pub id: String,
+ pub version: common_enums::ApiVersion,
+}
+
+impl PaymentMethod {
+ #[cfg(all(
+ any(feature = "v1", feature = "v2"),
+ not(feature = "payment_methods_v2")
+ ))]
+ pub fn get_id(&self) -> &String {
+ &self.payment_method_id
+ }
+
+ #[cfg(all(feature = "v2", feature = "payment_methods_v2"))]
+ pub fn get_id(&self) -> &String {
+ &self.id
+ }
+}
+
+#[cfg(all(
+ any(feature = "v1", feature = "v2"),
+ not(feature = "payment_methods_v2")
+))]
#[derive(
Clone, Debug, Eq, PartialEq, Insertable, router_derive::DebugAsDisplay, Serialize, Deserialize,
)]
@@ -81,12 +143,54 @@ pub struct PaymentMethodNew {
pub client_secret: Option<String>,
pub payment_method_billing_address: Option<Encryption>,
pub updated_by: Option<String>,
+ pub version: common_enums::ApiVersion,
+}
+
+#[cfg(all(feature = "v2", feature = "payment_methods_v2"))]
+#[derive(
+ Clone, Debug, Eq, PartialEq, Insertable, router_derive::DebugAsDisplay, Serialize, Deserialize,
+)]
+#[diesel(table_name = payment_methods)]
+pub struct PaymentMethodNew {
+ pub customer_id: common_utils::id_type::CustomerId,
+ pub merchant_id: common_utils::id_type::MerchantId,
+ pub payment_method: Option<storage_enums::PaymentMethod>,
+ pub payment_method_type: Option<storage_enums::PaymentMethodType>,
+ pub created_at: PrimitiveDateTime,
+ pub last_modified: PrimitiveDateTime,
+ pub metadata: Option<pii::SecretSerdeValue>,
+ pub payment_method_data: Option<Encryption>,
+ pub locker_id: Option<String>,
+ pub last_used_at: PrimitiveDateTime,
+ pub connector_mandate_details: Option<pii::SecretSerdeValue>,
+ pub customer_acceptance: Option<pii::SecretSerdeValue>,
+ pub status: storage_enums::PaymentMethodStatus,
+ pub network_transaction_id: Option<String>,
+ pub client_secret: Option<String>,
+ pub payment_method_billing_address: Option<Encryption>,
+ pub updated_by: Option<String>,
+ pub locker_fingerprint_id: Option<String>,
+ pub id: String,
+ pub version: common_enums::ApiVersion,
}
impl PaymentMethodNew {
pub fn update_storage_scheme(&mut self, storage_scheme: MerchantStorageScheme) {
self.updated_by = Some(storage_scheme.to_string());
}
+
+ #[cfg(all(
+ any(feature = "v1", feature = "v2"),
+ not(feature = "payment_methods_v2")
+ ))]
+ pub fn get_id(&self) -> &String {
+ &self.payment_method_id
+ }
+
+ #[cfg(all(feature = "v2", feature = "payment_methods_v2"))]
+ pub fn get_id(&self) -> &String {
+ &self.id
+ }
}
#[derive(Debug, Eq, PartialEq, Deserialize, Serialize)]
@@ -95,6 +199,10 @@ pub struct TokenizeCoreWorkflow {
pub pm: storage_enums::PaymentMethod,
}
+#[cfg(all(
+ any(feature = "v1", feature = "v2"),
+ not(feature = "payment_methods_v2")
+))]
#[derive(Debug, Serialize, Deserialize)]
pub enum PaymentMethodUpdate {
MetadataUpdateAndLastUsed {
@@ -131,6 +239,42 @@ pub enum PaymentMethodUpdate {
},
}
+#[cfg(all(feature = "v2", feature = "payment_methods_v2"))]
+#[derive(Debug, Serialize, Deserialize)]
+pub enum PaymentMethodUpdate {
+ MetadataUpdateAndLastUsed {
+ metadata: Option<pii::SecretSerdeValue>,
+ last_used_at: PrimitiveDateTime,
+ },
+ UpdatePaymentMethodDataAndLastUsed {
+ payment_method_data: Option<Encryption>,
+ last_used_at: PrimitiveDateTime,
+ },
+ PaymentMethodDataUpdate {
+ payment_method_data: Option<Encryption>,
+ },
+ LastUsedUpdate {
+ last_used_at: PrimitiveDateTime,
+ },
+ NetworkTransactionIdAndStatusUpdate {
+ network_transaction_id: Option<String>,
+ status: Option<storage_enums::PaymentMethodStatus>,
+ },
+ StatusUpdate {
+ status: Option<storage_enums::PaymentMethodStatus>,
+ },
+ AdditionalDataUpdate {
+ payment_method_data: Option<Encryption>,
+ status: Option<storage_enums::PaymentMethodStatus>,
+ locker_id: Option<String>,
+ payment_method: Option<storage_enums::PaymentMethod>,
+ payment_method_type: Option<storage_enums::PaymentMethodType>,
+ },
+ ConnectorMandateDetailsUpdate {
+ connector_mandate_details: Option<pii::SecretSerdeValue>,
+ },
+}
+
impl PaymentMethodUpdate {
pub fn convert_to_payment_method_update(
self,
@@ -142,9 +286,64 @@ impl PaymentMethodUpdate {
}
}
-#[derive(
- Clone, Debug, Default, AsChangeset, router_derive::DebugAsDisplay, Serialize, Deserialize,
-)]
+#[cfg(all(feature = "v2", feature = "payment_methods_v2"))]
+#[derive(Clone, Debug, AsChangeset, router_derive::DebugAsDisplay, Serialize, Deserialize)]
+#[diesel(table_name = payment_methods)]
+pub struct PaymentMethodUpdateInternal {
+ metadata: Option<pii::SecretSerdeValue>,
+ payment_method_data: Option<Encryption>,
+ last_used_at: Option<PrimitiveDateTime>,
+ network_transaction_id: Option<String>,
+ status: Option<storage_enums::PaymentMethodStatus>,
+ locker_id: Option<String>,
+ payment_method: Option<storage_enums::PaymentMethod>,
+ connector_mandate_details: Option<pii::SecretSerdeValue>,
+ updated_by: Option<String>,
+ payment_method_type: Option<storage_enums::PaymentMethodType>,
+ last_modified: PrimitiveDateTime,
+}
+
+#[cfg(all(feature = "v2", feature = "payment_methods_v2"))]
+impl PaymentMethodUpdateInternal {
+ pub fn create_payment_method(self, source: PaymentMethod) -> PaymentMethod {
+ let metadata = self.metadata;
+
+ PaymentMethod { metadata, ..source }
+ }
+
+ pub fn apply_changeset(self, source: PaymentMethod) -> PaymentMethod {
+ let Self {
+ metadata,
+ payment_method_data,
+ last_used_at,
+ network_transaction_id,
+ status,
+ connector_mandate_details,
+ updated_by,
+ ..
+ } = self;
+
+ PaymentMethod {
+ metadata: metadata.map_or(source.metadata, Some),
+ payment_method_data: payment_method_data.map_or(source.payment_method_data, Some),
+ last_used_at: last_used_at.unwrap_or(source.last_used_at),
+ network_transaction_id: network_transaction_id
+ .map_or(source.network_transaction_id, Some),
+ status: status.unwrap_or(source.status),
+ connector_mandate_details: connector_mandate_details
+ .map_or(source.connector_mandate_details, Some),
+ updated_by: updated_by.map_or(source.updated_by, Some),
+ last_modified: common_utils::date_time::now(),
+ ..source
+ }
+ }
+}
+
+#[cfg(all(
+ any(feature = "v1", feature = "v2"),
+ not(feature = "payment_methods_v2")
+))]
+#[derive(Clone, Debug, AsChangeset, router_derive::DebugAsDisplay, Serialize, Deserialize)]
#[diesel(table_name = payment_methods)]
pub struct PaymentMethodUpdateInternal {
metadata: Option<serde_json::Value>,
@@ -158,8 +357,13 @@ pub struct PaymentMethodUpdateInternal {
updated_by: Option<String>,
payment_method_type: Option<storage_enums::PaymentMethodType>,
payment_method_issuer: Option<String>,
+ last_modified: PrimitiveDateTime,
}
+#[cfg(all(
+ any(feature = "v1", feature = "v2"),
+ not(feature = "payment_methods_v2")
+))]
impl PaymentMethodUpdateInternal {
pub fn create_payment_method(self, source: PaymentMethod) -> PaymentMethod {
let metadata = self.metadata.map(Secret::new);
@@ -189,11 +393,16 @@ impl PaymentMethodUpdateInternal {
connector_mandate_details: connector_mandate_details
.map_or(source.connector_mandate_details, Some),
updated_by: updated_by.map_or(source.updated_by, Some),
+ last_modified: common_utils::date_time::now(),
..source
}
}
}
+#[cfg(all(
+ any(feature = "v1", feature = "v2"),
+ not(feature = "payment_methods_v2")
+))]
impl From<PaymentMethodUpdate> for PaymentMethodUpdateInternal {
fn from(payment_method_update: PaymentMethodUpdate) -> Self {
match payment_method_update {
@@ -212,6 +421,7 @@ impl From<PaymentMethodUpdate> for PaymentMethodUpdateInternal {
updated_by: None,
payment_method_issuer: None,
payment_method_type: None,
+ last_modified: common_utils::date_time::now(),
},
PaymentMethodUpdate::PaymentMethodDataUpdate {
payment_method_data,
@@ -227,6 +437,7 @@ impl From<PaymentMethodUpdate> for PaymentMethodUpdateInternal {
updated_by: None,
payment_method_issuer: None,
payment_method_type: None,
+ last_modified: common_utils::date_time::now(),
},
PaymentMethodUpdate::LastUsedUpdate { last_used_at } => Self {
metadata: None,
@@ -240,6 +451,7 @@ impl From<PaymentMethodUpdate> for PaymentMethodUpdateInternal {
updated_by: None,
payment_method_issuer: None,
payment_method_type: None,
+ last_modified: common_utils::date_time::now(),
},
PaymentMethodUpdate::UpdatePaymentMethodDataAndLastUsed {
payment_method_data,
@@ -256,6 +468,7 @@ impl From<PaymentMethodUpdate> for PaymentMethodUpdateInternal {
updated_by: None,
payment_method_issuer: None,
payment_method_type: None,
+ last_modified: common_utils::date_time::now(),
},
PaymentMethodUpdate::NetworkTransactionIdAndStatusUpdate {
network_transaction_id,
@@ -272,6 +485,7 @@ impl From<PaymentMethodUpdate> for PaymentMethodUpdateInternal {
updated_by: None,
payment_method_issuer: None,
payment_method_type: None,
+ last_modified: common_utils::date_time::now(),
},
PaymentMethodUpdate::StatusUpdate { status } => Self {
metadata: None,
@@ -285,6 +499,7 @@ impl From<PaymentMethodUpdate> for PaymentMethodUpdateInternal {
updated_by: None,
payment_method_issuer: None,
payment_method_type: None,
+ last_modified: common_utils::date_time::now(),
},
PaymentMethodUpdate::AdditionalDataUpdate {
payment_method_data,
@@ -305,6 +520,7 @@ impl From<PaymentMethodUpdate> for PaymentMethodUpdateInternal {
updated_by: None,
payment_method_issuer,
payment_method_type,
+ last_modified: common_utils::date_time::now(),
},
PaymentMethodUpdate::ConnectorMandateDetailsUpdate {
connector_mandate_details,
@@ -320,11 +536,147 @@ impl From<PaymentMethodUpdate> for PaymentMethodUpdateInternal {
updated_by: None,
payment_method_issuer: None,
payment_method_type: None,
+ last_modified: common_utils::date_time::now(),
},
}
}
}
+#[cfg(all(feature = "v2", feature = "payment_methods_v2"))]
+impl From<PaymentMethodUpdate> for PaymentMethodUpdateInternal {
+ fn from(payment_method_update: PaymentMethodUpdate) -> Self {
+ match payment_method_update {
+ PaymentMethodUpdate::MetadataUpdateAndLastUsed {
+ metadata,
+ last_used_at,
+ } => Self {
+ metadata,
+ payment_method_data: None,
+ last_used_at: Some(last_used_at),
+ network_transaction_id: None,
+ status: None,
+ locker_id: None,
+ payment_method: None,
+ connector_mandate_details: None,
+ updated_by: None,
+ payment_method_type: None,
+ last_modified: common_utils::date_time::now(),
+ },
+ PaymentMethodUpdate::PaymentMethodDataUpdate {
+ payment_method_data,
+ } => Self {
+ metadata: None,
+ payment_method_data,
+ last_used_at: None,
+ network_transaction_id: None,
+ status: None,
+ locker_id: None,
+ payment_method: None,
+ connector_mandate_details: None,
+ updated_by: None,
+ payment_method_type: None,
+ last_modified: common_utils::date_time::now(),
+ },
+ PaymentMethodUpdate::LastUsedUpdate { last_used_at } => Self {
+ metadata: None,
+ payment_method_data: None,
+ last_used_at: Some(last_used_at),
+ network_transaction_id: None,
+ status: None,
+ locker_id: None,
+ payment_method: None,
+ connector_mandate_details: None,
+ updated_by: None,
+ payment_method_type: None,
+ last_modified: common_utils::date_time::now(),
+ },
+ PaymentMethodUpdate::UpdatePaymentMethodDataAndLastUsed {
+ payment_method_data,
+ last_used_at,
+ } => Self {
+ metadata: None,
+ payment_method_data,
+ last_used_at: Some(last_used_at),
+ network_transaction_id: None,
+ status: None,
+ locker_id: None,
+ payment_method: None,
+ connector_mandate_details: None,
+ updated_by: None,
+ payment_method_type: None,
+ last_modified: common_utils::date_time::now(),
+ },
+ PaymentMethodUpdate::NetworkTransactionIdAndStatusUpdate {
+ network_transaction_id,
+ status,
+ } => Self {
+ metadata: None,
+ payment_method_data: None,
+ last_used_at: None,
+ network_transaction_id,
+ status,
+ locker_id: None,
+ payment_method: None,
+ connector_mandate_details: None,
+ updated_by: None,
+ payment_method_type: None,
+ last_modified: common_utils::date_time::now(),
+ },
+ PaymentMethodUpdate::StatusUpdate { status } => Self {
+ metadata: None,
+ payment_method_data: None,
+ last_used_at: None,
+ network_transaction_id: None,
+ status,
+ locker_id: None,
+ payment_method: None,
+ connector_mandate_details: None,
+ updated_by: None,
+ payment_method_type: None,
+ last_modified: common_utils::date_time::now(),
+ },
+ PaymentMethodUpdate::AdditionalDataUpdate {
+ payment_method_data,
+ status,
+ locker_id,
+ payment_method,
+ payment_method_type,
+ } => Self {
+ metadata: None,
+ payment_method_data,
+ last_used_at: None,
+ network_transaction_id: None,
+ status,
+ locker_id,
+ payment_method,
+ connector_mandate_details: None,
+ updated_by: None,
+ payment_method_type,
+ last_modified: common_utils::date_time::now(),
+ },
+ PaymentMethodUpdate::ConnectorMandateDetailsUpdate {
+ connector_mandate_details,
+ } => Self {
+ metadata: None,
+ payment_method_data: None,
+ last_used_at: None,
+ status: None,
+ locker_id: None,
+ payment_method: None,
+ connector_mandate_details,
+ network_transaction_id: None,
+ updated_by: None,
+ payment_method_type: None,
+ last_modified: common_utils::date_time::now(),
+ },
+ }
+ }
+}
+
+#[cfg(all(
+ any(feature = "v1", feature = "v2"),
+ not(feature = "payment_methods_v2")
+))]
impl From<&PaymentMethodNew> for PaymentMethod {
fn from(payment_method_new: &PaymentMethodNew) -> Self {
Self {
@@ -360,6 +712,37 @@ impl From<&PaymentMethodNew> for PaymentMethod {
payment_method_billing_address: payment_method_new
.payment_method_billing_address
.clone(),
+ version: payment_method_new.version,
+ }
+ }
+}
+
+#[cfg(all(feature = "v2", feature = "payment_methods_v2"))]
+impl From<&PaymentMethodNew> for PaymentMethod {
+ fn from(payment_method_new: &PaymentMethodNew) -> Self {
+ Self {
+ customer_id: payment_method_new.customer_id.clone(),
+ merchant_id: payment_method_new.merchant_id.clone(),
+ locker_id: payment_method_new.locker_id.clone(),
+ created_at: payment_method_new.created_at,
+ last_modified: payment_method_new.last_modified,
+ payment_method: payment_method_new.payment_method,
+ payment_method_type: payment_method_new.payment_method_type,
+ metadata: payment_method_new.metadata.clone(),
+ payment_method_data: payment_method_new.payment_method_data.clone(),
+ last_used_at: payment_method_new.last_used_at,
+ connector_mandate_details: payment_method_new.connector_mandate_details.clone(),
+ customer_acceptance: payment_method_new.customer_acceptance.clone(),
+ status: payment_method_new.status,
+ network_transaction_id: payment_method_new.network_transaction_id.clone(),
+ client_secret: payment_method_new.client_secret.clone(),
+ updated_by: payment_method_new.updated_by.clone(),
+ payment_method_billing_address: payment_method_new
+ .payment_method_billing_address
+ .clone(),
+ id: payment_method_new.id.clone(),
+ locker_fingerprint_id: payment_method_new.locker_fingerprint_id.clone(),
+ version: payment_method_new.version,
}
}
}
diff --git a/crates/diesel_models/src/query/payment_method.rs b/crates/diesel_models/src/query/payment_method.rs
index 90bf455294d..1684356480e 100644
--- a/crates/diesel_models/src/query/payment_method.rs
+++ b/crates/diesel_models/src/query/payment_method.rs
@@ -1,15 +1,36 @@
+#[cfg(all(
+ any(feature = "v1", feature = "v2"),
+ not(feature = "payment_methods_v2")
+))]
use async_bb8_diesel::AsyncRunQueryDsl;
-use diesel::{
- associations::HasTable, debug_query, pg::Pg, BoolExpressionMethods, ExpressionMethods,
- QueryDsl, Table,
-};
+#[cfg(all(
+ any(feature = "v1", feature = "v2"),
+ not(feature = "payment_methods_v2")
+))]
+use diesel::Table;
+use diesel::{associations::HasTable, BoolExpressionMethods, ExpressionMethods};
+#[cfg(all(
+ any(feature = "v1", feature = "v2"),
+ not(feature = "payment_methods_v2")
+))]
+use diesel::{debug_query, pg::Pg, QueryDsl};
+#[cfg(all(
+ any(feature = "v1", feature = "v2"),
+ not(feature = "payment_methods_v2")
+))]
use error_stack::ResultExt;
use super::generics;
+#[cfg(all(
+ any(feature = "v1", feature = "v2"),
+ not(feature = "payment_methods_v2")
+))]
+use crate::schema::payment_methods::dsl;
+#[cfg(all(feature = "v2", feature = "payment_methods_v2"))]
+use crate::schema_v2::payment_methods::dsl::{self, id as pm_id};
use crate::{
enums as storage_enums, errors,
payment_method::{self, PaymentMethod, PaymentMethodNew},
- schema::payment_methods::dsl,
PgPooledConn, StorageResult,
};
@@ -19,6 +40,10 @@ impl PaymentMethodNew {
}
}
+#[cfg(all(
+ any(feature = "v1", feature = "v2"),
+ not(feature = "payment_methods_v2")
+))]
impl PaymentMethod {
pub async fn delete_by_payment_method_id(
conn: &PgPooledConn,
@@ -173,3 +198,63 @@ impl PaymentMethod {
}
}
}
+
+#[cfg(all(feature = "v2", feature = "payment_methods_v2"))]
+impl PaymentMethod {
+ pub async fn find_by_id(conn: &PgPooledConn, id: &str) -> StorageResult<Self> {
+ generics::generic_find_one::<<Self as HasTable>::Table, _, _>(conn, pm_id.eq(id.to_owned()))
+ .await
+ }
+
+ pub async fn find_by_customer_id_merchant_id_status(
+ conn: &PgPooledConn,
+ customer_id: &common_utils::id_type::CustomerId,
+ merchant_id: &common_utils::id_type::MerchantId,
+ status: storage_enums::PaymentMethodStatus,
+ limit: Option<i64>,
+ ) -> StorageResult<Vec<Self>> {
+ generics::generic_filter::<<Self as HasTable>::Table, _, _, _>(
+ conn,
+ dsl::customer_id
+ .eq(customer_id.to_owned())
+ .and(dsl::merchant_id.eq(merchant_id.to_owned()))
+ .and(dsl::status.eq(status)),
+ limit,
+ None,
+ Some(dsl::last_used_at.desc()),
+ )
+ .await
+ }
+
+ pub async fn update_with_id(
+ self,
+ conn: &PgPooledConn,
+ payment_method: payment_method::PaymentMethodUpdateInternal,
+ ) -> StorageResult<Self> {
+ match generics::generic_update_with_unique_predicate_get_result::<
+ <Self as HasTable>::Table,
+ _,
+ _,
+ _,
+ >(conn, pm_id.eq(self.id.to_owned()), payment_method)
+ .await
+ {
+ Err(error) => match error.current_context() {
+ errors::DatabaseError::NoFieldsToUpdate => Ok(self),
+ _ => Err(error),
+ },
+ result => result,
+ }
+ }
+
+ pub async fn find_by_fingerprint_id(
+ conn: &PgPooledConn,
+ fingerprint_id: &str,
+ ) -> StorageResult<Self> {
+ generics::generic_find_one::<<Self as HasTable>::Table, _, _>(
+ conn,
+ dsl::locker_fingerprint_id.eq(fingerprint_id.to_owned()),
+ )
+ .await
+ }
+}
diff --git a/crates/diesel_models/src/schema.rs b/crates/diesel_models/src/schema.rs
index e0f2b9a0bd2..7927dfee106 100644
--- a/crates/diesel_models/src/schema.rs
+++ b/crates/diesel_models/src/schema.rs
@@ -1002,6 +1002,7 @@ diesel::table! {
payment_method_billing_address -> Nullable<Bytea>,
#[max_length = 64]
updated_by -> Nullable<Varchar>,
+ version -> ApiVersion,
}
}
diff --git a/crates/diesel_models/src/schema_v2.rs b/crates/diesel_models/src/schema_v2.rs
index 410c541441b..41bf563a3a3 100644
--- a/crates/diesel_models/src/schema_v2.rs
+++ b/crates/diesel_models/src/schema_v2.rs
@@ -933,39 +933,16 @@ diesel::table! {
use diesel::sql_types::*;
use crate::enums::diesel_exports::*;
- payment_methods (payment_method_id) {
- id -> Int4,
+ payment_methods (id) {
#[max_length = 64]
customer_id -> Varchar,
#[max_length = 64]
merchant_id -> Varchar,
- #[max_length = 64]
- payment_method_id -> Varchar,
- accepted_currency -> Nullable<Array<Nullable<Currency>>>,
- #[max_length = 32]
- scheme -> Nullable<Varchar>,
- #[max_length = 128]
- token -> Nullable<Varchar>,
- #[max_length = 255]
- cardholder_name -> Nullable<Varchar>,
- #[max_length = 64]
- issuer_name -> Nullable<Varchar>,
- #[max_length = 64]
- issuer_country -> Nullable<Varchar>,
- payer_country -> Nullable<Array<Nullable<Text>>>,
- is_stored -> Nullable<Bool>,
- #[max_length = 32]
- swift_code -> Nullable<Varchar>,
- #[max_length = 128]
- direct_debit_token -> Nullable<Varchar>,
created_at -> Timestamp,
last_modified -> Timestamp,
payment_method -> Nullable<Varchar>,
#[max_length = 64]
payment_method_type -> Nullable<Varchar>,
- #[max_length = 128]
- payment_method_issuer -> Nullable<Varchar>,
- payment_method_issuer_code -> Nullable<PaymentMethodIssuerCode>,
metadata -> Nullable<Json>,
payment_method_data -> Nullable<Bytea>,
#[max_length = 64]
@@ -982,6 +959,11 @@ diesel::table! {
payment_method_billing_address -> Nullable<Bytea>,
#[max_length = 64]
updated_by -> Nullable<Varchar>,
+ #[max_length = 64]
+ locker_fingerprint_id -> Nullable<Varchar>,
+ #[max_length = 64]
+ id -> Varchar,
+ version -> ApiVersion,
}
}
diff --git a/crates/hyperswitch_domain_models/Cargo.toml b/crates/hyperswitch_domain_models/Cargo.toml
index f84d065fd9d..e2ae011c828 100644
--- a/crates/hyperswitch_domain_models/Cargo.toml
+++ b/crates/hyperswitch_domain_models/Cargo.toml
@@ -17,6 +17,7 @@ v2 = ["api_models/v2", "diesel_models/v2"]
v1 = ["api_models/v1", "diesel_models/v1"]
customer_v2 = ["api_models/customer_v2", "diesel_models/customer_v2"]
payment_v2 = ["api_models/payment_v2", "diesel_models/payment_v2"]
+payment_methods_v2 = ["api_models/payment_methods_v2", "diesel_models/payment_methods_v2"]
[dependencies]
# First party deps
diff --git a/crates/hyperswitch_domain_models/src/lib.rs b/crates/hyperswitch_domain_models/src/lib.rs
index 85f35116910..54920dee6ba 100644
--- a/crates/hyperswitch_domain_models/src/lib.rs
+++ b/crates/hyperswitch_domain_models/src/lib.rs
@@ -10,6 +10,7 @@ pub mod merchant_connector_account;
pub mod merchant_key_store;
pub mod payment_address;
pub mod payment_method_data;
+pub mod payment_methods;
pub mod payments;
#[cfg(feature = "payouts")]
pub mod payouts;
diff --git a/crates/hyperswitch_domain_models/src/payment_methods.rs b/crates/hyperswitch_domain_models/src/payment_methods.rs
new file mode 100644
index 00000000000..ef8d90d0e43
--- /dev/null
+++ b/crates/hyperswitch_domain_models/src/payment_methods.rs
@@ -0,0 +1,380 @@
+use common_utils::{
+ crypto::OptionalEncryptableValue,
+ // date_time,
+ // encryption::Encryption,
+ errors::{CustomResult, ValidationError},
+ pii,
+ type_name,
+ types::keymanager,
+};
+use diesel_models::enums as storage_enums;
+use error_stack::ResultExt;
+use masking::{PeekInterface, Secret};
+use time::PrimitiveDateTime;
+
+use crate::type_encryption::{crypto_operation, AsyncLift, CryptoOperation};
+
+#[cfg(all(
+ any(feature = "v1", feature = "v2"),
+ not(feature = "payment_methods_v2")
+))]
+#[derive(Clone, Debug)]
+pub struct PaymentMethod {
+ pub customer_id: common_utils::id_type::CustomerId,
+ pub merchant_id: common_utils::id_type::MerchantId,
+ pub payment_method_id: String,
+ pub accepted_currency: Option<Vec<storage_enums::Currency>>,
+ pub scheme: Option<String>,
+ pub token: Option<String>,
+ pub cardholder_name: Option<Secret<String>>,
+ pub issuer_name: Option<String>,
+ pub issuer_country: Option<String>,
+ pub payer_country: Option<Vec<String>>,
+ pub is_stored: Option<bool>,
+ pub swift_code: Option<String>,
+ pub direct_debit_token: Option<String>,
+ pub created_at: PrimitiveDateTime,
+ pub last_modified: PrimitiveDateTime,
+ pub payment_method: Option<storage_enums::PaymentMethod>,
+ pub payment_method_type: Option<storage_enums::PaymentMethodType>,
+ pub payment_method_issuer: Option<String>,
+ pub payment_method_issuer_code: Option<storage_enums::PaymentMethodIssuerCode>,
+ pub metadata: Option<pii::SecretSerdeValue>,
+ pub payment_method_data: OptionalEncryptableValue,
+ pub locker_id: Option<String>,
+ pub last_used_at: PrimitiveDateTime,
+ pub connector_mandate_details: Option<serde_json::Value>,
+ pub customer_acceptance: Option<pii::SecretSerdeValue>,
+ pub status: storage_enums::PaymentMethodStatus,
+ pub network_transaction_id: Option<String>,
+ pub client_secret: Option<String>,
+ pub payment_method_billing_address: OptionalEncryptableValue,
+ pub updated_by: Option<String>,
+ pub version: common_enums::ApiVersion,
+}
+
+#[cfg(all(feature = "v2", feature = "payment_methods_v2"))]
+#[derive(Clone, Debug)]
+pub struct PaymentMethod {
+ pub customer_id: common_utils::id_type::CustomerId,
+ pub merchant_id: common_utils::id_type::MerchantId,
+ pub created_at: PrimitiveDateTime,
+ pub last_modified: PrimitiveDateTime,
+ pub payment_method: Option<storage_enums::PaymentMethod>,
+ pub payment_method_type: Option<storage_enums::PaymentMethodType>,
+ pub metadata: Option<pii::SecretSerdeValue>,
+ pub payment_method_data: OptionalEncryptableValue,
+ pub locker_id: Option<String>,
+ pub last_used_at: PrimitiveDateTime,
+ pub connector_mandate_details: Option<pii::SecretSerdeValue>,
+ pub customer_acceptance: Option<pii::SecretSerdeValue>,
+ pub status: storage_enums::PaymentMethodStatus,
+ pub network_transaction_id: Option<String>,
+ pub client_secret: Option<String>,
+ pub payment_method_billing_address: OptionalEncryptableValue,
+ pub updated_by: Option<String>,
+ pub locker_fingerprint_id: Option<String>,
+ pub id: String,
+ pub version: common_enums::ApiVersion,
+}
+
+impl PaymentMethod {
+ #[cfg(all(
+ any(feature = "v1", feature = "v2"),
+ not(feature = "payment_methods_v2")
+ ))]
+ pub fn get_id(&self) -> &String {
+ &self.payment_method_id
+ }
+
+ #[cfg(all(feature = "v2", feature = "payment_methods_v2"))]
+ pub fn get_id(&self) -> &String {
+ &self.id
+ }
+}
+
+#[cfg(all(
+ any(feature = "v1", feature = "v2"),
+ not(feature = "payment_methods_v2")
+))]
+#[async_trait::async_trait]
+impl super::behaviour::Conversion for PaymentMethod {
+ type DstType = diesel_models::payment_method::PaymentMethod;
+ type NewDstType = diesel_models::payment_method::PaymentMethodNew;
+ async fn convert(self) -> CustomResult<Self::DstType, ValidationError> {
+ Ok(Self::DstType {
+ customer_id: self.customer_id,
+ merchant_id: self.merchant_id,
+ payment_method_id: self.payment_method_id,
+ accepted_currency: self.accepted_currency,
+ scheme: self.scheme,
+ token: self.token,
+ cardholder_name: self.cardholder_name,
+ issuer_name: self.issuer_name,
+ issuer_country: self.issuer_country,
+ payer_country: self.payer_country,
+ is_stored: self.is_stored,
+ swift_code: self.swift_code,
+ direct_debit_token: self.direct_debit_token,
+ created_at: self.created_at,
+ last_modified: self.last_modified,
+ payment_method: self.payment_method,
+ payment_method_type: self.payment_method_type,
+ payment_method_issuer: self.payment_method_issuer,
+ payment_method_issuer_code: self.payment_method_issuer_code,
+ metadata: self.metadata,
+ payment_method_data: self.payment_method_data.map(|val| val.into()),
+ locker_id: self.locker_id,
+ last_used_at: self.last_used_at,
+ connector_mandate_details: self.connector_mandate_details,
+ customer_acceptance: self.customer_acceptance,
+ status: self.status,
+ network_transaction_id: self.network_transaction_id,
+ client_secret: self.client_secret,
+ payment_method_billing_address: self
+ .payment_method_billing_address
+ .map(|val| val.into()),
+ updated_by: self.updated_by,
+ version: self.version,
+ })
+ }
+
+ async fn convert_back(
+ state: &keymanager::KeyManagerState,
+ item: Self::DstType,
+ key: &Secret<Vec<u8>>,
+ key_manager_identifier: keymanager::Identifier,
+ ) -> CustomResult<Self, ValidationError>
+ where
+ Self: Sized,
+ {
+ async {
+ Ok::<Self, error_stack::Report<common_utils::errors::CryptoError>>(Self {
+ customer_id: item.customer_id,
+ merchant_id: item.merchant_id,
+ payment_method_id: item.payment_method_id,
+ accepted_currency: item.accepted_currency,
+ scheme: item.scheme,
+ token: item.token,
+ cardholder_name: item.cardholder_name,
+ issuer_name: item.issuer_name,
+ issuer_country: item.issuer_country,
+ payer_country: item.payer_country,
+ is_stored: item.is_stored,
+ swift_code: item.swift_code,
+ direct_debit_token: item.direct_debit_token,
+ created_at: item.created_at,
+ last_modified: item.last_modified,
+ payment_method: item.payment_method,
+ payment_method_type: item.payment_method_type,
+ payment_method_issuer: item.payment_method_issuer,
+ payment_method_issuer_code: item.payment_method_issuer_code,
+ metadata: item.metadata,
+ payment_method_data: item
+ .payment_method_data
+ .async_lift(|inner| async {
+ crypto_operation(
+ state,
+ type_name!(Self::DstType),
+ CryptoOperation::DecryptOptional(inner),
+ key_manager_identifier.clone(),
+ key.peek(),
+ )
+ .await
+ .and_then(|val| val.try_into_optionaloperation())
+ })
+ .await?,
+ locker_id: item.locker_id,
+ last_used_at: item.last_used_at,
+ connector_mandate_details: item.connector_mandate_details,
+ customer_acceptance: item.customer_acceptance,
+ status: item.status,
+ network_transaction_id: item.network_transaction_id,
+ client_secret: item.client_secret,
+ payment_method_billing_address: item
+ .payment_method_billing_address
+ .async_lift(|inner| async {
+ crypto_operation(
+ state,
+ type_name!(Self::DstType),
+ CryptoOperation::DecryptOptional(inner),
+ key_manager_identifier.clone(),
+ key.peek(),
+ )
+ .await
+ .and_then(|val| val.try_into_optionaloperation())
+ })
+ .await?,
+ updated_by: item.updated_by,
+ version: item.version,
+ })
+ }
+ .await
+ .change_context(ValidationError::InvalidValue {
+ message: "Failed while decrypting payment method data".to_string(),
+ })
+ }
+
+ async fn construct_new(self) -> CustomResult<Self::NewDstType, ValidationError> {
+ Ok(Self::NewDstType {
+ customer_id: self.customer_id,
+ merchant_id: self.merchant_id,
+ payment_method_id: self.payment_method_id,
+ accepted_currency: self.accepted_currency,
+ scheme: self.scheme,
+ token: self.token,
+ cardholder_name: self.cardholder_name,
+ issuer_name: self.issuer_name,
+ issuer_country: self.issuer_country,
+ payer_country: self.payer_country,
+ is_stored: self.is_stored,
+ swift_code: self.swift_code,
+ direct_debit_token: self.direct_debit_token,
+ created_at: self.created_at,
+ last_modified: self.last_modified,
+ payment_method: self.payment_method,
+ payment_method_type: self.payment_method_type,
+ payment_method_issuer: self.payment_method_issuer,
+ payment_method_issuer_code: self.payment_method_issuer_code,
+ metadata: self.metadata,
+ payment_method_data: self.payment_method_data.map(|val| val.into()),
+ locker_id: self.locker_id,
+ last_used_at: self.last_used_at,
+ connector_mandate_details: self.connector_mandate_details,
+ customer_acceptance: self.customer_acceptance,
+ status: self.status,
+ network_transaction_id: self.network_transaction_id,
+ client_secret: self.client_secret,
+ payment_method_billing_address: self
+ .payment_method_billing_address
+ .map(|val| val.into()),
+ updated_by: self.updated_by,
+ version: self.version,
+ })
+ }
+}
+
+#[cfg(all(feature = "v2", feature = "payment_methods_v2"))]
+#[async_trait::async_trait]
+impl super::behaviour::Conversion for PaymentMethod {
+ type DstType = diesel_models::payment_method::PaymentMethod;
+ type NewDstType = diesel_models::payment_method::PaymentMethodNew;
+ async fn convert(self) -> CustomResult<Self::DstType, ValidationError> {
+ Ok(Self::DstType {
+ customer_id: self.customer_id,
+ merchant_id: self.merchant_id,
+ id: self.id,
+ created_at: self.created_at,
+ last_modified: self.last_modified,
+ payment_method: self.payment_method,
+ payment_method_type: self.payment_method_type,
+ metadata: self.metadata,
+ payment_method_data: self.payment_method_data.map(|val| val.into()),
+ locker_id: self.locker_id,
+ last_used_at: self.last_used_at,
+ connector_mandate_details: self.connector_mandate_details,
+ customer_acceptance: self.customer_acceptance,
+ status: self.status,
+ network_transaction_id: self.network_transaction_id,
+ client_secret: self.client_secret,
+ payment_method_billing_address: self
+ .payment_method_billing_address
+ .map(|val| val.into()),
+ updated_by: self.updated_by,
+ locker_fingerprint_id: self.locker_fingerprint_id,
+ version: self.version,
+ })
+ }
+
+ async fn convert_back(
+ state: &keymanager::KeyManagerState,
+ item: Self::DstType,
+ key: &Secret<Vec<u8>>,
+ key_manager_identifier: keymanager::Identifier,
+ ) -> CustomResult<Self, ValidationError>
+ where
+ Self: Sized,
+ {
+ async {
+ Ok::<Self, error_stack::Report<common_utils::errors::CryptoError>>(Self {
+ customer_id: item.customer_id,
+ merchant_id: item.merchant_id,
+ id: item.id,
+ created_at: item.created_at,
+ last_modified: item.last_modified,
+ payment_method: item.payment_method,
+ payment_method_type: item.payment_method_type,
+ metadata: item.metadata,
+ payment_method_data: item
+ .payment_method_data
+ .async_lift(|inner| async {
+ crypto_operation(
+ state,
+ type_name!(Self::DstType),
+ CryptoOperation::DecryptOptional(inner),
+ key_manager_identifier.clone(),
+ key.peek(),
+ )
+ .await
+ .and_then(|val| val.try_into_optionaloperation())
+ })
+ .await?,
+ locker_id: item.locker_id,
+ last_used_at: item.last_used_at,
+ connector_mandate_details: item.connector_mandate_details,
+ customer_acceptance: item.customer_acceptance,
+ status: item.status,
+ network_transaction_id: item.network_transaction_id,
+ client_secret: item.client_secret,
+ payment_method_billing_address: item
+ .payment_method_billing_address
+ .async_lift(|inner| async {
+ crypto_operation(
+ state,
+ type_name!(Self::DstType),
+ CryptoOperation::DecryptOptional(inner),
+ key_manager_identifier.clone(),
+ key.peek(),
+ )
+ .await
+ .and_then(|val| val.try_into_optionaloperation())
+ })
+ .await?,
+ updated_by: item.updated_by,
+ locker_fingerprint_id: item.locker_fingerprint_id,
+ version: item.version,
+ })
+ }
+ .await
+ .change_context(ValidationError::InvalidValue {
+ message: "Failed while decrypting payment method data".to_string(),
+ })
+ }
+
+ async fn construct_new(self) -> CustomResult<Self::NewDstType, ValidationError> {
+ Ok(Self::NewDstType {
+ customer_id: self.customer_id,
+ merchant_id: self.merchant_id,
+ id: self.id,
+ created_at: self.created_at,
+ last_modified: self.last_modified,
+ payment_method: self.payment_method,
+ payment_method_type: self.payment_method_type,
+ metadata: self.metadata,
+ payment_method_data: self.payment_method_data.map(|val| val.into()),
+ locker_id: self.locker_id,
+ last_used_at: self.last_used_at,
+ connector_mandate_details: self.connector_mandate_details,
+ customer_acceptance: self.customer_acceptance,
+ status: self.status,
+ network_transaction_id: self.network_transaction_id,
+ client_secret: self.client_secret,
+ payment_method_billing_address: self
+ .payment_method_billing_address
+ .map(|val| val.into()),
+ updated_by: self.updated_by,
+ locker_fingerprint_id: self.locker_fingerprint_id,
+ version: self.version,
+ })
+ }
+}
diff --git a/crates/router/src/core/customers.rs b/crates/router/src/core/customers.rs
index a38078b5a2b..8de8a42763a 100644
--- a/crates/router/src/core/customers.rs
+++ b/crates/router/src/core/customers.rs
@@ -532,7 +532,11 @@ pub async fn list_customers(
Ok(services::ApplicationResponse::Json(customers))
}
-#[cfg(all(any(feature = "v1", feature = "v2"), not(feature = "customer_v2")))]
+#[cfg(all(
+ any(feature = "v1", feature = "v2"),
+ not(feature = "customer_v2"),
+ not(feature = "payment_methods_v2")
+))]
#[instrument(skip_all)]
pub async fn delete_customer(
state: SessionState,
@@ -566,6 +570,8 @@ pub async fn delete_customer(
match db
.find_payment_method_by_customer_id_merchant_id_list(
+ key_manager_state,
+ &key_store,
&req.customer_id,
merchant_account.get_id(),
None,
@@ -586,6 +592,8 @@ pub async fn delete_customer(
.switch()?;
}
db.delete_payment_method_by_merchant_id_payment_method_id(
+ key_manager_state,
+ &key_store,
merchant_account.get_id(),
&pm.payment_method_id,
)
diff --git a/crates/router/src/core/locker_migration.rs b/crates/router/src/core/locker_migration.rs
index 107586ee26d..8fd4b10ed3f 100644
--- a/crates/router/src/core/locker_migration.rs
+++ b/crates/router/src/core/locker_migration.rs
@@ -10,7 +10,6 @@ use common_utils::{errors::CustomResult, id_type};
not(feature = "payment_methods_v2")
))]
use diesel_models::enums as storage_enums;
-use diesel_models::PaymentMethod;
#[cfg(all(any(feature = "v1", feature = "v2"), not(feature = "customer_v2")))]
use error_stack::FutureExt;
use error_stack::ResultExt;
@@ -36,7 +35,11 @@ use crate::services::logger;
use crate::types::api;
use crate::{errors, routes::SessionState, services, types::domain};
-#[cfg(all(feature = "v2", feature = "customer_v2"))]
+#[cfg(all(
+ feature = "v2",
+ feature = "customer_v2",
+ feature = "payment_methods_v2"
+))]
pub async fn rust_locker_migration(
_state: SessionState,
_merchant_id: &id_type::MerchantId,
@@ -44,7 +47,11 @@ pub async fn rust_locker_migration(
todo!()
}
-#[cfg(all(any(feature = "v1", feature = "v2"), not(feature = "customer_v2")))]
+#[cfg(all(
+ any(feature = "v1", feature = "v2"),
+ not(feature = "customer_v2"),
+ not(feature = "payment_methods_v2")
+))]
pub async fn rust_locker_migration(
state: SessionState,
merchant_id: &id_type::MerchantId,
@@ -86,6 +93,8 @@ pub async fn rust_locker_migration(
for customer in domain_customers {
let result = db
.find_payment_method_by_customer_id_merchant_id_list(
+ key_manager_state,
+ &key_store,
&customer.customer_id,
merchant_id,
None,
@@ -122,7 +131,7 @@ pub async fn rust_locker_migration(
))]
pub async fn call_to_locker(
state: &SessionState,
- payment_methods: Vec<PaymentMethod>,
+ payment_methods: Vec<domain::PaymentMethod>,
customer_id: &id_type::CustomerId,
merchant_id: &id_type::MerchantId,
merchant_account: &domain::MerchantAccount,
@@ -220,7 +229,7 @@ pub async fn call_to_locker(
#[cfg(all(feature = "v2", feature = "payment_methods_v2"))]
pub async fn call_to_locker(
_state: &SessionState,
- _payment_methods: Vec<PaymentMethod>,
+ _payment_methods: Vec<domain::PaymentMethod>,
_customer_id: &id_type::CustomerId,
_merchant_id: &id_type::MerchantId,
_merchant_account: &domain::MerchantAccount,
diff --git a/crates/router/src/core/mandate/helpers.rs b/crates/router/src/core/mandate/helpers.rs
index e5fa762aeb0..96f00a0d20e 100644
--- a/crates/router/src/core/mandate/helpers.rs
+++ b/crates/router/src/core/mandate/helpers.rs
@@ -90,5 +90,5 @@ pub struct MandateGenericData {
pub recurring_mandate_payment_data:
Option<hyperswitch_domain_models::router_data::RecurringMandatePaymentData>,
pub mandate_connector: Option<payments::MandateConnectorDetails>,
- pub payment_method_info: Option<diesel_models::PaymentMethod>,
+ pub payment_method_info: Option<domain::PaymentMethod>,
}
diff --git a/crates/router/src/core/payment_methods.rs b/crates/router/src/core/payment_methods.rs
index fa030656528..88624cfd092 100644
--- a/crates/router/src/core/payment_methods.rs
+++ b/crates/router/src/core/payment_methods.rs
@@ -400,7 +400,7 @@ fn generate_task_id_for_payment_method_status_update_workflow(
pub async fn add_payment_method_status_update_task(
db: &dyn StorageInterface,
- payment_method: &diesel_models::PaymentMethod,
+ payment_method: &domain::PaymentMethod,
prev_status: enums::PaymentMethodStatus,
curr_status: enums::PaymentMethodStatus,
merchant_id: &common_utils::id_type::MerchantId,
@@ -410,7 +410,7 @@ pub async fn add_payment_method_status_update_task(
created_at.saturating_add(Duration::seconds(consts::DEFAULT_SESSION_EXPIRY));
let tracking_data = storage::PaymentMethodStatusTrackingData {
- payment_method_id: payment_method.payment_method_id.clone(),
+ payment_method_id: payment_method.get_id().clone(),
prev_status,
curr_status,
merchant_id: merchant_id.to_owned(),
@@ -421,7 +421,7 @@ pub async fn add_payment_method_status_update_task(
let tag = [PAYMENT_METHOD_STATUS_TAG];
let process_tracker_id = generate_task_id_for_payment_method_status_update_workflow(
- payment_method.payment_method_id.as_str(),
+ payment_method.get_id().as_str(),
&runner,
task,
);
@@ -443,7 +443,7 @@ pub async fn add_payment_method_status_update_task(
.attach_printable_lazy(|| {
format!(
"Failed while inserting PAYMENT_METHOD_STATUS_UPDATE reminder to process_tracker for payment_method_id: {}",
- payment_method.payment_method_id.clone()
+ payment_method.get_id().clone()
)
})?;
diff --git a/crates/router/src/core/payment_methods/cards.rs b/crates/router/src/core/payment_methods/cards.rs
index f459210be7a..4fd3fc00089 100644
--- a/crates/router/src/core/payment_methods/cards.rs
+++ b/crates/router/src/core/payment_methods/cards.rs
@@ -26,7 +26,7 @@ use api_models::{
use common_enums::{enums::MerchantStorageScheme, ConnectorType};
use common_utils::{
consts,
- crypto::Encryptable,
+ crypto::{self, Encryptable},
encryption::Encryption,
ext_traits::{AsyncExt, Encode, StringExt, ValueExt},
generate_id, id_type, type_name,
@@ -123,15 +123,15 @@ pub async fn create_payment_method(
merchant_id: &id_type::MerchantId,
pm_metadata: Option<serde_json::Value>,
customer_acceptance: Option<serde_json::Value>,
- payment_method_data: Option<Encryption>,
+ payment_method_data: crypto::OptionalEncryptableValue,
key_store: &domain::MerchantKeyStore,
connector_mandate_details: Option<serde_json::Value>,
status: Option<enums::PaymentMethodStatus>,
network_transaction_id: Option<String>,
storage_scheme: MerchantStorageScheme,
- payment_method_billing_address: Option<Encryption>,
+ payment_method_billing_address: crypto::OptionalEncryptableValue,
card_scheme: Option<String>,
-) -> errors::CustomResult<storage::PaymentMethod, errors::ApiErrorResponse> {
+) -> errors::CustomResult<domain::PaymentMethod, errors::ApiErrorResponse> {
let db = &*state.store;
let customer = db
.find_customer_by_customer_id_merchant_id(
@@ -153,7 +153,9 @@ pub async fn create_payment_method(
let response = db
.insert_payment_method(
- storage::PaymentMethodNew {
+ &state.into(),
+ key_store,
+ domain::PaymentMethod {
customer_id: customer_id.to_owned(),
merchant_id: merchant_id.to_owned(),
payment_method_id: payment_method_id.to_string(),
@@ -184,6 +186,7 @@ pub async fn create_payment_method(
last_used_at: current_time,
payment_method_billing_address,
updated_by: None,
+ version: domain::consts::API_VERSION,
},
storage_scheme,
)
@@ -230,7 +233,7 @@ pub async fn create_payment_method(
_storage_scheme: MerchantStorageScheme,
_payment_method_billing_address: Option<Encryption>,
_card_scheme: Option<String>,
-) -> errors::CustomResult<storage::PaymentMethod, errors::ApiErrorResponse> {
+) -> errors::CustomResult<domain::PaymentMethod, errors::ApiErrorResponse> {
todo!()
}
@@ -279,7 +282,6 @@ pub fn store_default_payment_method(
) {
todo!()
}
-
#[cfg(all(
any(feature = "v1", feature = "v2"),
not(feature = "payment_methods_v2")
@@ -292,13 +294,19 @@ pub async fn get_or_insert_payment_method(
merchant_account: &domain::MerchantAccount,
customer_id: &id_type::CustomerId,
key_store: &domain::MerchantKeyStore,
-) -> errors::RouterResult<diesel_models::PaymentMethod> {
+) -> errors::RouterResult<domain::PaymentMethod> {
let mut payment_method_id = resp.payment_method_id.clone();
let mut locker_id = None;
let db = &*state.store;
+ let key_manager_state = &(state.into());
let payment_method = {
let existing_pm_by_pmid = db
- .find_payment_method(&payment_method_id, merchant_account.storage_scheme)
+ .find_payment_method(
+ key_manager_state,
+ key_store,
+ &payment_method_id,
+ merchant_account.storage_scheme,
+ )
.await;
if let Err(err) = existing_pm_by_pmid {
@@ -306,13 +314,15 @@ pub async fn get_or_insert_payment_method(
locker_id = Some(payment_method_id.clone());
let existing_pm_by_locker_id = db
.find_payment_method_by_locker_id(
+ key_manager_state,
+ key_store,
&payment_method_id,
merchant_account.storage_scheme,
)
.await;
match &existing_pm_by_locker_id {
- Ok(pm) => payment_method_id.clone_from(&pm.payment_method_id),
+ Ok(pm) => payment_method_id.clone_from(pm.get_id()),
Err(_) => payment_method_id = generate_id(consts::ID_LENGTH, "pm"),
};
existing_pm_by_locker_id
@@ -363,7 +373,7 @@ pub async fn get_or_insert_payment_method(
_merchant_account: &domain::MerchantAccount,
_customer_id: &id_type::CustomerId,
_key_store: &domain::MerchantKeyStore,
-) -> errors::RouterResult<diesel_models::PaymentMethod> {
+) -> errors::RouterResult<domain::PaymentMethod> {
todo!()
}
@@ -706,7 +716,9 @@ pub async fn skip_locker_call_and_migrate_payment_method(
let response = db
.insert_payment_method(
- storage::PaymentMethodNew {
+ &(&state).into(),
+ key_store,
+ domain::PaymentMethod {
customer_id: customer_id.to_owned(),
merchant_id: merchant_id.to_owned(),
payment_method_id: payment_method_id.to_string(),
@@ -737,6 +749,7 @@ pub async fn skip_locker_call_and_migrate_payment_method(
last_used_at: current_time,
payment_method_billing_address: payment_method_billing_address.map(Into::into),
updated_by: None,
+ version: domain::consts::API_VERSION,
},
merchant_account.storage_scheme,
)
@@ -895,7 +908,7 @@ pub async fn get_client_secret_or_add_payment_method(
#[instrument(skip_all)]
pub fn authenticate_pm_client_secret_and_check_expiry(
req_client_secret: &String,
- payment_method: &diesel_models::PaymentMethod,
+ payment_method: &domain::PaymentMethod,
) -> errors::CustomResult<bool, errors::ApiErrorResponse> {
let stored_client_secret = payment_method
.client_secret
@@ -945,7 +958,12 @@ pub async fn add_payment_method_data(
.clone()
.get_required_value("client_secret")?;
let payment_method = db
- .find_payment_method(pm_id.as_str(), merchant_account.storage_scheme)
+ .find_payment_method(
+ &((&state).into()),
+ &key_store,
+ pm_id.as_str(),
+ merchant_account.storage_scheme,
+ )
.await
.change_context(errors::ApiErrorResponse::PaymentMethodNotFound)
.attach_printable("Unable to find payment method")?;
@@ -996,6 +1014,8 @@ pub async fn add_payment_method_data(
};
db.update_payment_method(
+ &((&state).into()),
+ &key_store,
payment_method,
pm_update,
merchant_account.storage_scheme,
@@ -1064,6 +1084,8 @@ pub async fn add_payment_method_data(
};
db.update_payment_method(
+ &((&state).into()),
+ &key_store,
payment_method,
pm_update,
merchant_account.storage_scheme,
@@ -1099,6 +1121,8 @@ pub async fn add_payment_method_data(
};
db.update_payment_method(
+ &((&state).into()),
+ &key_store,
payment_method,
pm_update,
merchant_account.storage_scheme,
@@ -1264,6 +1288,8 @@ pub async fn add_payment_method(
if let Err(err) = add_card_resp {
logger::error!(vault_err=?err);
db.delete_payment_method_by_merchant_id_payment_method_id(
+ &(state.into()),
+ key_store,
merchant_id,
&resp.payment_method_id,
)
@@ -1275,8 +1301,7 @@ pub async fn add_payment_method(
};
let existing_pm_data =
- get_card_details_without_locker_fallback(&existing_pm, state, key_store)
- .await?;
+ get_card_details_without_locker_fallback(&existing_pm, state).await?;
let updated_card = Some(api::CardDetailFromLocker {
scheme: existing_pm.scheme.clone(),
@@ -1318,6 +1343,8 @@ pub async fn add_payment_method(
};
db.update_payment_method(
+ &(state.into()),
+ key_store,
existing_pm,
pm_update,
merchant_account.storage_scheme,
@@ -1394,14 +1421,14 @@ pub async fn insert_payment_method(
connector_mandate_details: Option<serde_json::Value>,
network_transaction_id: Option<String>,
storage_scheme: MerchantStorageScheme,
- payment_method_billing_address: Option<Encryption>,
-) -> errors::RouterResult<diesel_models::PaymentMethod> {
+ payment_method_billing_address: crypto::OptionalEncryptableValue,
+) -> errors::RouterResult<domain::PaymentMethod> {
let pm_card_details = resp
.card
.clone()
.map(|card| PaymentMethodsData::Card(CardDetailsPaymentMethod::from(card.clone())));
- let pm_data_encrypted: Option<Encryptable<Secret<serde_json::Value>>> = pm_card_details
+ let pm_data_encrypted: crypto::OptionalEncryptableValue = pm_card_details
.clone()
.async_map(|pm_card| create_encrypted_data(state, key_store, pm_card))
.await
@@ -1418,7 +1445,7 @@ pub async fn insert_payment_method(
merchant_id,
pm_metadata,
customer_acceptance,
- pm_data_encrypted.map(Into::into),
+ pm_data_encrypted,
key_store,
connector_mandate_details,
None,
@@ -1449,7 +1476,7 @@ pub async fn insert_payment_method(
network_transaction_id: Option<String>,
storage_scheme: MerchantStorageScheme,
payment_method_billing_address: Option<Encryption>,
-) -> errors::RouterResult<diesel_models::PaymentMethod> {
+) -> errors::RouterResult<domain::PaymentMethod> {
let pm_card_details = match &resp.payment_method_data {
Some(api::PaymentMethodResponseData::Card(card_data)) => Some(PaymentMethodsData::Card(
CardDetailsPaymentMethod::from(card_data.clone()),
@@ -1503,7 +1530,12 @@ pub async fn update_customer_payment_method(
let db = state.store.as_ref();
let pm = db
- .find_payment_method(payment_method_id, merchant_account.storage_scheme)
+ .find_payment_method(
+ &((&state).into()),
+ &key_store,
+ payment_method_id,
+ merchant_account.storage_scheme,
+ )
.await
.to_not_found_response(errors::ApiErrorResponse::PaymentMethodNotFound)?;
@@ -1528,36 +1560,28 @@ pub async fn update_customer_payment_method(
}
// Fetch the existing payment method data from db
- let existing_card_data = domain::types::crypto_operation::<
- serde_json::Value,
- masking::WithType,
- >(
- &(&state).into(),
- type_name!(payment_method::PaymentMethod),
- domain::types::CryptoOperation::DecryptOptional(pm.payment_method_data.clone()),
- Identifier::Merchant(key_store.merchant_id.clone()),
- key_store.key.get_inner().peek(),
- )
- .await
- .and_then(|val| val.try_into_optionaloperation())
- .change_context(errors::ApiErrorResponse::InternalServerError)
- .attach_printable("Failed to decrypt card details")?
- .map(|x| x.into_inner().expose())
- .map(
- |value| -> Result<PaymentMethodsData, error_stack::Report<errors::ApiErrorResponse>> {
- value
- .parse_value::<PaymentMethodsData>("PaymentMethodsData")
- .change_context(errors::ApiErrorResponse::InternalServerError)
- .attach_printable("Failed to deserialize payment methods data")
- },
- )
- .transpose()?
- .and_then(|pmd| match pmd {
- PaymentMethodsData::Card(crd) => Some(api::CardDetailFromLocker::from(crd)),
- _ => None,
- })
- .ok_or(errors::ApiErrorResponse::InternalServerError)
- .attach_printable("Failed to obtain decrypted card object from db")?;
+ let existing_card_data =
+ pm.payment_method_data
+ .clone()
+ .map(|x| x.into_inner().expose())
+ .map(
+ |value| -> Result<
+ PaymentMethodsData,
+ error_stack::Report<errors::ApiErrorResponse>,
+ > {
+ value
+ .parse_value::<PaymentMethodsData>("PaymentMethodsData")
+ .change_context(errors::ApiErrorResponse::InternalServerError)
+ .attach_printable("Failed to deserialize payment methods data")
+ },
+ )
+ .transpose()?
+ .and_then(|pmd| match pmd {
+ PaymentMethodsData::Card(crd) => Some(api::CardDetailFromLocker::from(crd)),
+ _ => None,
+ })
+ .ok_or(errors::ApiErrorResponse::InternalServerError)
+ .attach_printable("Failed to obtain decrypted card object from db")?;
let is_card_updation_required =
validate_payment_method_update(card_update.clone(), existing_card_data.clone());
@@ -1675,10 +1699,16 @@ pub async fn update_customer_payment_method(
.payment_method_id
.clone_from(&pm.payment_method_id);
- db.update_payment_method(pm, pm_update, merchant_account.storage_scheme)
- .await
- .change_context(errors::ApiErrorResponse::InternalServerError)
- .attach_printable("Failed to update payment method in db")?;
+ db.update_payment_method(
+ &((&state).into()),
+ &key_store,
+ pm,
+ pm_update,
+ merchant_account.storage_scheme,
+ )
+ .await
+ .change_context(errors::ApiErrorResponse::InternalServerError)
+ .attach_printable("Failed to update payment method in db")?;
add_card_resp
} else {
@@ -2165,9 +2195,15 @@ pub async fn call_to_locker_hs(
Ok(stored_card)
}
+#[cfg(all(
+ any(feature = "v1", feature = "v2"),
+ not(feature = "payment_methods_v2")
+))]
pub async fn update_payment_method_metadata_and_last_used(
+ state: &routes::SessionState,
+ key_store: &domain::MerchantKeyStore,
db: &dyn db::StorageInterface,
- pm: payment_method::PaymentMethod,
+ pm: domain::PaymentMethod,
pm_metadata: Option<serde_json::Value>,
storage_scheme: MerchantStorageScheme,
) -> errors::CustomResult<(), errors::VaultError> {
@@ -2175,15 +2211,36 @@ pub async fn update_payment_method_metadata_and_last_used(
metadata: pm_metadata,
last_used_at: common_utils::date_time::now(),
};
- db.update_payment_method(pm, pm_update, storage_scheme)
+ db.update_payment_method(&(state.into()), key_store, pm, pm_update, storage_scheme)
+ .await
+ .change_context(errors::VaultError::UpdateInPaymentMethodDataTableFailed)?;
+ Ok(())
+}
+
+#[cfg(all(feature = "v2", feature = "payment_methods_v2"))]
+pub async fn update_payment_method_metadata_and_last_used(
+ state: &routes::SessionState,
+ key_store: &domain::MerchantKeyStore,
+ db: &dyn db::StorageInterface,
+ pm: domain::PaymentMethod,
+ pm_metadata: Option<serde_json::Value>,
+ storage_scheme: MerchantStorageScheme,
+) -> errors::CustomResult<(), errors::VaultError> {
+ let pm_update = payment_method::PaymentMethodUpdate::MetadataUpdateAndLastUsed {
+ metadata: pm_metadata.map(Secret::new),
+ last_used_at: common_utils::date_time::now(),
+ };
+ db.update_payment_method(&(state.into()), key_store, pm, pm_update, storage_scheme)
.await
.change_context(errors::VaultError::UpdateInPaymentMethodDataTableFailed)?;
Ok(())
}
pub async fn update_payment_method_and_last_used(
+ state: &routes::SessionState,
+ key_store: &domain::MerchantKeyStore,
db: &dyn db::StorageInterface,
- pm: payment_method::PaymentMethod,
+ pm: domain::PaymentMethod,
payment_method_update: Option<Encryption>,
storage_scheme: MerchantStorageScheme,
) -> errors::CustomResult<(), errors::VaultError> {
@@ -2191,15 +2248,40 @@ pub async fn update_payment_method_and_last_used(
payment_method_data: payment_method_update,
last_used_at: common_utils::date_time::now(),
};
- db.update_payment_method(pm, pm_update, storage_scheme)
+ db.update_payment_method(&(state.into()), key_store, pm, pm_update, storage_scheme)
+ .await
+ .change_context(errors::VaultError::UpdateInPaymentMethodDataTableFailed)?;
+ Ok(())
+}
+
+#[cfg(all(feature = "v2", feature = "payment_methods_v2"))]
+pub async fn update_payment_method_connector_mandate_details(
+ state: &routes::SessionState,
+ key_store: &domain::MerchantKeyStore,
+ db: &dyn db::StorageInterface,
+ pm: domain::PaymentMethod,
+ connector_mandate_details: Option<serde_json::Value>,
+ storage_scheme: MerchantStorageScheme,
+) -> errors::CustomResult<(), errors::VaultError> {
+ let pm_update = payment_method::PaymentMethodUpdate::ConnectorMandateDetailsUpdate {
+ connector_mandate_details: connector_mandate_details.map(Secret::new),
+ };
+
+ db.update_payment_method(&(state.into()), key_store, pm, pm_update, storage_scheme)
.await
.change_context(errors::VaultError::UpdateInPaymentMethodDataTableFailed)?;
Ok(())
}
+#[cfg(all(
+ any(feature = "v1", feature = "v2"),
+ not(feature = "payment_methods_v2")
+))]
pub async fn update_payment_method_connector_mandate_details(
+ state: &routes::SessionState,
+ key_store: &domain::MerchantKeyStore,
db: &dyn db::StorageInterface,
- pm: payment_method::PaymentMethod,
+ pm: domain::PaymentMethod,
connector_mandate_details: Option<serde_json::Value>,
storage_scheme: MerchantStorageScheme,
) -> errors::CustomResult<(), errors::VaultError> {
@@ -2207,7 +2289,7 @@ pub async fn update_payment_method_connector_mandate_details(
connector_mandate_details,
};
- db.update_payment_method(pm, pm_update, storage_scheme)
+ db.update_payment_method(&(state.into()), key_store, pm, pm_update, storage_scheme)
.await
.change_context(errors::VaultError::UpdateInPaymentMethodDataTableFailed)?;
Ok(())
@@ -2558,7 +2640,11 @@ fn get_val(str: String, val: &serde_json::Value) -> Option<String> {
.and_then(|v| v.as_str())
.map(|s| s.to_string())
}
-#[cfg(all(feature = "v2", feature = "customer_v2"))]
+#[cfg(all(
+ feature = "v2",
+ feature = "customer_v2",
+ feature = "payment_methods_v2"
+))]
pub async fn list_payment_methods(
_state: routes::SessionState,
_merchant_account: domain::MerchantAccount,
@@ -2568,7 +2654,11 @@ pub async fn list_payment_methods(
todo!()
}
-#[cfg(all(any(feature = "v1", feature = "v2"), not(feature = "customer_v2")))]
+#[cfg(all(
+ any(feature = "v1", feature = "v2"),
+ not(feature = "customer_v2"),
+ not(feature = "payment_methods_v2")
+))]
pub async fn list_payment_methods(
state: routes::SessionState,
merchant_account: domain::MerchantAccount,
@@ -2580,7 +2670,14 @@ pub async fn list_payment_methods(
let key_manager_state = &(&state).into();
let payment_intent = if let Some(cs) = &req.client_secret {
if cs.starts_with("pm_") {
- validate_payment_method_and_client_secret(cs, db, &merchant_account).await?;
+ validate_payment_method_and_client_secret(
+ &state,
+ cs,
+ db,
+ &merchant_account,
+ &key_store,
+ )
+ .await?;
None
} else {
helpers::verify_payment_intent_time_and_client_secret(
@@ -2830,6 +2927,8 @@ pub async fn list_payment_methods(
if wallet_pm_exists {
match db
.find_payment_method_by_customer_id_merchant_id_list(
+ &((&state).into()),
+ &key_store,
&customer.customer_id,
merchant_account.get_id(),
None,
@@ -3626,9 +3725,11 @@ fn should_collect_shipping_or_billing_details_from_wallet_connector(
}
async fn validate_payment_method_and_client_secret(
+ state: &routes::SessionState,
cs: &String,
db: &dyn db::StorageInterface,
merchant_account: &domain::MerchantAccount,
+ key_store: &domain::MerchantKeyStore,
) -> Result<(), error_stack::Report<errors::ApiErrorResponse>> {
let pm_vec = cs.split("_secret").collect::<Vec<&str>>();
let pm_id = pm_vec
@@ -3638,7 +3739,12 @@ async fn validate_payment_method_and_client_secret(
})?;
let payment_method = db
- .find_payment_method(pm_id, merchant_account.storage_scheme)
+ .find_payment_method(
+ &(state.into()),
+ key_store,
+ pm_id,
+ merchant_account.storage_scheme,
+ )
.await
.change_context(errors::ApiErrorResponse::PaymentMethodNotFound)
.attach_printable("Unable to find payment method")?;
@@ -4216,6 +4322,8 @@ pub async fn list_customer_payment_method(
let resp = db
.find_payment_method_by_customer_id_merchant_id_status(
+ &(state.into()),
+ &key_store,
customer_id,
merchant_account.get_id(),
common_enums::PaymentMethodStatus::Active,
@@ -4275,23 +4383,22 @@ pub async fn list_customer_payment_method(
// Retrieve the masked bank details to be sent as a response
let bank_details = if payment_method == enums::PaymentMethod::BankDebit {
- get_masked_bank_details(state, &pm, &key_store)
- .await
- .unwrap_or_else(|error| {
- logger::error!(?error);
- None
- })
+ get_masked_bank_details(&pm).await.unwrap_or_else(|error| {
+ logger::error!(?error);
+ None
+ })
} else {
None
};
- let payment_method_billing = decrypt_generic_data::<api_models::payments::Address>(
- state,
- pm.payment_method_billing_address,
- &key_store,
- )
- .await
- .attach_printable("unable to decrypt payment method billing address details")?;
+ let payment_method_billing = pm
+ .payment_method_billing_address
+ .clone()
+ .map(|decrypted_data| decrypted_data.into_inner().expose())
+ .map(|decrypted_value| decrypted_value.parse_value("payment method billing address"))
+ .transpose()
+ .change_context(errors::ApiErrorResponse::InternalServerError)
+ .attach_printable("unable to decrypt payment method billing address details")?;
let connector_mandate_details = pm
.connector_mandate_details
.clone()
@@ -4416,15 +4523,16 @@ pub async fn list_customer_payment_method(
async fn get_pm_list_context(
state: &routes::SessionState,
payment_method: &enums::PaymentMethod,
- key_store: &domain::MerchantKeyStore,
- pm: &diesel_models::PaymentMethod,
+ #[cfg(feature = "payouts")] key_store: &domain::MerchantKeyStore,
+ #[cfg(not(feature = "payouts"))] _key_store: &domain::MerchantKeyStore,
+ pm: &domain::PaymentMethod,
#[cfg(feature = "payouts")] parent_payment_method_token: Option<String>,
#[cfg(not(feature = "payouts"))] _parent_payment_method_token: Option<String>,
is_payment_associated: bool,
) -> Result<Option<PaymentMethodListContext>, error_stack::Report<errors::ApiErrorResponse>> {
let payment_method_retrieval_context = match payment_method {
enums::PaymentMethod::Card => {
- let card_details = get_card_details_with_locker_fallback(pm, state, key_store).await?;
+ let card_details = get_card_details_with_locker_fallback(pm, state).await?;
card_details.as_ref().map(|card| PaymentMethodListContext {
card_details: Some(card.clone()),
@@ -4432,9 +4540,9 @@ async fn get_pm_list_context(
bank_transfer_details: None,
hyperswitch_token_data: is_payment_associated.then_some(
PaymentTokenData::permanent_card(
- Some(pm.payment_method_id.clone()),
- pm.locker_id.clone().or(Some(pm.payment_method_id.clone())),
- pm.locker_id.clone().unwrap_or(pm.payment_method_id.clone()),
+ Some(pm.get_id().clone()),
+ pm.locker_id.clone().or(Some(pm.get_id().clone())),
+ pm.locker_id.clone().unwrap_or(pm.get_id().clone()),
),
),
})
@@ -4442,7 +4550,7 @@ async fn get_pm_list_context(
enums::PaymentMethod::BankDebit => {
// Retrieve the pm_auth connector details so that it can be tokenized
- let bank_account_token_data = get_bank_account_connector_details(state, pm, key_store)
+ let bank_account_token_data = get_bank_account_connector_details(pm)
.await
.unwrap_or_else(|err| {
logger::error!(error=?err);
@@ -4466,7 +4574,7 @@ async fn get_pm_list_context(
#[cfg(feature = "payouts")]
bank_transfer_details: None,
hyperswitch_token_data: is_payment_associated
- .then_some(PaymentTokenData::wallet_token(pm.payment_method_id.clone())),
+ .then_some(PaymentTokenData::wallet_token(pm.get_id().clone())),
}),
#[cfg(feature = "payouts")]
@@ -4479,7 +4587,7 @@ async fn get_pm_list_context(
parent_payment_method_token.as_ref(),
&pm.customer_id,
&pm.merchant_id,
- pm.locker_id.as_ref().unwrap_or(&pm.payment_method_id),
+ pm.locker_id.as_ref().unwrap_or(pm.get_id()),
)
.await?,
),
@@ -4714,6 +4822,8 @@ pub async fn list_customer_payment_method(
let saved_payment_methods = db
.find_payment_method_by_customer_id_merchant_id_status(
+ key_manager_state,
+ &key_store,
customer_id,
merchant_account.get_id(),
common_enums::PaymentMethodStatus::Active,
@@ -4794,7 +4904,7 @@ async fn generate_saved_pm_response(
pm_list_context: (
PaymentMethodListContext,
Option<String>,
- diesel_models::PaymentMethod,
+ domain::PaymentMethod,
),
customer: &domain::Customer,
payment_info: Option<&SavedPMLPaymentsInfo>,
@@ -4803,23 +4913,22 @@ async fn generate_saved_pm_response(
let payment_method = pm.payment_method.get_required_value("payment_method")?;
let bank_details = if payment_method == enums::PaymentMethod::BankDebit {
- get_masked_bank_details(state, &pm, key_store)
- .await
- .unwrap_or_else(|err| {
- logger::error!(error=?err);
- None
- })
+ get_masked_bank_details(&pm).await.unwrap_or_else(|err| {
+ logger::error!(error=?err);
+ None
+ })
} else {
None
};
- let payment_method_billing = decrypt_generic_data::<api_models::payments::Address>(
- state,
- pm.payment_method_billing_address,
- key_store,
- )
- .await
- .attach_printable("unable to decrypt payment method billing address details")?;
+ let payment_method_billing = pm
+ .payment_method_billing_address
+ .clone()
+ .map(|decrypted_data| decrypted_data.into_inner().expose())
+ .map(|decrypted_value| decrypted_value.parse_value("payment_method_billing_address"))
+ .transpose()
+ .change_context(errors::ApiErrorResponse::InternalServerError)
+ .attach_printable("unable to parse payment method billing address details")?;
let connector_mandate_details = pm
.connector_mandate_details
@@ -4875,12 +4984,12 @@ async fn generate_saved_pm_response(
let pma = api::CustomerPaymentMethod {
payment_token: parent_payment_method_token.clone(),
- payment_method_id: pm.payment_method_id.clone(),
- customer_id: pm.customer_id,
+ payment_method_id: pm.get_id().clone(),
+ customer_id: pm.customer_id.to_owned(),
payment_method,
payment_method_type: pm.payment_method_type,
payment_method_data: pmd,
- metadata: pm.metadata,
+ metadata: pm.metadata.clone(),
recurring_enabled: mca_enabled,
created: Some(pm.created_at),
bank: bank_details,
@@ -4889,7 +4998,7 @@ async fn generate_saved_pm_response(
&& !(off_session_payment_flag && pm.connector_mandate_details.is_some()),
last_used_at: Some(pm.last_used_at),
is_default: customer.default_payment_method_id.is_some()
- && customer.default_payment_method_id == Some(pm.payment_method_id),
+ && customer.default_payment_method_id.as_ref() == Some(pm.get_id()),
billing: payment_method_billing,
};
@@ -4983,31 +5092,18 @@ where
not(feature = "payment_methods_v2")
))]
pub async fn get_card_details_with_locker_fallback(
- pm: &payment_method::PaymentMethod,
+ pm: &domain::PaymentMethod,
state: &routes::SessionState,
- key_store: &domain::MerchantKeyStore,
) -> errors::RouterResult<Option<api::CardDetailFromLocker>> {
- let key = key_store.key.get_inner().peek();
- let identifier = Identifier::Merchant(key_store.merchant_id.clone());
- let card_decrypted = domain::types::crypto_operation::<serde_json::Value, masking::WithType>(
- &state.into(),
- type_name!(payment_method::PaymentMethod),
- domain::types::CryptoOperation::DecryptOptional(pm.payment_method_data.clone()),
- identifier,
- key,
- )
- .await
- .and_then(|val| val.try_into_optionaloperation())
- .change_context(errors::StorageError::DecryptionError)
- .attach_printable("unable to decrypt card details")
- .ok()
- .flatten()
- .map(|x| x.into_inner().expose())
- .and_then(|v| serde_json::from_value::<PaymentMethodsData>(v).ok())
- .and_then(|pmd| match pmd {
- PaymentMethodsData::Card(crd) => Some(api::CardDetailFromLocker::from(crd)),
- _ => None,
- });
+ let card_decrypted = pm
+ .payment_method_data
+ .clone()
+ .map(|x| x.into_inner().expose())
+ .and_then(|v| serde_json::from_value::<PaymentMethodsData>(v).ok())
+ .and_then(|pmd| match pmd {
+ PaymentMethodsData::Card(crd) => Some(api::CardDetailFromLocker::from(crd)),
+ _ => None,
+ });
Ok(if let Some(mut crd) = card_decrypted {
crd.scheme.clone_from(&pm.scheme);
@@ -5022,31 +5118,18 @@ pub async fn get_card_details_with_locker_fallback(
#[cfg(all(feature = "v2", feature = "payment_methods_v2"))]
pub async fn get_card_details_with_locker_fallback(
- pm: &payment_method::PaymentMethod,
+ pm: &domain::PaymentMethod,
state: &routes::SessionState,
- key_store: &domain::MerchantKeyStore,
) -> errors::RouterResult<Option<api::CardDetailFromLocker>> {
- let key = key_store.key.get_inner().peek();
- let identifier = Identifier::Merchant(key_store.merchant_id.clone());
- let card_decrypted = domain::types::crypto_operation::<serde_json::Value, masking::WithType>(
- &state.into(),
- type_name!(payment_method::PaymentMethod),
- domain::types::CryptoOperation::DecryptOptional(pm.payment_method_data.clone()),
- identifier,
- key,
- )
- .await
- .and_then(|val| val.try_into_optionaloperation())
- .change_context(errors::StorageError::DecryptionError)
- .attach_printable("unable to decrypt card details")
- .ok()
- .flatten()
- .map(|x| x.into_inner().expose())
- .and_then(|v| serde_json::from_value::<PaymentMethodsData>(v).ok())
- .and_then(|pmd| match pmd {
- PaymentMethodsData::Card(crd) => Some(api::CardDetailFromLocker::from(crd)),
- _ => None,
- });
+ let card_decrypted = pm
+ .payment_method_data
+ .clone()
+ .map(|x| x.into_inner().expose())
+ .and_then(|v| serde_json::from_value::<PaymentMethodsData>(v).ok())
+ .and_then(|pmd| match pmd {
+ PaymentMethodsData::Card(crd) => Some(api::CardDetailFromLocker::from(crd)),
+ _ => None,
+ });
Ok(if let Some(crd) = card_decrypted {
Some(crd)
@@ -5063,31 +5146,18 @@ pub async fn get_card_details_with_locker_fallback(
not(feature = "payment_methods_v2")
))]
pub async fn get_card_details_without_locker_fallback(
- pm: &payment_method::PaymentMethod,
+ pm: &domain::PaymentMethod,
state: &routes::SessionState,
- key_store: &domain::MerchantKeyStore,
) -> errors::RouterResult<api::CardDetailFromLocker> {
- let key = key_store.key.get_inner().peek();
- let identifier = Identifier::Merchant(key_store.merchant_id.clone());
- let card_decrypted = domain::types::crypto_operation::<serde_json::Value, masking::WithType>(
- &state.into(),
- type_name!(payment_method::PaymentMethod),
- domain::types::CryptoOperation::DecryptOptional(pm.payment_method_data.clone()),
- identifier,
- key,
- )
- .await
- .and_then(|val| val.try_into_optionaloperation())
- .change_context(errors::StorageError::DecryptionError)
- .attach_printable("unable to decrypt card details")
- .ok()
- .flatten()
- .map(|x| x.into_inner().expose())
- .and_then(|v| serde_json::from_value::<PaymentMethodsData>(v).ok())
- .and_then(|pmd| match pmd {
- PaymentMethodsData::Card(crd) => Some(api::CardDetailFromLocker::from(crd)),
- _ => None,
- });
+ let card_decrypted = pm
+ .payment_method_data
+ .clone()
+ .map(|x| x.into_inner().expose())
+ .and_then(|v| serde_json::from_value::<PaymentMethodsData>(v).ok())
+ .and_then(|pmd| match pmd {
+ PaymentMethodsData::Card(crd) => Some(api::CardDetailFromLocker::from(crd)),
+ _ => None,
+ });
Ok(if let Some(mut crd) = card_decrypted {
crd.scheme.clone_from(&pm.scheme);
@@ -5102,31 +5172,18 @@ pub async fn get_card_details_without_locker_fallback(
#[cfg(all(feature = "v2", feature = "payment_methods_v2"))]
pub async fn get_card_details_without_locker_fallback(
- pm: &payment_method::PaymentMethod,
+ pm: &domain::PaymentMethod,
state: &routes::SessionState,
- key_store: &domain::MerchantKeyStore,
) -> errors::RouterResult<api::CardDetailFromLocker> {
- let key = key_store.key.get_inner().peek();
- let identifier = Identifier::Merchant(key_store.merchant_id.clone());
- let card_decrypted = domain::types::crypto_operation::<serde_json::Value, masking::WithType>(
- &state.into(),
- type_name!(payment_method::PaymentMethod),
- domain::types::CryptoOperation::DecryptOptional(pm.payment_method_data.clone()),
- identifier,
- key,
- )
- .await
- .and_then(|val| val.try_into_optionaloperation())
- .change_context(errors::StorageError::DecryptionError)
- .attach_printable("unable to decrypt card details")
- .ok()
- .flatten()
- .map(|x| x.into_inner().expose())
- .and_then(|v| serde_json::from_value::<PaymentMethodsData>(v).ok())
- .and_then(|pmd| match pmd {
- PaymentMethodsData::Card(crd) => Some(api::CardDetailFromLocker::from(crd)),
- _ => None,
- });
+ let card_decrypted = pm
+ .payment_method_data
+ .clone()
+ .map(|x| x.into_inner().expose())
+ .and_then(|v| serde_json::from_value::<PaymentMethodsData>(v).ok())
+ .and_then(|pmd| match pmd {
+ PaymentMethodsData::Card(crd) => Some(api::CardDetailFromLocker::from(crd)),
+ _ => None,
+ });
Ok(if let Some(crd) = card_decrypted {
crd
} else {
@@ -5139,13 +5196,13 @@ pub async fn get_card_details_without_locker_fallback(
pub async fn get_card_details_from_locker(
state: &routes::SessionState,
- pm: &storage::PaymentMethod,
+ pm: &domain::PaymentMethod,
) -> errors::RouterResult<api::CardDetailFromLocker> {
let card = get_card_from_locker(
state,
&pm.customer_id,
&pm.merchant_id,
- pm.locker_id.as_ref().unwrap_or(&pm.payment_method_id),
+ pm.locker_id.as_ref().unwrap_or(pm.get_id()),
)
.await
.change_context(errors::ApiErrorResponse::InternalServerError)
@@ -5159,7 +5216,7 @@ pub async fn get_card_details_from_locker(
pub async fn get_lookup_key_from_locker(
state: &routes::SessionState,
payment_token: &str,
- pm: &storage::PaymentMethod,
+ pm: &domain::PaymentMethod,
merchant_key_store: &domain::MerchantKeyStore,
) -> errors::RouterResult<api::CardDetailFromLocker> {
let card_detail = get_card_details_from_locker(state, pm).await?;
@@ -5177,25 +5234,11 @@ pub async fn get_lookup_key_from_locker(
}
async fn get_masked_bank_details(
- state: &routes::SessionState,
- pm: &payment_method::PaymentMethod,
- key_store: &domain::MerchantKeyStore,
+ pm: &domain::PaymentMethod,
) -> errors::RouterResult<Option<MaskedBankDetails>> {
- let key = key_store.key.get_inner().peek();
- let identifier = Identifier::Merchant(key_store.merchant_id.clone());
- let payment_method_data =
- domain::types::crypto_operation::<serde_json::Value, masking::WithType>(
- &state.into(),
- type_name!(payment_method::PaymentMethod),
- domain::types::CryptoOperation::DecryptOptional(pm.payment_method_data.clone()),
- identifier,
- key,
- )
- .await
- .and_then(|val| val.try_into_optionaloperation())
- .change_context(errors::StorageError::DecryptionError)
- .change_context(errors::ApiErrorResponse::InternalServerError)
- .attach_printable("unable to decrypt bank details")?
+ let payment_method_data = pm
+ .payment_method_data
+ .clone()
.map(|x| x.into_inner().expose())
.map(
|v| -> Result<PaymentMethodsData, error_stack::Report<errors::ApiErrorResponse>> {
@@ -5220,25 +5263,11 @@ async fn get_masked_bank_details(
}
async fn get_bank_account_connector_details(
- state: &routes::SessionState,
- pm: &payment_method::PaymentMethod,
- key_store: &domain::MerchantKeyStore,
+ pm: &domain::PaymentMethod,
) -> errors::RouterResult<Option<BankAccountTokenData>> {
- let key = key_store.key.get_inner().peek();
- let identifier = Identifier::Merchant(key_store.merchant_id.clone());
- let payment_method_data =
- domain::types::crypto_operation::<serde_json::Value, masking::WithType>(
- &state.into(),
- type_name!(payment_method::PaymentMethod),
- domain::types::CryptoOperation::DecryptOptional(pm.payment_method_data.clone()),
- identifier,
- key,
- )
- .await
- .and_then(|val| val.try_into_optionaloperation())
- .change_context(errors::StorageError::DecryptionError)
- .change_context(errors::ApiErrorResponse::InternalServerError)
- .attach_printable("unable to decrypt bank details")?
+ let payment_method_data = pm
+ .payment_method_data
+ .clone()
.map(|x| x.into_inner().expose())
.map(
|v| -> Result<PaymentMethodsData, error_stack::Report<errors::ApiErrorResponse>> {
@@ -5322,7 +5351,12 @@ pub async fn set_default_payment_method(
.to_not_found_response(errors::ApiErrorResponse::CustomerNotFound)?;
// check for the presence of payment_method
let payment_method = db
- .find_payment_method(&payment_method_id, storage_scheme)
+ .find_payment_method(
+ &(state.into()),
+ &key_store,
+ &payment_method_id,
+ storage_scheme,
+ )
.await
.to_not_found_response(errors::ApiErrorResponse::PaymentMethodNotFound)?;
let pm = payment_method
@@ -5379,9 +5413,10 @@ pub async fn set_default_payment_method(
}
pub async fn update_last_used_at(
- payment_method: &diesel_models::PaymentMethod,
+ payment_method: &domain::PaymentMethod,
state: &routes::SessionState,
storage_scheme: MerchantStorageScheme,
+ key_store: &domain::MerchantKeyStore,
) -> errors::RouterResult<()> {
let update_last_used = storage::PaymentMethodUpdate::LastUsedUpdate {
last_used_at: common_utils::date_time::now(),
@@ -5389,7 +5424,13 @@ pub async fn update_last_used_at(
state
.store
- .update_payment_method(payment_method.clone(), update_last_used, storage_scheme)
+ .update_payment_method(
+ &(state.into()),
+ key_store,
+ payment_method.clone(),
+ update_last_used,
+ storage_scheme,
+ )
.await
.change_context(errors::ApiErrorResponse::InternalServerError)
.attach_printable("Failed to update the last_used_at in db")?;
@@ -5456,7 +5497,7 @@ impl TempLockerCardSupport {
state: &routes::SessionState,
payment_token: &str,
card: api::CardDetailFromLocker,
- pm: &storage::PaymentMethod,
+ pm: &domain::PaymentMethod,
merchant_key_store: &domain::MerchantKeyStore,
) -> errors::RouterResult<api::CardDetailFromLocker> {
let card_number = card.card_number.clone().get_required_value("card_number")?;
@@ -5491,7 +5532,7 @@ impl TempLockerCardSupport {
None,
None,
Some(pm.customer_id.clone()),
- Some(pm.payment_method_id.to_string()),
+ Some(pm.get_id().to_string()),
)
.change_context(errors::ApiErrorResponse::InternalServerError)
.attach_printable("Error getting Value2 for locker")?;
@@ -5546,7 +5587,12 @@ pub async fn retrieve_payment_method(
) -> errors::RouterResponse<api::PaymentMethodResponse> {
let db = state.store.as_ref();
let pm = db
- .find_payment_method(&pm.payment_method_id, merchant_account.storage_scheme)
+ .find_payment_method(
+ &((&state).into()),
+ &key_store,
+ &pm.payment_method_id,
+ merchant_account.storage_scheme,
+ )
.await
.to_not_found_response(errors::ApiErrorResponse::PaymentMethodNotFound)?;
@@ -5565,7 +5611,7 @@ pub async fn retrieve_payment_method(
.change_context(errors::ApiErrorResponse::InternalServerError)
.attach_printable("Failed while getting card details from locker")?
} else {
- get_card_details_without_locker_fallback(&pm, &state, &key_store).await?
+ get_card_details_without_locker_fallback(&pm, &state).await?
};
Some(card_detail)
} else {
@@ -5602,7 +5648,12 @@ pub async fn retrieve_payment_method(
) -> errors::RouterResponse<api::PaymentMethodResponse> {
let db = state.store.as_ref();
let pm = db
- .find_payment_method(&pm.payment_method_id, merchant_account.storage_scheme)
+ .find_payment_method(
+ &((&state).into()),
+ &key_store,
+ &pm.payment_method_id,
+ merchant_account.storage_scheme,
+ )
.await
.to_not_found_response(errors::ApiErrorResponse::PaymentMethodNotFound)?;
@@ -5612,7 +5663,7 @@ pub async fn retrieve_payment_method(
&state,
&pm.customer_id,
&pm.merchant_id,
- pm.locker_id.as_ref().unwrap_or(&pm.payment_method_id),
+ pm.locker_id.as_ref().unwrap_or(pm.get_id()),
)
.await
.change_context(errors::ApiErrorResponse::InternalServerError)
@@ -5621,7 +5672,7 @@ pub async fn retrieve_payment_method(
.change_context(errors::ApiErrorResponse::InternalServerError)
.attach_printable("Failed while getting card details from locker")?
} else {
- get_card_details_without_locker_fallback(&pm, &state, &key_store).await?
+ get_card_details_without_locker_fallback(&pm, &state).await?
};
Some(card_detail)
} else {
@@ -5629,9 +5680,9 @@ pub async fn retrieve_payment_method(
};
Ok(services::ApplicationResponse::Json(
api::PaymentMethodResponse {
- merchant_id: pm.merchant_id,
- customer_id: pm.customer_id,
- payment_method_id: pm.payment_method_id,
+ merchant_id: pm.merchant_id.to_owned(),
+ customer_id: pm.customer_id.to_owned(),
+ payment_method_id: pm.get_id().clone(),
payment_method: pm.payment_method,
payment_method_type: pm.payment_method_type,
metadata: pm.metadata,
@@ -5671,6 +5722,8 @@ pub async fn delete_payment_method(
let key_manager_state = &(&state).into();
let key = db
.find_payment_method(
+ &((&state).into()),
+ &key_store,
pm_id.payment_method_id.as_str(),
merchant_account.storage_scheme,
)
@@ -5707,6 +5760,8 @@ pub async fn delete_payment_method(
}
db.delete_payment_method_by_merchant_id_payment_method_id(
+ &((&state).into()),
+ &key_store,
merchant_account.get_id(),
pm_id.payment_method_id.as_str(),
)
diff --git a/crates/router/src/core/payment_methods/transformers.rs b/crates/router/src/core/payment_methods/transformers.rs
index ed4f2d9d15f..da97fedf2cd 100644
--- a/crates/router/src/core/payment_methods/transformers.rs
+++ b/crates/router/src/core/payment_methods/transformers.rs
@@ -18,7 +18,7 @@ use crate::{
headers,
pii::{prelude::*, Secret},
services::{api as services, encryption},
- types::{api, storage},
+ types::{api, domain},
utils::OptionExt,
};
@@ -538,7 +538,7 @@ pub fn mk_delete_card_response(
not(feature = "payment_methods_v2")
))]
pub fn get_card_detail(
- pm: &storage::PaymentMethod,
+ pm: &domain::PaymentMethod,
response: Card,
) -> CustomResult<api::CardDetailFromLocker, errors::VaultError> {
let card_number = response.card_number;
@@ -567,7 +567,7 @@ pub fn get_card_detail(
#[cfg(all(feature = "v2", feature = "payment_methods_v2"))]
pub fn get_card_detail(
- pm: &storage::PaymentMethod,
+ _pm: &domain::PaymentMethod,
response: Card,
) -> CustomResult<api::CardDetailFromLocker, errors::VaultError> {
let card_number = response.card_number;
@@ -575,13 +575,7 @@ pub fn get_card_detail(
//fetch form card bin
let card_detail = api::CardDetailFromLocker {
- issuer_country: pm
- .issuer_country
- .as_ref()
- .map(|c| api_enums::CountryAlpha2::from_str(c))
- .transpose()
- .ok()
- .flatten(),
+ issuer_country: None,
last4_digits: Some(last4_digits),
card_number: Some(card_number),
expiry_month: Some(response.card_exp_month),
diff --git a/crates/router/src/core/payments.rs b/crates/router/src/core/payments.rs
index 678c9522a9b..8778079e728 100644
--- a/crates/router/src/core/payments.rs
+++ b/crates/router/src/core/payments.rs
@@ -2731,7 +2731,7 @@ where
pub confirm: Option<bool>,
pub force_sync: Option<bool>,
pub payment_method_data: Option<domain::PaymentMethodData>,
- pub payment_method_info: Option<storage::PaymentMethod>,
+ pub payment_method_info: Option<domain::PaymentMethod>,
pub refunds: Vec<storage::Refund>,
pub disputes: Vec<storage::Dispute>,
pub attempts: Option<Vec<storage::PaymentAttempt>>,
@@ -3761,7 +3761,7 @@ pub async fn decide_multiplex_connector_for_normal_or_recurring_payment<F: Clone
mandate_reference_record.connector_mandate_id.clone(),
),
payment_method_id: Some(
- payment_method_info.payment_method_id.clone(),
+ payment_method_info.get_id().clone(),
),
update_history: None,
},
@@ -3849,7 +3849,7 @@ pub fn is_network_transaction_id_flow(
state: &SessionState,
is_connector_agnostic_mit_enabled: Option<bool>,
connector: enums::Connector,
- payment_method_info: &storage::PaymentMethod,
+ payment_method_info: &domain::PaymentMethod,
) -> bool {
let ntid_supported_connectors = &state
.conf
diff --git a/crates/router/src/core/payments/helpers.rs b/crates/router/src/core/payments/helpers.rs
index 38f0fd127f4..8ce183d3e3d 100644
--- a/crates/router/src/core/payments/helpers.rs
+++ b/crates/router/src/core/payments/helpers.rs
@@ -380,6 +380,23 @@ pub async fn get_address_by_id(
}
}
+#[cfg(all(feature = "v2", feature = "payment_methods_v2"))]
+pub async fn get_token_pm_type_mandate_details(
+ _state: &SessionState,
+ _request: &api::PaymentsRequest,
+ _mandate_type: Option<api::MandateTransactionType>,
+ _merchant_account: &domain::MerchantAccount,
+ _merchant_key_store: &domain::MerchantKeyStore,
+ _payment_method_id: Option<String>,
+ _payment_intent_customer_id: Option<&id_type::CustomerId>,
+) -> RouterResult<MandateGenericData> {
+ todo!()
+}
+
+#[cfg(all(
+ any(feature = "v1", feature = "v2"),
+ not(feature = "payment_methods_v2")
+))]
pub async fn get_token_pm_type_mandate_details(
state: &SessionState,
request: &api::PaymentsRequest,
@@ -479,6 +496,8 @@ pub async fn get_token_pm_type_mandate_details(
let payment_method_info = state
.store
.find_payment_method(
+ &(state.into()),
+ merchant_key_store,
payment_method_id,
merchant_account.storage_scheme,
)
@@ -542,6 +561,8 @@ pub async fn get_token_pm_type_mandate_details(
let customer_saved_pm_option = match state
.store
.find_payment_method_by_customer_id_merchant_id_list(
+ &(state.into()),
+ merchant_key_store,
customer_id,
merchant_account.get_id(),
None,
@@ -596,6 +617,8 @@ pub async fn get_token_pm_type_mandate_details(
state
.store
.find_payment_method(
+ &(state.into()),
+ merchant_key_store,
&payment_method_id,
merchant_account.storage_scheme,
)
@@ -624,7 +647,12 @@ pub async fn get_token_pm_type_mandate_details(
.async_map(|payment_method_id| async move {
state
.store
- .find_payment_method(&payment_method_id, merchant_account.storage_scheme)
+ .find_payment_method(
+ &(state.into()),
+ merchant_key_store,
+ &payment_method_id,
+ merchant_account.storage_scheme,
+ )
.await
.to_not_found_response(errors::ApiErrorResponse::PaymentMethodNotFound)
})
@@ -716,7 +744,12 @@ pub async fn get_token_for_recurring_mandate(
)?;
let payment_method = db
- .find_payment_method(payment_method_id.as_str(), merchant_account.storage_scheme)
+ .find_payment_method(
+ &(state.into()),
+ merchant_key_store,
+ payment_method_id.as_str(),
+ merchant_account.storage_scheme,
+ )
.await
.to_not_found_response(errors::ApiErrorResponse::PaymentMethodNotFound)?;
@@ -1900,15 +1933,21 @@ pub async fn retrieve_card_with_permanent_token(
pub async fn retrieve_payment_method_from_db_with_token_data(
state: &SessionState,
+ merchant_key_store: &domain::MerchantKeyStore,
token_data: &storage::PaymentTokenData,
storage_scheme: storage::enums::MerchantStorageScheme,
-) -> RouterResult<Option<storage::PaymentMethod>> {
+) -> RouterResult<Option<domain::PaymentMethod>> {
match token_data {
storage::PaymentTokenData::PermanentCard(data) => {
if let Some(ref payment_method_id) = data.payment_method_id {
state
.store
- .find_payment_method(payment_method_id, storage_scheme)
+ .find_payment_method(
+ &(state.into()),
+ merchant_key_store,
+ payment_method_id,
+ storage_scheme,
+ )
.await
.to_not_found_response(errors::ApiErrorResponse::PaymentMethodNotFound)
.attach_printable("error retrieving payment method from DB")
@@ -1920,7 +1959,12 @@ pub async fn retrieve_payment_method_from_db_with_token_data(
storage::PaymentTokenData::WalletToken(data) => state
.store
- .find_payment_method(&data.payment_method_id, storage_scheme)
+ .find_payment_method(
+ &(state.into()),
+ merchant_key_store,
+ &data.payment_method_id,
+ storage_scheme,
+ )
.await
.to_not_found_response(errors::ApiErrorResponse::PaymentMethodNotFound)
.attach_printable("error retrieveing payment method from DB")
@@ -2018,15 +2062,15 @@ pub async fn make_pm_data<'a, F: Clone, R>(
if payment_method_info.payment_method == Some(storage_enums::PaymentMethod::Card) {
payment_data.token_data =
Some(storage::PaymentTokenData::PermanentCard(CardTokenData {
- payment_method_id: Some(payment_method_info.payment_method_id.clone()),
+ payment_method_id: Some(payment_method_info.get_id().clone()),
locker_id: payment_method_info
.locker_id
.clone()
- .or(Some(payment_method_info.payment_method_id.clone())),
+ .or(Some(payment_method_info.get_id().clone())),
token: payment_method_info
.locker_id
.clone()
- .unwrap_or(payment_method_info.payment_method_id.clone()),
+ .unwrap_or(payment_method_info.get_id().clone()),
}));
}
}
diff --git a/crates/router/src/core/payments/operations/payment_confirm.rs b/crates/router/src/core/payments/operations/payment_confirm.rs
index 3e7944838a6..3edefd29466 100644
--- a/crates/router/src/core/payments/operations/payment_confirm.rs
+++ b/crates/router/src/core/payments/operations/payment_confirm.rs
@@ -11,8 +11,6 @@ use api_models::{
use api_models::{payment_methods::PaymentMethodsData, payments::AdditionalPaymentData};
use async_trait::async_trait;
use common_utils::ext_traits::{AsyncExt, Encode, StringExt, ValueExt};
-#[cfg(all(any(feature = "v1", feature = "v2"), not(feature = "customer_v2")))]
-use common_utils::{type_name, types::keymanager::Identifier};
use error_stack::{report, ResultExt};
use futures::FutureExt;
#[cfg(all(any(feature = "v1", feature = "v2"), not(feature = "customer_v2")))]
@@ -27,7 +25,6 @@ use super::{BoxedOperation, Domain, GetTracker, Operation, UpdateTracker, Valida
use crate::{
core::payment_methods::cards::create_encrypted_data,
events::audit_events::{AuditEvent, AuditEventType},
- types::domain::types::{crypto_operation, CryptoOperation},
};
use crate::{
core::{
@@ -600,6 +597,7 @@ impl<F: Send + Clone> GetTracker<F, PaymentData<F>, api::PaymentsRequest> for Pa
let payment_method_info = helpers::retrieve_payment_method_from_db_with_token_data(
state,
+ key_store,
&token_data,
storage_scheme,
)
@@ -1160,24 +1158,11 @@ impl<F: Clone> UpdateTracker<F, PaymentData<F>, api::PaymentsRequest> for Paymen
.transpose()
.change_context(errors::ApiErrorResponse::InternalServerError)
.attach_printable("Failed to encode additional pm data")?;
- let key_manager_state = &state.into();
+
let encode_additional_pm_to_value = if let Some(ref pm) = payment_data.payment_method_info {
- let key = key_store.key.get_inner().peek();
-
- let card_detail_from_locker: Option<api::CardDetailFromLocker> =
- crypto_operation::<serde_json::Value, masking::WithType>(
- key_manager_state,
- type_name!(storage::PaymentMethod),
- CryptoOperation::DecryptOptional(pm.payment_method_data.clone()),
- Identifier::Merchant(key_store.merchant_id.clone()),
- key,
- )
- .await
- .and_then(|val| val.try_into_optionaloperation())
- .change_context(errors::StorageError::DecryptionError)
- .attach_printable("unable to decrypt card details")
- .ok()
- .flatten()
+ let card_detail_from_locker: Option<api::CardDetailFromLocker> = pm
+ .payment_method_data
+ .clone()
.map(|x| x.into_inner().expose())
.and_then(|v| serde_json::from_value::<PaymentMethodsData>(v).ok())
.and_then(|pmd| match pmd {
diff --git a/crates/router/src/core/payments/operations/payment_create.rs b/crates/router/src/core/payments/operations/payment_create.rs
index a947d66bae5..6c0b748fc43 100644
--- a/crates/router/src/core/payments/operations/payment_create.rs
+++ b/crates/router/src/core/payments/operations/payment_create.rs
@@ -7,15 +7,13 @@ use api_models::{
use async_trait::async_trait;
use common_utils::{
ext_traits::{AsyncExt, Encode, ValueExt},
- type_name,
- types::{keymanager::Identifier, MinorUnit},
+ types::MinorUnit,
};
-use diesel_models::{ephemeral_key, PaymentMethod};
+use diesel_models::ephemeral_key;
use error_stack::{self, ResultExt};
use hyperswitch_domain_models::{
mandates::{MandateData, MandateDetails},
payments::{payment_attempt::PaymentAttempt, payment_intent::CustomerData},
- type_encryption::{crypto_operation, CryptoOperation},
};
use masking::{ExposeInterface, PeekInterface, Secret};
use router_derive::PaymentOperation;
@@ -877,8 +875,8 @@ impl PaymentCreate {
browser_info: Option<serde_json::Value>,
state: &SessionState,
payment_method_billing_address_id: Option<String>,
- payment_method_info: &Option<PaymentMethod>,
- key_store: &domain::MerchantKeyStore,
+ payment_method_info: &Option<domain::PaymentMethod>,
+ _key_store: &domain::MerchantKeyStore,
profile_id: common_utils::id_type::ProfileId,
customer_acceptance: &Option<payments::CustomerAcceptance>,
) -> RouterResult<(
@@ -917,36 +915,28 @@ impl PaymentCreate {
// If recurring payment is made using payment_method_id, then fetch payment_method_data from retrieved payment_method object
additional_pm_data = payment_method_info
.as_ref()
- .async_and_then(|pm_info| async {
- crypto_operation::<serde_json::Value, masking::WithType>(
- &state.into(),
- type_name!(PaymentMethod),
- CryptoOperation::DecryptOptional(pm_info.payment_method_data.clone()),
- Identifier::Merchant(key_store.merchant_id.clone()),
- key_store.key.get_inner().peek(),
- )
- .await
- .and_then(|val| val.try_into_optionaloperation())
- .map_err(|err| logger::error!("Failed to decrypt card details: {:?}", err))
- .ok()
- .flatten()
- .map(|x| x.into_inner().expose())
- .and_then(|v| {
- serde_json::from_value::<PaymentMethodsData>(v)
- .map_err(|err| {
- logger::error!(
- "Unable to deserialize payment methods data: {:?}",
- err
- )
- })
- .ok()
- })
- .and_then(|pmd| match pmd {
- PaymentMethodsData::Card(crd) => Some(api::CardDetailFromLocker::from(crd)),
- _ => None,
- })
+ .and_then(|pm_info| {
+ pm_info
+ .payment_method_data
+ .clone()
+ .map(|x| x.into_inner().expose())
+ .and_then(|v| {
+ serde_json::from_value::<PaymentMethodsData>(v)
+ .map_err(|err| {
+ logger::error!(
+ "Unable to deserialize payment methods data: {:?}",
+ err
+ )
+ })
+ .ok()
+ })
+ .and_then(|pmd| match pmd {
+ PaymentMethodsData::Card(crd) => {
+ Some(api::CardDetailFromLocker::from(crd))
+ }
+ _ => None,
+ })
})
- .await
.map(|card| {
api_models::payments::AdditionalPaymentData::Card(Box::new(card.into()))
});
@@ -1032,7 +1022,7 @@ impl PaymentCreate {
offer_amount: None,
payment_method_id: payment_method_info
.as_ref()
- .map(|pm_info| pm_info.payment_method_id.clone()),
+ .map(|pm_info| pm_info.get_id().clone()),
cancellation_reason: None,
error_code: None,
connector_metadata: None,
diff --git a/crates/router/src/core/payments/operations/payment_response.rs b/crates/router/src/core/payments/operations/payment_response.rs
index 5583d41a235..675c64aeb98 100644
--- a/crates/router/src/core/payments/operations/payment_response.rs
+++ b/crates/router/src/core/payments/operations/payment_response.rs
@@ -132,6 +132,7 @@ impl<F: Send + Clone> PostUpdateTracker<F, PaymentData<F>, types::PaymentsAuthor
payment_method_info,
state,
merchant_account.storage_scheme,
+ key_store,
)
.await
.map_err(|e| {
@@ -193,8 +194,7 @@ impl<F: Send + Clone> PostUpdateTracker<F, PaymentData<F>, types::PaymentsAuthor
Ok(())
} else if should_avoid_saving {
if let Some(pm_info) = &payment_data.payment_method_info {
- payment_data.payment_attempt.payment_method_id =
- Some(pm_info.payment_method_id.clone());
+ payment_data.payment_attempt.payment_method_id = Some(pm_info.get_id().clone());
};
Ok(())
} else {
@@ -436,7 +436,7 @@ impl<F: Clone> PostUpdateTracker<F, PaymentData<F>, types::PaymentsSyncData> for
state: &SessionState,
resp: &types::RouterData<F, types::PaymentsSyncData, types::PaymentsResponseData>,
merchant_account: &domain::MerchantAccount,
- _key_store: &domain::MerchantKeyStore,
+ key_store: &domain::MerchantKeyStore,
payment_data: &mut PaymentData<F>,
business_profile: &domain::BusinessProfile,
) -> CustomResult<(), errors::ApiErrorResponse>
@@ -445,6 +445,7 @@ impl<F: Clone> PostUpdateTracker<F, PaymentData<F>, types::PaymentsSyncData> for
{
update_payment_method_status_and_ntid(
state,
+ key_store,
payment_data,
resp.status,
resp.response.clone(),
@@ -751,7 +752,7 @@ impl<F: Clone> PostUpdateTracker<F, PaymentData<F>, types::CompleteAuthorizeData
state: &SessionState,
resp: &types::RouterData<F, types::CompleteAuthorizeData, types::PaymentsResponseData>,
merchant_account: &domain::MerchantAccount,
- _key_store: &domain::MerchantKeyStore,
+ key_store: &domain::MerchantKeyStore,
payment_data: &mut PaymentData<F>,
business_profile: &domain::BusinessProfile,
) -> CustomResult<(), errors::ApiErrorResponse>
@@ -760,6 +761,7 @@ impl<F: Clone> PostUpdateTracker<F, PaymentData<F>, types::CompleteAuthorizeData
{
update_payment_method_status_and_ntid(
state,
+ key_store,
payment_data,
resp.status,
resp.response.clone(),
@@ -1358,6 +1360,8 @@ async fn payment_response_update_tracker<F: Clone, T: types::Capturable>(
connector_mandate_id,
)?;
payment_methods::cards::update_payment_method_connector_mandate_details(
+ state,
+ key_store,
&*state.store,
payment_method.clone(),
connector_mandate_details,
@@ -1449,6 +1453,7 @@ async fn payment_response_update_tracker<F: Clone, T: types::Capturable>(
async fn update_payment_method_status_and_ntid<F: Clone>(
state: &SessionState,
+ key_store: &domain::MerchantKeyStore,
payment_data: &mut PaymentData<F>,
attempt_status: common_enums::AttemptStatus,
payment_response: Result<types::PaymentsResponseData, ErrorResponse>,
@@ -1458,7 +1463,11 @@ async fn update_payment_method_status_and_ntid<F: Clone>(
// If the payment_method is deleted then ignore the error related to retrieving payment method
// This should be handled when the payment method is soft deleted
if let Some(id) = &payment_data.payment_attempt.payment_method_id {
- let payment_method = match state.store.find_payment_method(id, storage_scheme).await {
+ let payment_method = match state
+ .store
+ .find_payment_method(&(state.into()), key_store, id, storage_scheme)
+ .await
+ {
Ok(payment_method) => payment_method,
Err(error) => {
if error.current_context().is_db_not_found() {
@@ -1520,7 +1529,13 @@ async fn update_payment_method_status_and_ntid<F: Clone>(
state
.store
- .update_payment_method(payment_method, pm_update, storage_scheme)
+ .update_payment_method(
+ &(state.into()),
+ key_store,
+ payment_method,
+ pm_update,
+ storage_scheme,
+ )
.await
.change_context(errors::ApiErrorResponse::InternalServerError)
.attach_printable("Failed to update payment method in db")?;
diff --git a/crates/router/src/core/payments/operations/payment_status.rs b/crates/router/src/core/payments/operations/payment_status.rs
index f9aa1c2be56..85dab242de4 100644
--- a/crates/router/src/core/payments/operations/payment_status.rs
+++ b/crates/router/src/core/payments/operations/payment_status.rs
@@ -379,7 +379,12 @@ async fn get_tracker_for_sync<
let payment_method_info =
if let Some(ref payment_method_id) = payment_attempt.payment_method_id.clone() {
match db
- .find_payment_method(payment_method_id, storage_scheme)
+ .find_payment_method(
+ &(state.into()),
+ key_store,
+ payment_method_id,
+ storage_scheme,
+ )
.await
{
Ok(payment_method) => Some(payment_method),
diff --git a/crates/router/src/core/payments/tokenization.rs b/crates/router/src/core/payments/tokenization.rs
index 6a922e1d407..609d5592ffd 100644
--- a/crates/router/src/core/payments/tokenization.rs
+++ b/crates/router/src/core/payments/tokenization.rs
@@ -247,6 +247,8 @@ where
let payment_method = {
let existing_pm_by_pmid = db
.find_payment_method(
+ &(state.into()),
+ key_store,
&payment_method_id,
merchant_account.storage_scheme,
)
@@ -257,6 +259,8 @@ where
locker_id = Some(payment_method_id.clone());
let existing_pm_by_locker_id = db
.find_payment_method_by_locker_id(
+ &(state.into()),
+ key_store,
&payment_method_id,
merchant_account.storage_scheme,
)
@@ -289,6 +293,8 @@ where
connector_token,
)?;
payment_methods::cards::update_payment_method_metadata_and_last_used(
+ state,
+ key_store,
db,
pm.clone(),
pm_metadata,
@@ -308,7 +314,8 @@ where
connector_mandate_id.clone(),
)?;
- payment_methods::cards::update_payment_method_connector_mandate_details(db, pm, connector_mandate_details, merchant_account.storage_scheme).await.change_context(
+ payment_methods::cards::update_payment_method_connector_mandate_details(state,
+ key_store,db, pm, connector_mandate_details, merchant_account.storage_scheme).await.change_context(
errors::ApiErrorResponse::InternalServerError,
)
.attach_printable("Failed to update payment method in db")?;
@@ -356,6 +363,8 @@ where
let payment_method = {
let existing_pm_by_pmid = db
.find_payment_method(
+ &(state.into()),
+ key_store,
&payment_method_id,
merchant_account.storage_scheme,
)
@@ -366,6 +375,8 @@ where
locker_id = Some(payment_method_id.clone());
let existing_pm_by_locker_id = db
.find_payment_method_by_locker_id(
+ &(state.into()),
+ key_store,
&payment_method_id,
merchant_account.storage_scheme,
)
@@ -406,7 +417,8 @@ where
connector_mandate_id.clone(),
)?;
- payment_methods::cards::update_payment_method_connector_mandate_details(db, pm.clone(), connector_mandate_details, merchant_account.storage_scheme).await.change_context(
+ payment_methods::cards::update_payment_method_connector_mandate_details( state,
+ key_store,db, pm.clone(), connector_mandate_details, merchant_account.storage_scheme).await.change_context(
errors::ApiErrorResponse::InternalServerError,
)
.attach_printable("Failed to update payment method in db")?;
@@ -481,6 +493,8 @@ where
if let Err(err) = add_card_resp {
logger::error!(vault_err=?err);
db.delete_payment_method_by_merchant_id_payment_method_id(
+ &(state.into()),
+ key_store,
merchant_id,
&resp.payment_method_id,
)
@@ -495,9 +509,7 @@ where
))?
};
- let existing_pm_data = payment_methods::cards::get_card_details_without_locker_fallback(&existing_pm,state,
- key_store,
- )
+ let existing_pm_data = payment_methods::cards::get_card_details_without_locker_fallback(&existing_pm,state)
.await?;
let updated_card = Some(CardDetailFromLocker {
@@ -539,6 +551,8 @@ where
.attach_printable("Unable to encrypt payment method data")?;
payment_methods::cards::update_payment_method_and_last_used(
+ state,
+ key_store,
db,
existing_pm,
pm_data_encrypted.map(Into::into),
@@ -559,6 +573,8 @@ where
match state
.store
.find_payment_method_by_customer_id_merchant_id_list(
+ &(state.into()),
+ key_store,
&customer_id,
merchant_id,
None,
@@ -594,6 +610,7 @@ where
&customer_saved_pm,
state,
merchant_account.storage_scheme,
+ key_store,
)
.await
.map_err(|e| {
@@ -1007,7 +1024,7 @@ pub fn add_connector_mandate_details_in_payment_method(
}
pub fn update_connector_mandate_details_in_payment_method(
- payment_method: diesel_models::PaymentMethod,
+ payment_method: domain::PaymentMethod,
payment_method_type: Option<storage_enums::PaymentMethodType>,
authorized_amount: Option<i64>,
authorized_currency: Option<storage_enums::Currency>,
diff --git a/crates/router/src/core/payments/transformers.rs b/crates/router/src/core/payments/transformers.rs
index b2070718892..a41205a496d 100644
--- a/crates/router/src/core/payments/transformers.rs
+++ b/crates/router/src/core/payments/transformers.rs
@@ -18,7 +18,6 @@ use crate::{
connector::{Helcim, Nexinets},
core::{
errors::{self, RouterResponse, RouterResult},
- payment_methods::cards::decrypt_generic_data,
payments::{self, helpers},
utils as core_utils,
},
@@ -67,7 +66,7 @@ pub async fn construct_payment_router_data<'a, F, T>(
payment_data: PaymentData<F>,
connector_id: &str,
merchant_account: &domain::MerchantAccount,
- key_store: &domain::MerchantKeyStore,
+ _key_store: &domain::MerchantKeyStore,
customer: &'a Option<domain::Customer>,
merchant_connector_account: &helpers::MerchantConnectorAccountType,
merchant_recipient_data: Option<types::MerchantRecipientData>,
@@ -158,22 +157,23 @@ where
Some(merchant_connector_account),
);
- let unified_address =
- if let Some(payment_method_info) = payment_data.payment_method_info.clone() {
- let payment_method_billing = decrypt_generic_data::<Address>(
- state,
- payment_method_info.payment_method_billing_address,
- key_store,
- )
- .await
- .attach_printable("unable to decrypt payment method billing address details")?;
- payment_data
- .address
- .clone()
- .unify_with_payment_data_billing(payment_method_billing)
- } else {
- payment_data.address
- };
+ let unified_address = if let Some(payment_method_info) =
+ payment_data.payment_method_info.clone()
+ {
+ let payment_method_billing = payment_method_info
+ .payment_method_billing_address
+ .map(|decrypted_data| decrypted_data.into_inner().expose())
+ .map(|decrypted_value| decrypted_value.parse_value("payment_method_billing_address"))
+ .transpose()
+ .change_context(errors::ApiErrorResponse::InternalServerError)
+ .attach_printable("unable to parse payment_method_billing_address")?;
+ payment_data
+ .address
+ .clone()
+ .unify_with_payment_data_billing(payment_method_billing)
+ } else {
+ payment_data.address
+ };
crate::logger::debug!("unified address details {:?}", unified_address);
diff --git a/crates/router/src/core/payouts/helpers.rs b/crates/router/src/core/payouts/helpers.rs
index 1249b5d3050..7408a7ea2be 100644
--- a/crates/router/src/core/payouts/helpers.rs
+++ b/crates/router/src/core/payouts/helpers.rs
@@ -324,7 +324,12 @@ pub async fn save_payout_data_to_locker(
// Use locker ref as payment_method_id
let existing_pm_by_pmid = db
- .find_payment_method(&locker_ref, merchant_account.storage_scheme)
+ .find_payment_method(
+ &(state.into()),
+ key_store,
+ &locker_ref,
+ merchant_account.storage_scheme,
+ )
.await;
match existing_pm_by_pmid {
@@ -343,6 +348,8 @@ pub async fn save_payout_data_to_locker(
if err.current_context().is_db_not_found() {
match db
.find_payment_method_by_locker_id(
+ &(state.into()),
+ key_store,
&locker_ref,
merchant_account.storage_scheme,
)
@@ -570,6 +577,8 @@ pub async fn save_payout_data_to_locker(
if let Err(err) = stored_resp {
logger::error!(vault_err=?err);
db.delete_payment_method_by_merchant_id_payment_method_id(
+ &(state.into()),
+ key_store,
merchant_account.get_id(),
&existing_pm.payment_method_id,
)
@@ -585,10 +594,16 @@ pub async fn save_payout_data_to_locker(
let pm_update = storage::PaymentMethodUpdate::PaymentMethodDataUpdate {
payment_method_data: card_details_encrypted.map(Into::into),
};
- db.update_payment_method(existing_pm, pm_update, merchant_account.storage_scheme)
- .await
- .change_context(errors::ApiErrorResponse::InternalServerError)
- .attach_printable("Failed to add payment method in db")?;
+ db.update_payment_method(
+ &(state.into()),
+ key_store,
+ existing_pm,
+ pm_update,
+ merchant_account.storage_scheme,
+ )
+ .await
+ .change_context(errors::ApiErrorResponse::InternalServerError)
+ .attach_printable("Failed to add payment method in db")?;
};
// Store card_reference in payouts table
diff --git a/crates/router/src/core/pm_auth.rs b/crates/router/src/core/pm_auth.rs
index ba464d27f01..4380d60955b 100644
--- a/crates/router/src/core/pm_auth.rs
+++ b/crates/router/src/core/pm_auth.rs
@@ -12,9 +12,9 @@ pub mod transformers;
use common_utils::{
consts,
crypto::{HmacSha256, SignMessage},
- ext_traits::AsyncExt,
- generate_id, type_name,
- types::{self as util_types, keymanager::Identifier, AmountConvertor},
+ ext_traits::{AsyncExt, ValueExt},
+ generate_id,
+ types::{self as util_types, AmountConvertor},
};
use error_stack::ResultExt;
use helpers::PaymentAuthConnectorDataExt;
@@ -42,12 +42,7 @@ use crate::{
logger,
routes::SessionState,
services::{pm_auth as pm_auth_services, ApplicationResponse},
- types::{
- self,
- domain::{self, types::crypto_operation},
- storage,
- transformers::ForeignTryFrom,
- },
+ types::{self, domain, storage, transformers::ForeignTryFrom},
};
pub async fn create_link_token(
@@ -303,7 +298,6 @@ async fn store_bank_details_in_payment_methods(
connector_details: (&str, Secret<String>),
mca_id: common_utils::id_type::MerchantConnectorAccountId,
) -> RouterResult<()> {
- let key = key_store.key.get_inner().peek();
let db = &*state.clone().store;
let (connector_name, access_token) = connector_details;
@@ -322,11 +316,31 @@ async fn store_bank_details_in_payment_methods(
.customer_id
.ok_or(ApiErrorResponse::CustomerNotFound)?;
+ #[cfg(all(
+ any(feature = "v1", feature = "v2"),
+ not(feature = "payment_methods_v2")
+ ))]
let payment_methods = db
.find_payment_method_by_customer_id_merchant_id_list(
+ &((&state).into()),
+ &key_store,
+ &customer_id,
+ merchant_account.get_id(),
+ None,
+ )
+ .await
+ .change_context(ApiErrorResponse::InternalServerError)?;
+
+ #[cfg(all(feature = "v2", feature = "payment_methods_v2"))]
+ let payment_methods = db
+ .find_payment_method_by_customer_id_merchant_id_status(
+ &((&state).into()),
+ &key_store,
&customer_id,
merchant_account.get_id(),
+ common_enums::enums::PaymentMethodStatus::Active,
None,
+ merchant_account.storage_scheme,
)
.await
.change_context(ApiErrorResponse::InternalServerError)?;
@@ -334,7 +348,7 @@ async fn store_bank_details_in_payment_methods(
let mut hash_to_payment_method: HashMap<
String,
(
- storage::PaymentMethod,
+ domain::PaymentMethod,
payment_methods::PaymentMethodDataBankCreds,
),
> = HashMap::new();
@@ -343,33 +357,24 @@ async fn store_bank_details_in_payment_methods(
if pm.payment_method == Some(enums::PaymentMethod::BankDebit)
&& pm.payment_method_data.is_some()
{
- let bank_details_pm_data = crypto_operation::<serde_json::Value, masking::WithType>(
- &(&state).into(),
- type_name!(storage::PaymentMethod),
- domain::types::CryptoOperation::DecryptOptional(pm.payment_method_data.clone()),
- Identifier::Merchant(key_store.merchant_id.clone()),
- key,
- )
- .await
- .and_then(|val| val.try_into_optionaloperation())
- .change_context(ApiErrorResponse::InternalServerError)
- .attach_printable("unable to decrypt bank account details")?
- .map(|x| x.into_inner().expose())
- .map(|v| {
- serde_json::from_value::<payment_methods::PaymentMethodsData>(v)
- .change_context(errors::StorageError::DeserializationFailed)
- .attach_printable("Failed to deserialize Payment Method Auth config")
- })
- .transpose()
- .unwrap_or_else(|error| {
- logger::error!(?error);
- None
- })
- .and_then(|pmd| match pmd {
- payment_methods::PaymentMethodsData::BankDetails(bank_creds) => Some(bank_creds),
- _ => None,
- })
- .ok_or(ApiErrorResponse::InternalServerError)?;
+ let bank_details_pm_data = pm
+ .payment_method_data
+ .clone()
+ .map(|x| x.into_inner().expose())
+ .map(|v| v.parse_value("PaymentMethodsData"))
+ .transpose()
+ .unwrap_or_else(|error| {
+ logger::error!(?error);
+ None
+ })
+ .and_then(|pmd| match pmd {
+ payment_methods::PaymentMethodsData::BankDetails(bank_creds) => {
+ Some(bank_creds)
+ }
+ _ => None,
+ })
+ .ok_or(ApiErrorResponse::InternalServerError)
+ .attach_printable("Unable to parse PaymentMethodsData")?;
hash_to_payment_method.insert(
bank_details_pm_data.hash.clone(),
@@ -386,9 +391,8 @@ async fn store_bank_details_in_payment_methods(
.clone()
.expose();
- let mut update_entries: Vec<(storage::PaymentMethod, storage::PaymentMethodUpdate)> =
- Vec::new();
- let mut new_entries: Vec<storage::PaymentMethodNew> = Vec::new();
+ let mut update_entries: Vec<(domain::PaymentMethod, storage::PaymentMethodUpdate)> = Vec::new();
+ let mut new_entries: Vec<domain::PaymentMethod> = Vec::new();
for creds in bank_account_details_resp.credentials {
let (account_number, hash_string) = match creds.account_details {
@@ -475,7 +479,11 @@ async fn store_bank_details_in_payment_methods(
.attach_printable("Unable to encrypt customer details")?;
let pm_id = generate_id(consts::ID_LENGTH, "pm");
let now = common_utils::date_time::now();
- let pm_new = storage::PaymentMethodNew {
+ #[cfg(all(
+ any(feature = "v1", feature = "v2"),
+ not(feature = "payment_methods_v2")
+ ))]
+ let pm_new = domain::PaymentMethod {
customer_id: customer_id.clone(),
merchant_id: merchant_account.get_id().clone(),
payment_method_id: pm_id,
@@ -485,7 +493,7 @@ async fn store_bank_details_in_payment_methods(
payment_method_issuer: None,
scheme: None,
metadata: None,
- payment_method_data: Some(encrypted_data.into()),
+ payment_method_data: Some(encrypted_data),
payment_method_issuer_code: None,
accepted_currency: None,
token: None,
@@ -506,6 +514,31 @@ async fn store_bank_details_in_payment_methods(
client_secret: None,
payment_method_billing_address: None,
updated_by: None,
+ version: domain::consts::API_VERSION,
+ };
+
+ #[cfg(all(feature = "v2", feature = "payment_methods_v2"))]
+ let pm_new = domain::PaymentMethod {
+ customer_id: customer_id.clone(),
+ merchant_id: merchant_account.get_id().clone(),
+ id: pm_id,
+ payment_method: Some(enums::PaymentMethod::BankDebit),
+ payment_method_type: Some(creds.payment_method_type),
+ status: enums::PaymentMethodStatus::Active,
+ metadata: None,
+ payment_method_data: Some(encrypted_data.into()),
+ created_at: now,
+ last_modified: now,
+ locker_id: None,
+ last_used_at: now,
+ connector_mandate_details: None,
+ customer_acceptance: None,
+ network_transaction_id: None,
+ client_secret: None,
+ payment_method_billing_address: None,
+ updated_by: None,
+ locker_fingerprint_id: None,
+ version: domain::consts::API_VERSION,
};
new_entries.push(pm_new);
@@ -513,6 +546,8 @@ async fn store_bank_details_in_payment_methods(
}
store_in_db(
+ &state,
+ &key_store,
update_entries,
new_entries,
db,
@@ -524,19 +559,26 @@ async fn store_bank_details_in_payment_methods(
}
async fn store_in_db(
- update_entries: Vec<(storage::PaymentMethod, storage::PaymentMethodUpdate)>,
- new_entries: Vec<storage::PaymentMethodNew>,
+ state: &SessionState,
+ key_store: &domain::MerchantKeyStore,
+ update_entries: Vec<(domain::PaymentMethod, storage::PaymentMethodUpdate)>,
+ new_entries: Vec<domain::PaymentMethod>,
db: &dyn StorageInterface,
storage_scheme: MerchantStorageScheme,
) -> RouterResult<()> {
+ let key_manager_state = &(state.into());
let update_entries_futures = update_entries
.into_iter()
- .map(|(pm, pm_update)| db.update_payment_method(pm, pm_update, storage_scheme))
+ .map(|(pm, pm_update)| {
+ db.update_payment_method(key_manager_state, key_store, pm, pm_update, storage_scheme)
+ })
.collect::<Vec<_>>();
let new_entries_futures = new_entries
.into_iter()
- .map(|pm_new| db.insert_payment_method(pm_new, storage_scheme))
+ .map(|pm_new| {
+ db.insert_payment_method(key_manager_state, key_store, pm_new, storage_scheme)
+ })
.collect::<Vec<_>>();
let update_futures = futures::future::join_all(update_entries_futures);
diff --git a/crates/router/src/db/customers.rs b/crates/router/src/db/customers.rs
index 24402c343fa..3d8483f14f1 100644
--- a/crates/router/src/db/customers.rs
+++ b/crates/router/src/db/customers.rs
@@ -210,7 +210,7 @@ mod storage {
MerchantStorageScheme::RedisKv => {
let key = PartitionKey::MerchantIdCustomerId {
merchant_id,
- customer_id: customer_id.get_string_repr(),
+ customer_id,
};
let field = format!("cust_{}", customer_id.get_string_repr());
Box::pin(db_utils::try_redis_get_else_try_database_get(
@@ -281,7 +281,7 @@ mod storage {
MerchantStorageScheme::RedisKv => {
let key = PartitionKey::MerchantIdCustomerId {
merchant_id,
- customer_id: customer_id.get_string_repr(),
+ customer_id,
};
let field = format!("cust_{}", customer_id.get_string_repr());
Box::pin(db_utils::try_redis_get_else_try_database_get(
@@ -344,9 +344,9 @@ mod storage {
let maybe_customer = match storage_scheme {
MerchantStorageScheme::PostgresOnly => database_call().await,
MerchantStorageScheme::RedisKv => {
- let key = PartitionKey::MerchantIdCustomerId {
+ let key = PartitionKey::MerchantIdMerchantReferenceId {
merchant_id,
- customer_id: merchant_reference_id.get_string_repr(),
+ merchant_reference_id: merchant_reference_id.get_string_repr(),
};
let field = format!("cust_{}", merchant_reference_id.get_string_repr());
Box::pin(db_utils::try_redis_get_else_try_database_get(
@@ -416,7 +416,7 @@ mod storage {
};
let key = PartitionKey::MerchantIdCustomerId {
merchant_id: &merchant_id,
- customer_id: customer_id.get_string_repr(),
+ customer_id: &customer_id,
};
let field = format!("cust_{}", customer_id.get_string_repr());
let storage_scheme = decide_storage_scheme::<_, diesel_models::Customer>(
@@ -564,7 +564,7 @@ mod storage {
MerchantStorageScheme::RedisKv => {
let key = PartitionKey::MerchantIdCustomerId {
merchant_id,
- customer_id: customer_id.get_string_repr(),
+ customer_id,
};
let field = format!("cust_{}", customer_id.get_string_repr());
Box::pin(db_utils::try_redis_get_else_try_database_get(
@@ -747,7 +747,7 @@ mod storage {
MerchantStorageScheme::RedisKv => {
let key = PartitionKey::MerchantIdCustomerId {
merchant_id: &merchant_id,
- customer_id: customer_id.get_string_repr(),
+ customer_id: &customer_id,
};
let field = format!("cust_{}", customer_id.get_string_repr());
diff --git a/crates/router/src/db/kafka_store.rs b/crates/router/src/db/kafka_store.rs
index 0293dd2b328..577ccfebabf 100644
--- a/crates/router/src/db/kafka_store.rs
+++ b/crates/router/src/db/kafka_store.rs
@@ -1693,35 +1693,53 @@ impl PaymentIntentInterface for KafkaStore {
impl PaymentMethodInterface for KafkaStore {
async fn find_payment_method(
&self,
+ state: &KeyManagerState,
+ key_store: &domain::MerchantKeyStore,
payment_method_id: &str,
storage_scheme: MerchantStorageScheme,
- ) -> CustomResult<storage::PaymentMethod, errors::StorageError> {
+ ) -> CustomResult<domain::PaymentMethod, errors::StorageError> {
self.diesel_store
- .find_payment_method(payment_method_id, storage_scheme)
+ .find_payment_method(state, key_store, payment_method_id, storage_scheme)
.await
}
+ #[cfg(all(
+ any(feature = "v1", feature = "v2"),
+ not(feature = "payment_methods_v2")
+ ))]
async fn find_payment_method_by_customer_id_merchant_id_list(
&self,
+ state: &KeyManagerState,
+ key_store: &domain::MerchantKeyStore,
customer_id: &id_type::CustomerId,
merchant_id: &id_type::MerchantId,
limit: Option<i64>,
- ) -> CustomResult<Vec<storage::PaymentMethod>, errors::StorageError> {
+ ) -> CustomResult<Vec<domain::PaymentMethod>, errors::StorageError> {
self.diesel_store
- .find_payment_method_by_customer_id_merchant_id_list(customer_id, merchant_id, limit)
+ .find_payment_method_by_customer_id_merchant_id_list(
+ state,
+ key_store,
+ customer_id,
+ merchant_id,
+ limit,
+ )
.await
}
async fn find_payment_method_by_customer_id_merchant_id_status(
&self,
+ state: &KeyManagerState,
+ key_store: &domain::MerchantKeyStore,
customer_id: &id_type::CustomerId,
merchant_id: &id_type::MerchantId,
status: common_enums::PaymentMethodStatus,
limit: Option<i64>,
storage_scheme: MerchantStorageScheme,
- ) -> CustomResult<Vec<storage::PaymentMethod>, errors::StorageError> {
+ ) -> CustomResult<Vec<domain::PaymentMethod>, errors::StorageError> {
self.diesel_store
.find_payment_method_by_customer_id_merchant_id_status(
+ state,
+ key_store,
customer_id,
merchant_id,
status,
@@ -1731,6 +1749,10 @@ impl PaymentMethodInterface for KafkaStore {
.await
}
+ #[cfg(all(
+ any(feature = "v1", feature = "v2"),
+ not(feature = "payment_methods_v2")
+ ))]
async fn get_payment_method_count_by_customer_id_merchant_id_status(
&self,
customer_id: &id_type::CustomerId,
@@ -1746,44 +1768,95 @@ impl PaymentMethodInterface for KafkaStore {
.await
}
+ #[cfg(all(
+ any(feature = "v1", feature = "v2"),
+ not(feature = "payment_methods_v2")
+ ))]
async fn find_payment_method_by_locker_id(
&self,
+ state: &KeyManagerState,
+ key_store: &domain::MerchantKeyStore,
locker_id: &str,
storage_scheme: MerchantStorageScheme,
- ) -> CustomResult<storage::PaymentMethod, errors::StorageError> {
+ ) -> CustomResult<domain::PaymentMethod, errors::StorageError> {
self.diesel_store
- .find_payment_method_by_locker_id(locker_id, storage_scheme)
+ .find_payment_method_by_locker_id(state, key_store, locker_id, storage_scheme)
.await
}
async fn insert_payment_method(
&self,
- m: storage::PaymentMethodNew,
+ state: &KeyManagerState,
+ key_store: &domain::MerchantKeyStore,
+ m: domain::PaymentMethod,
storage_scheme: MerchantStorageScheme,
- ) -> CustomResult<storage::PaymentMethod, errors::StorageError> {
+ ) -> CustomResult<domain::PaymentMethod, errors::StorageError> {
self.diesel_store
- .insert_payment_method(m, storage_scheme)
+ .insert_payment_method(state, key_store, m, storage_scheme)
.await
}
async fn update_payment_method(
&self,
- payment_method: storage::PaymentMethod,
+ state: &KeyManagerState,
+ key_store: &domain::MerchantKeyStore,
+ payment_method: domain::PaymentMethod,
payment_method_update: storage::PaymentMethodUpdate,
storage_scheme: MerchantStorageScheme,
- ) -> CustomResult<storage::PaymentMethod, errors::StorageError> {
+ ) -> CustomResult<domain::PaymentMethod, errors::StorageError> {
self.diesel_store
- .update_payment_method(payment_method, payment_method_update, storage_scheme)
+ .update_payment_method(
+ state,
+ key_store,
+ payment_method,
+ payment_method_update,
+ storage_scheme,
+ )
.await
}
+ #[cfg(all(
+ any(feature = "v1", feature = "v2"),
+ not(feature = "payment_methods_v2")
+ ))]
async fn delete_payment_method_by_merchant_id_payment_method_id(
&self,
+ state: &KeyManagerState,
+ key_store: &domain::MerchantKeyStore,
merchant_id: &id_type::MerchantId,
payment_method_id: &str,
- ) -> CustomResult<storage::PaymentMethod, errors::StorageError> {
+ ) -> CustomResult<domain::PaymentMethod, errors::StorageError> {
+ self.diesel_store
+ .delete_payment_method_by_merchant_id_payment_method_id(
+ state,
+ key_store,
+ merchant_id,
+ payment_method_id,
+ )
+ .await
+ }
+
+ #[cfg(all(feature = "v2", feature = "payment_methods_v2"))]
+ async fn delete_payment_method(
+ &self,
+ state: &KeyManagerState,
+ key_store: &domain::MerchantKeyStore,
+ payment_method: domain::PaymentMethod,
+ ) -> CustomResult<domain::PaymentMethod, errors::StorageError> {
+ self.diesel_store
+ .delete_payment_method(state, key_store, payment_method)
+ .await
+ }
+
+ #[cfg(all(feature = "v2", feature = "payment_methods_v2"))]
+ async fn find_payment_method_by_fingerprint_id(
+ &self,
+ state: &KeyManagerState,
+ key_store: &domain::MerchantKeyStore,
+ fingerprint_id: &str,
+ ) -> CustomResult<domain::PaymentMethod, errors::StorageError> {
self.diesel_store
- .delete_payment_method_by_merchant_id_payment_method_id(merchant_id, payment_method_id)
+ .find_payment_method_by_fingerprint_id(state, key_store, fingerprint_id)
.await
}
}
diff --git a/crates/router/src/db/payment_method.rs b/crates/router/src/db/payment_method.rs
index e182d62c3f3..62c34e7103b 100644
--- a/crates/router/src/db/payment_method.rs
+++ b/crates/router/src/db/payment_method.rs
@@ -1,43 +1,68 @@
-use common_utils::id_type;
+use common_utils::{id_type, types::keymanager::KeyManagerState};
use diesel_models::payment_method::PaymentMethodUpdateInternal;
use error_stack::ResultExt;
+use hyperswitch_domain_models::behaviour::{Conversion, ReverseConversion};
use super::MockDb;
use crate::{
core::errors::{self, CustomResult},
- types::storage::{self as storage_types, enums::MerchantStorageScheme},
+ types::{
+ domain,
+ storage::{self as storage_types, enums::MerchantStorageScheme},
+ },
};
#[async_trait::async_trait]
pub trait PaymentMethodInterface {
async fn find_payment_method(
&self,
+ state: &KeyManagerState,
+ key_store: &domain::MerchantKeyStore,
payment_method_id: &str,
storage_scheme: MerchantStorageScheme,
- ) -> CustomResult<storage_types::PaymentMethod, errors::StorageError>;
+ ) -> CustomResult<domain::PaymentMethod, errors::StorageError>;
+ #[cfg(all(
+ any(feature = "v1", feature = "v2"),
+ not(feature = "payment_methods_v2")
+ ))]
async fn find_payment_method_by_locker_id(
&self,
+ state: &KeyManagerState,
+ key_store: &domain::MerchantKeyStore,
locker_id: &str,
storage_scheme: MerchantStorageScheme,
- ) -> CustomResult<storage_types::PaymentMethod, errors::StorageError>;
+ ) -> CustomResult<domain::PaymentMethod, errors::StorageError>;
+ #[cfg(all(
+ any(feature = "v1", feature = "v2"),
+ not(feature = "payment_methods_v2")
+ ))]
async fn find_payment_method_by_customer_id_merchant_id_list(
&self,
+ state: &KeyManagerState,
+ key_store: &domain::MerchantKeyStore,
customer_id: &id_type::CustomerId,
merchant_id: &id_type::MerchantId,
limit: Option<i64>,
- ) -> CustomResult<Vec<storage_types::PaymentMethod>, errors::StorageError>;
+ ) -> CustomResult<Vec<domain::PaymentMethod>, errors::StorageError>;
+ #[allow(clippy::too_many_arguments)]
async fn find_payment_method_by_customer_id_merchant_id_status(
&self,
+ state: &KeyManagerState,
+ key_store: &domain::MerchantKeyStore,
customer_id: &id_type::CustomerId,
merchant_id: &id_type::MerchantId,
status: common_enums::PaymentMethodStatus,
limit: Option<i64>,
storage_scheme: MerchantStorageScheme,
- ) -> CustomResult<Vec<storage_types::PaymentMethod>, errors::StorageError>;
+ ) -> CustomResult<Vec<domain::PaymentMethod>, errors::StorageError>;
+ #[cfg(all(
+ any(feature = "v1", feature = "v2"),
+ not(feature = "payment_methods_v2")
+ ))]
async fn get_payment_method_count_by_customer_id_merchant_id_status(
&self,
customer_id: &id_type::CustomerId,
@@ -47,29 +72,58 @@ pub trait PaymentMethodInterface {
async fn insert_payment_method(
&self,
- payment_method_new: storage_types::PaymentMethodNew,
+ state: &KeyManagerState,
+ key_store: &domain::MerchantKeyStore,
+ payment_method: domain::PaymentMethod,
storage_scheme: MerchantStorageScheme,
- ) -> CustomResult<storage_types::PaymentMethod, errors::StorageError>;
+ ) -> CustomResult<domain::PaymentMethod, errors::StorageError>;
async fn update_payment_method(
&self,
- payment_method: storage_types::PaymentMethod,
+ state: &KeyManagerState,
+ key_store: &domain::MerchantKeyStore,
+ payment_method: domain::PaymentMethod,
payment_method_update: storage_types::PaymentMethodUpdate,
storage_scheme: MerchantStorageScheme,
- ) -> CustomResult<storage_types::PaymentMethod, errors::StorageError>;
+ ) -> CustomResult<domain::PaymentMethod, errors::StorageError>;
+ #[cfg(all(feature = "v2", feature = "payment_methods_v2"))]
+ async fn delete_payment_method(
+ &self,
+ state: &KeyManagerState,
+ key_store: &domain::MerchantKeyStore,
+ payment_method: domain::PaymentMethod,
+ ) -> CustomResult<domain::PaymentMethod, errors::StorageError>;
+
+ #[cfg(all(feature = "v2", feature = "payment_methods_v2"))]
+ async fn find_payment_method_by_fingerprint_id(
+ &self,
+ state: &KeyManagerState,
+ key_store: &domain::MerchantKeyStore,
+ fingerprint_id: &str,
+ ) -> CustomResult<domain::PaymentMethod, errors::StorageError>;
+
+ #[cfg(all(
+ any(feature = "v1", feature = "v2"),
+ not(feature = "payment_methods_v2")
+ ))]
async fn delete_payment_method_by_merchant_id_payment_method_id(
&self,
+ state: &KeyManagerState,
+ key_store: &domain::MerchantKeyStore,
merchant_id: &id_type::MerchantId,
payment_method_id: &str,
- ) -> CustomResult<storage_types::PaymentMethod, errors::StorageError>;
+ ) -> CustomResult<domain::PaymentMethod, errors::StorageError>;
}
#[cfg(feature = "kv_store")]
mod storage {
- use common_utils::{fallback_reverse_lookup_not_found, id_type};
+ use common_utils::{
+ fallback_reverse_lookup_not_found, id_type, types::keymanager::KeyManagerState,
+ };
use diesel_models::{kv, PaymentMethodUpdateInternal};
use error_stack::{report, ResultExt};
+ use hyperswitch_domain_models::behaviour::{Conversion, ReverseConversion};
use redis_interface::HsetnxReply;
use router_env::{instrument, tracing};
use storage_impl::redis::kv_store::{
@@ -82,18 +136,27 @@ mod storage {
core::errors::{self, utils::RedisErrorExt, CustomResult},
db::reverse_lookup::ReverseLookupInterface,
services::Store,
- types::storage::{self as storage_types, enums::MerchantStorageScheme},
+ types::{
+ domain,
+ storage::{self as storage_types, enums::MerchantStorageScheme},
+ },
utils::db_utils,
};
#[async_trait::async_trait]
impl PaymentMethodInterface for Store {
+ #[cfg(all(
+ any(feature = "v1", feature = "v2"),
+ not(feature = "payment_methods_v2")
+ ))]
#[instrument(skip_all)]
async fn find_payment_method(
&self,
+ state: &KeyManagerState,
+ key_store: &domain::MerchantKeyStore,
payment_method_id: &str,
storage_scheme: MerchantStorageScheme,
- ) -> CustomResult<storage_types::PaymentMethod, errors::StorageError> {
+ ) -> CustomResult<domain::PaymentMethod, errors::StorageError> {
let conn = connection::pg_connection_read(self).await?;
let database_call = || async {
storage_types::PaymentMethod::find_by_payment_method_id(&conn, payment_method_id)
@@ -106,43 +169,129 @@ mod storage {
Op::Find,
)
.await;
- match storage_scheme {
- MerchantStorageScheme::PostgresOnly => database_call().await,
- MerchantStorageScheme::RedisKv => {
- let lookup_id = format!("payment_method_{}", payment_method_id);
- let lookup = fallback_reverse_lookup_not_found!(
- self.get_lookup_by_lookup_id(&lookup_id, storage_scheme)
- .await,
- database_call().await
- );
-
- let key = PartitionKey::CombinationKey {
- combination: &lookup.pk_id,
- };
+ let get_pm = || async {
+ match storage_scheme {
+ MerchantStorageScheme::PostgresOnly => database_call().await,
+ MerchantStorageScheme::RedisKv => {
+ let lookup_id = format!("payment_method_{}", payment_method_id);
+ let lookup = fallback_reverse_lookup_not_found!(
+ self.get_lookup_by_lookup_id(&lookup_id, storage_scheme)
+ .await,
+ database_call().await
+ );
- Box::pin(db_utils::try_redis_get_else_try_database_get(
- async {
- kv_wrapper(
- self,
- KvOperation::<storage_types::PaymentMethod>::HGet(&lookup.sk_id),
- key,
- )
- .await?
- .try_into_hget()
- },
- database_call,
- ))
+ let key = PartitionKey::CombinationKey {
+ combination: &lookup.pk_id,
+ };
+
+ Box::pin(db_utils::try_redis_get_else_try_database_get(
+ async {
+ kv_wrapper(
+ self,
+ KvOperation::<storage_types::PaymentMethod>::HGet(
+ &lookup.sk_id,
+ ),
+ key,
+ )
+ .await?
+ .try_into_hget()
+ },
+ database_call,
+ ))
+ .await
+ }
+ }
+ };
+
+ get_pm()
+ .await?
+ .convert(
+ state,
+ key_store.key.get_inner(),
+ key_store.merchant_id.clone().into(),
+ )
+ .await
+ .change_context(errors::StorageError::DecryptionError)
+ }
+
+ #[cfg(all(feature = "v2", feature = "payment_methods_v2"))]
+ #[instrument(skip_all)]
+ async fn find_payment_method(
+ &self,
+ state: &KeyManagerState,
+ key_store: &domain::MerchantKeyStore,
+ payment_method_id: &str,
+ storage_scheme: MerchantStorageScheme,
+ ) -> CustomResult<domain::PaymentMethod, errors::StorageError> {
+ let conn = connection::pg_connection_read(self).await?;
+ let database_call = || async {
+ storage_types::PaymentMethod::find_by_id(&conn, payment_method_id)
.await
+ .map_err(|error| report!(errors::StorageError::from(error)))
+ };
+ let storage_scheme = decide_storage_scheme::<_, storage_types::PaymentMethod>(
+ self,
+ storage_scheme,
+ Op::Find,
+ )
+ .await;
+ let get_pm = || async {
+ match storage_scheme {
+ MerchantStorageScheme::PostgresOnly => database_call().await,
+ MerchantStorageScheme::RedisKv => {
+ let lookup_id = format!("payment_method_{}", payment_method_id);
+ let lookup = fallback_reverse_lookup_not_found!(
+ self.get_lookup_by_lookup_id(&lookup_id, storage_scheme)
+ .await,
+ database_call().await
+ );
+
+ let key = PartitionKey::CombinationKey {
+ combination: &lookup.pk_id,
+ };
+
+ Box::pin(db_utils::try_redis_get_else_try_database_get(
+ async {
+ kv_wrapper(
+ self,
+ KvOperation::<storage_types::PaymentMethod>::HGet(
+ &lookup.sk_id,
+ ),
+ key,
+ )
+ .await?
+ .try_into_hget()
+ },
+ database_call,
+ ))
+ .await
+ }
}
- }
+ };
+
+ get_pm()
+ .await?
+ .convert(
+ state,
+ key_store.key.get_inner(),
+ key_store.merchant_id.clone().into(),
+ )
+ .await
+ .change_context(errors::StorageError::DecryptionError)
}
+ #[cfg(all(
+ any(feature = "v1", feature = "v2"),
+ not(feature = "payment_methods_v2")
+ ))]
#[instrument(skip_all)]
async fn find_payment_method_by_locker_id(
&self,
+ state: &KeyManagerState,
+ key_store: &domain::MerchantKeyStore,
locker_id: &str,
storage_scheme: MerchantStorageScheme,
- ) -> CustomResult<storage_types::PaymentMethod, errors::StorageError> {
+ ) -> CustomResult<domain::PaymentMethod, errors::StorageError> {
let conn = connection::pg_connection_read(self).await?;
let database_call = || async {
storage_types::PaymentMethod::find_by_locker_id(&conn, locker_id)
@@ -155,37 +304,56 @@ mod storage {
Op::Find,
)
.await;
- match storage_scheme {
- MerchantStorageScheme::PostgresOnly => database_call().await,
- MerchantStorageScheme::RedisKv => {
- let lookup_id = format!("payment_method_locker_{}", locker_id);
- let lookup = fallback_reverse_lookup_not_found!(
- self.get_lookup_by_lookup_id(&lookup_id, storage_scheme)
- .await,
- database_call().await
- );
-
- let key = PartitionKey::CombinationKey {
- combination: &lookup.pk_id,
- };
+ let get_pm = || async {
+ match storage_scheme {
+ MerchantStorageScheme::PostgresOnly => database_call().await,
+ MerchantStorageScheme::RedisKv => {
+ let lookup_id = format!("payment_method_locker_{}", locker_id);
+ let lookup = fallback_reverse_lookup_not_found!(
+ self.get_lookup_by_lookup_id(&lookup_id, storage_scheme)
+ .await,
+ database_call().await
+ );
- Box::pin(db_utils::try_redis_get_else_try_database_get(
- async {
- kv_wrapper(
- self,
- KvOperation::<storage_types::PaymentMethod>::HGet(&lookup.sk_id),
- key,
- )
- .await?
- .try_into_hget()
- },
- database_call,
- ))
- .await
+ let key = PartitionKey::CombinationKey {
+ combination: &lookup.pk_id,
+ };
+
+ Box::pin(db_utils::try_redis_get_else_try_database_get(
+ async {
+ kv_wrapper(
+ self,
+ KvOperation::<storage_types::PaymentMethod>::HGet(
+ &lookup.sk_id,
+ ),
+ key,
+ )
+ .await?
+ .try_into_hget()
+ },
+ database_call,
+ ))
+ .await
+ }
}
- }
+ };
+
+ get_pm()
+ .await?
+ .convert(
+ state,
+ key_store.key.get_inner(),
+ key_store.merchant_id.clone().into(),
+ )
+ .await
+ .change_context(errors::StorageError::DecryptionError)
}
+
// not supported in kv
+ #[cfg(all(
+ any(feature = "v1", feature = "v2"),
+ not(feature = "payment_methods_v2")
+ ))]
#[instrument(skip_all)]
async fn get_payment_method_count_by_customer_id_merchant_id_status(
&self,
@@ -207,17 +375,25 @@ mod storage {
#[instrument(skip_all)]
async fn insert_payment_method(
&self,
- mut payment_method_new: storage_types::PaymentMethodNew,
+ state: &KeyManagerState,
+ key_store: &domain::MerchantKeyStore,
+ payment_method: domain::PaymentMethod,
storage_scheme: MerchantStorageScheme,
- ) -> CustomResult<storage_types::PaymentMethod, errors::StorageError> {
+ ) -> CustomResult<domain::PaymentMethod, errors::StorageError> {
let storage_scheme = decide_storage_scheme::<_, storage_types::PaymentMethod>(
self,
storage_scheme,
Op::Insert,
)
.await;
+
+ let mut payment_method_new = payment_method
+ .construct_new()
+ .await
+ .change_context(errors::StorageError::DecryptionError)?;
+
payment_method_new.update_storage_scheme(storage_scheme);
- match storage_scheme {
+ let pm = match storage_scheme {
MerchantStorageScheme::PostgresOnly => {
let conn = connection::pg_connection_write(self).await?;
payment_method_new
@@ -231,11 +407,10 @@ mod storage {
let key = PartitionKey::MerchantIdCustomerId {
merchant_id: &merchant_id,
- customer_id: customer_id.get_string_repr(),
+ customer_id: &customer_id,
};
let key_str = key.to_string();
- let field =
- format!("payment_method_id_{}", payment_method_new.payment_method_id);
+ let field = format!("payment_method_id_{}", payment_method_new.get_id());
let reverse_lookup_entry = |v: String| diesel_models::ReverseLookupNew {
sk_id: field.clone(),
@@ -245,8 +420,7 @@ mod storage {
updated_by: storage_scheme.to_string(),
};
- let lookup_id1 =
- format!("payment_method_{}", &payment_method_new.payment_method_id);
+ let lookup_id1 = format!("payment_method_{}", payment_method_new.get_id());
let mut reverse_lookups = vec![lookup_id1];
if let Some(locker_id) = &payment_method_new.locker_id {
reverse_lookups.push(format!("payment_method_locker_{}", locker_id))
@@ -281,37 +455,55 @@ mod storage {
{
Ok(HsetnxReply::KeyNotSet) => Err(errors::StorageError::DuplicateValue {
entity: "payment_method",
- key: Some(storage_payment_method.payment_method_id),
+ key: Some(storage_payment_method.get_id().clone()),
}
.into()),
Ok(HsetnxReply::KeySet) => Ok(storage_payment_method),
Err(er) => Err(er).change_context(errors::StorageError::KVError),
}
}
- }
+ }?;
+
+ pm.convert(
+ state,
+ key_store.key.get_inner(),
+ key_store.merchant_id.clone().into(),
+ )
+ .await
+ .change_context(errors::StorageError::DecryptionError)
}
+ #[cfg(all(
+ any(feature = "v1", feature = "v2"),
+ not(feature = "payment_methods_v2")
+ ))]
#[instrument(skip_all)]
async fn update_payment_method(
&self,
- payment_method: storage_types::PaymentMethod,
+ state: &KeyManagerState,
+ key_store: &domain::MerchantKeyStore,
+ payment_method: domain::PaymentMethod,
payment_method_update: storage_types::PaymentMethodUpdate,
storage_scheme: MerchantStorageScheme,
- ) -> CustomResult<storage_types::PaymentMethod, errors::StorageError> {
+ ) -> CustomResult<domain::PaymentMethod, errors::StorageError> {
+ let payment_method = Conversion::convert(payment_method)
+ .await
+ .change_context(errors::StorageError::DecryptionError)?;
+
let merchant_id = payment_method.merchant_id.clone();
let customer_id = payment_method.customer_id.clone();
let key = PartitionKey::MerchantIdCustomerId {
merchant_id: &merchant_id,
- customer_id: customer_id.get_string_repr(),
+ customer_id: &customer_id,
};
- let field = format!("payment_method_id_{}", payment_method.payment_method_id);
+ let field = format!("payment_method_id_{}", payment_method.get_id());
let storage_scheme = decide_storage_scheme::<_, storage_types::PaymentMethod>(
self,
storage_scheme,
Op::Update(key.clone(), &field, payment_method.updated_by.as_deref()),
)
.await;
- match storage_scheme {
+ let pm = match storage_scheme {
MerchantStorageScheme::PostgresOnly => {
let conn = connection::pg_connection_write(self).await?;
payment_method
@@ -359,36 +551,155 @@ mod storage {
Ok(updated_payment_method)
}
- }
+ }?;
+
+ pm.convert(
+ state,
+ key_store.key.get_inner(),
+ key_store.merchant_id.clone().into(),
+ )
+ .await
+ .change_context(errors::StorageError::DecryptionError)
}
+ #[cfg(all(feature = "v2", feature = "payment_methods_v2"))]
+ #[instrument(skip_all)]
+ async fn update_payment_method(
+ &self,
+ state: &KeyManagerState,
+ key_store: &domain::MerchantKeyStore,
+ payment_method: domain::PaymentMethod,
+ payment_method_update: storage_types::PaymentMethodUpdate,
+ storage_scheme: MerchantStorageScheme,
+ ) -> CustomResult<domain::PaymentMethod, errors::StorageError> {
+ let payment_method = Conversion::convert(payment_method)
+ .await
+ .change_context(errors::StorageError::DecryptionError)?;
+
+ let merchant_id = payment_method.merchant_id.clone();
+ let customer_id = payment_method.customer_id.clone();
+ let key = PartitionKey::MerchantIdCustomerId {
+ merchant_id: &merchant_id,
+ customer_id: &customer_id,
+ };
+ let field = format!("payment_method_id_{}", payment_method.get_id());
+ let storage_scheme = decide_storage_scheme::<_, storage_types::PaymentMethod>(
+ self,
+ storage_scheme,
+ Op::Update(key.clone(), &field, payment_method.updated_by.as_deref()),
+ )
+ .await;
+ let pm = match storage_scheme {
+ MerchantStorageScheme::PostgresOnly => {
+ let conn = connection::pg_connection_write(self).await?;
+ payment_method
+ .update_with_id(
+ &conn,
+ payment_method_update.convert_to_payment_method_update(storage_scheme),
+ )
+ .await
+ .map_err(|error| report!(errors::StorageError::from(error)))
+ }
+ MerchantStorageScheme::RedisKv => {
+ let key_str = key.to_string();
+
+ let p_update: PaymentMethodUpdateInternal =
+ payment_method_update.convert_to_payment_method_update(storage_scheme);
+ let updated_payment_method =
+ p_update.clone().apply_changeset(payment_method.clone());
+
+ let redis_value = serde_json::to_string(&updated_payment_method)
+ .change_context(errors::StorageError::SerializationFailed)?;
+
+ let redis_entry = kv::TypedSql {
+ op: kv::DBOperation::Update {
+ updatable: kv::Updateable::PaymentMethodUpdate(
+ kv::PaymentMethodUpdateMems {
+ orig: payment_method,
+ update_data: p_update,
+ },
+ ),
+ },
+ };
+
+ kv_wrapper::<(), _, _>(
+ self,
+ KvOperation::<diesel_models::PaymentMethod>::Hset(
+ (&field, redis_value),
+ redis_entry,
+ ),
+ key,
+ )
+ .await
+ .map_err(|err| err.to_redis_failed_response(&key_str))?
+ .try_into_hset()
+ .change_context(errors::StorageError::KVError)?;
+
+ Ok(updated_payment_method)
+ }
+ }?;
+
+ pm.convert(
+ state,
+ key_store.key.get_inner(),
+ key_store.merchant_id.clone().into(),
+ )
+ .await
+ .change_context(errors::StorageError::DecryptionError)
+ }
+
+ #[cfg(all(
+ any(feature = "v1", feature = "v2"),
+ not(feature = "payment_methods_v2")
+ ))]
#[instrument(skip_all)]
async fn find_payment_method_by_customer_id_merchant_id_list(
&self,
+ state: &KeyManagerState,
+ key_store: &domain::MerchantKeyStore,
customer_id: &id_type::CustomerId,
merchant_id: &id_type::MerchantId,
limit: Option<i64>,
- ) -> CustomResult<Vec<storage_types::PaymentMethod>, errors::StorageError> {
+ ) -> CustomResult<Vec<domain::PaymentMethod>, errors::StorageError> {
let conn = connection::pg_connection_read(self).await?;
- storage_types::PaymentMethod::find_by_customer_id_merchant_id(
+ let payment_methods = storage_types::PaymentMethod::find_by_customer_id_merchant_id(
&conn,
customer_id,
merchant_id,
limit,
)
.await
- .map_err(|error| report!(errors::StorageError::from(error)))
+ .map_err(|error| report!(errors::StorageError::from(error)))?;
+
+ let pm_futures = payment_methods
+ .into_iter()
+ .map(|pm| async {
+ pm.convert(
+ state,
+ key_store.key.get_inner(),
+ key_store.merchant_id.clone().into(),
+ )
+ .await
+ .change_context(errors::StorageError::DecryptionError)
+ })
+ .collect::<Vec<_>>();
+
+ let domain_payment_methods = futures::future::try_join_all(pm_futures).await?;
+
+ Ok(domain_payment_methods)
}
#[instrument(skip_all)]
async fn find_payment_method_by_customer_id_merchant_id_status(
&self,
+ state: &KeyManagerState,
+ key_store: &domain::MerchantKeyStore,
customer_id: &id_type::CustomerId,
merchant_id: &id_type::MerchantId,
status: common_enums::PaymentMethodStatus,
limit: Option<i64>,
storage_scheme: MerchantStorageScheme,
- ) -> CustomResult<Vec<storage_types::PaymentMethod>, errors::StorageError> {
+ ) -> CustomResult<Vec<domain::PaymentMethod>, errors::StorageError> {
let conn = connection::pg_connection_read(self).await?;
let database_call = || async {
storage_types::PaymentMethod::find_by_customer_id_merchant_id_status(
@@ -402,12 +713,12 @@ mod storage {
.map_err(|error| report!(errors::StorageError::from(error)))
};
- match storage_scheme {
+ let payment_methods = match storage_scheme {
MerchantStorageScheme::PostgresOnly => database_call().await,
MerchantStorageScheme::RedisKv => {
let key = PartitionKey::MerchantIdCustomerId {
merchant_id,
- customer_id: customer_id.get_string_repr(),
+ customer_id,
};
let pattern = "payment_method_id_*";
@@ -435,14 +746,37 @@ mod storage {
))
.await
}
- }
+ }?;
+
+ let pm_futures = payment_methods
+ .into_iter()
+ .map(|pm| async {
+ pm.convert(
+ state,
+ key_store.key.get_inner(),
+ key_store.merchant_id.clone().into(),
+ )
+ .await
+ .change_context(errors::StorageError::DecryptionError)
+ })
+ .collect::<Vec<_>>();
+
+ let domain_payment_methods = futures::future::try_join_all(pm_futures).await?;
+
+ Ok(domain_payment_methods)
}
+ #[cfg(all(
+ any(feature = "v1", feature = "v2"),
+ not(feature = "payment_methods_v2")
+ ))]
async fn delete_payment_method_by_merchant_id_payment_method_id(
&self,
+ state: &KeyManagerState,
+ key_store: &domain::MerchantKeyStore,
merchant_id: &id_type::MerchantId,
payment_method_id: &str,
- ) -> CustomResult<storage_types::PaymentMethod, errors::StorageError> {
+ ) -> CustomResult<domain::PaymentMethod, errors::StorageError> {
let conn = connection::pg_connection_write(self).await?;
storage_types::PaymentMethod::delete_by_merchant_id_payment_method_id(
&conn,
@@ -450,15 +784,72 @@ mod storage {
payment_method_id,
)
.await
- .map_err(|error| report!(errors::StorageError::from(error)))
+ .map_err(|error| report!(errors::StorageError::from(error)))?
+ .convert(
+ state,
+ key_store.key.get_inner(),
+ key_store.merchant_id.clone().into(),
+ )
+ .await
+ .change_context(errors::StorageError::DecryptionError)
+ }
+
+ // Soft delete, Check if KV stuff is needed here
+ #[cfg(all(feature = "v2", feature = "payment_methods_v2"))]
+ async fn delete_payment_method(
+ &self,
+ state: &KeyManagerState,
+ key_store: &domain::MerchantKeyStore,
+ payment_method: domain::PaymentMethod,
+ ) -> CustomResult<domain::PaymentMethod, errors::StorageError> {
+ let payment_method = Conversion::convert(payment_method)
+ .await
+ .change_context(errors::StorageError::DecryptionError)?;
+ let conn = connection::pg_connection_write(self).await?;
+ let payment_method_update = storage_types::PaymentMethodUpdate::StatusUpdate {
+ status: Some(common_enums::PaymentMethodStatus::Inactive),
+ };
+ payment_method
+ .update_with_id(&conn, payment_method_update.into())
+ .await
+ .map_err(|error| report!(errors::StorageError::from(error)))?
+ .convert(
+ state,
+ key_store.key.get_inner(),
+ key_store.merchant_id.clone().into(),
+ )
+ .await
+ .change_context(errors::StorageError::DecryptionError)
+ }
+
+ // Check if KV stuff is needed here
+ #[cfg(all(feature = "v2", feature = "payment_methods_v2"))]
+ async fn find_payment_method_by_fingerprint_id(
+ &self,
+ state: &KeyManagerState,
+ key_store: &domain::MerchantKeyStore,
+ fingerprint_id: &str,
+ ) -> CustomResult<domain::PaymentMethod, errors::StorageError> {
+ let conn = connection::pg_connection_read(self).await?;
+ storage_types::PaymentMethod::find_by_fingerprint_id(&conn, fingerprint_id)
+ .await
+ .map_err(|error| report!(errors::StorageError::from(error)))?
+ .convert(
+ state,
+ key_store.key.get_inner(),
+ key_store.merchant_id.clone().into(),
+ )
+ .await
+ .change_context(errors::StorageError::DecryptionError)
}
}
}
#[cfg(not(feature = "kv_store"))]
mod storage {
- use common_utils::id_type;
- use error_stack::report;
+ use common_utils::{id_type, types::keymanager::KeyManagerState};
+ use error_stack::{report, ResultExt};
+ use hyperswitch_domain_models::behaviour::{Conversion, ReverseConversion};
use router_env::{instrument, tracing};
use super::PaymentMethodInterface;
@@ -466,35 +857,89 @@ mod storage {
connection,
core::errors::{self, CustomResult},
services::Store,
- types::storage::{self as storage_types, enums::MerchantStorageScheme},
+ types::{
+ domain,
+ storage::{self as storage_types, enums::MerchantStorageScheme},
+ },
};
#[async_trait::async_trait]
impl PaymentMethodInterface for Store {
#[instrument(skip_all)]
+ #[cfg(all(
+ any(feature = "v1", feature = "v2"),
+ not(feature = "payment_methods_v2")
+ ))]
async fn find_payment_method(
&self,
+ state: &KeyManagerState,
+ key_store: &domain::MerchantKeyStore,
payment_method_id: &str,
_storage_scheme: MerchantStorageScheme,
- ) -> CustomResult<storage_types::PaymentMethod, errors::StorageError> {
+ ) -> CustomResult<domain::PaymentMethod, errors::StorageError> {
let conn = connection::pg_connection_read(self).await?;
storage_types::PaymentMethod::find_by_payment_method_id(&conn, payment_method_id)
.await
- .map_err(|error| report!(errors::StorageError::from(error)))
+ .map_err(|error| report!(errors::StorageError::from(error)))?
+ .convert(
+ state,
+ key_store.key.get_inner(),
+ key_store.merchant_id.clone().into(),
+ )
+ .await
+ .change_context(errors::StorageError::DecryptionError)
}
+ #[cfg(all(feature = "v2", feature = "payment_methods_v2"))]
+ async fn find_payment_method(
+ &self,
+ state: &KeyManagerState,
+ key_store: &domain::MerchantKeyStore,
+ payment_method_id: &str,
+ _storage_scheme: MerchantStorageScheme,
+ ) -> CustomResult<domain::PaymentMethod, errors::StorageError> {
+ let conn = connection::pg_connection_read(self).await?;
+ storage_types::PaymentMethod::find_by_id(&conn, payment_method_id)
+ .await
+ .map_err(|error| report!(errors::StorageError::from(error)))?
+ .convert(
+ state,
+ key_store.key.get_inner(),
+ key_store.merchant_id.clone().into(),
+ )
+ .await
+ .change_context(errors::StorageError::DecryptionError)
+ }
+
+ #[cfg(all(
+ any(feature = "v1", feature = "v2"),
+ not(feature = "payment_methods_v2")
+ ))]
#[instrument(skip_all)]
async fn find_payment_method_by_locker_id(
&self,
+ state: &KeyManagerState,
+ key_store: &domain::MerchantKeyStore,
locker_id: &str,
_storage_scheme: MerchantStorageScheme,
- ) -> CustomResult<storage_types::PaymentMethod, errors::StorageError> {
+ ) -> CustomResult<domain::PaymentMethod, errors::StorageError> {
let conn = connection::pg_connection_read(self).await?;
storage_types::PaymentMethod::find_by_locker_id(&conn, locker_id)
.await
- .map_err(|error| report!(errors::StorageError::from(error)))
+ .map_err(|error| report!(errors::StorageError::from(error)))?
+ .convert(
+ state,
+ key_store.key.get_inner(),
+ key_store.merchant_id.clone().into(),
+ )
+ .await
+ .change_context(errors::StorageError::DecryptionError)
}
+ #[cfg(all(
+ any(feature = "v1", feature = "v2"),
+ not(feature = "payment_methods_v2")
+ ))]
#[instrument(skip_all)]
async fn get_payment_method_count_by_customer_id_merchant_id_status(
&self,
@@ -516,74 +961,187 @@ mod storage {
#[instrument(skip_all)]
async fn insert_payment_method(
&self,
- payment_method_new: storage_types::PaymentMethodNew,
+ state: &KeyManagerState,
+ key_store: &domain::MerchantKeyStore,
+ payment_method: domain::PaymentMethod,
_storage_scheme: MerchantStorageScheme,
- ) -> CustomResult<storage_types::PaymentMethod, errors::StorageError> {
+ ) -> CustomResult<domain::PaymentMethod, errors::StorageError> {
+ let payment_method_new = payment_method
+ .construct_new()
+ .await
+ .change_context(errors::StorageError::DecryptionError)?;
+
let conn = connection::pg_connection_write(self).await?;
payment_method_new
.insert(&conn)
.await
- .map_err(|error| report!(errors::StorageError::from(error)))
+ .map_err(|error| report!(errors::StorageError::from(error)))?
+ .convert(
+ state,
+ key_store.key.get_inner(),
+ key_store.merchant_id.clone().into(),
+ )
+ .await
+ .change_context(errors::StorageError::DecryptionError)
}
+ #[cfg(all(
+ any(feature = "v1", feature = "v2"),
+ not(feature = "payment_methods_v2")
+ ))]
#[instrument(skip_all)]
async fn update_payment_method(
&self,
- payment_method: storage_types::PaymentMethod,
+ state: &KeyManagerState,
+ key_store: &domain::MerchantKeyStore,
+ payment_method: domain::PaymentMethod,
payment_method_update: storage_types::PaymentMethodUpdate,
_storage_scheme: MerchantStorageScheme,
- ) -> CustomResult<storage_types::PaymentMethod, errors::StorageError> {
+ ) -> CustomResult<domain::PaymentMethod, errors::StorageError> {
+ let payment_method = Conversion::convert(payment_method)
+ .await
+ .change_context(errors::StorageError::DecryptionError)?;
+
let conn = connection::pg_connection_write(self).await?;
payment_method
.update_with_payment_method_id(&conn, payment_method_update.into())
.await
- .map_err(|error| report!(errors::StorageError::from(error)))
+ .map_err(|error| report!(errors::StorageError::from(error)))?
+ .convert(
+ state,
+ key_store.key.get_inner(),
+ key_store.merchant_id.clone().into(),
+ )
+ .await
+ .change_context(errors::StorageError::DecryptionError)
+ }
+
+ #[cfg(all(feature = "v2", feature = "payment_methods_v2"))]
+ #[instrument(skip_all)]
+ async fn update_payment_method(
+ &self,
+ state: &KeyManagerState,
+ key_store: &domain::MerchantKeyStore,
+ payment_method: domain::PaymentMethod,
+ payment_method_update: storage_types::PaymentMethodUpdate,
+ _storage_scheme: MerchantStorageScheme,
+ ) -> CustomResult<domain::PaymentMethod, errors::StorageError> {
+ let payment_method = payment_method
+ .convert(
+ state,
+ key_store.key.get_inner(),
+ key_store.merchant_id.clone().into(),
+ )
+ .await
+ .change_context(errors::StorageError::DecryptionError)?;
+
+ let conn = connection::pg_connection_write(self).await?;
+ payment_method
+ .update_with_id(&conn, payment_method_update.into())
+ .await
+ .map_err(|error| report!(errors::StorageError::from(error)))?
+ .convert(
+ state,
+ key_store.key.get_inner(),
+ key_store.merchant_id.clone().into(),
+ )
+ .await
+ .change_context(errors::StorageError::DecryptionError)
}
+ #[cfg(all(
+ any(feature = "v1", feature = "v2"),
+ not(feature = "payment_methods_v2")
+ ))]
#[instrument(skip_all)]
async fn find_payment_method_by_customer_id_merchant_id_list(
&self,
+ state: &KeyManagerState,
+ key_store: &domain::MerchantKeyStore,
customer_id: &id_type::CustomerId,
merchant_id: &id_type::MerchantId,
limit: Option<i64>,
- ) -> CustomResult<Vec<storage_types::PaymentMethod>, errors::StorageError> {
+ ) -> CustomResult<Vec<domain::PaymentMethod>, errors::StorageError> {
let conn = connection::pg_connection_read(self).await?;
- storage_types::PaymentMethod::find_by_customer_id_merchant_id(
+ let payment_methods = storage_types::PaymentMethod::find_by_customer_id_merchant_id(
&conn,
customer_id,
merchant_id,
limit,
)
.await
- .map_err(|error| report!(errors::StorageError::from(error)))
+ .map_err(|error| report!(errors::StorageError::from(error)))?;
+
+ let pm_futures = payment_methods
+ .into_iter()
+ .map(|pm| async {
+ pm.convert(
+ state,
+ key_store.key.get_inner(),
+ key_store.merchant_id.clone().into(),
+ )
+ .await
+ .change_context(errors::StorageError::DecryptionError)
+ })
+ .collect::<Vec<_>>();
+
+ let domain_payment_methods = futures::future::try_join_all(pm_futures).await?;
+
+ Ok(domain_payment_methods)
}
#[instrument(skip_all)]
async fn find_payment_method_by_customer_id_merchant_id_status(
&self,
+ state: &KeyManagerState,
+ key_store: &domain::MerchantKeyStore,
customer_id: &id_type::CustomerId,
merchant_id: &id_type::MerchantId,
status: common_enums::PaymentMethodStatus,
limit: Option<i64>,
_storage_scheme: MerchantStorageScheme,
- ) -> CustomResult<Vec<storage_types::PaymentMethod>, errors::StorageError> {
+ ) -> CustomResult<Vec<domain::PaymentMethod>, errors::StorageError> {
let conn = connection::pg_connection_read(self).await?;
- storage_types::PaymentMethod::find_by_customer_id_merchant_id_status(
- &conn,
- customer_id,
- merchant_id,
- status,
- limit,
- )
- .await
- .map_err(|error| report!(errors::StorageError::from(error)))
+ let payment_methods =
+ storage_types::PaymentMethod::find_by_customer_id_merchant_id_status(
+ &conn,
+ customer_id,
+ merchant_id,
+ status,
+ limit,
+ )
+ .await
+ .map_err(|error| report!(errors::StorageError::from(error)))?;
+
+ let pm_futures = payment_methods
+ .into_iter()
+ .map(|pm| async {
+ pm.convert(
+ state,
+ key_store.key.get_inner(),
+ key_store.merchant_id.clone().into(),
+ )
+ .await
+ .change_context(errors::StorageError::DecryptionError)
+ })
+ .collect::<Vec<_>>();
+
+ let domain_payment_methods = futures::future::try_join_all(pm_futures).await?;
+
+ Ok(domain_payment_methods)
}
+ #[cfg(all(
+ any(feature = "v1", feature = "v2"),
+ not(feature = "payment_methods_v2")
+ ))]
async fn delete_payment_method_by_merchant_id_payment_method_id(
&self,
+ state: &KeyManagerState,
+ key_store: &domain::MerchantKeyStore,
merchant_id: &id_type::MerchantId,
payment_method_id: &str,
- ) -> CustomResult<storage_types::PaymentMethod, errors::StorageError> {
+ ) -> CustomResult<domain::PaymentMethod, errors::StorageError> {
let conn = connection::pg_connection_write(self).await?;
storage_types::PaymentMethod::delete_by_merchant_id_payment_method_id(
&conn,
@@ -591,7 +1149,61 @@ mod storage {
payment_method_id,
)
.await
- .map_err(|error| report!(errors::StorageError::from(error)))
+ .map_err(|error| report!(errors::StorageError::from(error)))?
+ .convert(
+ state,
+ key_store.key.get_inner(),
+ key_store.merchant_id.clone().into(),
+ )
+ .await
+ .change_context(errors::StorageError::DecryptionError)
+ }
+
+ #[cfg(all(feature = "v2", feature = "payment_methods_v2"))]
+ async fn delete_payment_method(
+ &self,
+ state: &KeyManagerState,
+ key_store: &domain::MerchantKeyStore,
+ payment_method: domain::PaymentMethod,
+ ) -> CustomResult<domain::PaymentMethod, errors::StorageError> {
+ let payment_method = Conversion::convert(payment_method)
+ .await
+ .change_context(errors::StorageError::DecryptionError)?;
+ let conn = connection::pg_connection_write(self).await?;
+ let payment_method_update = storage_types::PaymentMethodUpdate::StatusUpdate {
+ status: Some(common_enums::PaymentMethodStatus::Inactive),
+ };
+ payment_method
+ .update_with_id(&conn, payment_method_update.into())
+ .await
+ .map_err(|error| report!(errors::StorageError::from(error)))?
+ .convert(
+ state,
+ key_store.key.get_inner(),
+ key_store.merchant_id.clone().into(),
+ )
+ .await
+ .change_context(errors::StorageError::DecryptionError)
+ }
+
+ #[cfg(all(feature = "v2", feature = "payment_methods_v2"))]
+ async fn find_payment_method_by_fingerprint_id(
+ &self,
+ state: &KeyManagerState,
+ key_store: &domain::MerchantKeyStore,
+ fingerprint_id: &str,
+ ) -> CustomResult<domain::PaymentMethod, errors::StorageError> {
+ let conn = connection::pg_connection_read(self).await?;
+ storage_types::PaymentMethod::find_by_fingerprint_id(&conn, fingerprint_id)
+ .await
+ .map_err(|error| report!(errors::StorageError::from(error)))?
+ .convert(
+ state,
+ key_store.key.get_inner(),
+ key_store.merchant_id.clone().into(),
+ )
+ .await
+ .change_context(errors::StorageError::DecryptionError)
}
}
}
@@ -600,17 +1212,26 @@ mod storage {
impl PaymentMethodInterface for MockDb {
async fn find_payment_method(
&self,
+ state: &KeyManagerState,
+ key_store: &domain::MerchantKeyStore,
payment_method_id: &str,
_storage_scheme: MerchantStorageScheme,
- ) -> CustomResult<storage_types::PaymentMethod, errors::StorageError> {
+ ) -> CustomResult<domain::PaymentMethod, errors::StorageError> {
let payment_methods = self.payment_methods.lock().await;
let payment_method = payment_methods
.iter()
- .find(|pm| pm.payment_method_id == payment_method_id)
+ .find(|pm| pm.get_id() == payment_method_id)
.cloned();
match payment_method {
- Some(pm) => Ok(pm),
+ Some(pm) => Ok(pm
+ .convert(
+ state,
+ key_store.key.get_inner(),
+ key_store.merchant_id.clone().into(),
+ )
+ .await
+ .change_context(errors::StorageError::DecryptionError)?),
None => Err(errors::StorageError::ValueNotFound(
"cannot find payment method".to_string(),
)
@@ -618,11 +1239,17 @@ impl PaymentMethodInterface for MockDb {
}
}
+ #[cfg(all(
+ any(feature = "v1", feature = "v2"),
+ not(feature = "payment_methods_v2")
+ ))]
async fn find_payment_method_by_locker_id(
&self,
+ state: &KeyManagerState,
+ key_store: &domain::MerchantKeyStore,
locker_id: &str,
_storage_scheme: MerchantStorageScheme,
- ) -> CustomResult<storage_types::PaymentMethod, errors::StorageError> {
+ ) -> CustomResult<domain::PaymentMethod, errors::StorageError> {
let payment_methods = self.payment_methods.lock().await;
let payment_method = payment_methods
.iter()
@@ -630,7 +1257,14 @@ impl PaymentMethodInterface for MockDb {
.cloned();
match payment_method {
- Some(pm) => Ok(pm),
+ Some(pm) => Ok(pm
+ .convert(
+ state,
+ key_store.key.get_inner(),
+ key_store.merchant_id.clone().into(),
+ )
+ .await
+ .change_context(errors::StorageError::DecryptionError)?),
None => Err(errors::StorageError::ValueNotFound(
"cannot find payment method".to_string(),
)
@@ -638,6 +1272,10 @@ impl PaymentMethodInterface for MockDb {
}
}
+ #[cfg(all(
+ any(feature = "v1", feature = "v2"),
+ not(feature = "payment_methods_v2")
+ ))]
async fn get_payment_method_count_by_customer_id_merchant_id_status(
&self,
customer_id: &id_type::CustomerId,
@@ -658,53 +1296,33 @@ impl PaymentMethodInterface for MockDb {
async fn insert_payment_method(
&self,
- payment_method_new: storage_types::PaymentMethodNew,
+ _state: &KeyManagerState,
+ _key_store: &domain::MerchantKeyStore,
+ payment_method: domain::PaymentMethod,
_storage_scheme: MerchantStorageScheme,
- ) -> CustomResult<storage_types::PaymentMethod, errors::StorageError> {
+ ) -> CustomResult<domain::PaymentMethod, errors::StorageError> {
let mut payment_methods = self.payment_methods.lock().await;
- let payment_method = storage_types::PaymentMethod {
- customer_id: payment_method_new.customer_id,
- merchant_id: payment_method_new.merchant_id,
- payment_method_id: payment_method_new.payment_method_id,
- locker_id: payment_method_new.locker_id,
- accepted_currency: payment_method_new.accepted_currency,
- scheme: payment_method_new.scheme,
- token: payment_method_new.token,
- cardholder_name: payment_method_new.cardholder_name,
- issuer_name: payment_method_new.issuer_name,
- issuer_country: payment_method_new.issuer_country,
- payer_country: payment_method_new.payer_country,
- is_stored: payment_method_new.is_stored,
- swift_code: payment_method_new.swift_code,
- direct_debit_token: payment_method_new.direct_debit_token,
- created_at: payment_method_new.created_at,
- last_modified: payment_method_new.last_modified,
- payment_method: payment_method_new.payment_method,
- payment_method_type: payment_method_new.payment_method_type,
- payment_method_issuer: payment_method_new.payment_method_issuer,
- payment_method_issuer_code: payment_method_new.payment_method_issuer_code,
- metadata: payment_method_new.metadata,
- payment_method_data: payment_method_new.payment_method_data,
- last_used_at: payment_method_new.last_used_at,
- connector_mandate_details: payment_method_new.connector_mandate_details,
- customer_acceptance: payment_method_new.customer_acceptance,
- status: payment_method_new.status,
- client_secret: payment_method_new.client_secret,
- network_transaction_id: payment_method_new.network_transaction_id,
- updated_by: payment_method_new.updated_by,
- payment_method_billing_address: payment_method_new.payment_method_billing_address,
- };
- payment_methods.push(payment_method.clone());
+ let pm = Conversion::convert(payment_method.clone())
+ .await
+ .change_context(errors::StorageError::DecryptionError)?;
+
+ payment_methods.push(pm);
Ok(payment_method)
}
+ #[cfg(all(
+ any(feature = "v1", feature = "v2"),
+ not(feature = "payment_methods_v2")
+ ))]
async fn find_payment_method_by_customer_id_merchant_id_list(
&self,
+ state: &KeyManagerState,
+ key_store: &domain::MerchantKeyStore,
customer_id: &id_type::CustomerId,
merchant_id: &id_type::MerchantId,
_limit: Option<i64>,
- ) -> CustomResult<Vec<storage_types::PaymentMethod>, errors::StorageError> {
+ ) -> CustomResult<Vec<domain::PaymentMethod>, errors::StorageError> {
let payment_methods = self.payment_methods.lock().await;
let payment_methods_found: Vec<storage_types::PaymentMethod> = payment_methods
.iter()
@@ -718,18 +1336,35 @@ impl PaymentMethodInterface for MockDb {
.into(),
)
} else {
- Ok(payment_methods_found)
+ let pm_futures = payment_methods_found
+ .into_iter()
+ .map(|pm| async {
+ pm.convert(
+ state,
+ key_store.key.get_inner(),
+ key_store.merchant_id.clone().into(),
+ )
+ .await
+ .change_context(errors::StorageError::DecryptionError)
+ })
+ .collect::<Vec<_>>();
+
+ let domain_payment_methods = futures::future::try_join_all(pm_futures).await?;
+
+ Ok(domain_payment_methods)
}
}
async fn find_payment_method_by_customer_id_merchant_id_status(
&self,
+ state: &KeyManagerState,
+ key_store: &domain::MerchantKeyStore,
customer_id: &id_type::CustomerId,
merchant_id: &id_type::MerchantId,
status: common_enums::PaymentMethodStatus,
_limit: Option<i64>,
_storage_scheme: MerchantStorageScheme,
- ) -> CustomResult<Vec<storage_types::PaymentMethod>, errors::StorageError> {
+ ) -> CustomResult<Vec<domain::PaymentMethod>, errors::StorageError> {
let payment_methods = self.payment_methods.lock().await;
let payment_methods_found: Vec<storage_types::PaymentMethod> = payment_methods
.iter()
@@ -747,22 +1382,51 @@ impl PaymentMethodInterface for MockDb {
.into(),
)
} else {
- Ok(payment_methods_found)
+ let pm_futures = payment_methods_found
+ .into_iter()
+ .map(|pm| async {
+ pm.convert(
+ state,
+ key_store.key.get_inner(),
+ key_store.merchant_id.clone().into(),
+ )
+ .await
+ .change_context(errors::StorageError::DecryptionError)
+ })
+ .collect::<Vec<_>>();
+
+ let domain_payment_methods = futures::future::try_join_all(pm_futures).await?;
+
+ Ok(domain_payment_methods)
}
}
+ #[cfg(all(
+ any(feature = "v1", feature = "v2"),
+ not(feature = "payment_methods_v2")
+ ))]
async fn delete_payment_method_by_merchant_id_payment_method_id(
&self,
+ state: &KeyManagerState,
+ key_store: &domain::MerchantKeyStore,
merchant_id: &id_type::MerchantId,
payment_method_id: &str,
- ) -> CustomResult<storage_types::PaymentMethod, errors::StorageError> {
+ ) -> CustomResult<domain::PaymentMethod, errors::StorageError> {
let mut payment_methods = self.payment_methods.lock().await;
- match payment_methods.iter().position(|pm| {
- pm.merchant_id == *merchant_id && pm.payment_method_id == payment_method_id
- }) {
+ match payment_methods
+ .iter()
+ .position(|pm| pm.merchant_id == *merchant_id && pm.get_id() == payment_method_id)
+ {
Some(index) => {
let deleted_payment_method = payment_methods.remove(index);
- Ok(deleted_payment_method)
+ Ok(deleted_payment_method
+ .convert(
+ state,
+ key_store.key.get_inner(),
+ key_store.merchant_id.clone().into(),
+ )
+ .await
+ .change_context(errors::StorageError::DecryptionError)?)
}
None => Err(errors::StorageError::ValueNotFound(
"cannot find payment method to delete".to_string(),
@@ -773,16 +1437,18 @@ impl PaymentMethodInterface for MockDb {
async fn update_payment_method(
&self,
- payment_method: storage_types::PaymentMethod,
+ state: &KeyManagerState,
+ key_store: &domain::MerchantKeyStore,
+ payment_method: domain::PaymentMethod,
payment_method_update: storage_types::PaymentMethodUpdate,
_storage_scheme: MerchantStorageScheme,
- ) -> CustomResult<storage_types::PaymentMethod, errors::StorageError> {
+ ) -> CustomResult<domain::PaymentMethod, errors::StorageError> {
let pm_update_res = self
.payment_methods
.lock()
.await
.iter_mut()
- .find(|pm| pm.payment_method_id == payment_method.payment_method_id)
+ .find(|pm| pm.get_id() == payment_method.get_id())
.map(|pm| {
let payment_method_updated =
PaymentMethodUpdateInternal::from(payment_method_update)
@@ -792,11 +1458,88 @@ impl PaymentMethodInterface for MockDb {
});
match pm_update_res {
- Some(result) => Ok(result),
+ Some(result) => Ok(result
+ .convert(
+ state,
+ key_store.key.get_inner(),
+ key_store.merchant_id.clone().into(),
+ )
+ .await
+ .change_context(errors::StorageError::DecryptionError)?),
None => Err(errors::StorageError::ValueNotFound(
"cannot find payment method to update".to_string(),
)
.into()),
}
}
+
+ #[cfg(all(feature = "v2", feature = "payment_methods_v2"))]
+ async fn delete_payment_method(
+ &self,
+ state: &KeyManagerState,
+ key_store: &domain::MerchantKeyStore,
+ payment_method: domain::PaymentMethod,
+ ) -> CustomResult<domain::PaymentMethod, errors::StorageError> {
+ let payment_method_update = storage_types::PaymentMethodUpdate::StatusUpdate {
+ status: Some(common_enums::PaymentMethodStatus::Inactive),
+ };
+
+ let pm_update_res = self
+ .payment_methods
+ .lock()
+ .await
+ .iter_mut()
+ .find(|pm| pm.get_id() == payment_method.get_id())
+ .map(|pm| {
+ let payment_method_updated =
+ PaymentMethodUpdateInternal::from(payment_method_update)
+ .create_payment_method(pm.clone());
+ *pm = payment_method_updated.clone();
+ payment_method_updated
+ });
+
+ match pm_update_res {
+ Some(result) => Ok(result
+ .convert(
+ state,
+ key_store.key.get_inner(),
+ key_store.merchant_id.clone().into(),
+ )
+ .await
+ .change_context(errors::StorageError::DecryptionError)?),
+ None => Err(errors::StorageError::ValueNotFound(
+ "cannot find payment method to update".to_string(),
+ )
+ .into()),
+ }
+ }
+
+ #[cfg(all(feature = "v2", feature = "payment_methods_v2"))]
+ async fn find_payment_method_by_fingerprint_id(
+ &self,
+ state: &KeyManagerState,
+ key_store: &domain::MerchantKeyStore,
+ fingerprint_id: &str,
+ ) -> CustomResult<domain::PaymentMethod, errors::StorageError> {
+ let payment_methods = self.payment_methods.lock().await;
+ let payment_method = payment_methods
+ .iter()
+ .find(|pm| pm.locker_fingerprint_id == Some(fingerprint_id.to_string()))
+ .cloned();
+
+ match payment_method {
+ Some(pm) => Ok(pm
+ .convert(
+ state,
+ key_store.key.get_inner(),
+ key_store.merchant_id.clone().into(),
+ )
+ .await
+ .change_context(errors::StorageError::DecryptionError)?),
+ None => Err(errors::StorageError::ValueNotFound(
+ "cannot find payment method".to_string(),
+ )
+ .into()),
+ }
+ }
}
diff --git a/crates/router/src/types/api/mandates.rs b/crates/router/src/types/api/mandates.rs
index bf8f00526e9..9262877a385 100644
--- a/crates/router/src/types/api/mandates.rs
+++ b/crates/router/src/types/api/mandates.rs
@@ -32,6 +32,91 @@ pub(crate) trait MandateResponseExt: Sized {
) -> RouterResult<Self>;
}
+#[cfg(all(
+ any(feature = "v1", feature = "v2"),
+ not(feature = "payment_methods_v2")
+))]
+#[async_trait::async_trait]
+impl MandateResponseExt for MandateResponse {
+ async fn from_db_mandate(
+ state: &SessionState,
+ key_store: domain::MerchantKeyStore,
+ mandate: storage::Mandate,
+ storage_scheme: storage_enums::MerchantStorageScheme,
+ ) -> RouterResult<Self> {
+ let db = &*state.store;
+ let payment_method = db
+ .find_payment_method(
+ &(state.into()),
+ &key_store,
+ &mandate.payment_method_id,
+ storage_scheme,
+ )
+ .await
+ .to_not_found_response(errors::ApiErrorResponse::PaymentMethodNotFound)?;
+
+ let pm = payment_method
+ .payment_method
+ .get_required_value("payment_method")
+ .change_context(errors::ApiErrorResponse::PaymentMethodNotFound)
+ .attach_printable("payment_method not found")?;
+
+ let card = if pm == storage_enums::PaymentMethod::Card {
+ // if locker is disabled , decrypt the payment method data
+ let card_details = if state.conf.locker.locker_enabled {
+ let card = payment_methods::cards::get_card_from_locker(
+ state,
+ &payment_method.customer_id,
+ &payment_method.merchant_id,
+ payment_method
+ .locker_id
+ .as_ref()
+ .unwrap_or(payment_method.get_id()),
+ )
+ .await?;
+
+ payment_methods::transformers::get_card_detail(&payment_method, card)
+ .change_context(errors::ApiErrorResponse::InternalServerError)
+ .attach_printable("Failed while getting card details")?
+ } else {
+ payment_methods::cards::get_card_details_without_locker_fallback(
+ &payment_method,
+ state,
+ )
+ .await?
+ };
+
+ Some(MandateCardDetails::from(card_details).into_inner())
+ } else {
+ None
+ };
+ let payment_method_type = payment_method
+ .payment_method_type
+ .map(|pmt| pmt.to_string());
+ Ok(Self {
+ mandate_id: mandate.mandate_id,
+ customer_acceptance: Some(api::payments::CustomerAcceptance {
+ acceptance_type: if mandate.customer_ip_address.is_some() {
+ api::payments::AcceptanceType::Online
+ } else {
+ api::payments::AcceptanceType::Offline
+ },
+ accepted_at: mandate.customer_accepted_at,
+ online: Some(api::payments::OnlineMandate {
+ ip_address: mandate.customer_ip_address,
+ user_agent: mandate.customer_user_agent.unwrap_or_default(),
+ }),
+ }),
+ card,
+ status: mandate.mandate_status,
+ payment_method: pm.to_string(),
+ payment_method_type,
+ payment_method_id: mandate.payment_method_id,
+ })
+ }
+}
+
+#[cfg(all(feature = "v2", feature = "payment_methods_v2"))]
#[async_trait::async_trait]
impl MandateResponseExt for MandateResponse {
async fn from_db_mandate(
@@ -42,7 +127,12 @@ impl MandateResponseExt for MandateResponse {
) -> RouterResult<Self> {
let db = &*state.store;
let payment_method = db
- .find_payment_method(&mandate.payment_method_id, storage_scheme)
+ .find_payment_method(
+ &(state.into()),
+ &key_store,
+ &mandate.payment_method_id,
+ storage_scheme,
+ )
.await
.to_not_found_response(errors::ApiErrorResponse::PaymentMethodNotFound)?;
@@ -62,7 +152,7 @@ impl MandateResponseExt for MandateResponse {
payment_method
.locker_id
.as_ref()
- .unwrap_or(&payment_method.payment_method_id),
+ .unwrap_or(&payment_method.id),
)
.await?;
@@ -73,7 +163,6 @@ impl MandateResponseExt for MandateResponse {
payment_methods::cards::get_card_details_without_locker_fallback(
&payment_method,
state,
- &key_store,
)
.await?
};
diff --git a/crates/router/src/types/domain.rs b/crates/router/src/types/domain.rs
index d1dad53ce34..37b8d2b8016 100644
--- a/crates/router/src/types/domain.rs
+++ b/crates/router/src/types/domain.rs
@@ -25,6 +25,12 @@ mod merchant_connector_account;
mod merchant_key_store {
pub use hyperswitch_domain_models::merchant_key_store::MerchantKeyStore;
}
+pub mod payment_methods {
+ pub use hyperswitch_domain_models::payment_methods::*;
+}
+pub mod consts {
+ pub use hyperswitch_domain_models::consts::*;
+}
pub mod payments;
pub mod types;
#[cfg(feature = "olap")]
@@ -33,9 +39,11 @@ pub mod user_key_store;
pub use address::*;
pub use business_profile::*;
+pub use consts::*;
pub use event::*;
pub use merchant_connector_account::*;
pub use merchant_key_store::*;
+pub use payment_methods::*;
pub use payments::*;
#[cfg(feature = "olap")]
pub use user::*;
diff --git a/crates/router/src/types/transformers.rs b/crates/router/src/types/transformers.rs
index ca4ba575d79..7b637b76c16 100644
--- a/crates/router/src/types/transformers.rs
+++ b/crates/router/src/types/transformers.rs
@@ -88,19 +88,19 @@ impl ForeignFrom<api_models::refunds::RefundType> for storage_enums::RefundType
impl
ForeignFrom<(
Option<payment_methods::CardDetailFromLocker>,
- diesel_models::PaymentMethod,
+ domain::PaymentMethod,
)> for payment_methods::PaymentMethodResponse
{
fn foreign_from(
(card_details, item): (
Option<payment_methods::CardDetailFromLocker>,
- diesel_models::PaymentMethod,
+ domain::PaymentMethod,
),
) -> Self {
Self {
- merchant_id: item.merchant_id,
- customer_id: Some(item.customer_id),
- payment_method_id: item.payment_method_id,
+ 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.payment_method,
payment_method_type: item.payment_method_type,
card: card_details,
@@ -121,23 +121,22 @@ impl
impl
ForeignFrom<(
Option<payment_methods::CardDetailFromLocker>,
- diesel_models::PaymentMethod,
+ domain::PaymentMethod,
)> for payment_methods::PaymentMethodResponse
{
fn foreign_from(
(card_details, item): (
Option<payment_methods::CardDetailFromLocker>,
- diesel_models::PaymentMethod,
+ domain::PaymentMethod,
),
) -> Self {
Self {
- merchant_id: item.merchant_id,
- customer_id: item.customer_id,
- payment_method_id: item.payment_method_id,
+ merchant_id: item.merchant_id.to_owned(),
+ customer_id: item.customer_id.to_owned(),
+ payment_method_id: item.get_id().clone(),
payment_method: item.payment_method,
payment_method_type: item.payment_method_type,
- payment_method_data: card_details
- .map(|card| payment_methods::PaymentMethodResponseData::Card(card.clone())),
+ payment_method_data: card_details.map(payment_methods::PaymentMethodResponseData::Card),
recurring_enabled: false,
metadata: item.metadata,
created: Some(item.created_at),
diff --git a/crates/router/src/workflows/payment_method_status_update.rs b/crates/router/src/workflows/payment_method_status_update.rs
index 5120f1ba197..abc30074cda 100644
--- a/crates/router/src/workflows/payment_method_status_update.rs
+++ b/crates/router/src/workflows/payment_method_status_update.rs
@@ -45,7 +45,12 @@ impl ProcessTrackerWorkflow<SessionState> for PaymentMethodStatusUpdateWorkflow
.await?;
let payment_method = db
- .find_payment_method(&pm_id, merchant_account.storage_scheme)
+ .find_payment_method(
+ &(state.into()),
+ &key_store,
+ &pm_id,
+ merchant_account.storage_scheme,
+ )
.await?;
if payment_method.status != prev_pm_status {
@@ -61,7 +66,13 @@ impl ProcessTrackerWorkflow<SessionState> for PaymentMethodStatusUpdateWorkflow
};
let res = db
- .update_payment_method(payment_method, pm_update, merchant_account.storage_scheme)
+ .update_payment_method(
+ &(state.into()),
+ &key_store,
+ payment_method,
+ pm_update,
+ merchant_account.storage_scheme,
+ )
.await
.map_err(errors::ProcessTrackerError::EStorageError);
diff --git a/crates/storage_impl/Cargo.toml b/crates/storage_impl/Cargo.toml
index 557f6969fb7..22badd47cd0 100644
--- a/crates/storage_impl/Cargo.toml
+++ b/crates/storage_impl/Cargo.toml
@@ -16,6 +16,7 @@ v1 = ["api_models/v1", "diesel_models/v1", "hyperswitch_domain_models/v1"]
v2 = ["api_models/v2", "diesel_models/v2", "hyperswitch_domain_models/v2"]
payment_v2 = ["hyperswitch_domain_models/payment_v2", "diesel_models/payment_v2"]
customer_v2 = ["api_models/customer_v2", "diesel_models/customer_v2", "hyperswitch_domain_models/customer_v2"]
+payment_methods_v2 = ["diesel_models/payment_methods_v2", "api_models/payment_methods_v2", "hyperswitch_domain_models/payment_methods_v2"]
[dependencies]
# First Party dependencies
diff --git a/crates/storage_impl/src/lib.rs b/crates/storage_impl/src/lib.rs
index 995f11b9cc6..c00d2b445f8 100644
--- a/crates/storage_impl/src/lib.rs
+++ b/crates/storage_impl/src/lib.rs
@@ -406,6 +406,10 @@ impl UniqueConstraints for diesel_models::PayoutAttempt {
}
}
+#[cfg(all(
+ any(feature = "v1", feature = "v2"),
+ not(feature = "payment_methods_v2")
+))]
impl UniqueConstraints for diesel_models::PaymentMethod {
fn unique_constraints(&self) -> Vec<String> {
vec![format!("paymentmethod_{}", self.payment_method_id)]
@@ -415,6 +419,16 @@ impl UniqueConstraints for diesel_models::PaymentMethod {
}
}
+#[cfg(all(feature = "v2", feature = "payment_methods_v2"))]
+impl UniqueConstraints for diesel_models::PaymentMethod {
+ fn unique_constraints(&self) -> Vec<String> {
+ vec![format!("paymentmethod_{}", self.id)]
+ }
+ fn table_name(&self) -> &str {
+ "PaymentMethod"
+ }
+}
+
impl UniqueConstraints for diesel_models::Mandate {
fn unique_constraints(&self) -> Vec<String> {
vec![format!(
diff --git a/crates/storage_impl/src/redis/kv_store.rs b/crates/storage_impl/src/redis/kv_store.rs
index 8b5674084a2..8511702baa2 100644
--- a/crates/storage_impl/src/redis/kv_store.rs
+++ b/crates/storage_impl/src/redis/kv_store.rs
@@ -32,7 +32,7 @@ pub enum PartitionKey<'a> {
},
MerchantIdCustomerId {
merchant_id: &'a common_utils::id_type::MerchantId,
- customer_id: &'a str,
+ customer_id: &'a common_utils::id_type::CustomerId,
},
#[cfg(all(feature = "v2", feature = "customer_v2"))]
MerchantIdMerchantReferenceId {
@@ -73,8 +73,9 @@ impl<'a> std::fmt::Display for PartitionKey<'a> {
merchant_id,
customer_id,
} => f.write_str(&format!(
- "mid_{}_cust_{customer_id}",
- merchant_id.get_string_repr()
+ "mid_{}_cust_{}",
+ merchant_id.get_string_repr(),
+ customer_id.get_string_repr()
)),
#[cfg(all(feature = "v2", feature = "customer_v2"))]
PartitionKey::MerchantIdMerchantReferenceId {
diff --git a/migrations/2024-09-02-112941_add_version_in_payment_methods/down.sql b/migrations/2024-09-02-112941_add_version_in_payment_methods/down.sql
new file mode 100644
index 00000000000..e3635ea68f0
--- /dev/null
+++ b/migrations/2024-09-02-112941_add_version_in_payment_methods/down.sql
@@ -0,0 +1,2 @@
+-- This file should undo anything in `up.sql`
+ALTER TABLE payment_methods DROP COLUMN IF EXISTS version;
\ No newline at end of file
diff --git a/migrations/2024-09-02-112941_add_version_in_payment_methods/up.sql b/migrations/2024-09-02-112941_add_version_in_payment_methods/up.sql
new file mode 100644
index 00000000000..70d8c9d34b7
--- /dev/null
+++ b/migrations/2024-09-02-112941_add_version_in_payment_methods/up.sql
@@ -0,0 +1,3 @@
+-- Your SQL goes here
+ALTER TABLE payment_methods
+ADD COLUMN IF NOT EXISTS version "ApiVersion" NOT NULL DEFAULT 'v1';
\ No newline at end of file
diff --git a/v2_migrations/2024-08-23-112510_payment_methods_v2_db_changes/down.sql b/v2_migrations/2024-08-23-112510_payment_methods_v2_db_changes/down.sql
new file mode 100644
index 00000000000..cde77d754f8
--- /dev/null
+++ b/v2_migrations/2024-08-23-112510_payment_methods_v2_db_changes/down.sql
@@ -0,0 +1,44 @@
+-- This file should undo anything in `up.sql`
+ALTER TABLE payment_methods ADD COLUMN IF NOT EXISTS accepted_currency "Currency"[];
+
+ALTER TABLE payment_methods ADD COLUMN IF NOT EXISTS scheme VARCHAR(32);
+
+ALTER TABLE payment_methods ADD COLUMN IF NOT EXISTS token VARCHAR(128);
+
+ALTER TABLE payment_methods ADD COLUMN IF NOT EXISTS cardholder_name VARCHAR(255);
+
+ALTER TABLE payment_methods ADD COLUMN IF NOT EXISTS issuer_name VARCHAR(64);
+
+ALTER TABLE payment_methods ADD COLUMN IF NOT EXISTS issuer_country VARCHAR(64);
+
+ALTER TABLE payment_methods ADD COLUMN IF NOT EXISTS is_stored BOOLEAN;
+
+ALTER TABLE payment_methods ADD COLUMN IF NOT EXISTS direct_debit_token VARCHAR(128);
+
+ALTER TABLE payment_methods ADD COLUMN IF NOT EXISTS swift_code VARCHAR(32);
+
+ALTER TABLE payment_methods ADD COLUMN IF NOT EXISTS payment_method_issuer VARCHAR(128);
+
+CREATE TYPE "PaymentMethodIssuerCode" AS ENUM (
+ 'jp_hdfc',
+ 'jp_icici',
+ 'jp_googlepay',
+ 'jp_applepay',
+ 'jp_phonepe',
+ 'jp_wechat',
+ 'jp_sofort',
+ 'jp_giropay',
+ 'jp_sepa',
+ 'jp_bacs'
+);
+
+ALTER TABLE payment_methods ADD COLUMN IF NOT EXISTS payment_method_issuer_code "PaymentMethodIssuerCode";
+
+ALTER TABLE payment_methods DROP COLUMN IF EXISTS locker_fingerprint_id;
+
+ALTER TABLE payment_methods ADD COLUMN IF NOT EXISTS payment_method_id VARCHAR(64);
+UPDATE payment_methods SET payment_method_id = id;
+ALTER TABLE payment_methods DROP CONSTRAINT IF EXISTS payment_methods_pkey;
+ALTER TABLE payment_methods ADD CONSTRAINT payment_methods_pkey PRIMARY KEY (payment_method_id);
+ALTER TABLE payment_methods DROP COLUMN IF EXISTS id;
+ALTER TABLE payment_methods ADD COLUMN IF NOT EXISTS id SERIAL;
\ No newline at end of file
diff --git a/v2_migrations/2024-08-23-112510_payment_methods_v2_db_changes/up.sql b/v2_migrations/2024-08-23-112510_payment_methods_v2_db_changes/up.sql
new file mode 100644
index 00000000000..151cf068cff
--- /dev/null
+++ b/v2_migrations/2024-08-23-112510_payment_methods_v2_db_changes/up.sql
@@ -0,0 +1,35 @@
+-- Your SQL goes here
+ALTER TABLE payment_methods DROP COLUMN IF EXISTS accepted_currency;
+
+ALTER TABLE payment_methods DROP COLUMN IF EXISTS scheme;
+
+ALTER TABLE payment_methods DROP COLUMN IF EXISTS token;
+
+ALTER TABLE payment_methods DROP COLUMN IF EXISTS cardholder_name;
+
+ALTER TABLE payment_methods DROP COLUMN IF EXISTS issuer_name;
+
+ALTER TABLE payment_methods DROP COLUMN IF EXISTS issuer_country;
+
+ALTER TABLE payment_methods DROP COLUMN IF EXISTS payer_country;
+
+ALTER TABLE payment_methods DROP COLUMN IF EXISTS is_stored;
+
+ALTER TABLE payment_methods DROP COLUMN IF EXISTS direct_debit_token;
+
+ALTER TABLE payment_methods DROP COLUMN IF EXISTS swift_code;
+
+ALTER TABLE payment_methods DROP COLUMN IF EXISTS payment_method_issuer;
+
+ALTER TABLE payment_methods DROP COLUMN IF EXISTS payment_method_issuer_code;
+
+DROP TYPE IF EXISTS "PaymentMethodIssuerCode";
+
+ALTER TABLE payment_methods ADD COLUMN IF NOT EXISTS locker_fingerprint_id VARCHAR(64);
+
+ALTER TABLE payment_methods DROP COLUMN IF EXISTS id;
+ALTER TABLE payment_methods ADD COLUMN IF NOT EXISTS id VARCHAR(64);
+UPDATE payment_methods SET id = payment_method_id;
+ALTER TABLE payment_methods DROP CONSTRAINT IF EXISTS payment_methods_pkey;
+ALTER TABLE payment_methods ADD CONSTRAINT payment_methods_pkey PRIMARY KEY (id);
+ALTER TABLE payment_methods DROP COLUMN IF EXISTS payment_method_id;
\ No newline at end of file
|
2024-08-26T12:48:06Z
|
## Type of Change
<!-- Put an `x` in the boxes that apply -->
- [ ] Bugfix
- [x] New feature
- [ ] Enhancement
- [ ] Refactoring
- [ ] Dependency updates
- [ ] Documentation
- [ ] CI/CD
## Description
<!-- Describe your changes in detail -->
- Diesel model for payment methods v2
- Domain models for payment methods v1/v2
### Additional Changes
- [ ] This PR modifies the API contract
- [x] This PR modifies the database schema
- [ ] This PR modifies application configuration/environment variables
<!--
Provide links to the files with corresponding changes.
Following are the paths where you can find config files:
1. `config`
2. `crates/router/src/configs`
3. `loadtest/config`
-->
## Motivation and Context
<!--
Why is this change required? What problem does it solve?
If it fixes an open issue, please link to the issue here.
If you don't have an issue, we'd recommend starting with one first so the PR
can focus on the implementation (unless it is an obvious bug or documentation fix
that will have little conversation).
-->
## How did you test it?
<!--
Did you write an integration/unit/API test to verify the code changes?
Or did you test this change manually (provide relevant screenshots)?
-->
- Test all flows (payments/payment_methods) for v1
- v2 cannot be tested as core logic is incomplete
## Checklist
<!-- Put an `x` in the boxes that apply -->
- [x] I formatted the code `cargo +nightly fmt --all`
- [x] I addressed lints thrown by `cargo clippy`
- [ ] I reviewed the submitted code
- [ ] I added unit tests for my changes where possible
|
b85322612078a68fbe09e98494bfe849c6c123c2
|
|
juspay/hyperswitch
|
juspay__hyperswitch-5422
|
Bug: [FEATURE] Fixes in PM Auth
### Feature Description
Bugs related to PML in PM Auth needs to be fixed
### Possible Implementation
Implementation depends on the specific bugs encountered.
### Have you spent some time checking if this feature request has been raised before?
- [X] I checked and didn't find a similar issue
### Have you read the Contributing Guidelines?
- [X] I have read the [Contributing Guidelines](https://github.com/juspay/hyperswitch/blob/main/docs/CONTRIBUTING.md)
### Are you willing to submit a PR?
Yes, I am willing to submit a PR!
|
diff --git a/crates/router/src/core/payment_methods/cards.rs b/crates/router/src/core/payment_methods/cards.rs
index 70a0a4e4cd1..a55e9c76b0f 100644
--- a/crates/router/src/core/payment_methods/cards.rs
+++ b/crates/router/src/core/payment_methods/cards.rs
@@ -2356,7 +2356,8 @@ pub async fn list_payment_methods(
.await?;
// filter out connectors based on the business country
- let filtered_mcas = helpers::filter_mca_based_on_business_profile(all_mcas, profile_id.clone());
+ let filtered_mcas =
+ helpers::filter_mca_based_on_business_profile(all_mcas.clone(), profile_id.clone());
logger::debug!(mca_before_filtering=?filtered_mcas);
@@ -2667,33 +2668,34 @@ pub async fn list_payment_methods(
});
if let Some(config) = pm_auth_config {
- config
- .enabled_payment_methods
- .iter()
- .for_each(|inner_config| {
- if inner_config.payment_method_type == *payment_method_type {
- let pm = pmt_to_auth_connector
- .get(&inner_config.payment_method)
- .cloned();
-
- let inner_map = if let Some(mut inner_map) = pm {
- inner_map.insert(
- *payment_method_type,
- inner_config.connector_name.clone(),
- );
- inner_map
- } else {
- HashMap::from([(
- *payment_method_type,
- inner_config.connector_name.clone(),
- )])
- };
-
- pmt_to_auth_connector
- .insert(inner_config.payment_method, inner_map);
- val.push(inner_config.clone());
- }
- });
+ for inner_config in config.enabled_payment_methods.iter() {
+ let is_active_mca = all_mcas
+ .iter()
+ .any(|mca| mca.merchant_connector_id == inner_config.mca_id);
+
+ if inner_config.payment_method_type == *payment_method_type && is_active_mca
+ {
+ let pm = pmt_to_auth_connector
+ .get(&inner_config.payment_method)
+ .cloned();
+
+ let inner_map = if let Some(mut inner_map) = pm {
+ inner_map.insert(
+ *payment_method_type,
+ inner_config.connector_name.clone(),
+ );
+ inner_map
+ } else {
+ HashMap::from([(
+ *payment_method_type,
+ inner_config.connector_name.clone(),
+ )])
+ };
+
+ pmt_to_auth_connector.insert(inner_config.payment_method, inner_map);
+ val.push(inner_config.clone());
+ }
+ }
};
}
}
|
2024-07-23T14:01:03Z
|
## Type of Change
<!-- Put an `x` in the boxes that apply -->
- [x] Bugfix
- [ ] New feature
- [ ] Enhancement
- [ ] Refactoring
- [ ] Dependency updates
- [ ] Documentation
- [ ] CI/CD
## Description
<!-- Describe your changes in detail -->
Added a check in mca for pm_auth_connectors to include only the active ones.
If a Pm auth connector is disabled, it should not show up in the `pm_auth_connector` field in PML response
### Additional Changes
- [ ] This PR modifies the API contract
- [ ] This PR modifies the database schema
- [ ] This PR modifies application configuration/environment variables
<!--
Provide links to the files with corresponding changes.
Following are the paths where you can find config files:
1. `config`
2. `crates/router/src/configs`
3. `loadtest/config`
-->
## Motivation and Context
<!--
Why is this change required? What problem does it solve?
If it fixes an open issue, please link to the issue here.
If you don't have an issue, we'd recommend starting with one first so the PR
can focus on the implementation (unless it is an obvious bug or documentation fix
that will have little conversation).
-->
## How did you test it?
<!--
Did you write an integration/unit/API test to verify the code changes?
Or did you test this change manually (provide relevant screenshots)?
-->
1. Deactivate the pm_auth account -
```
curl --location --request POST 'http://localhost:8080/account/merchant_1721742760/connectors/mca_r7PzL0AWF5tHJ8sUWqIG' \
--header 'Content-Type: application/json' \
--header 'Accept: application/json' \
--header 'api-key: test_admin' \
--data-raw '{
"connector_type": "payment_method_auth",
"status": "inactive",
"metadata": {
"city": "NY",
"unit": "245"
}
}'
```
2. Call PML for merchant
```
curl --location --request GET 'http://localhost:8080/account/payment_methods?client_secret=pay_zj0McWhRpiXD0LHDLUmf_secret_59U5b2KF3XTaYnkVCkh5' \
--header 'Accept: application/json' \
--header 'api-key: pk_dev_96d5dd30db4542d9bb0135c05abf79f3' \
--data-raw ''
```
Resposne
```
{
"redirect_url": "https://google.com/success",
"currency": "USD",
"payment_methods": [
{
"payment_method": "pay_later",
"payment_method_types": [
{
"payment_method_type": "klarna",
"payment_experience": [
{
"payment_experience_type": "redirect_to_url",
"eligible_connectors": [
"stripe"
]
}
],
"card_networks": null,
"bank_names": null,
"bank_debits": null,
"bank_transfers": null,
"required_fields": {
"email": {
"required_field": "email",
"display_name": "email",
"field_type": "user_email_address",
"value": "guest@example.com"
},
"payment_method_data.pay_later.klarna.billing_country": {
"required_field": "payment_method_data.pay_later.klarna.billing_country",
"display_name": "billing_country",
"field_type": {
"user_address_country": {
"options": [
"ALL"
]
}
},
"value": null
}
},
"surcharge_details": null,
"pm_auth_connector": null
},
{
"payment_method_type": "afterpay_clearpay",
"payment_experience": [
{
"payment_experience_type": "redirect_to_url",
"eligible_connectors": [
"stripe"
]
}
],
"card_networks": null,
"bank_names": null,
"bank_debits": null,
"bank_transfers": null,
"required_fields": {
"payment_method_data.pay_later.afterpay_clearpay_redirect.billing_email": {
"required_field": "payment_method_data.pay_later.afterpay_clearpay_redirect.billing_email",
"display_name": "billing_email",
"field_type": "user_email_address",
"value": null
},
"name": {
"required_field": "name",
"display_name": "cust_name",
"field_type": "user_full_name",
"value": "John Doe"
}
},
"surcharge_details": null,
"pm_auth_connector": null
},
{
"payment_method_type": "affirm",
"payment_experience": [
{
"payment_experience_type": "redirect_to_url",
"eligible_connectors": [
"stripe"
]
}
],
"card_networks": null,
"bank_names": null,
"bank_debits": null,
"bank_transfers": null,
"required_fields": {},
"surcharge_details": null,
"pm_auth_connector": null
}
]
},
{
"payment_method": "bank_transfer",
"payment_method_types": [
{
"payment_method_type": "ach",
"payment_experience": [
{
"payment_experience_type": "redirect_to_url",
"eligible_connectors": [
"stripe"
]
}
],
"card_networks": null,
"bank_names": null,
"bank_debits": null,
"bank_transfers": null,
"required_fields": {},
"surcharge_details": null,
"pm_auth_connector": null
},
{
"payment_method_type": "sepa",
"payment_experience": [
{
"payment_experience_type": "redirect_to_url",
"eligible_connectors": [
"stripe"
]
}
],
"card_networks": null,
"bank_names": null,
"bank_debits": null,
"bank_transfers": null,
"required_fields": null,
"surcharge_details": null,
"pm_auth_connector": null
}
]
},
{
"payment_method": "card",
"payment_method_types": [
{
"payment_method_type": "debit",
"payment_experience": null,
"card_networks": [
{
"card_network": "Visa",
"surcharge_details": null,
"eligible_connectors": [
"stripe"
]
},
{
"card_network": "Mastercard",
"surcharge_details": null,
"eligible_connectors": [
"stripe"
]
}
],
"bank_names": null,
"bank_debits": null,
"bank_transfers": null,
"required_fields": {
"payment_method_data.card.card_exp_month": {
"required_field": "payment_method_data.card.card_exp_month",
"display_name": "card_exp_month",
"field_type": "user_card_expiry_month",
"value": null
},
"payment_method_data.card.card_number": {
"required_field": "payment_method_data.card.card_number",
"display_name": "card_number",
"field_type": "user_card_number",
"value": null
},
"payment_method_data.card.card_exp_year": {
"required_field": "payment_method_data.card.card_exp_year",
"display_name": "card_exp_year",
"field_type": "user_card_expiry_year",
"value": null
},
"payment_method_data.card.card_cvc": {
"required_field": "payment_method_data.card.card_cvc",
"display_name": "card_cvc",
"field_type": "user_card_cvc",
"value": null
}
},
"surcharge_details": null,
"pm_auth_connector": null
},
{
"payment_method_type": "credit",
"payment_experience": null,
"card_networks": [
{
"card_network": "Mastercard",
"surcharge_details": null,
"eligible_connectors": [
"stripe"
]
},
{
"card_network": "Visa",
"surcharge_details": null,
"eligible_connectors": [
"stripe"
]
}
],
"bank_names": null,
"bank_debits": null,
"bank_transfers": null,
"required_fields": {
"payment_method_data.card.card_cvc": {
"required_field": "payment_method_data.card.card_cvc",
"display_name": "card_cvc",
"field_type": "user_card_cvc",
"value": null
},
"payment_method_data.card.card_number": {
"required_field": "payment_method_data.card.card_number",
"display_name": "card_number",
"field_type": "user_card_number",
"value": null
},
"payment_method_data.card.card_exp_month": {
"required_field": "payment_method_data.card.card_exp_month",
"display_name": "card_exp_month",
"field_type": "user_card_expiry_month",
"value": null
},
"payment_method_data.card.card_exp_year": {
"required_field": "payment_method_data.card.card_exp_year",
"display_name": "card_exp_year",
"field_type": "user_card_expiry_year",
"value": null
}
},
"surcharge_details": null,
"pm_auth_connector": null
}
]
},
{
"payment_method": "bank_debit",
"payment_method_types": [
{
"payment_method_type": "ach",
"payment_experience": null,
"card_networks": null,
"bank_names": null,
"bank_debits": {
"eligible_connectors": [
"stripe"
]
},
"bank_transfers": null,
"required_fields": {
"billing.address.first_name": {
"required_field": "payment_method_data.billing.address.first_name",
"display_name": "billing_first_name",
"field_type": "user_billing_name",
"value": "joseph"
}
},
"surcharge_details": null,
"pm_auth_connector": null
},
{
"payment_method_type": "sepa",
"payment_experience": null,
"card_networks": null,
"bank_names": null,
"bank_debits": {
"eligible_connectors": [
"stripe"
]
},
"bank_transfers": null,
"required_fields": {
"billing.address.first_name": {
"required_field": "payment_method_data.billing.address.first_name",
"display_name": "billing_first_name",
"field_type": "user_billing_name",
"value": "joseph"
}
},
"surcharge_details": null,
"pm_auth_connector": null
},
{
"payment_method_type": "bacs",
"payment_experience": null,
"card_networks": null,
"bank_names": null,
"bank_debits": {
"eligible_connectors": [
"stripe"
]
},
"bank_transfers": null,
"required_fields": {
"billing.address.first_name": {
"required_field": "payment_method_data.billing.address.first_name",
"display_name": "billing_first_name",
"field_type": "user_billing_name",
"value": "joseph"
}
},
"surcharge_details": null,
"pm_auth_connector": null
}
]
},
{
"payment_method": "bank_transfer",
"payment_method_types": [
{
"payment_method_type": "ach",
"payment_experience": null,
"card_networks": null,
"bank_names": null,
"bank_debits": null,
"bank_transfers": {
"eligible_connectors": [
"stripe"
]
},
"required_fields": {},
"surcharge_details": null,
"pm_auth_connector": null
},
{
"payment_method_type": "sepa",
"payment_experience": null,
"card_networks": null,
"bank_names": null,
"bank_debits": null,
"bank_transfers": {
"eligible_connectors": [
"stripe"
]
},
"required_fields": null,
"surcharge_details": null,
"pm_auth_connector": null
},
{
"payment_method_type": "bacs",
"payment_experience": null,
"card_networks": null,
"bank_names": null,
"bank_debits": null,
"bank_transfers": {
"eligible_connectors": [
"stripe"
]
},
"required_fields": null,
"surcharge_details": null,
"pm_auth_connector": null
}
]
}
],
"mandate_payment": null,
"merchant_name": "Sarthak1",
"show_surcharge_breakup_screen": false,
"payment_type": "normal",
"request_external_three_ds_authentication": false,
"collect_shipping_details_from_wallets": false,
"collect_billing_details_from_wallets": false
}
```
## Checklist
<!-- Put an `x` in the boxes that apply -->
- [x] I formatted the code `cargo +nightly fmt --all`
- [x] I addressed lints thrown by `cargo clippy`
- [ ] I reviewed the submitted code
- [ ] I added unit tests for my changes where possible
|
0f89a0acbfc2d55f415e0daeb27e8d9022e6a862
|
|
juspay/hyperswitch
|
juspay__hyperswitch-5413
|
Bug: [FEATURE] Include created_at and modified_at keys in PaymentAttemptResponse
### Feature Description
Include created_at and modified_at keys in PaymentAttemptResponse, to display in payments dashboard
### Possible Implementation
Include created_at and modified_at keys in PaymentAttemptResponse, to display in payments dashboard
### Have you spent some time checking if this feature request has been raised before?
- [X] I checked and didn't find a similar issue
### Have you read the Contributing Guidelines?
- [X] I have read the [Contributing Guidelines](https://github.com/juspay/hyperswitch/blob/main/docs/CONTRIBUTING.md)
### Are you willing to submit a PR?
Yes, I am willing to submit a PR!
|
diff --git a/crates/api_models/src/payments.rs b/crates/api_models/src/payments.rs
index 5ac8d0edcc3..dd4ae572fd0 100644
--- a/crates/api_models/src/payments.rs
+++ b/crates/api_models/src/payments.rs
@@ -758,9 +758,7 @@ impl HeaderPayload {
}
}
-#[derive(
- Default, Debug, serde::Serialize, Clone, PartialEq, ToSchema, router_derive::PolymorphicSchema,
-)]
+#[derive(Debug, serde::Serialize, Clone, PartialEq, ToSchema, router_derive::PolymorphicSchema)]
pub struct PaymentAttemptResponse {
/// Unique identifier for the attempt
pub attempt_id: String,
@@ -788,6 +786,14 @@ pub struct PaymentAttemptResponse {
/// The transaction authentication can be set to undergo payer authentication. By default, the authentication will be marked as NO_THREE_DS
#[schema(value_type = Option<AuthenticationType>, example = "no_three_ds", default = "three_ds")]
pub authentication_type: Option<enums::AuthenticationType>,
+ /// Time at which the payment attempt was created
+ #[schema(value_type = PrimitiveDateTime, example = "2022-09-10T10:11:12Z")]
+ #[serde(with = "common_utils::custom_serde::iso8601")]
+ pub created_at: PrimitiveDateTime,
+ /// Time at which the payment attempt was last modified
+ #[schema(value_type = PrimitiveDateTime, example = "2022-09-10T10:11:12Z")]
+ #[serde(with = "common_utils::custom_serde::iso8601")]
+ pub modified_at: PrimitiveDateTime,
/// If the payment was cancelled the reason will be provided here
pub cancellation_reason: Option<String>,
/// A unique identifier to link the payment to a mandate, can be use instead of payment_method_data
diff --git a/crates/router/src/types/transformers.rs b/crates/router/src/types/transformers.rs
index 3cad4f16e81..b32ce2c9e51 100644
--- a/crates/router/src/types/transformers.rs
+++ b/crates/router/src/types/transformers.rs
@@ -1006,6 +1006,8 @@ impl ForeignFrom<storage::PaymentAttempt> for payments::PaymentAttemptResponse {
connector_transaction_id: payment_attempt.connector_transaction_id,
capture_method: payment_attempt.capture_method,
authentication_type: payment_attempt.authentication_type,
+ created_at: payment_attempt.created_at,
+ modified_at: payment_attempt.modified_at,
cancellation_reason: payment_attempt.cancellation_reason,
mandate_id: payment_attempt.mandate_id,
error_code: payment_attempt.error_code,
|
2024-07-23T09:45:40Z
|
## Type of Change
<!-- Put an `x` in the boxes that apply -->
- [ ] Bugfix
- [ ] New feature
- [x] Enhancement
- [ ] Refactoring
- [ ] Dependency updates
- [ ] Documentation
- [ ] CI/CD
## Description
<!-- Describe your changes in detail -->
## Summary
This PR introduces the created_at and modified_at keys to the PaymentAttemptResponse object. These keys will store the timestamps for when a payment attempt is created and last modified, respectively.
**Changes**
Added **created_at** key: This key records the timestamp of when a payment attempt is initially created.
Added **modified_at** key: This key captures the timestamp of the most recent modification to a payment attempt.
**Impact**
Enhanced Data Tracking: With the inclusion of created_at and modified_at, users will have better visibility into the lifecycle of a payment attempt.
Improved Auditing: These timestamps will facilitate more precise auditing and troubleshooting.
Backward Compatibility: Existing integrations will remain unaffected as these additions are non-breaking.
### Additional Changes
- [ ] This PR modifies the API contract
- [ ] This PR modifies the database schema
- [ ] This PR modifies application configuration/environment variables
<!--
Provide links to the files with corresponding changes.
Following are the paths where you can find config files:
1. `config`
2. `crates/router/src/configs`
3. `loadtest/config`
-->
## Motivation and Context
<!--
Why is this change required? What problem does it solve?
If it fixes an open issue, please link to the issue here.
If you don't have an issue, we'd recommend starting with one first so the PR
can focus on the implementation (unless it is an obvious bug or documentation fix
that will have little conversation).
-->
## How did you test it?
<!--
Did you write an integration/unit/API test to verify the code changes?
Or did you test this change manually (provide relevant screenshots)?
-->
```
curl 'http://localhost:8080/payments/pay_sQBhXpPgst6s57BvS9Fk?expand_attempts=true' \
-H 'Accept: */*' \
-H 'Accept-Language: en-GB,en-US;q=0.9,en;q=0.8,fr;q=0.7' \
-H 'Cache-Control: no-cache' \
-H 'Connection: keep-alive' \
-H 'Content-Type: application/json' \
-H 'Origin: http://localhost:9000' \
-H 'Pragma: no-cache' \
-H 'Referer: http://localhost:9000/' \
-H 'Sec-Fetch-Dest: empty' \
-H 'Sec-Fetch-Mode: cors' \
-H 'Sec-Fetch-Site: same-site' \
-H 'User-Agent: Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/126.0.0.0 Safari/537.36' \
-H 'api-key: hyperswitch' \
-H 'authorization: Bearer eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJ1c2VyX2lkIjoiZjA0MmUxZjQtMTczYS00MjI1LWE1YWMtYWIwY2VhYzkyODM2IiwibWVyY2hhbnRfaWQiOiJtZXJjaGFudF8xNzE2Mzc5MTEyIiwicm9sZV9pZCI6Im9yZ19hZG1pbiIsImV4cCI6MTcyMTg5OTY3MCwib3JnX2lkIjoib3JnXzc5RnRJcVRLQnpibW9Wd2dPc3dCIn0.fMpzPPQM1tNOnUBEkT-rk0HmAJgRc4wl4IU9eEFoe_E' \
-H 'sec-ch-ua: "Not/A)Brand";v="8", "Chromium";v="126", "Google Chrome";v="126"' \
-H 'sec-ch-ua-mobile: ?0' \
-H 'sec-ch-ua-platform: "macOS"'
```
Response - attempts
```
{
...,
"attempts": [
{
"attempt_id": "pay_sQBhXpPgst6s57BvS9Fk_1",
"status": "charged",
"amount": 10000,
"currency": "USD",
"connector": "pretendpay",
"error_message": null,
"payment_method": "card",
"connector_transaction_id": "dummy_pay_lHI6sx97Y8oswLZizvcf",
"capture_method": "automatic",
"authentication_type": "no_three_ds",
"created_at": "2024-07-23 09:31:57.179205",
"modified_at": "2024-07-23 09:35:27.53897",
"cancellation_reason": null,
"mandate_id": null,
"error_code": null,
"payment_token": null,
"connector_metadata": null,
"payment_experience": null,
"payment_method_type": null,
"reference_id": null,
"unified_code": null,
"unified_message": null,
"client_source": "Payment",
"client_version": "0.54.0"
}
]
}
```
## Checklist
<!-- Put an `x` in the boxes that apply -->
- [x] I formatted the code `cargo +nightly fmt --all`
- [x] I addressed lints thrown by `cargo clippy`
- [ ] I reviewed the submitted code
- [ ] I added unit tests for my changes where possible
|
876eeea0f426f63d0419021ba85372a016d46e27
|
|
juspay/hyperswitch
|
juspay__hyperswitch-5407
|
Bug: Fix(bug): Backend Issue for 4-Digit Input and Correct 3DS Routing Through no_3ds for Datatrans
https://github.com/juspay/hyperswitch-cloud/issues/6000
1)Expiry Month : YYYY gives error
2)3ds should get routed through no_3ds, and should not throw an error
|
diff --git a/crates/router/src/connector/datatrans/transformers.rs b/crates/router/src/connector/datatrans/transformers.rs
index 9c4ab6cf6a6..96c7bcd8b2c 100644
--- a/crates/router/src/connector/datatrans/transformers.rs
+++ b/crates/router/src/connector/datatrans/transformers.rs
@@ -7,7 +7,7 @@ use serde::{Deserialize, Serialize};
use crate::{
connector::{
utils as connector_utils,
- utils::{PaymentsAuthorizeRequestData, RouterData},
+ utils::{CardData, PaymentsAuthorizeRequestData},
},
core::errors,
types::{
@@ -158,21 +158,15 @@ impl TryFrom<&DatatransRouterData<&types::PaymentsAuthorizeRouterData>>
fn try_from(
item: &DatatransRouterData<&types::PaymentsAuthorizeRouterData>,
) -> Result<Self, Self::Error> {
- if item.router_data.is_three_ds() {
- return Err(errors::ConnectorError::NotImplemented(
- "Three_ds payments through Datatrans".to_string(),
- )
- .into());
- };
match item.router_data.request.payment_method_data.clone() {
domain::PaymentMethodData::Card(req_card) => Ok(Self {
amount: item.amount,
currency: item.router_data.request.currency,
card: PlainCardDetails {
res_type: "PLAIN".to_string(),
- number: req_card.card_number,
- expiry_month: req_card.card_exp_month,
- expiry_year: req_card.card_exp_year,
+ number: req_card.card_number.clone(),
+ expiry_month: req_card.card_exp_month.clone(),
+ expiry_year: req_card.get_card_expiry_year_2_digit()?,
},
refno: item.router_data.connector_request_reference_id.clone(),
auto_settle: matches!(
|
2024-07-23T07:52:44Z
|
## Type of Change
<!-- Put an `x` in the boxes that apply -->
- [x] Bugfix
- [ ] New feature
- [ ] Enhancement
- [ ] Refactoring
- [ ] Dependency updates
- [ ] Documentation
- [ ] CI/CD
## Description
<!-- Describe your changes in detail -->
1)Datatrans accepts expiry year in YY format only . Fixed that.
2) Removed the Check for 3ds flow (Earlier Not Implemented error was thrown)
### Additional Changes
- [ ] This PR modifies the API contract
- [ ] This PR modifies the database schema
- [ ] This PR modifies application configuration/environment variables
<!--
Provide links to the files with corresponding changes.
Following are the paths where you can find config files:
1. `config`
2. `crates/router/src/configs`
3. `loadtest/config`
-->
## Motivation and Context
https://github.com/juspay/hyperswitch-cloud/issues/6000#issuecomment-2238555051
## How did you test it?
**for 3DS**
Request
```
curl --location 'http://localhost:8080/payments' \
--header 'Content-Type: application/json' \
--header 'Accept: application/json' \
--header 'api-key:' \
--data '{
"amount": 800,
"currency": "USD",
"amount_to_capture":800,
"confirm": true,
"capture_method": "automatic",
"authentication_type": "three_ds",
"payment_method": "card",
"payment_method_type": "credit",
"payment_method_data": {
"card": {
"card_number": "4444090101010103",
"card_exp_month": "06",
"card_exp_year": "2025",
"card_holder_name": "joseph Doe",
"card_cvc":"232"
}
}
}'
```
Response
```
{
"payment_id": "pay_pftZ6ZUSVQHhl5x1LVqY",
"merchant_id": "merchant_1721718695",
"status": "succeeded",
"amount": 800,
"net_amount": 800,
"amount_capturable": 0,
"amount_received": 800,
"connector": "datatrans",
"client_secret": "",
"created": "2024-07-23T12:45:27.244Z",
"currency": "USD",
"customer_id": null,
"customer": null,
"description": null,
"refunds": null,
"disputes": null,
"mandate_id": null,
"mandate_data": null,
"setup_future_usage": null,
"off_session": null,
"capture_on": null,
"capture_method": "automatic",
"payment_method": "card",
"payment_method_data": {
"card": {
"last4": "0103",
"card_type": null,
"card_network": null,
"card_issuer": null,
"card_issuing_country": null,
"card_isin": "444409",
"card_extended_bin": null,
"card_exp_month": "06",
"card_exp_year": "2025",
"card_holder_name": "joseph Doe",
"payment_checks": null,
"authentication_data": null
},
"billing": null
},
"payment_token": null,
"shipping": null,
"billing": null,
"order_details": null,
"email": null,
"name": null,
"phone": null,
"return_url": null,
"authentication_type": "three_ds",
"statement_descriptor_name": null,
"statement_descriptor_suffix": null,
"next_action": null,
"cancellation_reason": null,
"error_code": null,
"error_message": null,
"unified_code": null,
"unified_message": null,
"payment_experience": null,
"payment_method_type": "credit",
"connector_label": null,
"business_country": null,
"business_label": "default",
"business_sub_label": null,
"allowed_payment_method_types": null,
"ephemeral_key": null,
"manual_retry_allowed": false,
"connector_transaction_id": "240723144528071750",
"frm_message": null,
"metadata": null,
"connector_metadata": null,
"feature_metadata": null,
"reference_id": null,
"payment_link": null,
"profile_id": "pro_6MuPGJ3Nd98kACtcKri3",
"surcharge_details": null,
"attempt_count": 1,
"merchant_decision": null,
"merchant_connector_id": "mca_6Z91ANL4judTAaUtsanU",
"incremental_authorization_allowed": null,
"authorization_count": null,
"incremental_authorizations": null,
"external_authentication_details": null,
"external_3ds_authentication_attempted": false,
"expires_on": "2024-07-23T13:00:27.244Z",
"fingerprint": null,
"browser_info": null,
"payment_method_id": null,
"payment_method_status": null,
"updated": "2024-07-23T12:45:28.213Z",
"charges": null,
"frm_metadata": null,
"merchant_order_reference_id": null
}
```
**For YYYY (expiry year in YYYY format)**
Request
```
curl --location 'http://localhost:8080/payments' \
--header 'Content-Type: application/json' \
--header 'Accept: application/json' \
--header 'api-key: dev_o8aYC1pZ22TWzVF1GpZx2DbTVEnuJThYNJIiLV7ui4voaLh7hsmVsvaZfzBz60RB' \
--data '{
"amount": 1000,
"currency": "USD",
"amount_to_capture":1000,
"confirm": true,
"capture_method": "automatic",
"payment_method": "card",
"payment_method_type": "credit",
"payment_method_data": {
"card": {
"card_number": "4000000000001000",
"card_exp_month": "06",
"card_exp_year": "2045",
"card_holder_name": "joseph Doe",
"card_cvc":"232"
}
}
}'
```
Response
```
{
"payment_id": "pay_PZlQaLUHloYO8lFr3TYm",
"merchant_id": "merchant_1721718695",
"status": "succeeded",
"amount": 1000,
"net_amount": 1000,
"amount_capturable": 0,
"amount_received": 1000,
"connector": "datatrans",
"client_secret": "pay_PZlQaLUHloYO8lFr3TYm_secret_zwBnsh3ejOBVlJDo6y3w",
"created": "2024-07-23T12:51:23.901Z",
"currency": "USD",
"customer_id": null,
"customer": null,
"description": null,
"refunds": null,
"disputes": null,
"mandate_id": null,
"mandate_data": null,
"setup_future_usage": null,
"off_session": null,
"capture_on": null,
"capture_method": "automatic",
"payment_method": "card",
"payment_method_data": {
"card": {
"last4": "1000",
"card_type": null,
"card_network": null,
"card_issuer": null,
"card_issuing_country": null,
"card_isin": "400000",
"card_extended_bin": null,
"card_exp_month": "06",
"card_exp_year": "2045",
"card_holder_name": "joseph Doe",
"payment_checks": null,
"authentication_data": null
},
"billing": null
},
"payment_token": null,
"shipping": null,
"billing": null,
"order_details": null,
"email": null,
"name": null,
"phone": null,
"return_url": null,
"authentication_type": "no_three_ds",
"statement_descriptor_name": null,
"statement_descriptor_suffix": null,
"next_action": null,
"cancellation_reason": null,
"error_code": null,
"error_message": null,
"unified_code": null,
"unified_message": null,
"payment_experience": null,
"payment_method_type": "credit",
"connector_label": null,
"business_country": null,
"business_label": "default",
"business_sub_label": null,
"allowed_payment_method_types": null,
"ephemeral_key": null,
"manual_retry_allowed": false,
"connector_transaction_id": "240723145124645224",
"frm_message": null,
"metadata": null,
"connector_metadata": null,
"feature_metadata": null,
"reference_id": null,
"payment_link": null,
"profile_id": "pro_6MuPGJ3Nd98kACtcKri3",
"surcharge_details": null,
"attempt_count": 1,
"merchant_decision": null,
"merchant_connector_id": "mca_6Z91ANL4judTAaUtsanU",
"incremental_authorization_allowed": null,
"authorization_count": null,
"incremental_authorizations": null,
"external_authentication_details": null,
"external_3ds_authentication_attempted": false,
"expires_on": "2024-07-23T13:06:23.901Z",
"fingerprint": null,
"browser_info": null,
"payment_method_id": null,
"payment_method_status": null,
"updated": "2024-07-23T12:51:24.760Z",
"charges": null,
"frm_metadata": null,
"merchant_order_reference_id": null
}
```
**YY -Expiry Year**
Request
```
curl --location 'http://localhost:8080/payments' \
--header 'Content-Type: application/json' \
--header 'Accept: application/json' \
--header 'api-key:' \
--data '{
"amount": 1000,
"currency": "USD",
"amount_to_capture":1000,
"confirm": true,
"capture_method": "automatic",
"payment_method": "card",
"payment_method_type": "credit",
"payment_method_data": {
"card": {
"card_number": "4000000000001000",
"card_exp_month": "06",
"card_exp_year": "45",
"card_holder_name": "joseph Doe",
"card_cvc":"232"
}
}
}'
```
Response
```
{
"payment_id": "pay_cNh1ZMQY66KYko3NW1Wf",
"merchant_id": "merchant_1721718695",
"status": "succeeded",
"amount": 1000,
"net_amount": 1000,
"amount_capturable": 0,
"amount_received": 1000,
"connector": "datatrans",
"client_secret": "pay_cNh1ZMQY66KYko3NW1Wf_secret_8iRn3JhcSLw6DoMX0fOu",
"created": "2024-07-23T14:13:23.596Z",
"currency": "USD",
"customer_id": null,
"customer": null,
"description": null,
"refunds": null,
"disputes": null,
"mandate_id": null,
"mandate_data": null,
"setup_future_usage": null,
"off_session": null,
"capture_on": null,
"capture_method": "automatic",
"payment_method": "card",
"payment_method_data": {
"card": {
"last4": "1000",
"card_type": null,
"card_network": null,
"card_issuer": null,
"card_issuing_country": null,
"card_isin": "400000",
"card_extended_bin": null,
"card_exp_month": "06",
"card_exp_year": "45",
"card_holder_name": "joseph Doe",
"payment_checks": null,
"authentication_data": null
},
"billing": null
},
"payment_token": null,
"shipping": null,
"billing": null,
"order_details": null,
"email": null,
"name": null,
"phone": null,
"return_url": null,
"authentication_type": "no_three_ds",
"statement_descriptor_name": null,
"statement_descriptor_suffix": null,
"next_action": null,
"cancellation_reason": null,
"error_code": null,
"error_message": null,
"unified_code": null,
"unified_message": null,
"payment_experience": null,
"payment_method_type": "credit",
"connector_label": null,
"business_country": null,
"business_label": "default",
"business_sub_label": null,
"allowed_payment_method_types": null,
"ephemeral_key": null,
"manual_retry_allowed": false,
"connector_transaction_id": "240723161326887353",
"frm_message": null,
"metadata": null,
"connector_metadata": null,
"feature_metadata": null,
"reference_id": null,
"payment_link": null,
"profile_id": "pro_6MuPGJ3Nd98kACtcKri3",
"surcharge_details": null,
"attempt_count": 1,
"merchant_decision": null,
"merchant_connector_id": "mca_6Z91ANL4judTAaUtsanU",
"incremental_authorization_allowed": null,
"authorization_count": null,
"incremental_authorizations": null,
"external_authentication_details": null,
"external_3ds_authentication_attempted": false,
"expires_on": "2024-07-23T14:28:23.596Z",
"fingerprint": null,
"browser_info": null,
"payment_method_id": null,
"payment_method_status": null,
"updated": "2024-07-23T14:13:26.821Z",
"charges": null,
"frm_metadata": null,
"merchant_order_reference_id": null
}
```
## Checklist
<!-- Put an `x` in the boxes that apply -->
- [x] I formatted the code `cargo +nightly fmt --all`
- [x] I addressed lints thrown by `cargo clippy`
- [x] I reviewed the submitted code
- [ ] I added unit tests for my changes where possible
|
876eeea0f426f63d0419021ba85372a016d46e27
|
|
juspay/hyperswitch
|
juspay__hyperswitch-5404
|
Bug: handle packages to run are being empty
<img width="679" alt="image" src="https://github.com/user-attachments/assets/0c3a8639-7713-414c-9cc7-72516767dabd">
During the cargo hack if the packages to run are empty the workflow will error out.
|
diff --git a/scripts/ci-checks.sh b/scripts/ci-checks.sh
index 7f2cecf8405..69bc56a623b 100755
--- a/scripts/ci-checks.sh
+++ b/scripts/ci-checks.sh
@@ -74,7 +74,7 @@ crates_with_v1_feature="$(
| .name as $name | .features[] | { $name, features: . } # Expand nested features object to have package - features combinations
| "\(.name) \(.features)" # Print out package name and features separated by space'
)"
-while IFS=' ' read -r crate features; do
+while IFS=' ' read -r crate features && [[ -n "${crate}" && -n "${features}" ]]; do
command="cargo check --all-targets --package \"${crate}\" --no-default-features --features \"${features}\""
all_commands+=("$command")
done <<< "${crates_with_v1_feature}"
@@ -87,11 +87,16 @@ crates_without_v1_feature="$(
'$crates_with_features[] | select(IN("v1"; .features[]) | not ) # Select crates without `v1` feature
| "\(.name)" # Print out package name'
)"
-while IFS= read -r crate; do
+while IFS= read -r crate && [[ -n "${crate}" ]]; do
command="cargo hack check --all-targets --each-feature --package \"${crate}\""
all_commands+=("$command")
done <<< "${crates_without_v1_feature}"
+if (( ${#all_commands[@]} == 0 )); then
+ echo "There are no commands to be be executed"
+ exit 0
+fi
+
echo "The list of commands that will be executed:"
printf "%s\n" "${all_commands[@]}"
echo
|
2024-07-22T14:08:33Z
|
## Type of Change
<!-- Put an `x` in the boxes that apply -->
- [x] Bugfix
- [ ] New feature
- [ ] Enhancement
- [ ] Refactoring
- [ ] Dependency updates
- [ ] Documentation
- [ ] CI/CD
## Description
<!-- Describe your changes in detail -->
handle packages to run are being empty
<img width="679" alt="image" src="https://github.com/user-attachments/assets/0ebc544d-7579-4a29-b533-c2c860e5a296">
### Additional Changes
- [ ] This PR modifies the API contract
- [ ] This PR modifies the database schema
- [ ] This PR modifies application configuration/environment variables
<!--
Provide links to the files with corresponding changes.
Following are the paths where you can find config files:
1. `config`
2. `crates/router/src/configs`
3. `loadtest/config`
-->
## Motivation and Context
<!--
Why is this change required? What problem does it solve?
If it fixes an open issue, please link to the issue here.
If you don't have an issue, we'd recommend starting with one first so the PR
can focus on the implementation (unless it is an obvious bug or documentation fix
that will have little conversation).
-->
## How did you test it?
<!--
Did you write an integration/unit/API test to verify the code changes?
Or did you test this change manually (provide relevant screenshots)?
-->
## Checklist
<!-- Put an `x` in the boxes that apply -->
- [x] I formatted the code `cargo +nightly fmt --all`
- [x] I addressed lints thrown by `cargo clippy`
- [x] I reviewed the submitted code
- [ ] I added unit tests for my changes where possible
|
eaa391a959076424399fb9331a78a16eaf790478
|
|
juspay/hyperswitch
|
juspay__hyperswitch-5402
|
Bug: refactor: Add customer_details, billing and shipping address in Payment LIst
Add decrypted customer_details, shipping and billling address in Payment list response for Dashboard usages
|
diff --git a/crates/api_models/src/payments.rs b/crates/api_models/src/payments.rs
index 45a6bb46385..04cf4cd5da3 100644
--- a/crates/api_models/src/payments.rs
+++ b/crates/api_models/src/payments.rs
@@ -206,7 +206,9 @@ pub struct CustomerDetails {
}
/// Details of customer attached to this payment
-#[derive(Debug, Default, serde::Serialize, Clone, ToSchema, PartialEq, Setter)]
+#[derive(
+ Debug, Default, serde::Serialize, serde::Deserialize, Clone, ToSchema, PartialEq, Setter,
+)]
pub struct CustomerDetailsResponse {
/// The identifier for the customer.
#[schema(value_type = Option<String>, max_length = 64, min_length = 1, example = "cus_y3oqhf46pyzuxjbcn2giaqnb44")]
diff --git a/crates/router/src/core/payments/transformers.rs b/crates/router/src/core/payments/transformers.rs
index 9b0fee274ee..4df48806530 100644
--- a/crates/router/src/core/payments/transformers.rs
+++ b/crates/router/src/core/payments/transformers.rs
@@ -1,8 +1,8 @@
use std::{fmt::Debug, marker::PhantomData, str::FromStr};
use api_models::payments::{
- CustomerDetailsResponse, FrmMessage, GetAddressFromPaymentMethodData, PaymentChargeRequest,
- PaymentChargeResponse, RequestSurchargeDetails,
+ Address, CustomerDetailsResponse, FrmMessage, GetAddressFromPaymentMethodData,
+ PaymentChargeRequest, PaymentChargeResponse, RequestSurchargeDetails,
};
#[cfg(feature = "payouts")]
use api_models::payouts::PayoutAttemptResponse;
@@ -1036,7 +1036,7 @@ impl ForeignFrom<(storage::PaymentIntent, storage::PaymentAttempt)> for api::Pay
description: pi.description,
metadata: pi.metadata,
order_details: pi.order_details,
- customer_id: pi.customer_id,
+ customer_id: pi.customer_id.clone(),
connector: pa.connector,
payment_method: pa.payment_method,
payment_method_type: pa.payment_method_type,
@@ -1060,6 +1060,40 @@ impl ForeignFrom<(storage::PaymentIntent, storage::PaymentAttempt)> for api::Pay
}
}),
merchant_order_reference_id: pi.merchant_order_reference_id,
+ customer: pi.customer_details.and_then(|customer_details|
+ match customer_details.into_inner().expose().parse_value::<CustomerData>("CustomerData"){
+ Ok(parsed_data) => Some(
+ CustomerDetailsResponse {
+ id: pi.customer_id,
+ name: parsed_data.name,
+ phone: parsed_data.phone,
+ email: parsed_data.email,
+ phone_country_code:parsed_data.phone_country_code
+ }),
+ Err(e) => {
+ router_env::logger::error!("Failed to parse 'CustomerDetailsResponse' from payment method data. Error: {e:?}");
+ None
+ }
+ }
+ ),
+ billing: pi.billing_details.and_then(|billing_details|
+ match billing_details.into_inner().expose().parse_value::<Address>("Address") {
+ Ok(parsed_data) => Some(parsed_data),
+ Err(e) => {
+ router_env::logger::error!("Failed to parse 'BillingAddress' from payment method data. Error: {e:?}");
+ None
+ }
+ }
+ ),
+ shipping: pi.shipping_details.and_then(|shipping_details|
+ match shipping_details.into_inner().expose().parse_value::<Address>("Address") {
+ Ok(parsed_data) => Some(parsed_data),
+ Err(e) => {
+ router_env::logger::error!("Failed to parse 'ShippingAddress' from payment method data. Error: {e:?}");
+ None
+ }
+ }
+ ),
..Default::default()
}
}
|
2024-07-22T13:24:41Z
|
## Type of Change
<!-- Put an `x` in the boxes that apply -->
- [ ] Bugfix
- [ ] New feature
- [ ] Enhancement
- [x] Refactoring
- [ ] Dependency updates
- [ ] Documentation
- [ ] CI/CD
## Description
<!-- Describe your changes in detail -->
This pr adds the decrypted customer_details, shipping and billling address in Payment list response.
### Additional Changes
- [ ] This PR modifies the API contract
- [ ] This PR modifies the database schema
- [ ] This PR modifies application configuration/environment variables
<!--
Provide links to the files with corresponding changes.
Following are the paths where you can find config files:
1. `config`
2. `crates/router/src/configs`
3. `loadtest/config`
-->
## Motivation and Context
<!--
Why is this change required? What problem does it solve?
If it fixes an open issue, please link to the issue here.
If you don't have an issue, we'd recommend starting with one first so the PR
can focus on the implementation (unless it is an obvious bug or documentation fix
that will have little conversation).
-->
Required for our Dashboard
## How did you test it?
<!--
Did you write an integration/unit/API test to verify the code changes?
Or did you test this change manually (provide relevant screenshots)?
-->
We need to make a payment with shipping, billing and customer details and then hit the Payment list api:
```
curl --location --request GET 'http://127.0.0.1:8080/payments/list' \
--header 'Accept: application/json' \
--header 'Content-Type: application/json' \
--header 'api-key:xxxxxxx' \
--data '{
}'
```
The response should contain the below fields:
```
"customer_id": "uiuiuiui",
"customer": {
"id": "uiuiuiui",
"name": null,
"email": "guest@ehjhjxample.com",
"phone": null,
"phone_country_code": null
},
"shipping": {
"address": {
"city": "San Fransico",
"country": "US",
"line1": "1467",
"line2": "Harrison Street",
"line3": "Harrison Street",
"zip": "94122",
"state": "California",
"first_name": "joseph",
"last_name": "Doe"
},
"phone": {
"number": "8056594427",
"country_code": "+91"
},
"email": null
},
"billing": {
"address": {
"city": "San Fransico",
"country": "NL",
"line1": "1467",
"line2": "Harrison Street",
"line3": "Harrison Street",
"zip": "94122",
"state": "California",
"first_name": "joseph",
"last_name": "Doe"
},
"phone": {
"number": "8056594427",
"country_code": "+91"
},
"email": "example@example.com"
},
```
## Checklist
<!-- Put an `x` in the boxes that apply -->
- [x] I formatted the code `cargo +nightly fmt --all`
- [x] I addressed lints thrown by `cargo clippy`
- [x] I reviewed the submitted code
- [ ] I added unit tests for my changes where possible
|
4838a86ebcb5000e65293e0d095e5de95e3a64a0
|
|
juspay/hyperswitch
|
juspay__hyperswitch-5400
|
Bug: store `network_transaction_id` in stripe `authorize` flow
Now we are trying to store the `network_transaction_id` that comes in the latest_attempt of the authorize response instead we should be storing the `network_transaction_id` that comes in the `latest_charge` object.
|
diff --git a/crates/router/src/connector/stripe/transformers.rs b/crates/router/src/connector/stripe/transformers.rs
index 786f4a060b7..90ddc9f0b90 100644
--- a/crates/router/src/connector/stripe/transformers.rs
+++ b/crates/router/src/connector/stripe/transformers.rs
@@ -2389,7 +2389,18 @@ impl<F, T>
//Note: we might have to call retrieve_setup_intent to get the network_transaction_id in case its not sent in PaymentIntentResponse
// Or we identify the mandate txns before hand and always call SetupIntent in case of mandate payment call
- let network_txn_id = Option::foreign_from(item.response.latest_attempt);
+ let network_txn_id = match item.response.latest_charge.as_ref() {
+ Some(StripeChargeEnum::ChargeObject(charge_object)) => charge_object
+ .payment_method_details
+ .as_ref()
+ .and_then(|payment_method_details| match payment_method_details {
+ StripePaymentMethodDetailsResponse::Card { card } => {
+ card.network_transaction_id.clone()
+ }
+ _ => None,
+ }),
+ _ => None,
+ };
let connector_metadata =
get_connector_metadata(item.response.next_action.as_ref(), item.response.amount)?;
|
2024-07-22T11:52:12Z
|
## Type of Change
<!-- Put an `x` in the boxes that apply -->
- [x] Bugfix
- [ ] New feature
- [ ] Enhancement
- [ ] Refactoring
- [ ] Dependency updates
- [ ] Documentation
- [ ] CI/CD
## Description
<!-- Describe your changes in detail -->
Now we are trying to store the `network_transaction_id` that comes in the latest_attempt of the authorize response instead we should be storing the `network_transaction_id` that comes in the `latest_charge` object.
### Additional Changes
- [ ] This PR modifies the API contract
- [ ] This PR modifies the database schema
- [ ] This PR modifies application configuration/environment variables
<!--
Provide links to the files with corresponding changes.
Following are the paths where you can find config files:
1. `config`
2. `crates/router/src/configs`
3. `loadtest/config`
-->
## Motivation and Context
<!--
Why is this change required? What problem does it solve?
If it fixes an open issue, please link to the issue here.
If you don't have an issue, we'd recommend starting with one first so the PR
can focus on the implementation (unless it is an obvious bug or documentation fix
that will have little conversation).
-->
## How did you test it?
<!--
Did you write an integration/unit/API test to verify the code changes?
Or did you test this change manually (provide relevant screenshots)?
-->
-> Create mca for stripe
-> Create a payment with `steup_future_usage: off_session` 0 amount
```
curl --location 'http://localhost:8080/payments' \
--header 'Accept: application/json' \
--header 'api-key: dev_WQrUfhm6TWzpFVlFlDScYFQxn9lKKoGHhOXk6YHQpWkQZclxtkrRdQX5wmc0p2dO' \
--header 'Content-Type: application/json' \
--data-raw '{
"amount": 0,
"payment_type": "setup_mandate",
"currency": "USD",
"confirm": true,
"capture_method": "automatic",
"capture_on": "2022-09-10T10:11:12Z",
"customer_id": "cu_1721649988",
"email": "guest@example.com",
"name": "John Doe",
"phone": "999999999",
"phone_country_code": "+65",
"description": "Its my first payment request",
"authentication_type": "no_three_ds",
"return_url": "https://google.com",
"payment_method": "card",
"payment_method_type": "credit",
"payment_method_data": {
"card": {
"card_number": "4242424242424242",
"card_exp_month": "03",
"card_exp_year": "2030",
"card_holder_name": "name name",
"card_cvc": "737"
}
},
"setup_future_usage": "off_session",
"customer_acceptance": {
"acceptance_type": "offline",
"accepted_at": "1963-05-03T04:07:52.723Z",
"online": {
"ip_address": "in sit",
"user_agent": "amet irure esse"
}
},
"billing": {
"address": {
"line1": "1467",
"line2": "Harrison Street",
"line3": "Harrison Street",
"city": "San Fransico",
"state": "California",
"zip": "94122",
"country": "US",
"first_name": "PiX",
"last_name": "ss"
}
},
"shipping": {
"address": {
"line1": "1467",
"line2": "Harrison Street",
"line3": "Harrison Street",
"city": "San Fransico",
"state": "California",
"zip": "94122",
"country": "US",
"first_name": "John",
"last_name": "Doe"
},
"phone": {
"number": "8056594427",
"country_code": "+91"
}
},
"browser_info": {
"user_agent": "Mozilla\/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit\/537.36 (KHTML, like Gecko) Chrome\/70.0.3538.110 Safari\/537.36",
"accept_header": "text\/html,application\/xhtml+xml,application\/xml;q=0.9,image\/webp,image\/apng,*\/*;q=0.8",
"language": "nl-NL",
"color_depth": 24,
"screen_height": 723,
"screen_width": 1536,
"time_zone": 0,
"java_enabled": true,
"java_script_enabled": true,
"ip_address": "125.0.0.1"
},
"statement_descriptor_name": "joseph",
"statement_descriptor_suffix": "JS",
"metadata": {},
"order_details": [
{
"product_name": "Apple iphone 15",
"quantity": 1,
"amount": 0,
"account_name": "transaction_processing"
}
]
}'
```
```
{
"payment_id": "pay_0hw6op372qaaKsTiuY5W",
"merchant_id": "merchant_1721642432",
"status": "succeeded",
"amount": 0,
"net_amount": 0,
"amount_capturable": 0,
"amount_received": null,
"connector": "stripe",
"client_secret": "pay_0hw6op372qaaKsTiuY5W_secret_vKfsIm6wiiaQV1KtEMhA",
"created": "2024-07-22T12:07:14.790Z",
"currency": "USD",
"customer_id": "cu_1721650035",
"customer": {
"id": "cu_1721650035",
"name": "John Doe",
"email": "guest@example.com",
"phone": "999999999",
"phone_country_code": "+65"
},
"description": "Its my first payment request",
"refunds": null,
"disputes": null,
"mandate_id": null,
"mandate_data": null,
"setup_future_usage": "off_session",
"off_session": null,
"capture_on": null,
"capture_method": "automatic",
"payment_method": "card",
"payment_method_data": {
"card": {
"last4": "4242",
"card_type": "CREDIT",
"card_network": "Visa",
"card_issuer": "STRIPE PAYMENTS UK LIMITED",
"card_issuing_country": "UNITEDKINGDOM",
"card_isin": "424242",
"card_extended_bin": null,
"card_exp_month": "03",
"card_exp_year": "2030",
"card_holder_name": "name name",
"payment_checks": {
"cvc_check": "pass",
"address_line1_check": null,
"address_postal_code_check": null
},
"authentication_data": null
},
"billing": null
},
"payment_token": null,
"shipping": {
"address": {
"city": "San Fransico",
"country": "US",
"line1": "1467",
"line2": "Harrison Street",
"line3": "Harrison Street",
"zip": "94122",
"state": "California",
"first_name": "John",
"last_name": "Doe"
},
"phone": {
"number": "8056594427",
"country_code": "+91"
},
"email": null
},
"billing": {
"address": {
"city": "San Fransico",
"country": "US",
"line1": "1467",
"line2": "Harrison Street",
"line3": "Harrison Street",
"zip": "94122",
"state": "California",
"first_name": "PiX",
"last_name": "ss"
},
"phone": null,
"email": null
},
"order_details": [
{
"brand": null,
"amount": 0,
"category": null,
"quantity": 1,
"product_id": null,
"product_name": "Apple iphone 15",
"product_type": null,
"sub_category": null,
"product_img_link": null,
"requires_shipping": null
}
],
"email": "guest@example.com",
"name": "John Doe",
"phone": "999999999",
"return_url": "https://google.com/",
"authentication_type": "no_three_ds",
"statement_descriptor_name": "joseph",
"statement_descriptor_suffix": "JS",
"next_action": null,
"cancellation_reason": null,
"error_code": null,
"error_message": null,
"unified_code": null,
"unified_message": null,
"payment_experience": null,
"payment_method_type": "credit",
"connector_label": null,
"business_country": null,
"business_label": "default",
"business_sub_label": null,
"allowed_payment_method_types": null,
"ephemeral_key": {
"customer_id": "cu_1721650035",
"created_at": 1721650034,
"expires": 1721653634,
"secret": "epk_eb1bb9c72ab04753bb3064b102e9b39c"
},
"manual_retry_allowed": false,
"connector_transaction_id": "seti_1PfL1MEOqOywnAIx12IOb9vg",
"frm_message": null,
"metadata": {},
"connector_metadata": null,
"feature_metadata": null,
"reference_id": "seti_1PfL1MEOqOywnAIx12IOb9vg",
"payment_link": null,
"profile_id": "pro_BWZKN9cFmoG8XWaD3pAC",
"surcharge_details": null,
"attempt_count": 1,
"merchant_decision": null,
"merchant_connector_id": "mca_mTDAnjYImojwhWV5Lzfh",
"incremental_authorization_allowed": null,
"authorization_count": null,
"incremental_authorizations": null,
"external_authentication_details": null,
"external_3ds_authentication_attempted": false,
"expires_on": "2024-07-22T12:22:14.790Z",
"fingerprint": null,
"browser_info": {
"language": "nl-NL",
"time_zone": 0,
"ip_address": "125.0.0.1",
"user_agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/70.0.3538.110 Safari/537.36",
"color_depth": 24,
"java_enabled": true,
"screen_width": 1536,
"accept_header": "text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,image/apng,*/*;q=0.8",
"screen_height": 723,
"java_script_enabled": true
},
"payment_method_id": "pm_dubT5ZFlL5rHPqNTUA1b",
"payment_method_status": null,
"updated": "2024-07-22T12:07:16.981Z",
"charges": null,
"frm_metadata": null,
"merchant_order_reference_id": null
}
```
<img width="918" alt="image" src="https://github.com/user-attachments/assets/352790d3-2e20-42af-959a-17fe5caa1efb">
-> Create a payment with `steup_future_usage: off_session` with some amount
```
{
"amount": 1000,
"currency": "USD",
"confirm": true,
"capture_method": "automatic",
"capture_on": "2022-09-10T10:11:12Z",
"customer_id": "cu_{{$timestamp}}",
"email": "guest@example.com",
"name": "John Doe",
"phone": "999999999",
"phone_country_code": "+65",
"description": "Its my first payment request",
"authentication_type": "no_three_ds",
"return_url": "https://google.com",
"payment_method": "card",
"payment_method_type": "credit",
"payment_method_data": {
"card": {
"card_number": "4242424242424242",
"card_exp_month": "03",
"card_exp_year": "2030",
"card_holder_name": "name name",
"card_cvc": "737"
}
},
"setup_future_usage": "off_session",
"customer_acceptance": {
"acceptance_type": "offline",
"accepted_at": "1963-05-03T04:07:52.723Z",
"online": {
"ip_address": "in sit",
"user_agent": "amet irure esse"
}
},
"billing": {
"address": {
"line1": "1467",
"line2": "Harrison Street",
"line3": "Harrison Street",
"city": "San Fransico",
"state": "California",
"zip": "94122",
"country": "US",
"first_name": "PiX",
"last_name": "ss"
}
},
"shipping": {
"address": {
"line1": "1467",
"line2": "Harrison Street",
"line3": "Harrison Street",
"city": "San Fransico",
"state": "California",
"zip": "94122",
"country": "US",
"first_name": "John",
"last_name": "Doe"
},
"phone": {
"number": "8056594427",
"country_code": "+91"
}
},
"browser_info": {
"user_agent": "Mozilla\/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit\/537.36 (KHTML, like Gecko) Chrome\/70.0.3538.110 Safari\/537.36",
"accept_header": "text\/html,application\/xhtml+xml,application\/xml;q=0.9,image\/webp,image\/apng,*\/*;q=0.8",
"language": "nl-NL",
"color_depth": 24,
"screen_height": 723,
"screen_width": 1536,
"time_zone": 0,
"java_enabled": true,
"java_script_enabled": true,
"ip_address": "125.0.0.1"
},
"statement_descriptor_name": "joseph",
"statement_descriptor_suffix": "JS",
"metadata": {},
"order_details": [
{
"product_name": "Apple iphone 15",
"quantity": 1,
"amount": 0,
"account_name": "transaction_processing"
}
]
}
```
```
{
"payment_id": "pay_2ZcZeTrSRop8Sbbc6sYa",
"merchant_id": "merchant_1721642432",
"status": "succeeded",
"amount": 1000,
"net_amount": 1000,
"amount_capturable": 0,
"amount_received": 1000,
"connector": "stripe",
"client_secret": "pay_2ZcZeTrSRop8Sbbc6sYa_secret_qPvPMsEI5XDx5Fi7ZRL5",
"created": "2024-07-22T12:10:40.889Z",
"currency": "USD",
"customer_id": "cu_1721650241",
"customer": {
"id": "cu_1721650241",
"name": "John Doe",
"email": "guest@example.com",
"phone": "999999999",
"phone_country_code": "+65"
},
"description": "Its my first payment request",
"refunds": null,
"disputes": null,
"mandate_id": null,
"mandate_data": null,
"setup_future_usage": "off_session",
"off_session": null,
"capture_on": null,
"capture_method": "automatic",
"payment_method": "card",
"payment_method_data": {
"card": {
"last4": "4242",
"card_type": "CREDIT",
"card_network": "Visa",
"card_issuer": "STRIPE PAYMENTS UK LIMITED",
"card_issuing_country": "UNITEDKINGDOM",
"card_isin": "424242",
"card_extended_bin": null,
"card_exp_month": "03",
"card_exp_year": "2030",
"card_holder_name": "name name",
"payment_checks": {
"cvc_check": "pass",
"address_line1_check": "pass",
"address_postal_code_check": "pass"
},
"authentication_data": null
},
"billing": null
},
"payment_token": null,
"shipping": {
"address": {
"city": "San Fransico",
"country": "US",
"line1": "1467",
"line2": "Harrison Street",
"line3": "Harrison Street",
"zip": "94122",
"state": "California",
"first_name": "John",
"last_name": "Doe"
},
"phone": {
"number": "8056594427",
"country_code": "+91"
},
"email": null
},
"billing": {
"address": {
"city": "San Fransico",
"country": "US",
"line1": "1467",
"line2": "Harrison Street",
"line3": "Harrison Street",
"zip": "94122",
"state": "California",
"first_name": "PiX",
"last_name": "ss"
},
"phone": null,
"email": null
},
"order_details": [
{
"brand": null,
"amount": 0,
"category": null,
"quantity": 1,
"product_id": null,
"product_name": "Apple iphone 15",
"product_type": null,
"sub_category": null,
"product_img_link": null,
"requires_shipping": null
}
],
"email": "guest@example.com",
"name": "John Doe",
"phone": "999999999",
"return_url": "https://google.com/",
"authentication_type": "no_three_ds",
"statement_descriptor_name": "joseph",
"statement_descriptor_suffix": "JS",
"next_action": null,
"cancellation_reason": null,
"error_code": null,
"error_message": null,
"unified_code": null,
"unified_message": null,
"payment_experience": null,
"payment_method_type": "credit",
"connector_label": null,
"business_country": null,
"business_label": "default",
"business_sub_label": null,
"allowed_payment_method_types": null,
"ephemeral_key": {
"customer_id": "cu_1721650241",
"created_at": 1721650240,
"expires": 1721653840,
"secret": "epk_adc1f18ee9044b5885104683a7ae3cf2"
},
"manual_retry_allowed": false,
"connector_transaction_id": "pi_3PfL4gEOqOywnAIx0F7mw5Mp",
"frm_message": null,
"metadata": {},
"connector_metadata": null,
"feature_metadata": null,
"reference_id": "pi_3PfL4gEOqOywnAIx0F7mw5Mp",
"payment_link": null,
"profile_id": "pro_BWZKN9cFmoG8XWaD3pAC",
"surcharge_details": null,
"attempt_count": 1,
"merchant_decision": null,
"merchant_connector_id": "mca_mTDAnjYImojwhWV5Lzfh",
"incremental_authorization_allowed": null,
"authorization_count": null,
"incremental_authorizations": null,
"external_authentication_details": null,
"external_3ds_authentication_attempted": false,
"expires_on": "2024-07-22T12:25:40.889Z",
"fingerprint": null,
"browser_info": {
"language": "nl-NL",
"time_zone": 0,
"ip_address": "125.0.0.1",
"user_agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/70.0.3538.110 Safari/537.36",
"color_depth": 24,
"java_enabled": true,
"screen_width": 1536,
"accept_header": "text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,image/apng,*/*;q=0.8",
"screen_height": 723,
"java_script_enabled": true
},
"payment_method_id": "pm_fA3gdoIyYaSQGW6WoHer",
"payment_method_status": null,
"updated": "2024-07-22T12:10:43.437Z",
"charges": null,
"frm_metadata": null,
"merchant_order_reference_id": null
}
```
<img width="939" alt="image" src="https://github.com/user-attachments/assets/29775ea1-153e-4895-829f-f5170af4b5cc">
## Checklist
<!-- Put an `x` in the boxes that apply -->
- [x] I formatted the code `cargo +nightly fmt --all`
- [x] I addressed lints thrown by `cargo clippy`
- [x] I reviewed the submitted code
- [ ] I added unit tests for my changes where possible
|
3d385bbf736f8d7dae73a233d64148a8e88ec17e
|
|
juspay/hyperswitch
|
juspay__hyperswitch-5396
|
Bug: refactor: alter query for merchant scoped metadata
Remove `is_null` from `find_merchant_scoped_dashboard_metadata`
This is done to make DB changes and support backward compatibility in next deployment.
|
diff --git a/crates/diesel_models/src/query/dashboard_metadata.rs b/crates/diesel_models/src/query/dashboard_metadata.rs
index 6f88629d82a..725a95ffef3 100644
--- a/crates/diesel_models/src/query/dashboard_metadata.rs
+++ b/crates/diesel_models/src/query/dashboard_metadata.rs
@@ -87,9 +87,8 @@ impl DashboardMetadata {
org_id: String,
data_types: Vec<enums::DashboardMetadata>,
) -> StorageResult<Vec<Self>> {
- let predicate = dsl::user_id
- .is_null()
- .and(dsl::merchant_id.eq(merchant_id))
+ let predicate = dsl::merchant_id
+ .eq(merchant_id)
.and(dsl::org_id.eq(org_id))
.and(dsl::data_key.eq_any(data_types));
diff --git a/crates/router/src/db/dashboard_metadata.rs b/crates/router/src/db/dashboard_metadata.rs
index 5267985e1ac..df36eb85ec0 100644
--- a/crates/router/src/db/dashboard_metadata.rs
+++ b/crates/router/src/db/dashboard_metadata.rs
@@ -276,8 +276,7 @@ impl DashboardMetadataInterface for MockDb {
let query_result = dashboard_metadata
.iter()
.filter(|metadata_inner| {
- metadata_inner.user_id.is_none()
- && metadata_inner.merchant_id == merchant_id
+ metadata_inner.merchant_id == merchant_id
&& metadata_inner.org_id == org_id
&& data_keys.contains(&metadata_inner.data_key)
})
|
2024-07-22T10:06:58Z
|
## Type of Change
<!-- Put an `x` in the boxes that apply -->
- [ ] Bugfix
- [ ] New feature
- [ ] Enhancement
- [x] Refactoring
- [ ] Dependency updates
- [ ] Documentation
- [ ] CI/CD
## Description
Alter query in `find_merchant_scoped_dashboard_metadata`
For merchant scoped metadata it need not to be considered whether user_id column is `null` or not
### Additional Changes
- [ ] This PR modifies the API contract
- [ ] This PR modifies the database schema
- [ ] This PR modifies application configuration/environment variables
<!--
Provide links to the files with corresponding changes.
Following are the paths where you can find config files:
1. `config`
2. `crates/router/src/configs`
3. `loadtest/config`
-->
## Motivation and Context
Closes #5396
## How did you test it?
To get the metadata use curl:
```
curl --location 'http://localhost:8080/user/data?keys=ProductionAgreement%2CSetupProcessor%2CConfigureEndpoint%2CSetupComplete%2CFirstProcessorConnected%2CSecondProcessorConnected%2CConfiguredRouting%2CTestPayment%2CIntegrationMethod%2CConfigurationType%2CIntegrationCompleted%2CStripeConnected%2CPaypalConnected%2CSPRoutingConfigured%2CFeedback%2CProdIntent%2CSPTestPayment%2CDownloadWoocom%2CConfigureWoocom%2CSetupWoocomWebhook%2CIsMultipleConfiguration%2CIsChangePasswordRequired' \
--header 'Authorization: Bearer JWT'
```
In response we will get the metadata both that set or unset:
```
[
{
"ProductionAgreement": false
},
{
"SetupProcessor": null
},
{
"ConfigureEndpoint": false
},
{
"SetupComplete": false
},
{
"FirstProcessorConnected": null
},
{
"SecondProcessorConnected": null
},
{
"ConfiguredRouting": null
},
{
"TestPayment": null
},
{
"IntegrationMethod": {
"integration_type": "test_type"
}
},
{
"ConfigurationType": null
},
{
"IntegrationCompleted": true
},
{
"StripeConnected": null
},
{
"PaypalConnected": null
},
{
"SPRoutingConfigured": null
},
{
"Feedback": {
"email": "sam234563@gmail.com",
"description": "Test Feedback",
"rating": 5,
"category": "test"
}
},
{
"ProdIntent": null
},
{
"SPTestPayment": false
},
{
"DownloadWoocom": false
},
{
"ConfigureWoocom": false
},
{
"SetupWoocomWebhook": false
},
{
"IsMultipleConfiguration": false
},
{
"IsChangePasswordRequired": false
}
]
```
## Checklist
<!-- Put an `x` in the boxes that apply -->
- [x] I formatted the code `cargo +nightly fmt --all`
- [x] I addressed lints thrown by `cargo clippy`
- [x] I reviewed the submitted code
- [ ] I added unit tests for my changes where possible
|
bc19fca1f4e76be6131e9c870b8aa1c709fef578
|
|
juspay/hyperswitch
|
juspay__hyperswitch-5395
|
Bug: refactor: change primary key of payment_methods table for v2
## Description
Previously our payment_methods table had `id` as PKey.
Which needs to be changed to a new Primary key namely `payment_method_id`.
|
diff --git a/crates/diesel_models/src/schema.rs b/crates/diesel_models/src/schema.rs
index b8c5344cbbb..55f8e935b14 100644
--- a/crates/diesel_models/src/schema.rs
+++ b/crates/diesel_models/src/schema.rs
@@ -934,7 +934,7 @@ diesel::table! {
use diesel::sql_types::*;
use crate::enums::diesel_exports::*;
- payment_methods (id) {
+ payment_methods (payment_method_id) {
id -> Int4,
#[max_length = 64]
customer_id -> Varchar,
diff --git a/crates/diesel_models/src/schema_v2.rs b/crates/diesel_models/src/schema_v2.rs
index 164600c88ac..90046d3fd95 100644
--- a/crates/diesel_models/src/schema_v2.rs
+++ b/crates/diesel_models/src/schema_v2.rs
@@ -931,7 +931,7 @@ diesel::table! {
use diesel::sql_types::*;
use crate::enums::diesel_exports::*;
- payment_methods (id) {
+ payment_methods (payment_method_id) {
id -> Int4,
#[max_length = 64]
customer_id -> Varchar,
diff --git a/migrations/2024-07-22-082828_change_primary_key_for_payment_methods/down.sql b/migrations/2024-07-22-082828_change_primary_key_for_payment_methods/down.sql
new file mode 100644
index 00000000000..26dd04d739b
--- /dev/null
+++ b/migrations/2024-07-22-082828_change_primary_key_for_payment_methods/down.sql
@@ -0,0 +1,5 @@
+-- This file should undo anything in `up.sql`
+ALTER TABLE payment_methods DROP CONSTRAINT payment_methods_pkey;
+
+ALTER TABLE payment_methods
+ADD PRIMARY KEY (id);
diff --git a/migrations/2024-07-22-082828_change_primary_key_for_payment_methods/up.sql b/migrations/2024-07-22-082828_change_primary_key_for_payment_methods/up.sql
new file mode 100644
index 00000000000..5fc305bc92c
--- /dev/null
+++ b/migrations/2024-07-22-082828_change_primary_key_for_payment_methods/up.sql
@@ -0,0 +1,12 @@
+-- Your SQL goes here
+-- The below query will lock the payment_methods table
+-- Running this query is not necessary on higher environments
+-- as the application will work fine without these queries being run
+-- This query should be run after the new version of application is deployed
+ALTER TABLE payment_methods DROP CONSTRAINT payment_methods_pkey;
+
+-- Use the `payment_method_id` column as primary key
+-- This is already unique, not null column
+-- So this query should not fail for not null or duplicate value reasons
+ALTER TABLE payment_methods
+ADD PRIMARY KEY (payment_method_id);
|
2024-07-22T08:39:07Z
|
## Type of Change
<!-- Put an `x` in the boxes that apply -->
- [ ] Bugfix
- [ ] New feature
- [ ] Enhancement
- [x] Refactoring
- [ ] Dependency updates
- [ ] Documentation
- [ ] CI/CD
## Description
<!-- Describe your changes in detail -->
Changing the primary key of the payment_methods table from (id) to the payment_method_id.
### Additional Changes
- [ ] This PR modifies the API contract
- [x] This PR modifies the database schema
- [ ] This PR modifies application configuration/environment variables
<!--
Provide links to the files with corresponding changes.
Following are the paths where you can find config files:
1. `config`
2. `crates/router/src/configs`
3. `loadtest/config`
-->
## Motivation and Context
<!--
Why is this change required? What problem does it solve?
If it fixes an open issue, please link to the issue here.
If you don't have an issue, we'd recommend starting with one first so the PR
can focus on the implementation (unless it is an obvious bug or documentation fix
that will have little conversation).
-->
Required for api_v2 migration
## How did you test it?
<!--
Did you write an integration/unit/API test to verify the code changes?
Or did you test this change manually (provide relevant screenshots)?
-->
Just Db id migration, doesn't requires any specific testing
## Checklist
<!-- Put an `x` in the boxes that apply -->
- [ ] I formatted the code `cargo +nightly fmt --all`
- [ ] I addressed lints thrown by `cargo clippy`
- [ ] I reviewed the submitted code
- [ ] I added unit tests for my changes where possible
|
bc19fca1f4e76be6131e9c870b8aa1c709fef578
|
|
juspay/hyperswitch
|
juspay__hyperswitch-5411
|
Bug: refactor: Patch file for DB migration
## Description
Create a patch file which removes id from schema.rs for all tables havin Integer id col.
|
diff --git a/crates/common_utils/src/id_type.rs b/crates/common_utils/src/id_type.rs
index 100f7957f5c..63f8497cae7 100644
--- a/crates/common_utils/src/id_type.rs
+++ b/crates/common_utils/src/id_type.rs
@@ -36,11 +36,11 @@ fn get_invalid_input_character(input_string: Cow<'static, str>) -> Option<char>
.find(|char| !is_valid_id_character(char))
}
-#[derive(Debug, PartialEq, Serialize, Clone, Eq, Hash)]
+#[derive(Debug, PartialEq, Hash, Serialize, Clone, Eq)]
/// A type for alphanumeric ids
pub(crate) struct AlphaNumericId(String);
-#[derive(Debug, Deserialize, Serialize, Error, Eq, PartialEq)]
+#[derive(Debug, Deserialize, Hash, Serialize, Error, Eq, PartialEq)]
#[error("value `{0}` contains invalid character `{1}`")]
/// The error type for alphanumeric id
pub(crate) struct AlphaNumericIdError(String, char);
@@ -82,7 +82,7 @@ impl AlphaNumericId {
}
/// A common type of id that can be used for reference ids with length constraint
-#[derive(Debug, Clone, Serialize, PartialEq, Eq, AsExpression, Hash)]
+#[derive(Debug, Clone, Serialize, Hash, PartialEq, Eq, AsExpression)]
#[diesel(sql_type = sql_types::Text)]
pub(crate) struct LengthId<const MAX_LENGTH: u8, const MIN_LENGTH: u8>(AlphaNumericId);
diff --git a/crates/common_utils/src/id_type/customer.rs b/crates/common_utils/src/id_type/customer.rs
index f56957025b2..00bd565d9e0 100644
--- a/crates/common_utils/src/id_type/customer.rs
+++ b/crates/common_utils/src/id_type/customer.rs
@@ -17,7 +17,7 @@ use crate::{
};
/// A type for customer_id that can be used for customer ids
-#[derive(Clone, Serialize, Deserialize, PartialEq, Eq, AsExpression)]
+#[derive(Clone, Serialize, Deserialize, Hash, PartialEq, Eq, AsExpression)]
#[diesel(sql_type = sql_types::Text)]
pub struct CustomerId(
LengthId<MAX_ALLOWED_MERCHANT_REFERENCE_ID_LENGTH, MIN_REQUIRED_MERCHANT_REFERENCE_ID_LENGTH>,
diff --git a/crates/diesel_models/remove_id.patch b/crates/diesel_models/remove_id.patch
new file mode 100644
index 00000000000..5b2e96ded3f
--- /dev/null
+++ b/crates/diesel_models/remove_id.patch
@@ -0,0 +1,108 @@
+diff --git a/crates/diesel_models/src/schema.rs b/crates/diesel_models/src/schema.rs
+index 55f8e935b..469ad1d22 100644
+--- a/crates/diesel_models/src/schema.rs
++++ b/crates/diesel_models/src/schema.rs
+@@ -5,7 +5,6 @@ diesel::table! {
+ use crate::enums::diesel_exports::*;
+
+ address (address_id) {
+- id -> Nullable<Int4>,
+ #[max_length = 64]
+ address_id -> Varchar,
+ #[max_length = 128]
+@@ -129,7 +128,6 @@ diesel::table! {
+ use crate::enums::diesel_exports::*;
+
+ blocklist (merchant_id, fingerprint_id) {
+- id -> Int4,
+ #[max_length = 64]
+ merchant_id -> Varchar,
+ #[max_length = 64]
+@@ -284,7 +282,6 @@ diesel::table! {
+ use crate::enums::diesel_exports::*;
+
+ customers (customer_id, merchant_id) {
+- id -> Int4,
+ #[max_length = 64]
+ customer_id -> Varchar,
+ #[max_length = 64]
+@@ -337,7 +334,6 @@ diesel::table! {
+ use crate::enums::diesel_exports::*;
+
+ dispute (dispute_id) {
+- id -> Int4,
+ #[max_length = 64]
+ dispute_id -> Varchar,
+ #[max_length = 255]
+@@ -588,7 +584,6 @@ diesel::table! {
+ use crate::enums::diesel_exports::*;
+
+ mandate (mandate_id) {
+- id -> Int4,
+ #[max_length = 64]
+ mandate_id -> Varchar,
+ #[max_length = 64]
+@@ -634,7 +629,6 @@ diesel::table! {
+ use crate::enums::diesel_exports::*;
+
+ merchant_account (merchant_id) {
+- id -> Int4,
+ #[max_length = 64]
+ merchant_id -> Varchar,
+ #[max_length = 255]
+@@ -678,7 +672,6 @@ diesel::table! {
+ use crate::enums::diesel_exports::*;
+
+ merchant_connector_account (merchant_connector_id) {
+- id -> Int4,
+ #[max_length = 64]
+ merchant_id -> Varchar,
+ #[max_length = 64]
+@@ -741,7 +734,6 @@ diesel::table! {
+ use crate::enums::diesel_exports::*;
+
+ payment_attempt (attempt_id, merchant_id) {
+- id -> Nullable<Int4>,
+ #[max_length = 64]
+ payment_id -> Varchar,
+ #[max_length = 64]
+@@ -832,7 +824,6 @@ diesel::table! {
+ use crate::enums::diesel_exports::*;
+
+ payment_intent (payment_id, merchant_id) {
+- id -> Nullable<Int4>,
+ #[max_length = 64]
+ payment_id -> Varchar,
+ #[max_length = 64]
+@@ -935,7 +926,6 @@ diesel::table! {
+ use crate::enums::diesel_exports::*;
+
+ payment_methods (payment_method_id) {
+- id -> Int4,
+ #[max_length = 64]
+ customer_id -> Varchar,
+ #[max_length = 64]
+@@ -1100,7 +1090,6 @@ diesel::table! {
+ use crate::enums::diesel_exports::*;
+
+ refund (merchant_id, refund_id) {
+- id -> Int4,
+ #[max_length = 64]
+ internal_reference_id -> Varchar,
+ #[max_length = 64]
+@@ -1169,7 +1158,6 @@ diesel::table! {
+ use crate::enums::diesel_exports::*;
+
+ roles (role_id) {
+- id -> Int4,
+ #[max_length = 64]
+ role_name -> Varchar,
+ #[max_length = 64]
+@@ -1276,7 +1263,6 @@ diesel::table! {
+ use crate::enums::diesel_exports::*;
+
+ users (user_id) {
+- id -> Int4,
+ #[max_length = 64]
+ user_id -> Varchar,
+ #[max_length = 255]
diff --git a/crates/diesel_models/src/address.rs b/crates/diesel_models/src/address.rs
index 8de7d8aa190..aaaa7fb747a 100644
--- a/crates/diesel_models/src/address.rs
+++ b/crates/diesel_models/src/address.rs
@@ -39,7 +39,6 @@ pub struct AddressNew {
#[derive(Clone, Debug, Queryable, Identifiable, Selectable, Serialize, Deserialize)]
#[diesel(table_name = address, primary_key(address_id), check_for_backend(diesel::pg::Pg))]
pub struct Address {
- pub id: Option<i32>,
pub address_id: String,
pub city: Option<String>,
pub country: Option<enums::CountryAlpha2>,
diff --git a/crates/diesel_models/src/blocklist.rs b/crates/diesel_models/src/blocklist.rs
index 0ef7daf0099..c4a5b48bad2 100644
--- a/crates/diesel_models/src/blocklist.rs
+++ b/crates/diesel_models/src/blocklist.rs
@@ -16,10 +16,8 @@ pub struct BlocklistNew {
#[derive(
Clone, Debug, Eq, PartialEq, Identifiable, Queryable, Selectable, Deserialize, Serialize,
)]
-#[diesel(table_name = blocklist, check_for_backend(diesel::pg::Pg))]
+#[diesel(table_name = blocklist, primary_key(merchant_id, fingerprint_id), check_for_backend(diesel::pg::Pg))]
pub struct Blocklist {
- #[serde(skip)]
- pub id: i32,
pub merchant_id: common_utils::id_type::MerchantId,
pub fingerprint_id: String,
pub data_kind: common_enums::BlocklistDataKind,
diff --git a/crates/diesel_models/src/customers.rs b/crates/diesel_models/src/customers.rs
index ea552e0d399..7219bb90524 100644
--- a/crates/diesel_models/src/customers.rs
+++ b/crates/diesel_models/src/customers.rs
@@ -33,7 +33,6 @@ impl CustomerNew {
impl From<CustomerNew> for Customer {
fn from(customer_new: CustomerNew) -> Self {
Self {
- id: 0i32,
customer_id: customer_new.customer_id,
merchant_id: customer_new.merchant_id,
name: customer_new.name,
@@ -55,9 +54,8 @@ impl From<CustomerNew> for Customer {
#[derive(
Clone, Debug, Identifiable, Queryable, Selectable, serde::Deserialize, serde::Serialize,
)]
-#[diesel(table_name = customers, check_for_backend(diesel::pg::Pg))]
+#[diesel(table_name = customers, primary_key(customer_id, merchant_id), check_for_backend(diesel::pg::Pg))]
pub struct Customer {
- pub id: i32,
pub customer_id: common_utils::id_type::CustomerId,
pub merchant_id: common_utils::id_type::MerchantId,
pub name: Option<Encryption>,
diff --git a/crates/diesel_models/src/dispute.rs b/crates/diesel_models/src/dispute.rs
index c2ef94e671f..704b1781e2a 100644
--- a/crates/diesel_models/src/dispute.rs
+++ b/crates/diesel_models/src/dispute.rs
@@ -33,10 +33,8 @@ pub struct DisputeNew {
}
#[derive(Clone, Debug, PartialEq, Serialize, Identifiable, Queryable, Selectable)]
-#[diesel(table_name = dispute, check_for_backend(diesel::pg::Pg))]
+#[diesel(table_name = dispute, primary_key(dispute_id), check_for_backend(diesel::pg::Pg))]
pub struct Dispute {
- #[serde(skip_serializing)]
- pub id: i32,
pub dispute_id: String,
pub amount: String,
pub currency: String,
diff --git a/crates/diesel_models/src/mandate.rs b/crates/diesel_models/src/mandate.rs
index ec4b572e8ee..bfac1849a58 100644
--- a/crates/diesel_models/src/mandate.rs
+++ b/crates/diesel_models/src/mandate.rs
@@ -9,9 +9,8 @@ use crate::{enums as storage_enums, schema::mandate};
#[derive(
Clone, Debug, Identifiable, Queryable, Selectable, serde::Serialize, serde::Deserialize,
)]
-#[diesel(table_name = mandate, check_for_backend(diesel::pg::Pg))]
+#[diesel(table_name = mandate, primary_key(mandate_id), check_for_backend(diesel::pg::Pg))]
pub struct Mandate {
- pub id: i32,
pub mandate_id: String,
pub customer_id: common_utils::id_type::CustomerId,
pub merchant_id: common_utils::id_type::MerchantId,
@@ -209,7 +208,6 @@ impl MandateUpdateInternal {
impl From<&MandateNew> for Mandate {
fn from(mandate_new: &MandateNew) -> Self {
Self {
- id: 0i32,
mandate_id: mandate_new.mandate_id.clone(),
customer_id: mandate_new.customer_id.clone(),
merchant_id: mandate_new.merchant_id.clone(),
diff --git a/crates/diesel_models/src/merchant_account.rs b/crates/diesel_models/src/merchant_account.rs
index 4e99900af2f..23bc642c2db 100644
--- a/crates/diesel_models/src/merchant_account.rs
+++ b/crates/diesel_models/src/merchant_account.rs
@@ -26,7 +26,6 @@ use crate::schema_v2::merchant_account;
)]
#[diesel(table_name = merchant_account, primary_key(merchant_id), check_for_backend(diesel::pg::Pg))]
pub struct MerchantAccount {
- pub id: i32,
pub merchant_id: id_type::MerchantId,
pub return_url: Option<String>,
pub enable_payment_response_hash: bool,
diff --git a/crates/diesel_models/src/merchant_connector_account.rs b/crates/diesel_models/src/merchant_connector_account.rs
index 4b6ab77d8ae..eb561f2f9c6 100644
--- a/crates/diesel_models/src/merchant_connector_account.rs
+++ b/crates/diesel_models/src/merchant_connector_account.rs
@@ -16,9 +16,8 @@ use crate::{enums as storage_enums, schema::merchant_connector_account};
Selectable,
router_derive::DebugAsDisplay,
)]
-#[diesel(table_name = merchant_connector_account, check_for_backend(diesel::pg::Pg))]
+#[diesel(table_name = merchant_connector_account, primary_key(merchant_connector_id), check_for_backend(diesel::pg::Pg))]
pub struct MerchantConnectorAccount {
- pub id: i32,
pub merchant_id: id_type::MerchantId,
pub connector_name: String,
pub connector_account_details: Encryption,
diff --git a/crates/diesel_models/src/payment_attempt.rs b/crates/diesel_models/src/payment_attempt.rs
index 791d4fb26e5..525c681a1e5 100644
--- a/crates/diesel_models/src/payment_attempt.rs
+++ b/crates/diesel_models/src/payment_attempt.rs
@@ -86,7 +86,6 @@ pub struct PaymentAttempt {
)]
#[diesel(table_name = payment_attempt, primary_key(attempt_id, merchant_id), check_for_backend(diesel::pg::Pg))]
pub struct PaymentAttempt {
- pub id: Option<i32>,
pub payment_id: String,
pub merchant_id: common_utils::id_type::MerchantId,
pub attempt_id: String,
@@ -1703,7 +1702,6 @@ mod tests {
#[test]
fn test_backwards_compatibility() {
let serialized_payment_attempt = r#"{
- "id": 1,
"payment_id": "PMT123456789",
"merchant_id": "M123456789",
"attempt_id": "ATMPT123456789",
diff --git a/crates/diesel_models/src/payment_intent.rs b/crates/diesel_models/src/payment_intent.rs
index 012376ae3d2..2d390b0b34c 100644
--- a/crates/diesel_models/src/payment_intent.rs
+++ b/crates/diesel_models/src/payment_intent.rs
@@ -74,7 +74,6 @@ pub struct PaymentIntent {
#[derive(Clone, Debug, PartialEq, Identifiable, Queryable, Serialize, Deserialize, Selectable)]
#[diesel(table_name = payment_intent, primary_key(payment_id, merchant_id), check_for_backend(diesel::pg::Pg))]
pub struct PaymentIntent {
- pub id: Option<i32>,
pub payment_id: String,
pub merchant_id: common_utils::id_type::MerchantId,
pub status: storage_enums::IntentStatus,
@@ -1027,7 +1026,6 @@ mod tests {
#[test]
fn test_backwards_compatibility() {
let serialized_payment_intent = r#"{
- "id": 123,
"payment_id": "payment_12345",
"merchant_id": "merchant_67890",
"status": "succeeded",
diff --git a/crates/diesel_models/src/payment_method.rs b/crates/diesel_models/src/payment_method.rs
index 0121ec5112c..b54824ad935 100644
--- a/crates/diesel_models/src/payment_method.rs
+++ b/crates/diesel_models/src/payment_method.rs
@@ -10,9 +10,8 @@ use crate::{enums as storage_enums, schema::payment_methods};
#[derive(
Clone, Debug, Eq, PartialEq, Identifiable, Queryable, Selectable, Serialize, Deserialize,
)]
-#[diesel(table_name = payment_methods, check_for_backend(diesel::pg::Pg))]
+#[diesel(table_name = payment_methods, primary_key(payment_method_id), check_for_backend(diesel::pg::Pg))]
pub struct PaymentMethod {
- pub id: i32,
pub customer_id: common_utils::id_type::CustomerId,
pub merchant_id: common_utils::id_type::MerchantId,
pub payment_method_id: String,
@@ -329,7 +328,6 @@ impl From<PaymentMethodUpdate> for PaymentMethodUpdateInternal {
impl From<&PaymentMethodNew> for PaymentMethod {
fn from(payment_method_new: &PaymentMethodNew) -> Self {
Self {
- id: 0i32,
customer_id: payment_method_new.customer_id.clone(),
merchant_id: payment_method_new.merchant_id.clone(),
payment_method_id: payment_method_new.payment_method_id.clone(),
diff --git a/crates/diesel_models/src/refund.rs b/crates/diesel_models/src/refund.rs
index b95ade2df1a..e4a74a6d66e 100644
--- a/crates/diesel_models/src/refund.rs
+++ b/crates/diesel_models/src/refund.rs
@@ -19,9 +19,8 @@ use crate::{enums as storage_enums, schema::refund};
serde::Serialize,
serde::Deserialize,
)]
-#[diesel(table_name = refund, check_for_backend(diesel::pg::Pg))]
+#[diesel(table_name = refund, primary_key(refund_id), check_for_backend(diesel::pg::Pg))]
pub struct Refund {
- pub id: i32,
pub internal_reference_id: String,
pub refund_id: String, //merchant_reference id
pub payment_id: String,
@@ -341,7 +340,6 @@ mod tests {
#[test]
fn test_backwards_compatibility() {
let serialized_refund = r#"{
- "id": 1,
"internal_reference_id": "internal_ref_123",
"refund_id": "refund_456",
"payment_id": "payment_789",
diff --git a/crates/diesel_models/src/role.rs b/crates/diesel_models/src/role.rs
index cf38f49aadf..713590adeda 100644
--- a/crates/diesel_models/src/role.rs
+++ b/crates/diesel_models/src/role.rs
@@ -5,9 +5,8 @@ use time::PrimitiveDateTime;
use crate::{enums, schema::roles};
#[derive(Clone, Debug, Identifiable, Queryable, Selectable)]
-#[diesel(table_name = roles, check_for_backend(diesel::pg::Pg))]
+#[diesel(table_name = roles, primary_key(role_id), check_for_backend(diesel::pg::Pg))]
pub struct Role {
- pub id: i32,
pub role_name: String,
pub role_id: String,
pub merchant_id: id_type::MerchantId,
diff --git a/crates/diesel_models/src/schema.rs b/crates/diesel_models/src/schema.rs
index 55f8e935b14..dd97469bc5e 100644
--- a/crates/diesel_models/src/schema.rs
+++ b/crates/diesel_models/src/schema.rs
@@ -5,7 +5,6 @@ diesel::table! {
use crate::enums::diesel_exports::*;
address (address_id) {
- id -> Nullable<Int4>,
#[max_length = 64]
address_id -> Varchar,
#[max_length = 128]
@@ -129,7 +128,6 @@ diesel::table! {
use crate::enums::diesel_exports::*;
blocklist (merchant_id, fingerprint_id) {
- id -> Int4,
#[max_length = 64]
merchant_id -> Varchar,
#[max_length = 64]
@@ -284,7 +282,6 @@ diesel::table! {
use crate::enums::diesel_exports::*;
customers (customer_id, merchant_id) {
- id -> Int4,
#[max_length = 64]
customer_id -> Varchar,
#[max_length = 64]
@@ -337,7 +334,6 @@ diesel::table! {
use crate::enums::diesel_exports::*;
dispute (dispute_id) {
- id -> Int4,
#[max_length = 64]
dispute_id -> Varchar,
#[max_length = 255]
@@ -588,7 +584,6 @@ diesel::table! {
use crate::enums::diesel_exports::*;
mandate (mandate_id) {
- id -> Int4,
#[max_length = 64]
mandate_id -> Varchar,
#[max_length = 64]
@@ -634,7 +629,6 @@ diesel::table! {
use crate::enums::diesel_exports::*;
merchant_account (merchant_id) {
- id -> Int4,
#[max_length = 64]
merchant_id -> Varchar,
#[max_length = 255]
@@ -678,7 +672,6 @@ diesel::table! {
use crate::enums::diesel_exports::*;
merchant_connector_account (merchant_connector_id) {
- id -> Int4,
#[max_length = 64]
merchant_id -> Varchar,
#[max_length = 64]
@@ -741,7 +734,6 @@ diesel::table! {
use crate::enums::diesel_exports::*;
payment_attempt (attempt_id, merchant_id) {
- id -> Nullable<Int4>,
#[max_length = 64]
payment_id -> Varchar,
#[max_length = 64]
@@ -832,7 +824,6 @@ diesel::table! {
use crate::enums::diesel_exports::*;
payment_intent (payment_id, merchant_id) {
- id -> Nullable<Int4>,
#[max_length = 64]
payment_id -> Varchar,
#[max_length = 64]
@@ -935,7 +926,6 @@ diesel::table! {
use crate::enums::diesel_exports::*;
payment_methods (payment_method_id) {
- id -> Int4,
#[max_length = 64]
customer_id -> Varchar,
#[max_length = 64]
@@ -1100,7 +1090,6 @@ diesel::table! {
use crate::enums::diesel_exports::*;
refund (merchant_id, refund_id) {
- id -> Int4,
#[max_length = 64]
internal_reference_id -> Varchar,
#[max_length = 64]
@@ -1169,7 +1158,6 @@ diesel::table! {
use crate::enums::diesel_exports::*;
roles (role_id) {
- id -> Int4,
#[max_length = 64]
role_name -> Varchar,
#[max_length = 64]
@@ -1276,7 +1264,6 @@ diesel::table! {
use crate::enums::diesel_exports::*;
users (user_id) {
- id -> Int4,
#[max_length = 64]
user_id -> Varchar,
#[max_length = 255]
diff --git a/crates/diesel_models/src/user.rs b/crates/diesel_models/src/user.rs
index 8469e4c2cab..582041ec42e 100644
--- a/crates/diesel_models/src/user.rs
+++ b/crates/diesel_models/src/user.rs
@@ -9,9 +9,8 @@ pub mod dashboard_metadata;
pub mod sample_data;
#[derive(Clone, Debug, Identifiable, Queryable, Selectable)]
-#[diesel(table_name = users, check_for_backend(diesel::pg::Pg))]
+#[diesel(table_name = users, primary_key(user_id), check_for_backend(diesel::pg::Pg))]
pub struct User {
- pub id: i32,
pub user_id: String,
pub email: pii::Email,
pub name: Secret<String>,
diff --git a/crates/hyperswitch_domain_models/src/customer.rs b/crates/hyperswitch_domain_models/src/customer.rs
index 558a8b4469c..504c1c20465 100644
--- a/crates/hyperswitch_domain_models/src/customer.rs
+++ b/crates/hyperswitch_domain_models/src/customer.rs
@@ -22,7 +22,6 @@ pub enum SoftDeleteStatus {
#[derive(Clone, Debug)]
pub struct Customer {
- pub id: Option<i32>,
pub customer_id: id_type::CustomerId,
pub merchant_id: id_type::MerchantId,
pub name: crypto::OptionalEncryptableName,
@@ -49,9 +48,6 @@ impl super::behaviour::Conversion for Customer {
type NewDstType = diesel_models::customers::CustomerNew;
async fn convert(self) -> CustomResult<Self::DstType, ValidationError> {
Ok(diesel_models::customers::Customer {
- id: self.id.ok_or(ValidationError::MissingRequiredField {
- field_name: "id".to_string(),
- })?,
customer_id: self.customer_id,
merchant_id: self.merchant_id,
name: self.name.map(|value| value.into()),
@@ -98,7 +94,6 @@ impl super::behaviour::Conversion for Customer {
})?;
Ok(Self {
- id: Some(item.id),
customer_id: item.customer_id,
merchant_id: item.merchant_id,
name: encryptable_customer.name,
diff --git a/crates/hyperswitch_domain_models/src/merchant_account.rs b/crates/hyperswitch_domain_models/src/merchant_account.rs
index eb5905c507e..6d311ea2d4d 100644
--- a/crates/hyperswitch_domain_models/src/merchant_account.rs
+++ b/crates/hyperswitch_domain_models/src/merchant_account.rs
@@ -22,7 +22,6 @@ use crate::type_encryption::{decrypt_optional, AsyncLift};
))]
#[derive(Clone, Debug, serde::Serialize)]
pub struct MerchantAccount {
- pub id: Option<i32>,
merchant_id: common_utils::id_type::MerchantId,
pub return_url: Option<String>,
pub enable_payment_response_hash: bool,
@@ -95,7 +94,6 @@ pub struct MerchantAccountSetter {
impl From<MerchantAccountSetter> for MerchantAccount {
fn from(item: MerchantAccountSetter) -> Self {
Self {
- id: None,
merchant_id: item.merchant_id,
return_url: item.return_url,
enable_payment_response_hash: item.enable_payment_response_hash,
@@ -416,9 +414,6 @@ impl super::behaviour::Conversion for MerchantAccount {
type NewDstType = diesel_models::merchant_account::MerchantAccountNew;
async fn convert(self) -> CustomResult<Self::DstType, ValidationError> {
Ok(diesel_models::merchant_account::MerchantAccount {
- id: self.id.ok_or(ValidationError::MissingRequiredField {
- field_name: "id".to_string(),
- })?,
merchant_id: self.merchant_id,
return_url: self.return_url,
enable_payment_response_hash: self.enable_payment_response_hash,
@@ -465,7 +460,6 @@ impl super::behaviour::Conversion for MerchantAccount {
})?;
async {
Ok::<Self, error_stack::Report<common_utils::errors::CryptoError>>(Self {
- id: Some(item.id),
merchant_id: item.merchant_id,
return_url: item.return_url,
enable_payment_response_hash: item.enable_payment_response_hash,
diff --git a/crates/hyperswitch_domain_models/src/payments/payment_attempt.rs b/crates/hyperswitch_domain_models/src/payments/payment_attempt.rs
index 7e4c5524727..9203a33239e 100644
--- a/crates/hyperswitch_domain_models/src/payments/payment_attempt.rs
+++ b/crates/hyperswitch_domain_models/src/payments/payment_attempt.rs
@@ -682,7 +682,6 @@ impl behaviour::Conversion for PaymentIntent {
async fn convert(self) -> CustomResult<Self::DstType, ValidationError> {
Ok(DieselPaymentIntent {
- id: None,
payment_id: self.payment_id,
merchant_id: self.merchant_id,
status: self.status,
diff --git a/crates/router/src/core/admin.rs b/crates/router/src/core/admin.rs
index 33d24eeccea..42da0feb840 100644
--- a/crates/router/src/core/admin.rs
+++ b/crates/router/src/core/admin.rs
@@ -1439,7 +1439,6 @@ pub async fn create_payment_connector(
business_sub_label: req.business_sub_label.clone(),
created_at: date_time::now(),
modified_at: date_time::now(),
- id: None,
connector_webhook_details: match req.connector_webhook_details {
Some(connector_webhook_details) => {
connector_webhook_details.encode_to_value(
diff --git a/crates/router/src/core/customers.rs b/crates/router/src/core/customers.rs
index 16f79e375b8..4c96f4fbe8f 100644
--- a/crates/router/src/core/customers.rs
+++ b/crates/router/src/core/customers.rs
@@ -170,7 +170,6 @@ impl CustomerCreateBridge for customers::CustomerRequest {
description: self.description.clone(),
phone_country_code: self.phone_country_code.clone(),
metadata: self.metadata.clone(),
- id: None,
connector_customer: None,
address_id: address_from_db.clone().map(|addr| addr.address_id),
created_at: common_utils::date_time::now(),
diff --git a/crates/router/src/core/payments/helpers.rs b/crates/router/src/core/payments/helpers.rs
index 6dd8f194724..f6bdd78fc25 100644
--- a/crates/router/src/core/payments/helpers.rs
+++ b/crates/router/src/core/payments/helpers.rs
@@ -362,7 +362,6 @@ pub async fn get_domain_address(
let encryptable_address = AddressDetailsWithPhone::from_encryptable(encrypted_data)
.change_context(common_utils::errors::CryptoError::EncodingFailed)?;
Ok(domain::Address {
- id: None,
phone_number: encryptable_address.phone_number,
country_code: address.phone.as_ref().and_then(|a| a.country_code.clone()),
merchant_id: merchant_id.to_owned(),
@@ -1680,7 +1679,6 @@ pub async fn create_customer_if_not_exist<'a, F: Clone, R>(
phone_country_code: request_customer_details.phone_country_code.clone(),
description: None,
created_at: common_utils::date_time::now(),
- id: None,
metadata: None,
modified_at: common_utils::date_time::now(),
connector_customer: None,
diff --git a/crates/router/src/core/payouts/helpers.rs b/crates/router/src/core/payouts/helpers.rs
index 41229552ad5..66ade4ee536 100644
--- a/crates/router/src/core/payouts/helpers.rs
+++ b/crates/router/src/core/payouts/helpers.rs
@@ -654,7 +654,6 @@ pub async fn get_or_create_customer_details(
phone_country_code: customer_details.phone_country_code.to_owned(),
metadata: None,
connector_customer: None,
- id: None,
created_at: common_utils::date_time::now(),
modified_at: common_utils::date_time::now(),
address_id: None,
diff --git a/crates/router/src/db/address.rs b/crates/router/src/db/address.rs
index f15adbeea69..10ad8ebe80a 100644
--- a/crates/router/src/db/address.rs
+++ b/crates/router/src/db/address.rs
@@ -571,7 +571,6 @@ mod storage {
};
let field = format!("add_{}", &address_new.address_id);
let created_address = diesel_models::Address {
- id: Some(0i32),
address_id: address_new.address_id.clone(),
city: address_new.city.clone(),
country: address_new.country,
diff --git a/crates/router/src/db/dispute.rs b/crates/router/src/db/dispute.rs
index 4de14057c18..073b725448d 100644
--- a/crates/router/src/db/dispute.rs
+++ b/crates/router/src/db/dispute.rs
@@ -1,4 +1,4 @@
-use error_stack::{report, ResultExt};
+use error_stack::report;
use router_env::{instrument, tracing};
use super::{MockDb, Store};
@@ -148,8 +148,6 @@ impl DisputeInterface for MockDb {
let now = common_utils::date_time::now();
let new_dispute = storage::Dispute {
- id: i32::try_from(locked_disputes.len())
- .change_context(errors::StorageError::MockDbError)?,
dispute_id: dispute.dispute_id,
amount: dispute.amount,
currency: dispute.currency,
@@ -674,7 +672,6 @@ mod tests {
.await
.unwrap();
- assert_eq!(created_dispute.id, updated_dispute.id);
assert_eq!(created_dispute.dispute_id, updated_dispute.dispute_id);
assert_eq!(created_dispute.amount, updated_dispute.amount);
assert_eq!(created_dispute.currency, updated_dispute.currency);
@@ -751,7 +748,6 @@ mod tests {
.await
.unwrap();
- assert_eq!(created_dispute.id, updated_dispute.id);
assert_eq!(created_dispute.dispute_id, updated_dispute.dispute_id);
assert_eq!(created_dispute.amount, updated_dispute.amount);
assert_eq!(created_dispute.currency, updated_dispute.currency);
@@ -827,7 +823,6 @@ mod tests {
.await
.unwrap();
- assert_eq!(created_dispute.id, updated_dispute.id);
assert_eq!(created_dispute.dispute_id, updated_dispute.dispute_id);
assert_eq!(created_dispute.amount, updated_dispute.amount);
assert_eq!(created_dispute.currency, updated_dispute.currency);
diff --git a/crates/router/src/db/mandate.rs b/crates/router/src/db/mandate.rs
index bdc51c8ad8b..c85bb4cb176 100644
--- a/crates/router/src/db/mandate.rs
+++ b/crates/router/src/db/mandate.rs
@@ -1,5 +1,4 @@
use common_utils::id_type;
-use error_stack::ResultExt;
use super::MockDb;
use crate::{
@@ -614,7 +613,6 @@ impl MandateInterface for MockDb {
) -> CustomResult<storage_types::Mandate, errors::StorageError> {
let mut mandates = self.mandates.lock().await;
let mandate = storage_types::Mandate {
- id: i32::try_from(mandates.len()).change_context(errors::StorageError::MockDbError)?,
mandate_id: mandate_new.mandate_id.clone(),
customer_id: mandate_new.customer_id,
merchant_id: mandate_new.merchant_id,
diff --git a/crates/router/src/db/merchant_connector_account.rs b/crates/router/src/db/merchant_connector_account.rs
index f48007d15b3..22f67b3538f 100644
--- a/crates/router/src/db/merchant_connector_account.rs
+++ b/crates/router/src/db/merchant_connector_account.rs
@@ -858,7 +858,6 @@ impl MerchantConnectorAccountInterface for MockDb {
) -> CustomResult<domain::MerchantConnectorAccount, errors::StorageError> {
let mut accounts = self.merchant_connector_accounts.lock().await;
let account = storage::MerchantConnectorAccount {
- id: i32::try_from(accounts.len()).change_context(errors::StorageError::MockDbError)?,
merchant_id: t.merchant_id,
connector_name: t.connector_name,
connector_account_details: t.connector_account_details.into(),
@@ -945,7 +944,7 @@ impl MerchantConnectorAccountInterface for MockDb {
.lock()
.await
.iter_mut()
- .find(|account| Some(account.id) == this.id)
+ .find(|account| account.merchant_connector_id == this.merchant_connector_id)
.map(|a| {
let updated =
merchant_connector_account.create_merchant_connector_account(a.clone());
@@ -1097,7 +1096,6 @@ mod merchant_connector_account_cache_tests {
.unwrap();
let mca = domain::MerchantConnectorAccount {
- id: Some(1),
merchant_id: merchant_id.to_owned(),
connector_name: "stripe".to_string(),
connector_account_details: domain::types::encrypt(
diff --git a/crates/router/src/db/payment_method.rs b/crates/router/src/db/payment_method.rs
index b0fed03e9b5..e182d62c3f3 100644
--- a/crates/router/src/db/payment_method.rs
+++ b/crates/router/src/db/payment_method.rs
@@ -664,8 +664,6 @@ impl PaymentMethodInterface for MockDb {
let mut payment_methods = self.payment_methods.lock().await;
let payment_method = storage_types::PaymentMethod {
- id: i32::try_from(payment_methods.len())
- .change_context(errors::StorageError::MockDbError)?,
customer_id: payment_method_new.customer_id,
merchant_id: payment_method_new.merchant_id,
payment_method_id: payment_method_new.payment_method_id,
@@ -784,7 +782,7 @@ impl PaymentMethodInterface for MockDb {
.lock()
.await
.iter_mut()
- .find(|pm| pm.id == payment_method.id)
+ .find(|pm| pm.payment_method_id == payment_method.payment_method_id)
.map(|pm| {
let payment_method_updated =
PaymentMethodUpdateInternal::from(payment_method_update)
diff --git a/crates/router/src/db/refund.rs b/crates/router/src/db/refund.rs
index 67be1d30e04..1fa7e28cb81 100644
--- a/crates/router/src/db/refund.rs
+++ b/crates/router/src/db/refund.rs
@@ -4,7 +4,6 @@ use std::collections::HashSet;
#[cfg(feature = "olap")]
use common_utils::types::MinorUnit;
use diesel_models::{errors::DatabaseError, refund::RefundUpdateInternal};
-use error_stack::ResultExt;
use super::MockDb;
use crate::{
@@ -372,7 +371,6 @@ mod storage {
// TODO: need to add an application generated payment attempt id to distinguish between multiple attempts for the same payment id
// Check for database presence as well Maybe use a read replica here ?
let created_refund = storage_types::Refund {
- id: 0i32,
refund_id: new.refund_id.clone(),
merchant_id: new.merchant_id.clone(),
attempt_id: new.attempt_id.clone(),
@@ -834,7 +832,6 @@ impl RefundInterface for MockDb {
let current_time = common_utils::date_time::now();
let refund = storage_types::Refund {
- id: i32::try_from(refunds.len()).change_context(errors::StorageError::MockDbError)?,
internal_reference_id: new.internal_reference_id,
refund_id: new.refund_id,
payment_id: new.payment_id,
diff --git a/crates/router/src/db/role.rs b/crates/router/src/db/role.rs
index 15dfc14d375..286a85190b8 100644
--- a/crates/router/src/db/role.rs
+++ b/crates/router/src/db/role.rs
@@ -1,7 +1,7 @@
use common_enums::enums;
use common_utils::id_type;
use diesel_models::role as storage;
-use error_stack::{report, ResultExt};
+use error_stack::report;
use router_env::{instrument, tracing};
use super::MockDb;
@@ -138,7 +138,6 @@ impl RoleInterface for MockDb {
})?
}
let role = storage::Role {
- id: i32::try_from(roles.len()).change_context(errors::StorageError::MockDbError)?,
role_name: role.role_name,
role_id: role.role_id,
merchant_id: role.merchant_id,
diff --git a/crates/router/src/db/user.rs b/crates/router/src/db/user.rs
index 742944bd1e0..b8c5001d910 100644
--- a/crates/router/src/db/user.rs
+++ b/crates/router/src/db/user.rs
@@ -1,5 +1,5 @@
use diesel_models::user as storage;
-use error_stack::{report, ResultExt};
+use error_stack::report;
use masking::Secret;
use router_env::{instrument, tracing};
@@ -152,7 +152,6 @@ impl UserInterface for MockDb {
}
let time_now = common_utils::date_time::now();
let user = storage::User {
- id: i32::try_from(users.len()).change_context(errors::StorageError::MockDbError)?,
user_id: user_data.user_id,
email: user_data.email,
name: user_data.name,
diff --git a/crates/router/src/types/domain/address.rs b/crates/router/src/types/domain/address.rs
index c7604622f3b..55d83679db9 100644
--- a/crates/router/src/types/domain/address.rs
+++ b/crates/router/src/types/domain/address.rs
@@ -17,8 +17,6 @@ use super::{behaviour, types};
#[derive(Clone, Debug, serde::Serialize)]
pub struct Address {
- #[serde(skip_serializing)]
- pub id: Option<i32>,
pub address_id: String,
pub city: Option<String>,
pub country: Option<enums::CountryAlpha2>,
@@ -161,7 +159,6 @@ impl behaviour::Conversion for Address {
async fn convert(self) -> CustomResult<Self::DstType, ValidationError> {
Ok(diesel_models::address::Address {
- id: self.id,
address_id: self.address_id,
city: self.city,
country: self.country,
@@ -206,7 +203,6 @@ impl behaviour::Conversion for Address {
message: "Failed while decrypting".to_string(),
})?;
Ok(Self {
- id: other.id,
address_id: other.address_id,
city: other.city,
country: other.country,
diff --git a/crates/router/src/types/domain/merchant_connector_account.rs b/crates/router/src/types/domain/merchant_connector_account.rs
index 6b0436b6f2f..170113c7a2a 100644
--- a/crates/router/src/types/domain/merchant_connector_account.rs
+++ b/crates/router/src/types/domain/merchant_connector_account.rs
@@ -16,7 +16,6 @@ use super::{
};
#[derive(Clone, Debug)]
pub struct MerchantConnectorAccount {
- pub id: Option<i32>,
pub merchant_id: common_utils::id_type::MerchantId,
pub connector_name: String,
pub connector_account_details: Encryptable<Secret<serde_json::Value>>,
@@ -74,9 +73,6 @@ impl behaviour::Conversion for MerchantConnectorAccount {
async fn convert(self) -> CustomResult<Self::DstType, ValidationError> {
Ok(
diesel_models::merchant_connector_account::MerchantConnectorAccount {
- id: self.id.ok_or(ValidationError::MissingRequiredField {
- field_name: "id".to_string(),
- })?,
merchant_id: self.merchant_id,
connector_name: self.connector_name,
connector_account_details: self.connector_account_details.into(),
@@ -113,7 +109,6 @@ impl behaviour::Conversion for MerchantConnectorAccount {
) -> CustomResult<Self, ValidationError> {
let identifier = Identifier::Merchant(other.merchant_id.clone());
Ok(Self {
- id: Some(other.id),
merchant_id: other.merchant_id,
connector_name: other.connector_name,
connector_account_details: decrypt(
diff --git a/crates/router/src/utils.rs b/crates/router/src/utils.rs
index ea3a36b518a..c86f9240c4b 100644
--- a/crates/router/src/utils.rs
+++ b/crates/router/src/utils.rs
@@ -755,7 +755,6 @@ impl CustomerAddress for api_models::customers::CustomerRequest {
let encryptable_address = AddressDetailsWithPhone::from_encryptable(encrypted_data)
.change_context(common_utils::errors::CryptoError::EncodingFailed)?;
let address = domain::Address {
- id: None,
city: address_details.city,
country: address_details.country,
line1: encryptable_address.line1,
diff --git a/crates/storage_impl/src/payments/payment_attempt.rs b/crates/storage_impl/src/payments/payment_attempt.rs
index f5d28f7698d..03a9ac6e454 100644
--- a/crates/storage_impl/src/payments/payment_attempt.rs
+++ b/crates/storage_impl/src/payments/payment_attempt.rs
@@ -1292,7 +1292,6 @@ impl DataModelExt for PaymentAttempt {
fn to_storage_model(self) -> Self::StorageModel {
DieselPaymentAttempt {
- id: None,
payment_id: self.payment_id,
merchant_id: self.merchant_id,
attempt_id: self.attempt_id,
diff --git a/diesel.toml b/diesel.toml
index 0496c748c3e..9079080b31f 100644
--- a/diesel.toml
+++ b/diesel.toml
@@ -5,3 +5,4 @@
file = "crates/diesel_models/src/schema.rs"
import_types = ["diesel::sql_types::*", "crate::enums::diesel_exports::*"]
generate_missing_sql_type_definitions = false
+patch_file="crates/diesel_models/remove_id.patch"
|
2024-07-22T11:51:33Z
|
## Type of Change
<!-- Put an `x` in the boxes that apply -->
- [ ] Bugfix
- [ ] New feature
- [ ] Enhancement
- [x] Refactoring
- [ ] Dependency updates
- [ ] Documentation
- [ ] CI/CD
## Description
<!-- Describe your changes in detail -->
This PR includes a patch file for removal of id from tables.
## Tables modified for API-V2:
**blocklist**
```
unique_key (merchant_id, fingerprint_id)
primary_key (merchant_id, fingerprint_id)
```
**payment_methods**
```
no unique_key
primary_key (payment_method_id)
```
**refund**
```
unique_key (refund_id, merchant_id)
primary_key (merchant_id, refund_id)
```
**user**
```
unique_key (user_id)
primary key (user_id)
```
**user_roles**
```
unique_key (user_id, merchant_id)
primary_key (user_id, merchant_id)
```
**roles**
```
unique_key (role_id)
primary_key (role_id)
```
### Additional Changes
- [ ] This PR modifies the API contract
- [x] This PR modifies the database schema
- [ ] This PR modifies application configuration/environment variables
<!--
Provide links to the files with corresponding changes.
Following are the paths where you can find config files:
1. `config`
2. `crates/router/src/configs`
3. `loadtest/config`
-->
## Motivation and Context
<!--
Why is this change required? What problem does it solve?
If it fixes an open issue, please link to the issue here.
If you don't have an issue, we'd recommend starting with one first so the PR
can focus on the implementation (unless it is an obvious bug or documentation fix
that will have little conversation).
-->
required for v2
## How did you test it?
<!--
Did you write an integration/unit/API test to verify the code changes?
Or did you test this change manually (provide relevant screenshots)?
-->
The code compilation works fine, and moreover it is id exclusion so we can probably skip testing.
## Checklist
<!-- Put an `x` in the boxes that apply -->
- [x] I formatted the code `cargo +nightly fmt --all`
- [x] I addressed lints thrown by `cargo clippy`
- [x] I reviewed the submitted code
- [ ] I added unit tests for my changes where possible
|
7068fbfbe2f561f71c2358d8d2a744d28672a892
|
|
juspay/hyperswitch
|
juspay__hyperswitch-5381
|
Bug: [BUG] Merchant Connector Account uses application decryption which should changed to API
### Bug Description
Due to recent v2 related changes Merchant Connector Account uses application decryption instead it should be changed API call to encryption service
### Expected Behavior
all encryption and decryption should happen in the encryption service
### Actual Behavior
Only of MCA decryption is happening in Application
### Steps To Reproduce
Create MCA, application throws 5xx due to decryption failure
### Context For The Bug
_No response_
### Environment
Are you using hyperswitch hosted version? Yes
If yes, please provide the value of the `x-request-id` response header to help us debug your issue.
If not (or if building/running locally), please provide the following details:
1. Operating System or Linux distribution:
2. Rust version (output of `rustc --version`): ``
3. App version (output of `cargo r --features vergen -- --version`): ``
### Have you spent some time checking if this bug has been raised before?
- [X] I checked and didn't find a similar issue
### Have you read the Contributing Guidelines?
- [X] I have read the [Contributing Guidelines](https://github.com/juspay/hyperswitch/blob/main/docs/CONTRIBUTING.md)
### Are you willing to submit a PR?
Yes, I am willing to submit a PR!
|
diff --git a/crates/hyperswitch_domain_models/src/merchant_account.rs b/crates/hyperswitch_domain_models/src/merchant_account.rs
index a430673c59a..47ced6573f8 100644
--- a/crates/hyperswitch_domain_models/src/merchant_account.rs
+++ b/crates/hyperswitch_domain_models/src/merchant_account.rs
@@ -14,7 +14,7 @@ use error_stack::ResultExt;
use masking::{PeekInterface, Secret};
use router_env::logger;
-use crate::type_encryption::{decrypt, AsyncLift};
+use crate::type_encryption::{decrypt_optional, AsyncLift};
#[derive(Clone, Debug, serde::Serialize)]
pub struct MerchantAccount {
@@ -220,11 +220,15 @@ impl super::behaviour::Conversion for MerchantAccount {
redirect_to_merchant_with_http_post: item.redirect_to_merchant_with_http_post,
merchant_name: item
.merchant_name
- .async_lift(|inner| decrypt(state, inner, identifier.clone(), key.peek()))
+ .async_lift(|inner| {
+ decrypt_optional(state, inner, identifier.clone(), key.peek())
+ })
.await?,
merchant_details: item
.merchant_details
- .async_lift(|inner| decrypt(state, inner, identifier.clone(), key.peek()))
+ .async_lift(|inner| {
+ decrypt_optional(state, inner, identifier.clone(), key.peek())
+ })
.await?,
webhook_details: item.webhook_details,
sub_merchants_enabled: item.sub_merchants_enabled,
diff --git a/crates/hyperswitch_domain_models/src/merchant_key_store.rs b/crates/hyperswitch_domain_models/src/merchant_key_store.rs
index 76acf0f1404..d48403b62ff 100644
--- a/crates/hyperswitch_domain_models/src/merchant_key_store.rs
+++ b/crates/hyperswitch_domain_models/src/merchant_key_store.rs
@@ -1,5 +1,5 @@
use common_utils::{
- crypto::{Encryptable, GcmAes256},
+ crypto::Encryptable,
custom_serde, date_time,
errors::{CustomResult, ValidationError},
types::keymanager::{Identifier, KeyManagerState},
@@ -8,7 +8,7 @@ use error_stack::ResultExt;
use masking::{PeekInterface, Secret};
use time::PrimitiveDateTime;
-use crate::type_encryption::TypeEncryption;
+use crate::type_encryption::decrypt;
#[derive(Clone, Debug, serde::Serialize)]
pub struct MerchantKeyStore {
@@ -41,7 +41,7 @@ impl super::behaviour::Conversion for MerchantKeyStore {
{
let identifier = Identifier::Merchant(item.merchant_id.clone());
Ok(Self {
- key: Encryptable::decrypt_via_api(state, item.key, identifier, key.peek(), GcmAes256)
+ key: decrypt(state, item.key, identifier, key.peek())
.await
.change_context(ValidationError::InvalidValue {
message: "Failed while decrypting customer data".to_string(),
diff --git a/crates/hyperswitch_domain_models/src/payments/payment_attempt.rs b/crates/hyperswitch_domain_models/src/payments/payment_attempt.rs
index 5f8dd3934a2..1f0dc3ca0b3 100644
--- a/crates/hyperswitch_domain_models/src/payments/payment_attempt.rs
+++ b/crates/hyperswitch_domain_models/src/payments/payment_attempt.rs
@@ -15,7 +15,7 @@ use super::PaymentIntent;
use crate::{
behaviour, errors,
mandates::{MandateDataType, MandateDetails},
- type_encryption::{decrypt, AsyncLift},
+ type_encryption::{decrypt_optional, AsyncLift},
ForeignIDRef, RemoteStorageObject,
};
@@ -552,7 +552,7 @@ impl behaviour::Conversion for PaymentIntent {
{
async {
let inner_decrypt = |inner| {
- decrypt(
+ decrypt_optional(
state,
inner,
common_utils::types::keymanager::Identifier::Merchant(key_store_ref_id.clone()),
diff --git a/crates/hyperswitch_domain_models/src/type_encryption.rs b/crates/hyperswitch_domain_models/src/type_encryption.rs
index d656afc9251..ed36ad59aec 100644
--- a/crates/hyperswitch_domain_models/src/type_encryption.rs
+++ b/crates/hyperswitch_domain_models/src/type_encryption.rs
@@ -908,25 +908,38 @@ where
}
#[inline]
-pub async fn decrypt<T: Clone, S: masking::Strategy<T>>(
+pub async fn decrypt_optional<T: Clone, S: masking::Strategy<T>>(
state: &KeyManagerState,
inner: Option<Encryption>,
identifier: Identifier,
key: &[u8],
) -> CustomResult<Option<crypto::Encryptable<Secret<T, S>>>, errors::CryptoError>
+where
+ crypto::Encryptable<Secret<T, S>>: TypeEncryption<T, crypto::GcmAes256, S>,
+{
+ inner
+ .async_map(|item| decrypt(state, item, identifier, key))
+ .await
+ .transpose()
+}
+
+#[inline]
+pub async fn decrypt<T: Clone, S: masking::Strategy<T>>(
+ state: &KeyManagerState,
+ inner: Encryption,
+ identifier: Identifier,
+ key: &[u8],
+) -> CustomResult<crypto::Encryptable<Secret<T, S>>, errors::CryptoError>
where
crypto::Encryptable<Secret<T, S>>: TypeEncryption<T, crypto::GcmAes256, S>,
{
record_operation_time(
- inner.async_map(|item| {
- crypto::Encryptable::decrypt_via_api(state, item, identifier, key, crypto::GcmAes256)
- }),
+ crypto::Encryptable::decrypt_via_api(state, inner, identifier, key, crypto::GcmAes256),
&metrics::DECRYPTION_TIME,
&metrics::CONTEXT,
&[],
)
.await
- .transpose()
}
#[inline]
diff --git a/crates/router/src/core/admin.rs b/crates/router/src/core/admin.rs
index bfefe893977..84c5df6a316 100644
--- a/crates/router/src/core/admin.rs
+++ b/crates/router/src/core/admin.rs
@@ -111,7 +111,10 @@ pub async fn create_merchant_account(
req: api::MerchantAccountCreate,
) -> RouterResponse<api::MerchantAccountResponse> {
#[cfg(feature = "keymanager_create")]
- use common_utils::keymanager;
+ use {
+ base64::Engine,
+ common_utils::{keymanager, types::keymanager::EncryptionTransferRequest},
+ };
let db = state.store.as_ref();
@@ -124,13 +127,13 @@ pub async fn create_merchant_account(
let key_manager_state = &(&state).into();
let merchant_id = req.get_merchant_reference_id().get_string_repr().to_owned();
let identifier = km_types::Identifier::Merchant(merchant_id.clone());
-
#[cfg(feature = "keymanager_create")]
{
- keymanager::create_key_in_key_manager(
+ keymanager::transfer_key_to_key_manager(
key_manager_state,
- km_types::EncryptionCreateRequest {
+ EncryptionTransferRequest {
identifier: identifier.clone(),
+ key: consts::BASE64_ENGINE.encode(key),
},
)
.await
diff --git a/crates/router/src/core/customers.rs b/crates/router/src/core/customers.rs
index e9126200acc..c0dc969db10 100644
--- a/crates/router/src/core/customers.rs
+++ b/crates/router/src/core/customers.rs
@@ -1,11 +1,12 @@
use api_models::customers::CustomerRequestWithEmail;
use common_utils::{
- crypto::{Encryptable, GcmAes256},
+ crypto::Encryptable,
errors::ReportSwitchExt,
ext_traits::OptionExt,
types::keymanager::{Identifier, ToEncryptable},
};
use error_stack::{report, ResultExt};
+use hyperswitch_domain_models::type_encryption::encrypt;
use masking::{Secret, SwitchStrategy};
use router_env::{instrument, tracing};
@@ -19,10 +20,7 @@ use crate::{
services,
types::{
api::customers,
- domain::{
- self,
- types::{self, TypeEncryption},
- },
+ domain::{self, types},
storage::{self, enums},
},
utils::CustomerAddress,
@@ -277,12 +275,11 @@ pub async fn delete_customer(
let key = key_store.key.get_inner().peek();
let identifier = Identifier::Merchant(key_store.merchant_id.clone());
- let redacted_encrypted_value: Encryptable<Secret<_>> = Encryptable::encrypt_via_api(
+ let redacted_encrypted_value: Encryptable<Secret<_>> = encrypt(
key_manager_state,
REDACTED.to_string().into(),
identifier.clone(),
key,
- GcmAes256,
)
.await
.switch()?;
@@ -336,12 +333,11 @@ pub async fn delete_customer(
let updated_customer = storage::CustomerUpdate::Update {
name: Some(redacted_encrypted_value.clone()),
email: Some(
- Encryptable::encrypt_via_api(
+ encrypt(
key_manager_state,
REDACTED.to_string().into(),
identifier,
key,
- GcmAes256,
)
.await
.switch()?,
diff --git a/crates/router/src/core/payment_methods/cards.rs b/crates/router/src/core/payment_methods/cards.rs
index 431826fbdb0..e96f2da158c 100644
--- a/crates/router/src/core/payment_methods/cards.rs
+++ b/crates/router/src/core/payment_methods/cards.rs
@@ -71,7 +71,7 @@ use crate::{
services,
types::{
api::{self, routing as routing_types, PaymentMethodCreateExt},
- domain::{self, types::decrypt},
+ domain::{self, types::decrypt_optional},
storage::{self, enums, PaymentMethodListContext, PaymentTokenData},
transformers::{ForeignFrom, ForeignTryFrom},
},
@@ -1209,7 +1209,7 @@ pub async fn update_customer_payment_method(
}
// Fetch the existing payment method data from db
- let existing_card_data = decrypt::<serde_json::Value, masking::WithType>(
+ let existing_card_data = decrypt_optional::<serde_json::Value, masking::WithType>(
&(&state).into(),
pm.payment_method_data.clone(),
Identifier::Merchant(key_store.merchant_id.clone()),
@@ -1683,7 +1683,7 @@ pub async fn decode_and_decrypt_locker_data(
.change_context(errors::VaultError::ResponseDeserializationFailed)
.attach_printable("Failed to decode hex string into bytes")?;
// Decrypt
- decrypt(
+ decrypt_optional(
&state.into(),
Some(Encryption::new(decoded_bytes.into())),
Identifier::Merchant(key_store.merchant_id.clone()),
@@ -4061,12 +4061,16 @@ where
{
let key = key_store.key.get_inner().peek();
let identifier = Identifier::Merchant(key_store.merchant_id.clone());
- let decrypted_data =
- decrypt::<serde_json::Value, masking::WithType>(&state.into(), data, identifier, key)
- .await
- .change_context(errors::StorageError::DecryptionError)
- .change_context(errors::ApiErrorResponse::InternalServerError)
- .attach_printable("unable to decrypt data")?;
+ let decrypted_data = decrypt_optional::<serde_json::Value, masking::WithType>(
+ &state.into(),
+ data,
+ identifier,
+ key,
+ )
+ .await
+ .change_context(errors::StorageError::DecryptionError)
+ .change_context(errors::ApiErrorResponse::InternalServerError)
+ .attach_printable("unable to decrypt data")?;
decrypted_data
.map(|decrypted_data| decrypted_data.into_inner().expose())
@@ -4083,7 +4087,7 @@ pub async fn get_card_details_with_locker_fallback(
) -> errors::RouterResult<Option<api::CardDetailFromLocker>> {
let key = key_store.key.get_inner().peek();
let identifier = Identifier::Merchant(key_store.merchant_id.clone());
- let card_decrypted = decrypt::<serde_json::Value, masking::WithType>(
+ let card_decrypted = decrypt_optional::<serde_json::Value, masking::WithType>(
&state.into(),
pm.payment_method_data.clone(),
identifier,
@@ -4119,7 +4123,7 @@ pub async fn get_card_details_without_locker_fallback(
) -> errors::RouterResult<api::CardDetailFromLocker> {
let key = key_store.key.get_inner().peek();
let identifier = Identifier::Merchant(key_store.merchant_id.clone());
- let card_decrypted = decrypt::<serde_json::Value, masking::WithType>(
+ let card_decrypted = decrypt_optional::<serde_json::Value, masking::WithType>(
&state.into(),
pm.payment_method_data.clone(),
identifier,
@@ -4194,7 +4198,7 @@ async fn get_masked_bank_details(
) -> errors::RouterResult<Option<MaskedBankDetails>> {
let key = key_store.key.get_inner().peek();
let identifier = Identifier::Merchant(key_store.merchant_id.clone());
- let payment_method_data = decrypt::<serde_json::Value, masking::WithType>(
+ let payment_method_data = decrypt_optional::<serde_json::Value, masking::WithType>(
&state.into(),
pm.payment_method_data.clone(),
identifier,
@@ -4234,7 +4238,7 @@ async fn get_bank_account_connector_details(
) -> errors::RouterResult<Option<BankAccountTokenData>> {
let key = key_store.key.get_inner().peek();
let identifier = Identifier::Merchant(key_store.merchant_id.clone());
- let payment_method_data = decrypt::<serde_json::Value, masking::WithType>(
+ let payment_method_data = decrypt_optional::<serde_json::Value, masking::WithType>(
&state.into(),
pm.payment_method_data.clone(),
identifier,
diff --git a/crates/router/src/core/payments/operations/payment_confirm.rs b/crates/router/src/core/payments/operations/payment_confirm.rs
index addd2f30670..ad3f8fb013e 100644
--- a/crates/router/src/core/payments/operations/payment_confirm.rs
+++ b/crates/router/src/core/payments/operations/payment_confirm.rs
@@ -39,7 +39,7 @@ use crate::{
types::{
self,
api::{self, ConnectorCallType, PaymentIdTypeExt},
- domain::{self, types::decrypt},
+ domain::{self, types::decrypt_optional},
storage::{self, enums as storage_enums},
},
utils::{self, OptionExt},
@@ -1084,7 +1084,7 @@ impl<F: Clone> UpdateTracker<F, PaymentData<F>, api::PaymentsRequest> for Paymen
let key = key_store.key.get_inner().peek();
let card_detail_from_locker: Option<api::CardDetailFromLocker> =
- decrypt::<serde_json::Value, masking::WithType>(
+ decrypt_optional::<serde_json::Value, masking::WithType>(
key_manager_state,
pm.payment_method_data.clone(),
Identifier::Merchant(key_store.merchant_id.clone()),
diff --git a/crates/router/src/core/payments/operations/payment_create.rs b/crates/router/src/core/payments/operations/payment_create.rs
index 929f404eae9..f264a056f6c 100644
--- a/crates/router/src/core/payments/operations/payment_create.rs
+++ b/crates/router/src/core/payments/operations/payment_create.rs
@@ -13,7 +13,7 @@ use error_stack::{self, ResultExt};
use hyperswitch_domain_models::{
mandates::{MandateData, MandateDetails},
payments::{payment_attempt::PaymentAttempt, payment_intent::CustomerData},
- type_encryption::decrypt,
+ type_encryption::decrypt_optional,
};
use masking::{ExposeInterface, PeekInterface, Secret};
use router_derive::PaymentOperation;
@@ -847,7 +847,7 @@ impl PaymentCreate {
additional_pm_data = payment_method_info
.as_ref()
.async_map(|pm_info| async {
- decrypt::<serde_json::Value, masking::WithType>(
+ decrypt_optional::<serde_json::Value, masking::WithType>(
&state.into(),
pm_info.payment_method_data.clone(),
Identifier::Merchant(key_store.merchant_id.clone()),
diff --git a/crates/router/src/core/pm_auth.rs b/crates/router/src/core/pm_auth.rs
index d6f5ffd9fb9..df28d257b36 100644
--- a/crates/router/src/core/pm_auth.rs
+++ b/crates/router/src/core/pm_auth.rs
@@ -45,7 +45,7 @@ use crate::{
services::{pm_auth as pm_auth_services, ApplicationResponse},
types::{
self,
- domain::{self, types::decrypt},
+ domain::{self, types::decrypt_optional},
storage,
transformers::ForeignTryFrom,
},
@@ -327,7 +327,7 @@ async fn store_bank_details_in_payment_methods(
for pm in payment_methods {
if pm.payment_method == Some(enums::PaymentMethod::BankDebit) {
- let bank_details_pm_data = decrypt::<serde_json::Value, masking::WithType>(
+ let bank_details_pm_data = decrypt_optional::<serde_json::Value, masking::WithType>(
&(&state).into(),
pm.payment_method_data.clone(),
Identifier::Merchant(key_store.merchant_id.clone()),
diff --git a/crates/router/src/core/webhooks/outgoing.rs b/crates/router/src/core/webhooks/outgoing.rs
index ed2b41dc64d..7f30a58e208 100644
--- a/crates/router/src/core/webhooks/outgoing.rs
+++ b/crates/router/src/core/webhooks/outgoing.rs
@@ -7,7 +7,7 @@ use api_models::{
use common_utils::{ext_traits::Encode, request::RequestContent, types::keymanager::Identifier};
use diesel_models::process_tracker::business_status;
use error_stack::{report, ResultExt};
-use hyperswitch_domain_models::type_encryption::decrypt;
+use hyperswitch_domain_models::type_encryption::decrypt_optional;
use masking::{ExposeInterface, Mask, PeekInterface, Secret};
use router_env::{
instrument,
@@ -575,7 +575,7 @@ pub(crate) async fn get_outgoing_webhook_request(
let transformed_outgoing_webhook = WebhookType::from(outgoing_webhook);
let payment_response_hash_key = business_profile.payment_response_hash_key.clone();
- let custom_headers = decrypt::<serde_json::Value, masking::WithType>(
+ let custom_headers = decrypt_optional::<serde_json::Value, masking::WithType>(
&state.into(),
business_profile
.outgoing_webhook_custom_http_headers
diff --git a/crates/router/src/types/api/admin.rs b/crates/router/src/types/api/admin.rs
index 054888d1dfe..6cd259f3e7b 100644
--- a/crates/router/src/types/api/admin.rs
+++ b/crates/router/src/types/api/admin.rs
@@ -13,7 +13,9 @@ use common_utils::{
types::keymanager::Identifier,
};
use error_stack::{report, ResultExt};
-use hyperswitch_domain_models::{merchant_key_store::MerchantKeyStore, type_encryption::decrypt};
+use hyperswitch_domain_models::{
+ merchant_key_store::MerchantKeyStore, type_encryption::decrypt_optional,
+};
use masking::{ExposeInterface, PeekInterface, Secret};
use crate::{
@@ -92,24 +94,25 @@ pub async fn business_profile_response(
item: storage::business_profile::BusinessProfile,
key_store: &MerchantKeyStore,
) -> Result<BusinessProfileResponse, error_stack::Report<errors::ParsingError>> {
- let outgoing_webhook_custom_http_headers = decrypt::<serde_json::Value, masking::WithType>(
- &state.into(),
- item.outgoing_webhook_custom_http_headers.clone(),
- Identifier::Merchant(key_store.merchant_id.clone()),
- key_store.key.get_inner().peek(),
- )
- .await
- .change_context(errors::ParsingError::StructParseFailure(
- "Outgoing webhook custom HTTP headers",
- ))
- .attach_printable("Failed to decrypt outgoing webhook custom HTTP headers")?
- .map(|decrypted_value| {
- decrypted_value
- .into_inner()
- .expose()
- .parse_value::<HashMap<String, String>>("HashMap<String,String>")
- })
- .transpose()?;
+ let outgoing_webhook_custom_http_headers =
+ decrypt_optional::<serde_json::Value, masking::WithType>(
+ &state.into(),
+ item.outgoing_webhook_custom_http_headers.clone(),
+ Identifier::Merchant(key_store.merchant_id.clone()),
+ key_store.key.get_inner().peek(),
+ )
+ .await
+ .change_context(errors::ParsingError::StructParseFailure(
+ "Outgoing webhook custom HTTP headers",
+ ))
+ .attach_printable("Failed to decrypt outgoing webhook custom HTTP headers")?
+ .map(|decrypted_value| {
+ decrypted_value
+ .into_inner()
+ .expose()
+ .parse_value::<HashMap<String, String>>("HashMap<String,String>")
+ })
+ .transpose()?;
Ok(BusinessProfileResponse {
merchant_id: item.merchant_id,
diff --git a/crates/router/src/types/domain/merchant_connector_account.rs b/crates/router/src/types/domain/merchant_connector_account.rs
index 6f654848f60..bd0bfe15e53 100644
--- a/crates/router/src/types/domain/merchant_connector_account.rs
+++ b/crates/router/src/types/domain/merchant_connector_account.rs
@@ -1,5 +1,5 @@
use common_utils::{
- crypto::{Encryptable, GcmAes256},
+ crypto::Encryptable,
date_time,
encryption::Encryption,
errors::{CustomResult, ValidationError},
@@ -12,7 +12,7 @@ use masking::{PeekInterface, Secret};
use super::{
behaviour,
- types::{self, AsyncLift, TypeEncryption},
+ types::{decrypt, decrypt_optional, AsyncLift},
};
#[derive(Clone, Debug)]
pub struct MerchantConnectorAccount {
@@ -117,12 +117,11 @@ impl behaviour::Conversion for MerchantConnectorAccount {
id: Some(other.id),
merchant_id: other.merchant_id,
connector_name: other.connector_name,
- connector_account_details: Encryptable::decrypt_via_api(
+ connector_account_details: decrypt(
state,
other.connector_account_details,
identifier.clone(),
key.peek(),
- GcmAes256,
)
.await
.change_context(ValidationError::InvalidValue {
@@ -149,14 +148,14 @@ impl behaviour::Conversion for MerchantConnectorAccount {
status: other.status,
connector_wallets_details: other
.connector_wallets_details
- .async_lift(|inner| types::decrypt(state, inner, identifier.clone(), key.peek()))
+ .async_lift(|inner| decrypt_optional(state, inner, identifier.clone(), key.peek()))
.await
.change_context(ValidationError::InvalidValue {
message: "Failed while decrypting connector wallets details".to_string(),
})?,
additional_merchant_data: if let Some(data) = other.additional_merchant_data {
Some(
- Encryptable::decrypt(data, key.peek(), GcmAes256)
+ decrypt(state, data, identifier, key.peek())
.await
.change_context(ValidationError::InvalidValue {
message: "Failed while decrypting additional_merchant_data".to_string(),
diff --git a/crates/router/src/types/domain/types.rs b/crates/router/src/types/domain/types.rs
index 53239cd27cf..fa9053a096f 100644
--- a/crates/router/src/types/domain/types.rs
+++ b/crates/router/src/types/domain/types.rs
@@ -1,7 +1,7 @@
use common_utils::types::keymanager::KeyManagerState;
pub use hyperswitch_domain_models::type_encryption::{
- batch_decrypt, batch_encrypt, decrypt, encrypt, encrypt_optional, AsyncLift, Lift,
- TypeEncryption,
+ batch_decrypt, batch_encrypt, decrypt, decrypt_optional, encrypt, encrypt_optional, AsyncLift,
+ Lift,
};
impl From<&crate::SessionState> for KeyManagerState {
diff --git a/crates/router/src/types/domain/user.rs b/crates/router/src/types/domain/user.rs
index ec44103a8f0..6988cdf6136 100644
--- a/crates/router/src/types/domain/user.rs
+++ b/crates/router/src/types/domain/user.rs
@@ -6,8 +6,6 @@ use api_models::{
use common_enums::TokenPurpose;
#[cfg(not(feature = "v2"))]
use common_utils::id_type;
-#[cfg(feature = "keymanager_create")]
-use common_utils::types::keymanager::EncryptionCreateRequest;
use common_utils::{
crypto::Encryptable, errors::CustomResult, new_type::MerchantName, pii,
types::keymanager::Identifier,
@@ -25,6 +23,8 @@ use once_cell::sync::Lazy;
use rand::distributions::{Alphanumeric, DistString};
use router_env::env;
use unicode_segmentation::UnicodeSegmentation;
+#[cfg(feature = "keymanager_create")]
+use {base64::Engine, common_utils::types::keymanager::EncryptionTransferRequest};
use crate::{
consts,
@@ -975,6 +975,19 @@ impl UserFromStorage {
.change_context(UserErrors::InternalServerError)
.attach_printable("Unable to generate aes 256 key")?;
+ #[cfg(feature = "keymanager_create")]
+ {
+ common_utils::keymanager::transfer_key_to_key_manager(
+ key_manager_state,
+ EncryptionTransferRequest {
+ identifier: Identifier::User(self.get_user_id().to_string()),
+ key: consts::BASE64_ENGINE.encode(key),
+ },
+ )
+ .await
+ .change_context(UserErrors::InternalServerError)?;
+ }
+
let key_store = UserKeyStore {
user_id: self.get_user_id().to_string(),
key: domain_types::encrypt(
@@ -988,18 +1001,6 @@ impl UserFromStorage {
created_at: common_utils::date_time::now(),
};
- #[cfg(feature = "keymanager_create")]
- {
- common_utils::keymanager::create_key_in_key_manager(
- key_manager_state,
- EncryptionCreateRequest {
- identifier: Identifier::User(key_store.user_id.clone()),
- },
- )
- .await
- .change_context(UserErrors::InternalServerError)?;
- }
-
state
.global_store
.insert_user_key_store(key_manager_state, key_store, &master_key.to_vec().into())
@@ -1039,7 +1040,7 @@ impl UserFromStorage {
.await
.change_context(UserErrors::InternalServerError)?;
- Ok(domain_types::decrypt::<String, masking::WithType>(
+ Ok(domain_types::decrypt_optional::<String, masking::WithType>(
key_manager_state,
self.0.totp_secret.clone(),
Identifier::User(user_key_store.user_id.clone()),
diff --git a/crates/router/src/types/domain/user_key_store.rs b/crates/router/src/types/domain/user_key_store.rs
index 3a1a9a60e95..40c8acd5695 100644
--- a/crates/router/src/types/domain/user_key_store.rs
+++ b/crates/router/src/types/domain/user_key_store.rs
@@ -1,16 +1,14 @@
use common_utils::{
- crypto::{Encryptable, GcmAes256},
+ crypto::Encryptable,
date_time,
types::keymanager::{Identifier, KeyManagerState},
};
use error_stack::ResultExt;
+use hyperswitch_domain_models::type_encryption::decrypt;
use masking::{PeekInterface, Secret};
use time::PrimitiveDateTime;
-use crate::{
- errors::{CustomResult, ValidationError},
- types::domain::types::TypeEncryption,
-};
+use crate::errors::{CustomResult, ValidationError};
#[derive(Clone, Debug, serde::Serialize)]
pub struct UserKeyStore {
@@ -43,7 +41,7 @@ impl super::behaviour::Conversion for UserKeyStore {
{
let identifier = Identifier::User(item.user_id.clone());
Ok(Self {
- key: Encryptable::decrypt_via_api(state, item.key, identifier, key.peek(), GcmAes256)
+ key: decrypt(state, item.key, identifier, key.peek())
.await
.change_context(ValidationError::InvalidValue {
message: "Failed while decrypting customer data".to_string(),
diff --git a/crates/router/src/utils/user.rs b/crates/router/src/utils/user.rs
index 9734122a260..ccb9ed7d37b 100644
--- a/crates/router/src/utils/user.rs
+++ b/crates/router/src/utils/user.rs
@@ -283,7 +283,7 @@ pub async fn decrypt_oidc_private_config(
.change_context(UserErrors::InternalServerError)
.attach_printable("Failed to decode DEK")?;
- let private_config = domain::types::decrypt::<serde_json::Value, masking::WithType>(
+ let private_config = domain::types::decrypt_optional::<serde_json::Value, masking::WithType>(
&state.into(),
encrypted_config,
Identifier::UserAuth(id),
|
2024-07-19T13:16:25Z
|
## Type of Change
<!-- Put an `x` in the boxes that apply -->
- [x] Bugfix
- [ ] New feature
- [ ] Enhancement
- [ ] Refactoring
- [ ] Dependency updates
- [ ] Documentation
- [ ] CI/CD
## Description
encrypt/decrypt should happen only via encryption service and DEK should be same in application and encryption service
### Additional Changes
- [ ] This PR modifies the API contract
- [ ] This PR modifies the database schema
- [ ] This PR modifies application configuration/environment variables
<!--
Provide links to the files with corresponding changes.
Following are the paths where you can find config files:
1. `config`
2. `crates/router/src/configs`
3. `loadtest/config`
-->
## Motivation and Context
encrypt/decrypt should happen only via encryption service and DEK should be same in application and encryption service
## How did you test it?
Changes can be verified only through logs. Look for "Fall back to Application Encryption" or "Fall back to Application Decryption" in the logs post deployment after running below tests. If logs are present encryption/decryption failed with encryption service and fall back to the application encryption which has to be investigated.
Test with merchant created before the changes deployed
1. Create Payment
2. Retrieve Payment
3. Create Refund
4. Retrieve Payment
Test with merchant created after the changes deployed
1. Create Merchant
2. Create API Key
3. Create MCA
4. Create Payment
6. Retrieve Payment
7. Create Refund
8. Retrieve Payment
Requires sanity on all the flows
## Checklist
<!-- Put an `x` in the boxes that apply -->
- [x] I formatted the code `cargo +nightly fmt --all`
- [x] I addressed lints thrown by `cargo clippy`
- [x] I reviewed the submitted code
- [ ] I added unit tests for my changes where possible
|
476aed5036eb41671c0736887d02dcac7f3573c6
|
|
juspay/hyperswitch
|
juspay__hyperswitch-5378
|
Bug: Email footer icons spacing
Footer icons must be separated for better usability.

|
diff --git a/crates/router/src/services/email/assets/api_key_expiry_reminder.html b/crates/router/src/services/email/assets/api_key_expiry_reminder.html
index 9d97d153eb6..3ec51164a50 100644
--- a/crates/router/src/services/email/assets/api_key_expiry_reminder.html
+++ b/crates/router/src/services/email/assets/api_key_expiry_reminder.html
@@ -136,7 +136,7 @@
height="15"
/>
</a>
- <a href="https://x.com/hyperswitchio?s=21" target="_blank">
+ <a href="https://x.com/hyperswitchio?s=21" target="_blank" style="margin: 0 6px 0">
<img
src="https://app.hyperswitch.io/email-assets/Twitter.png"
alt="Twitter"
diff --git a/crates/router/src/services/email/assets/bizemailprod.html b/crates/router/src/services/email/assets/bizemailprod.html
index 8035728d4c7..3645c953a02 100644
--- a/crates/router/src/services/email/assets/bizemailprod.html
+++ b/crates/router/src/services/email/assets/bizemailprod.html
@@ -146,7 +146,11 @@
height="15"
/>
</a>
- <a href="https://x.com/hyperswitchio?s=21" target="_blank">
+ <a
+ href="https://x.com/hyperswitchio?s=21"
+ target="_blank"
+ style="margin: 0 6px 0"
+ >
<img
src="https://app.hyperswitch.io/email-assets/Twitter.png"
alt="Twitter"
diff --git a/crates/router/src/services/email/assets/invite.html b/crates/router/src/services/email/assets/invite.html
index 4a2a6835e80..9962da06383 100644
--- a/crates/router/src/services/email/assets/invite.html
+++ b/crates/router/src/services/email/assets/invite.html
@@ -191,7 +191,11 @@
height="15"
/>
</a>
- <a href="https://x.com/hyperswitchio?s=21" target="_blank">
+ <a
+ href="https://x.com/hyperswitchio?s=21"
+ target="_blank"
+ style="margin: 0 6px 0"
+ >
<img
src="https://app.hyperswitch.io/email-assets/Twitter.png"
alt="Twitter"
diff --git a/crates/router/src/services/email/assets/magic_link.html b/crates/router/src/services/email/assets/magic_link.html
index b7516e8ae09..7cb474b52cb 100644
--- a/crates/router/src/services/email/assets/magic_link.html
+++ b/crates/router/src/services/email/assets/magic_link.html
@@ -190,7 +190,11 @@
height="15"
/>
</a>
- <a href="https://x.com/hyperswitchio?s=21" target="_blank">
+ <a
+ href="https://x.com/hyperswitchio?s=21"
+ target="_blank"
+ style="margin: 0 6px 0"
+ >
<img
src="https://app.hyperswitch.io/email-assets/Twitter.png"
alt="Twitter"
diff --git a/crates/router/src/services/email/assets/recon_activation.html b/crates/router/src/services/email/assets/recon_activation.html
index 512bda73227..f9de747bb1a 100644
--- a/crates/router/src/services/email/assets/recon_activation.html
+++ b/crates/router/src/services/email/assets/recon_activation.html
@@ -163,7 +163,7 @@
height="15"
/>
</a>
- <a href="https://x.com/hyperswitchio?s=21" target="_blank">
+ <a href="https://x.com/hyperswitchio?s=21" target="_blank" style="margin: 0 6px 0">
<img
src="https://app.hyperswitch.io/email-assets/Twitter.png"
alt="Twitter"
diff --git a/crates/router/src/services/email/assets/reset.html b/crates/router/src/services/email/assets/reset.html
index e50ea598976..23eadbeb062 100644
--- a/crates/router/src/services/email/assets/reset.html
+++ b/crates/router/src/services/email/assets/reset.html
@@ -188,7 +188,11 @@
height="15"
/>
</a>
- <a href="https://x.com/hyperswitchio?s=21" target="_blank">
+ <a
+ href="https://x.com/hyperswitchio?s=21"
+ target="_blank"
+ style="margin: 0 6px 0"
+ >
<img
src="https://app.hyperswitch.io/email-assets/Twitter.png"
alt="Twitter"
diff --git a/crates/router/src/services/email/assets/verify.html b/crates/router/src/services/email/assets/verify.html
index d67d130a75f..718e7446ec5 100644
--- a/crates/router/src/services/email/assets/verify.html
+++ b/crates/router/src/services/email/assets/verify.html
@@ -156,7 +156,11 @@
height="15"
/>
</a>
- <a href="https://x.com/hyperswitchio?s=21" target="_blank">
+ <a
+ href="https://x.com/hyperswitchio?s=21"
+ target="_blank"
+ style="margin: 0 6px 0"
+ >
<img
src="https://app.hyperswitch.io/email-assets/Twitter.png"
alt="Twitter"
|
2024-07-19T10:58:44Z
|
## Type of Change
<!-- Put an `x` in the boxes that apply -->
- [ ] Bugfix
- [ ] New feature
- [x] Enhancement
- [ ] Refactoring
- [ ] Dependency updates
- [ ] Documentation
- [ ] CI/CD
## Description
- Provided spacing between email template footer icons
### Additional Changes
- [ ] This PR modifies the API contract
- [ ] This PR modifies the database schema
- [ ] This PR modifies application configuration/environment variables
<!--
Provide links to the files with corresponding changes.
Following are the paths where you can find config files:
1. `config`
2. `crates/router/src/configs`
3. `loadtest/config`
-->
## Motivation and Context
<!--
Why is this change required? What problem does it solve?
If it fixes an open issue, please link to the issue here.
If you don't have an issue, we'd recommend starting with one first so the PR
can focus on the implementation (unless it is an obvious bug or documentation fix
that will have little conversation).
-->
## How did you test it?
Tested locally using AWS SES service

## Checklist
<!-- Put an `x` in the boxes that apply -->
- [x] I formatted the code `cargo +nightly fmt --all`
- [ ] I addressed lints thrown by `cargo clippy`
- [x] I reviewed the submitted code
- [ ] I added unit tests for my changes where possible
|
bc92e0cccbbc989f3b32ad16cae58a3e47babe8b
|
|
juspay/hyperswitch
|
juspay__hyperswitch-5394
|
Bug: [FEATURE] Supporting processors token in Payments API
### Feature Description
During the transition phase of Hyperswitch, Merchant should be able to send the processor's token to Hyperswitch to process MIT transaction. This is because, Merchant will not have the card data to migrate from Processor to Hyperswitch.
### Possible Implementation
**#Solution 1**
In payments create+confirm API, we will add new enum processor_token in type under recurring_details to support connector data. We will start supporting Bambora’s and we will slowly adopt every connectors.
- This field will be a replaceable field for payment method id. Merchant can either pass payment_method_id or {recurring_details.data:{processor_payment_token: "value", connector:"BAMBORA"}}. Connector can be enum.
- Based on this field, we will fork the main flow, which will skip the payment_method part and use this data given in the request.
**Expected Flow:**
- Merchant needs to create customer before calling this API.
- Call Payments API
**Technical changes information:**
- Routing is not involved - (No changes)
- Customer related process can also be ignored. (No changes, as merchant creates customer before calling this API)
- Populate connector_mandate_id in `router_data` from the request, instead of fetching from database.
**In V1 we can add if else to handle the flow, in v2, we will follow separate handler with the same route.**
**Flow shall be in the following order,**
- Get tracker (create+confirm)
- Get customer (create + confirm)
- Skip to call connector (create + confirm).
- response handling (create + confirm )
### Have you spent some time checking if this feature request has been raised before?
- [X] I checked and didn't find a similar issue
### Have you read the Contributing Guidelines?
- [X] I have read the [Contributing Guidelines](https://github.com/juspay/hyperswitch/blob/main/docs/CONTRIBUTING.md)
### Are you willing to submit a PR?
None
|
diff --git a/crates/api_models/src/mandates.rs b/crates/api_models/src/mandates.rs
index f4089a16c22..dc61aa08b0c 100644
--- a/crates/api_models/src/mandates.rs
+++ b/crates/api_models/src/mandates.rs
@@ -120,4 +120,14 @@ pub struct MandateListConstraints {
pub enum RecurringDetails {
MandateId(String),
PaymentMethodId(String),
+ ProcessorPaymentToken(ProcessorPaymentToken),
+}
+
+/// Processor payment token for MIT payments where payment_method_data is not available
+#[derive(Debug, Clone, serde::Serialize, serde::Deserialize, ToSchema)]
+pub struct ProcessorPaymentToken {
+ pub processor_payment_token: String,
+ #[schema(value_type = Connector, example = "stripe")]
+ pub connector: api_enums::Connector,
+ pub merchant_connector_id: String,
}
diff --git a/crates/diesel_models/src/payment_intent.rs b/crates/diesel_models/src/payment_intent.rs
index 2d390b0b34c..bdea1fe52a7 100644
--- a/crates/diesel_models/src/payment_intent.rs
+++ b/crates/diesel_models/src/payment_intent.rs
@@ -68,6 +68,7 @@ pub struct PaymentIntent {
pub billing_details: Option<Encryption>,
pub merchant_order_reference_id: Option<String>,
pub shipping_details: Option<Encryption>,
+ pub is_payment_processor_token_flow: Option<bool>,
}
#[cfg(all(any(feature = "v1", feature = "v2"), not(feature = "payment_v2")))]
@@ -128,6 +129,7 @@ pub struct PaymentIntent {
pub billing_details: Option<Encryption>,
pub merchant_order_reference_id: Option<String>,
pub shipping_details: Option<Encryption>,
+ pub is_payment_processor_token_flow: Option<bool>,
}
#[derive(
@@ -187,6 +189,7 @@ pub struct PaymentIntentNew {
pub billing_details: Option<Encryption>,
pub merchant_order_reference_id: Option<String>,
pub shipping_details: Option<Encryption>,
+ pub is_payment_processor_token_flow: Option<bool>,
}
#[derive(Debug, Clone, Serialize, Deserialize)]
@@ -291,6 +294,7 @@ pub struct PaymentIntentUpdateFields {
pub billing_details: Option<Encryption>,
pub merchant_order_reference_id: Option<String>,
pub shipping_details: Option<Encryption>,
+ pub is_payment_processor_token_flow: Option<bool>,
}
#[derive(Clone, Debug, AsChangeset, router_derive::DebugAsDisplay)]
@@ -331,6 +335,7 @@ pub struct PaymentIntentUpdateInternal {
pub billing_details: Option<Encryption>,
pub merchant_order_reference_id: Option<String>,
pub shipping_details: Option<Encryption>,
+ pub is_payment_processor_token_flow: Option<bool>,
}
impl PaymentIntentUpdate {
@@ -370,6 +375,7 @@ impl PaymentIntentUpdate {
billing_details,
merchant_order_reference_id,
shipping_details,
+ is_payment_processor_token_flow,
} = self.into();
PaymentIntent {
amount: amount.unwrap_or(source.amount),
@@ -412,6 +418,8 @@ impl PaymentIntentUpdate {
merchant_order_reference_id: merchant_order_reference_id
.or(source.merchant_order_reference_id),
shipping_details: shipping_details.or(source.shipping_details),
+ is_payment_processor_token_flow: is_payment_processor_token_flow
+ .or(source.is_payment_processor_token_flow),
..source
}
}
@@ -458,6 +466,7 @@ impl From<PaymentIntentUpdate> for PaymentIntentUpdateInternal {
billing_details: None,
merchant_order_reference_id: None,
shipping_details: None,
+ is_payment_processor_token_flow: None,
},
PaymentIntentUpdate::Update(value) => Self {
amount: Some(value.amount),
@@ -495,6 +504,7 @@ impl From<PaymentIntentUpdate> for PaymentIntentUpdateInternal {
surcharge_applicable: None,
incremental_authorization_allowed: None,
authorization_count: None,
+ is_payment_processor_token_flow: value.is_payment_processor_token_flow,
},
PaymentIntentUpdate::PaymentCreateUpdate {
return_url,
@@ -539,6 +549,7 @@ impl From<PaymentIntentUpdate> for PaymentIntentUpdateInternal {
billing_details: None,
merchant_order_reference_id: None,
shipping_details: None,
+ is_payment_processor_token_flow: None,
},
PaymentIntentUpdate::PGStatusUpdate {
status,
@@ -579,6 +590,7 @@ impl From<PaymentIntentUpdate> for PaymentIntentUpdateInternal {
billing_details: None,
merchant_order_reference_id: None,
shipping_details: None,
+ is_payment_processor_token_flow: None,
},
PaymentIntentUpdate::MerchantStatusUpdate {
status,
@@ -620,6 +632,7 @@ impl From<PaymentIntentUpdate> for PaymentIntentUpdateInternal {
billing_details: None,
merchant_order_reference_id: None,
shipping_details: None,
+ is_payment_processor_token_flow: None,
},
PaymentIntentUpdate::ResponseUpdate {
// amount,
@@ -669,6 +682,7 @@ impl From<PaymentIntentUpdate> for PaymentIntentUpdateInternal {
billing_details: None,
merchant_order_reference_id: None,
shipping_details: None,
+ is_payment_processor_token_flow: None,
},
PaymentIntentUpdate::PaymentAttemptAndAttemptCountUpdate {
active_attempt_id,
@@ -709,6 +723,7 @@ impl From<PaymentIntentUpdate> for PaymentIntentUpdateInternal {
billing_details: None,
merchant_order_reference_id: None,
shipping_details: None,
+ is_payment_processor_token_flow: None,
},
PaymentIntentUpdate::StatusAndAttemptUpdate {
status,
@@ -750,6 +765,7 @@ impl From<PaymentIntentUpdate> for PaymentIntentUpdateInternal {
billing_details: None,
merchant_order_reference_id: None,
shipping_details: None,
+ is_payment_processor_token_flow: None,
},
PaymentIntentUpdate::ApproveUpdate {
status,
@@ -790,6 +806,7 @@ impl From<PaymentIntentUpdate> for PaymentIntentUpdateInternal {
billing_details: None,
merchant_order_reference_id: None,
shipping_details: None,
+ is_payment_processor_token_flow: None,
},
PaymentIntentUpdate::RejectUpdate {
status,
@@ -830,6 +847,7 @@ impl From<PaymentIntentUpdate> for PaymentIntentUpdateInternal {
billing_details: None,
merchant_order_reference_id: None,
shipping_details: None,
+ is_payment_processor_token_flow: None,
},
PaymentIntentUpdate::SurchargeApplicableUpdate {
surcharge_applicable,
@@ -869,6 +887,7 @@ impl From<PaymentIntentUpdate> for PaymentIntentUpdateInternal {
billing_details: None,
merchant_order_reference_id: None,
shipping_details: None,
+ is_payment_processor_token_flow: None,
},
PaymentIntentUpdate::IncrementalAuthorizationAmountUpdate { amount } => Self {
amount: Some(amount),
@@ -905,6 +924,7 @@ impl From<PaymentIntentUpdate> for PaymentIntentUpdateInternal {
billing_details: None,
merchant_order_reference_id: None,
shipping_details: None,
+ is_payment_processor_token_flow: None,
},
PaymentIntentUpdate::AuthorizationCountUpdate {
authorization_count,
@@ -943,6 +963,7 @@ impl From<PaymentIntentUpdate> for PaymentIntentUpdateInternal {
billing_details: None,
merchant_order_reference_id: None,
shipping_details: None,
+ is_payment_processor_token_flow: None,
},
PaymentIntentUpdate::CompleteAuthorizeUpdate {
shipping_address_id,
@@ -981,6 +1002,7 @@ impl From<PaymentIntentUpdate> for PaymentIntentUpdateInternal {
billing_details: None,
merchant_order_reference_id: None,
shipping_details: None,
+ is_payment_processor_token_flow: None,
},
PaymentIntentUpdate::ManualUpdate { status, updated_by } => Self {
status,
@@ -1017,6 +1039,7 @@ impl From<PaymentIntentUpdate> for PaymentIntentUpdateInternal {
billing_details: None,
merchant_order_reference_id: None,
shipping_details: None,
+ is_payment_processor_token_flow: None,
},
}
}
diff --git a/crates/diesel_models/src/schema.rs b/crates/diesel_models/src/schema.rs
index d2c66fc37fe..e272c71ba24 100644
--- a/crates/diesel_models/src/schema.rs
+++ b/crates/diesel_models/src/schema.rs
@@ -897,6 +897,7 @@ diesel::table! {
#[max_length = 255]
merchant_order_reference_id -> Nullable<Varchar>,
shipping_details -> Nullable<Bytea>,
+ is_payment_processor_token_flow -> Nullable<Bool>,
}
}
diff --git a/crates/diesel_models/src/schema_v2.rs b/crates/diesel_models/src/schema_v2.rs
index 23f9dff31ea..246f37a4e49 100644
--- a/crates/diesel_models/src/schema_v2.rs
+++ b/crates/diesel_models/src/schema_v2.rs
@@ -897,6 +897,7 @@ diesel::table! {
#[max_length = 255]
merchant_order_reference_id -> Nullable<Varchar>,
shipping_details -> Nullable<Bytea>,
+ is_payment_processor_token_flow -> Nullable<Bool>,
}
}
diff --git a/crates/hyperswitch_domain_models/src/payments.rs b/crates/hyperswitch_domain_models/src/payments.rs
index ac79bc1a942..3f7cfde2f78 100644
--- a/crates/hyperswitch_domain_models/src/payments.rs
+++ b/crates/hyperswitch_domain_models/src/payments.rs
@@ -66,4 +66,5 @@ pub struct PaymentIntent {
pub billing_details: Option<Encryptable<Secret<serde_json::Value>>>,
pub merchant_order_reference_id: Option<String>,
pub shipping_details: Option<Encryptable<Secret<serde_json::Value>>>,
+ pub is_payment_processor_token_flow: Option<bool>,
}
diff --git a/crates/hyperswitch_domain_models/src/payments/payment_attempt.rs b/crates/hyperswitch_domain_models/src/payments/payment_attempt.rs
index 15c5aded500..8fe01d380e8 100644
--- a/crates/hyperswitch_domain_models/src/payments/payment_attempt.rs
+++ b/crates/hyperswitch_domain_models/src/payments/payment_attempt.rs
@@ -541,6 +541,7 @@ impl behaviour::Conversion for PaymentIntent {
billing_details: self.billing_details.map(Encryption::from),
merchant_order_reference_id: self.merchant_order_reference_id,
shipping_details: self.shipping_details.map(Encryption::from),
+ is_payment_processor_token_flow: self.is_payment_processor_token_flow,
})
}
async fn convert_back(
@@ -613,6 +614,7 @@ impl behaviour::Conversion for PaymentIntent {
.shipping_details
.async_lift(inner_decrypt)
.await?,
+ is_payment_processor_token_flow: storage_model.is_payment_processor_token_flow,
})
}
.await
@@ -670,6 +672,7 @@ impl behaviour::Conversion for PaymentIntent {
billing_details: self.billing_details.map(Encryption::from),
merchant_order_reference_id: self.merchant_order_reference_id,
shipping_details: self.shipping_details.map(Encryption::from),
+ is_payment_processor_token_flow: self.is_payment_processor_token_flow,
})
}
}
@@ -729,6 +732,7 @@ impl behaviour::Conversion for PaymentIntent {
billing_details: self.billing_details.map(Encryption::from),
merchant_order_reference_id: self.merchant_order_reference_id,
shipping_details: self.shipping_details.map(Encryption::from),
+ is_payment_processor_token_flow: self.is_payment_processor_token_flow,
})
}
@@ -802,6 +806,7 @@ impl behaviour::Conversion for PaymentIntent {
.shipping_details
.async_lift(inner_decrypt)
.await?,
+ is_payment_processor_token_flow: storage_model.is_payment_processor_token_flow,
})
}
.await
@@ -859,6 +864,7 @@ impl behaviour::Conversion for PaymentIntent {
billing_details: self.billing_details.map(Encryption::from),
merchant_order_reference_id: self.merchant_order_reference_id,
shipping_details: self.shipping_details.map(Encryption::from),
+ is_payment_processor_token_flow: self.is_payment_processor_token_flow,
})
}
}
diff --git a/crates/hyperswitch_domain_models/src/payments/payment_intent.rs b/crates/hyperswitch_domain_models/src/payments/payment_intent.rs
index 8033ec7706c..90e3619f02e 100644
--- a/crates/hyperswitch_domain_models/src/payments/payment_intent.rs
+++ b/crates/hyperswitch_domain_models/src/payments/payment_intent.rs
@@ -143,6 +143,7 @@ pub struct PaymentIntentNew {
pub customer_details: Option<Encryptable<Secret<serde_json::Value>>>,
pub billing_details: Option<Encryptable<Secret<serde_json::Value>>>,
pub shipping_details: Option<Encryptable<Secret<serde_json::Value>>>,
+ pub is_payment_processor_token_flow: Option<bool>,
}
#[derive(Debug, Clone, Serialize)]
@@ -172,6 +173,7 @@ pub struct PaymentIntentUpdateFields {
pub billing_details: Option<Encryptable<Secret<serde_json::Value>>>,
pub merchant_order_reference_id: Option<String>,
pub shipping_details: Option<Encryptable<Secret<serde_json::Value>>>,
+ pub is_payment_processor_token_flow: Option<bool>,
}
#[derive(Debug, Clone, Serialize)]
@@ -288,6 +290,7 @@ pub struct PaymentIntentUpdateInternal {
pub billing_details: Option<Encryptable<Secret<serde_json::Value>>>,
pub merchant_order_reference_id: Option<String>,
pub shipping_details: Option<Encryptable<Secret<serde_json::Value>>>,
+ pub is_payment_processor_token_flow: Option<bool>,
}
impl From<PaymentIntentUpdate> for PaymentIntentUpdateInternal {
@@ -329,6 +332,7 @@ impl From<PaymentIntentUpdate> for PaymentIntentUpdateInternal {
billing_details: value.billing_details,
merchant_order_reference_id: value.merchant_order_reference_id,
shipping_details: value.shipping_details,
+ is_payment_processor_token_flow: value.is_payment_processor_token_flow,
..Default::default()
},
PaymentIntentUpdate::PaymentCreateUpdate {
@@ -531,6 +535,7 @@ impl From<PaymentIntentUpdate> for DieselPaymentIntentUpdate {
billing_details: value.billing_details.map(Encryption::from),
merchant_order_reference_id: value.merchant_order_reference_id,
shipping_details: value.shipping_details.map(Encryption::from),
+ is_payment_processor_token_flow: value.is_payment_processor_token_flow,
}))
}
PaymentIntentUpdate::PaymentCreateUpdate {
@@ -674,6 +679,7 @@ impl From<PaymentIntentUpdateInternal> for diesel_models::PaymentIntentUpdateInt
billing_details,
merchant_order_reference_id,
shipping_details,
+ is_payment_processor_token_flow,
} = value;
Self {
@@ -711,6 +717,7 @@ impl From<PaymentIntentUpdateInternal> for diesel_models::PaymentIntentUpdateInt
billing_details: billing_details.map(Encryption::from),
merchant_order_reference_id,
shipping_details: shipping_details.map(Encryption::from),
+ is_payment_processor_token_flow,
}
}
}
diff --git a/crates/openapi/src/openapi.rs b/crates/openapi/src/openapi.rs
index b525c3aa930..4bbbfb8a7f1 100644
--- a/crates/openapi/src/openapi.rs
+++ b/crates/openapi/src/openapi.rs
@@ -465,6 +465,7 @@ Never share your secret api keys. Keep them guarded and secure.
api_models::mandates::MandateResponse,
api_models::mandates::MandateCardDetails,
api_models::mandates::RecurringDetails,
+ api_models::mandates::ProcessorPaymentToken,
api_models::ephemeral_key::EphemeralKeyCreateResponse,
api_models::payments::CustomerDetails,
api_models::payments::GiftCardData,
diff --git a/crates/router/src/core/payments.rs b/crates/router/src/core/payments.rs
index 78d0d8fd79d..cbc912bd0c2 100644
--- a/crates/router/src/core/payments.rs
+++ b/crates/router/src/core/payments.rs
@@ -1510,15 +1510,20 @@ where
)
.await?;
- let merchant_recipient_data = payment_data
- .get_merchant_recipient_data(
- state,
- merchant_account,
- key_store,
- &merchant_connector_account,
- &connector,
- )
- .await?;
+ let merchant_recipient_data =
+ if let Some(true) = payment_data.payment_intent.is_payment_processor_token_flow {
+ None
+ } else {
+ payment_data
+ .get_merchant_recipient_data(
+ state,
+ merchant_account,
+ key_store,
+ &merchant_connector_account,
+ &connector,
+ )
+ .await?
+ };
let mut router_data = payment_data
.construct_router_data(
diff --git a/crates/router/src/core/payments/helpers.rs b/crates/router/src/core/payments/helpers.rs
index 53fc1e1938c..80ab9ebaf90 100644
--- a/crates/router/src/core/payments/helpers.rs
+++ b/crates/router/src/core/payments/helpers.rs
@@ -446,6 +446,20 @@ pub async fn get_token_pm_type_mandate_details(
Some(api::MandateTransactionType::RecurringMandateTransaction) => {
match &request.recurring_details {
Some(recurring_details) => match recurring_details {
+ RecurringDetails::ProcessorPaymentToken(processor_payment_token) => (
+ None,
+ request.payment_method,
+ None,
+ None,
+ None,
+ Some(payments::MandateConnectorDetails {
+ connector: processor_payment_token.connector.to_string(),
+ merchant_connector_id: Some(
+ processor_payment_token.merchant_connector_id.clone(),
+ ),
+ }),
+ None,
+ ),
RecurringDetails::MandateId(mandate_id) => {
let mandate_generic_data = get_token_for_recurring_mandate(
state,
@@ -1168,26 +1182,31 @@ pub fn create_complete_authorize_url(
}
fn validate_recurring_mandate(req: api::MandateValidationFields) -> RouterResult<()> {
- req.recurring_details
- .check_value_present("recurring_details")?;
+ let recurring_details = req
+ .recurring_details
+ .get_required_value("recurring_details")?;
- req.customer_id.check_value_present("customer_id")?;
+ match recurring_details {
+ RecurringDetails::ProcessorPaymentToken(_) => Ok(()),
+ _ => {
+ req.customer_id.check_value_present("customer_id")?;
- let confirm = req.confirm.get_required_value("confirm")?;
- if !confirm {
- Err(report!(errors::ApiErrorResponse::PreconditionFailed {
- message: "`confirm` must be `true` for mandates".into()
- }))?
- }
+ let confirm = req.confirm.get_required_value("confirm")?;
+ if !confirm {
+ Err(report!(errors::ApiErrorResponse::PreconditionFailed {
+ message: "`confirm` must be `true` for mandates".into()
+ }))?
+ }
- let off_session = req.off_session.get_required_value("off_session")?;
- if !off_session {
- Err(report!(errors::ApiErrorResponse::PreconditionFailed {
- message: "`off_session` should be `true` for mandates".into()
- }))?
+ let off_session = req.off_session.get_required_value("off_session")?;
+ if !off_session {
+ Err(report!(errors::ApiErrorResponse::PreconditionFailed {
+ message: "`off_session` should be `true` for mandates".into()
+ }))?
+ }
+ Ok(())
+ }
}
-
- Ok(())
}
pub fn verify_mandate_details(
@@ -3079,6 +3098,7 @@ mod tests {
billing_details: None,
merchant_order_reference_id: None,
shipping_details: None,
+ is_payment_processor_token_flow: None,
};
let req_cs = Some("1".to_string());
assert!(authenticate_client_secret(req_cs.as_ref(), &payment_intent).is_ok());
@@ -3143,6 +3163,7 @@ mod tests {
billing_details: None,
merchant_order_reference_id: None,
shipping_details: None,
+ is_payment_processor_token_flow: None,
};
let req_cs = Some("1".to_string());
assert!(authenticate_client_secret(req_cs.as_ref(), &payment_intent,).is_err())
@@ -3205,6 +3226,7 @@ mod tests {
billing_details: None,
merchant_order_reference_id: None,
shipping_details: None,
+ is_payment_processor_token_flow: None,
};
let req_cs = Some("1".to_string());
assert!(authenticate_client_secret(req_cs.as_ref(), &payment_intent).is_err())
diff --git a/crates/router/src/core/payments/operations/payment_confirm.rs b/crates/router/src/core/payments/operations/payment_confirm.rs
index 52d76289d88..b62b97bdb20 100644
--- a/crates/router/src/core/payments/operations/payment_confirm.rs
+++ b/crates/router/src/core/payments/operations/payment_confirm.rs
@@ -628,6 +628,31 @@ impl<F: Send + Clone> GetTracker<F, PaymentData<F>, api::PaymentsRequest> for Pa
.as_ref()
.map(|payment_method_billing| payment_method_billing.address_id.clone());
+ // If processor_payment_token is passed in request then populating the same in PaymentData
+ let mandate_id = request
+ .recurring_details
+ .as_ref()
+ .and_then(|recurring_details| match recurring_details {
+ api_models::mandates::RecurringDetails::ProcessorPaymentToken(token) => {
+ payment_intent.is_payment_processor_token_flow = Some(true);
+ Some(api_models::payments::MandateIds {
+ mandate_id: None,
+ mandate_reference_id: Some(
+ api_models::payments::MandateReferenceId::ConnectorMandateId(
+ api_models::payments::ConnectorMandateReferenceId {
+ connector_mandate_id: Some(
+ token.processor_payment_token.clone(),
+ ),
+ payment_method_id: None,
+ update_history: None,
+ },
+ ),
+ ),
+ })
+ }
+ _ => None,
+ });
+
let payment_data = PaymentData {
flow: PhantomData,
payment_intent,
@@ -635,7 +660,7 @@ impl<F: Send + Clone> GetTracker<F, PaymentData<F>, api::PaymentsRequest> for Pa
currency,
amount,
email: request.email.clone(),
- mandate_id: None,
+ mandate_id: mandate_id.clone(),
mandate_connector,
setup_mandate,
customer_acceptance: customer_acceptance.map(From::from),
@@ -1279,6 +1304,8 @@ impl<F: Clone> UpdateTracker<F, PaymentData<F>, api::PaymentsRequest> for Paymen
let session_expiry = m_payment_data_payment_intent.session_expiry;
let m_key_store = key_store.clone();
let key_manager_state = state.into();
+ let is_payment_processor_token_flow =
+ payment_data.payment_intent.is_payment_processor_token_flow;
let payment_intent_fut = tokio::spawn(
async move {
@@ -1311,6 +1338,7 @@ impl<F: Clone> UpdateTracker<F, PaymentData<F>, api::PaymentsRequest> for Paymen
merchant_order_reference_id: None,
billing_details,
shipping_details,
+ is_payment_processor_token_flow,
})),
&m_key_store,
storage_scheme,
diff --git a/crates/router/src/core/payments/operations/payment_create.rs b/crates/router/src/core/payments/operations/payment_create.rs
index 1723084d0f1..983a31c50e5 100644
--- a/crates/router/src/core/payments/operations/payment_create.rs
+++ b/crates/router/src/core/payments/operations/payment_create.rs
@@ -376,6 +376,32 @@ impl<F: Send + Clone> GetTracker<F, PaymentData<F>, api::PaymentsRequest> for Pa
.await
.transpose()?;
+ let mandate_id = if mandate_id.is_none() {
+ request
+ .recurring_details
+ .as_ref()
+ .and_then(|recurring_details| match recurring_details {
+ RecurringDetails::ProcessorPaymentToken(token) => {
+ Some(api_models::payments::MandateIds {
+ mandate_id: None,
+ mandate_reference_id: Some(
+ api_models::payments::MandateReferenceId::ConnectorMandateId(
+ api_models::payments::ConnectorMandateReferenceId {
+ connector_mandate_id: Some(
+ token.processor_payment_token.clone(),
+ ),
+ payment_method_id: None,
+ update_history: None,
+ },
+ ),
+ ),
+ })
+ }
+ _ => None,
+ })
+ } else {
+ mandate_id
+ };
let operation = payments::if_not_create_change_operation::<_, F>(
payment_intent.status,
request.confirm,
@@ -429,7 +455,7 @@ impl<F: Send + Clone> GetTracker<F, PaymentData<F>, api::PaymentsRequest> for Pa
currency,
amount,
email: request.email.clone(),
- mandate_id,
+ mandate_id: mandate_id.clone(),
mandate_connector,
setup_mandate,
customer_acceptance,
@@ -1105,6 +1131,12 @@ impl PaymentCreate {
} else {
None
};
+ let is_payment_processor_token_flow = request.recurring_details.as_ref().and_then(
+ |recurring_details| match recurring_details {
+ RecurringDetails::ProcessorPaymentToken(_) => Some(true),
+ _ => None,
+ },
+ );
// Encrypting our Customer Details to be stored in Payment Intent
let customer_details = raw_customer_details
@@ -1165,6 +1197,7 @@ impl PaymentCreate {
customer_details,
merchant_order_reference_id: request.merchant_order_reference_id.clone(),
shipping_details,
+ is_payment_processor_token_flow,
})
}
diff --git a/crates/router/src/core/payments/operations/payment_update.rs b/crates/router/src/core/payments/operations/payment_update.rs
index 3a5cd00b9c3..58753586106 100644
--- a/crates/router/src/core/payments/operations/payment_update.rs
+++ b/crates/router/src/core/payments/operations/payment_update.rs
@@ -772,6 +772,7 @@ impl<F: Clone> UpdateTracker<F, PaymentData<F>, api::PaymentsRequest> for Paymen
merchant_order_reference_id,
billing_details,
shipping_details,
+ is_payment_processor_token_flow: None,
})),
key_store,
storage_scheme,
diff --git a/crates/router/src/utils/user/sample_data.rs b/crates/router/src/utils/user/sample_data.rs
index 86607234d4e..bbd709de66a 100644
--- a/crates/router/src/utils/user/sample_data.rs
+++ b/crates/router/src/utils/user/sample_data.rs
@@ -230,6 +230,7 @@ pub async fn generate_sample_data(
billing_details: None,
merchant_order_reference_id: Default::default(),
shipping_details: None,
+ is_payment_processor_token_flow: None,
};
let payment_attempt = PaymentAttemptBatchNew {
attempt_id: attempt_id.clone(),
diff --git a/migrations/2024-08-01-172628_add_is_payment_processor_token_flow_in_payment_intent_table/down.sql b/migrations/2024-08-01-172628_add_is_payment_processor_token_flow_in_payment_intent_table/down.sql
new file mode 100644
index 00000000000..02ff48e6b68
--- /dev/null
+++ b/migrations/2024-08-01-172628_add_is_payment_processor_token_flow_in_payment_intent_table/down.sql
@@ -0,0 +1,2 @@
+-- This file should undo anything in `up.sql`
+ALTER TABLE payment_intent DROP COLUMN IF EXISTS is_payment_processor_token_flow;
diff --git a/migrations/2024-08-01-172628_add_is_payment_processor_token_flow_in_payment_intent_table/up.sql b/migrations/2024-08-01-172628_add_is_payment_processor_token_flow_in_payment_intent_table/up.sql
new file mode 100644
index 00000000000..785806d09ef
--- /dev/null
+++ b/migrations/2024-08-01-172628_add_is_payment_processor_token_flow_in_payment_intent_table/up.sql
@@ -0,0 +1,3 @@
+-- Your SQL goes here
+ALTER TABLE payment_intent
+ADD COLUMN IF NOT EXISTS is_payment_processor_token_flow BOOLEAN;
|
2024-08-01T10:46:32Z
|
## Type of Change
<!-- Put an `x` in the boxes that apply -->
- [ ] Bugfix
- [x] New feature
- [ ] Enhancement
- [ ] Refactoring
- [ ] Dependency updates
- [ ] Documentation
- [ ] CI/CD
## Description
<!-- Describe your changes in detail -->
During the transition phase of Hyperswitch, Merchant should be able to send the processor's token to Hyperswitch to process MIT transaction. This is because, Merchant will not have the card data to migrate from Processor to Hyperswitch.
The migration is here:
'''
-- Your SQL goes here
ALTER TABLE payment_intent
ADD COLUMN IF NOT EXISTS is_payment_processor_token_flow BOOLEAN;
### Additional Changes
'''
- [ ] This PR modifies the API contract
- [ ] This PR modifies the database schema
- [ ] This PR modifies application configuration/environment variables
<!--
Provide links to the files with corresponding changes.
Following are the paths where you can find config files:
1. `config`
2. `crates/router/src/configs`
3. `loadtest/config`
-->
## Motivation and Context
<!--
Why is this change required? What problem does it solve?
If it fixes an open issue, please link to the issue here.
If you don't have an issue, we'd recommend starting with one first so the PR
can focus on the implementation (unless it is an obvious bug or documentation fix
that will have little conversation).
-->
## How did you test it?
<!--
Did you write an integration/unit/API test to verify the code changes?
Or did you test this change manually (provide relevant screenshots)?
-->
### The testing flows are as follows:
1. Create a Setup Mandate Payment.
2. Get the payment_method_id.
3. Get the connector_mandate_id from payment_method table in db (using pm_method_id) -> this is our payment_processor_token (PPT).
4. Now create a recurring_payment using the above ppt.
The curls for the same are as follows:
1. Create a Setup Mandate Payment.
```
curl --location 'http://127.0.0.1:8080/payments' \
--header 'Content-Type: application/json' \
--header 'Accept: application/json' \
--header 'api-key: ••••••' \
--data-raw '
{
"amount": 10000,
"currency": "USD",
"confirm": true,
"capture_method": "automatic",
"capture_on": "2022-09-10T10:11:12Z",
"customer_id": "cus_35RDuRN4P6XdVMgt2Px7",
"email": "abcdef123@gmail.com",
"name": "John Doe",
"phone": "999999999",
"phone_country_code": "+65",
"description": "Its my first payment request",
"authentication_type": "no_three_ds",
"return_url": "https://google.com",
"setup_future_usage": "off_session",
"off_session": true,
"browser_info": {
"user_agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/70.0.3538.110 Safari/537.36",
"accept_header": "text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,image/apng,*/*;q=0.8",
"language": "nl-NL",
"color_depth": 24,
"screen_height": 723,
"screen_width": 1536,
"time_zone": 0,
"java_enabled": true,
"java_script_enabled": true,
"ip_address": "127.0.0.1"
},
"shipping": {
"address": {
"line1": "1467",
"line2": "Harrison Street",
"line3": "Harrison Street",
"city": "San Fransico",
"state": "California",
"zip": "94122",
"country": "US",
"first_name": "John",
"last_name": "Doe"
}
},
"statement_descriptor_name": "joseph",
"statement_descriptor_suffix": "JS",
"metadata": {
"udf1": "value1",
"new_customer": "true",
"login_date": "2019-09-10T10:11:12Z"
},
"payment_type": "setup_mandate",
"payment_method": "card",
"payment_method_type": "credit",
"payment_method_data": {
"card": {
"card_number": "4242424242424242",
"card_exp_month": "02",
"card_exp_year": "26",
"card_holder_name": "Joseph Doe",
"card_cvc": "999"
}
},
"billing": {
"address": {
"line1": "8th block",
"line2": "8th block",
"line3": "8th block",
"city": "Bengaluru",
"state": "Karnataka",
"zip": "560095",
"country": "IN",
"first_name": "Sakil",
"last_name": "Mostak"
}
},
"customer_acceptance": {
"acceptance_type": "online"
}
}'
```
2. Get the payment_method_id.
```
"payment_method_id": "pm_A1YI0BNBELMQVw76ipT3",
```
3. Get the connector_mandate_id from payment_method table in db (using pm_method_id) -> this is our payment_processor_token (PPT).
```
connector_mandate_details | {"mca_A3fAZBZEG6X8cBb19z9w": {"payment_method_type": "credit", "connector_mandate_id": "**pm_1Pkk1YD5R7gDAGff2yPGAPgr**", "original_payment_authorized_amount": 10000, "original_payment_authorized_currency": "USD"}}
```
4. Now create a recurring_payment using the above ppt (confirm true).
```
curl --location 'http://127.0.0.1:8080/payments' \
--header 'Content-Type: application/json' \
--header 'Accept: application/json' \
--header 'api-key: dev_QP5rWb7dq1xSRpxdQoroFUxUiD3kLx6MgfsBBEe9FlvkAjXnqTYINyylTR8o5zkG' \
--data '{
"amount": 499,
"currency": "USD",
"capture_method": "automatic",
"customer_id": "cus_35RDuRN4P6XdVMgt2Px7",
"off_session": true,
"confirm": true,
"recurring_details": {
"type": "processor_payment_token",
"data": {
"processor_payment_token": "pm_1Pkk1YD5R7gDAGff2yPGAPgr",
"connector": "stripe",
"merchant_connector_id": "mca_A3fAZBZEG6X8cBb19z9w"
}
},
"payment_method": "card",
"authentication_type": "no_three_ds"
}'
```
4. Now create a recurring_payment using the above ppt (confirm false).
```
curl --location 'http://127.0.0.1:8080/payments' \
--header 'Content-Type: application/json' \
--header 'Accept: application/json' \
--header 'api-key: dev_QP5rWb7dq1xSRpxdQoroFUxUiD3kLx6MgfsBBEe9FlvkAjXnqTYINyylTR8o5zkG' \
--data '{
"amount": 499,
"currency": "USD",
"capture_method": "automatic",
"customer_id": "cus_35RDuRN4P6XdVMgt2Px7",
"off_session": true,
"confirm": false,
"authentication_type": "no_three_ds"
}'
```
5. Confirm the payment
```
curl --location 'http://localhost:8080/payments/pay_LG5wWKTQ5sLATRBchdc3/confirm' \
--header 'Content-Type: application/json' \
--header 'Accept: application/json' \
--header 'api-key: ••••••' \
--data '{
"off_session": true,
"payment_method": "card",
"recurring_details": {
"type": "processor_payment_token",
"data": {
"processor_payment_token": "pm_1Pkk1YD5R7gDAGff2yPGAPgr",
"connector": "stripe",
"merchant_connector_id": "mca_A3fAZBZEG6X8cBb19z9w"
}
}
}'
```
## Checklist
<!-- Put an `x` in the boxes that apply -->
- [ ] I formatted the code `cargo +nightly fmt --all`
- [ ] I addressed lints thrown by `cargo clippy`
- [ ] I reviewed the submitted code
- [ ] I added unit tests for my changes where possible
|
4364630d6ffbce43bef0947a0150ce255a43751a
|
|
juspay/hyperswitch
|
juspay__hyperswitch-5417
|
Bug: Add fields in business profile to collect address details (billing and shipping) irrespective of connector required fields
Always collect address details | Collect address details only if required by connector | Connector required fields | payment method list | Session call
-- | -- | -- | -- | --
False | False | False | False | False
False | False | True | True | False
False | True | True | True | True
False | True | False | False | False
True | True | False | True | True
True | True | True | True | True
True | False | False | True | True
True | False | True | True | True
Currently, we have business profile fields (`collect_shipping_details_from_wallet_connector` and `collect_billing_details_from_wallet_connector`) which will collect the address details from the wallet during the session call. Additionally, the address fields will be added to the payment method list, but only if these flags are enabled and the connector requires it.
This change is to collect address details (both billing and shipping) based on the merchant's requirements, regardless of the connector's required fields. The above details describes the behaviour of the payment method list and the session call based on the `Always collect address details`, `Collect address details only if required by connector`, and `Connector required fields`.
- `Always collect address details` fields for this are `always_collect_shipping_details_from_wallet_connector` and `always_collect_billing_details_from_wallet_connector`
- `Collect address details only if required by connector` fields for this are `collect_shipping_details_from_wallet_connector` and `collect_billing_details_from_wallet_connector`
|
diff --git a/api-reference-v2/openapi_spec.json b/api-reference-v2/openapi_spec.json
index 84711c7b35f..cd4c73abba4 100644
--- a/api-reference-v2/openapi_spec.json
+++ b/api-reference-v2/openapi_spec.json
@@ -3060,16 +3060,30 @@
"description": "Whether to use the billing details passed when creating the intent as payment method billing",
"nullable": true
},
- "collect_shipping_details_from_wallet_connector": {
+ "collect_shipping_details_from_wallet_connector_if_required": {
"type": "boolean",
- "description": "A boolean value to indicate if customer shipping details needs to be collected from wallet connector (Eg. Apple Pay, Google Pay, etc.)",
+ "description": "A boolean value to indicate if customer shipping details needs to be collected from wallet\nconnector only if it is required field for connector (Eg. Apple Pay, Google Pay etc)",
"default": false,
"example": false,
"nullable": true
},
- "collect_billing_details_from_wallet_connector": {
+ "collect_billing_details_from_wallet_connector_if_required": {
"type": "boolean",
- "description": "A boolean value to indicate if customer billing details needs to be collected from wallet connector (Eg. Apple Pay, Google Pay, etc.)",
+ "description": "A boolean value to indicate if customer billing details needs to be collected from wallet\nconnector only if it is required field for connector (Eg. Apple Pay, Google Pay etc)",
+ "default": false,
+ "example": false,
+ "nullable": true
+ },
+ "always_collect_shipping_details_from_wallet_connector": {
+ "type": "boolean",
+ "description": "A boolean value to indicate if customer shipping details needs to be collected from wallet\nconnector irrespective of connector required fields (Eg. Apple pay, Google pay etc)",
+ "default": false,
+ "example": false,
+ "nullable": true
+ },
+ "always_collect_billing_details_from_wallet_connector": {
+ "type": "boolean",
+ "description": "A boolean value to indicate if customer billing details needs to be collected from wallet\nconnector irrespective of connector required fields (Eg. Apple pay, Google pay etc)",
"default": false,
"example": false,
"nullable": true
@@ -3202,16 +3216,30 @@
],
"nullable": true
},
- "collect_shipping_details_from_wallet_connector": {
+ "collect_shipping_details_from_wallet_connector_if_required": {
+ "type": "boolean",
+ "description": "A boolean value to indicate if customer shipping details needs to be collected from wallet\nconnector only if it is required field for connector (Eg. Apple Pay, Google Pay etc)",
+ "default": false,
+ "example": false,
+ "nullable": true
+ },
+ "collect_billing_details_from_wallet_connector_if_required": {
+ "type": "boolean",
+ "description": "A boolean value to indicate if customer billing details needs to be collected from wallet\nconnector only if it is required field for connector (Eg. Apple Pay, Google Pay etc)",
+ "default": false,
+ "example": false,
+ "nullable": true
+ },
+ "always_collect_shipping_details_from_wallet_connector": {
"type": "boolean",
- "description": "A boolean value to indicate if customer shipping details needs to be collected from wallet connector (Eg. Apple Pay, Google Pay, etc.)",
+ "description": "A boolean value to indicate if customer shipping details needs to be collected from wallet\nconnector irrespective of connector required fields (Eg. Apple pay, Google pay etc)",
"default": false,
"example": false,
"nullable": true
},
- "collect_billing_details_from_wallet_connector": {
+ "always_collect_billing_details_from_wallet_connector": {
"type": "boolean",
- "description": "A boolean value to indicate if customer billing details needs to be collected from wallet connector (Eg. Apple Pay, Google Pay, etc.)",
+ "description": "A boolean value to indicate if customer billing details needs to be collected from wallet\nconnector irrespective of connector required fields (Eg. Apple pay, Google pay etc)",
"default": false,
"example": false,
"nullable": true
diff --git a/crates/api_models/src/admin.rs b/crates/api_models/src/admin.rs
index 081b0a1884a..a606316b616 100644
--- a/crates/api_models/src/admin.rs
+++ b/crates/api_models/src/admin.rs
@@ -1920,14 +1920,26 @@ pub struct BusinessProfileCreate {
/// Whether to use the billing details passed when creating the intent as payment method billing
pub use_billing_as_payment_method_billing: Option<bool>,
- /// A boolean value to indicate if customer shipping details needs to be collected from wallet connector (Eg. Apple Pay, Google Pay, etc.)
+ /// A boolean value to indicate if customer shipping details needs to be collected from wallet
+ /// connector only if it is required field for connector (Eg. Apple Pay, Google Pay etc)
#[schema(default = false, example = false)]
pub collect_shipping_details_from_wallet_connector: Option<bool>,
- /// A boolean value to indicate if customer billing details needs to be collected from wallet connector (Eg. Apple Pay, Google Pay, etc.)
+ /// A boolean value to indicate if customer billing details needs to be collected from wallet
+ /// connector only if it is required field for connector (Eg. Apple Pay, Google Pay etc)
#[schema(default = false, example = false)]
pub collect_billing_details_from_wallet_connector: Option<bool>,
+ /// A boolean value to indicate if customer shipping details needs to be collected from wallet
+ /// connector irrespective of connector required fields (Eg. Apple pay, Google pay etc)
+ #[schema(default = false, example = false)]
+ pub always_collect_shipping_details_from_wallet_connector: Option<bool>,
+
+ /// A boolean value to indicate if customer billing details needs to be collected from wallet
+ /// connector irrespective of connector required fields (Eg. Apple pay, Google pay etc)
+ #[schema(default = false, example = false)]
+ pub always_collect_billing_details_from_wallet_connector: Option<bool>,
+
/// Indicates if the MIT (merchant initiated transaction) payments can be made connector
/// agnostic, i.e., MITs may be processed through different connector than CIT (customer
/// initiated transaction) based on the routing rules.
@@ -2003,13 +2015,25 @@ pub struct BusinessProfileCreate {
/// Whether to use the billing details passed when creating the intent as payment method billing
pub use_billing_as_payment_method_billing: Option<bool>,
- /// A boolean value to indicate if customer shipping details needs to be collected from wallet connector (Eg. Apple Pay, Google Pay, etc.)
+ /// A boolean value to indicate if customer shipping details needs to be collected from wallet
+ /// connector only if it is required field for connector (Eg. Apple Pay, Google Pay etc)
#[schema(default = false, example = false)]
- pub collect_shipping_details_from_wallet_connector: Option<bool>,
+ pub collect_shipping_details_from_wallet_connector_if_required: Option<bool>,
- /// A boolean value to indicate if customer billing details needs to be collected from wallet connector (Eg. Apple Pay, Google Pay, etc.)
+ /// A boolean value to indicate if customer billing details needs to be collected from wallet
+ /// connector only if it is required field for connector (Eg. Apple Pay, Google Pay etc)
#[schema(default = false, example = false)]
- pub collect_billing_details_from_wallet_connector: Option<bool>,
+ pub collect_billing_details_from_wallet_connector_if_required: Option<bool>,
+
+ /// A boolean value to indicate if customer shipping details needs to be collected from wallet
+ /// connector irrespective of connector required fields (Eg. Apple pay, Google pay etc)
+ #[schema(default = false, example = false)]
+ pub always_collect_shipping_details_from_wallet_connector: Option<bool>,
+
+ /// A boolean value to indicate if customer billing details needs to be collected from wallet
+ /// connector irrespective of connector required fields (Eg. Apple pay, Google pay etc)
+ #[schema(default = false, example = false)]
+ pub always_collect_billing_details_from_wallet_connector: Option<bool>,
/// Indicates if the MIT (merchant initiated transaction) payments can be made connector
/// agnostic, i.e., MITs may be processed through different connector than CIT (customer
@@ -2103,14 +2127,26 @@ pub struct BusinessProfileResponse {
/// Merchant's config to support extended card info feature
pub extended_card_info_config: Option<ExtendedCardInfoConfig>,
- /// A boolean value to indicate if customer shipping details needs to be collected from wallet connector (Eg. Apple Pay, Google Pay, etc.)
+ /// A boolean value to indicate if customer shipping details needs to be collected from wallet
+ /// connector only if it is required field for connector (Eg. Apple Pay, Google Pay etc)
#[schema(default = false, example = false)]
pub collect_shipping_details_from_wallet_connector: Option<bool>,
- /// A boolean value to indicate if customer billing details needs to be collected from wallet connector (Eg. Apple Pay, Google Pay, etc.)
+ /// A boolean value to indicate if customer billing details needs to be collected from wallet
+ /// connector only if it is required field for connector (Eg. Apple Pay, Google Pay etc)
#[schema(default = false, example = false)]
pub collect_billing_details_from_wallet_connector: Option<bool>,
+ /// A boolean value to indicate if customer shipping details needs to be collected from wallet
+ /// connector irrespective of connector required fields (Eg. Apple pay, Google pay etc)
+ #[schema(default = false, example = false)]
+ pub always_collect_shipping_details_from_wallet_connector: Option<bool>,
+
+ /// A boolean value to indicate if customer billing details needs to be collected from wallet
+ /// connector irrespective of connector required fields (Eg. Apple pay, Google pay etc)
+ #[schema(default = false, example = false)]
+ pub always_collect_billing_details_from_wallet_connector: Option<bool>,
+
/// Indicates if the MIT (merchant initiated transaction) payments can be made connector
/// agnostic, i.e., MITs may be processed through different connector than CIT (customer
/// initiated transaction) based on the routing rules.
@@ -2183,13 +2219,25 @@ pub struct BusinessProfileResponse {
/// Merchant's config to support extended card info feature
pub extended_card_info_config: Option<ExtendedCardInfoConfig>,
- /// A boolean value to indicate if customer shipping details needs to be collected from wallet connector (Eg. Apple Pay, Google Pay, etc.)
+ /// A boolean value to indicate if customer shipping details needs to be collected from wallet
+ /// connector only if it is required field for connector (Eg. Apple Pay, Google Pay etc)
#[schema(default = false, example = false)]
- pub collect_shipping_details_from_wallet_connector: Option<bool>,
+ pub collect_shipping_details_from_wallet_connector_if_required: Option<bool>,
- /// A boolean value to indicate if customer billing details needs to be collected from wallet connector (Eg. Apple Pay, Google Pay, etc.)
+ /// A boolean value to indicate if customer billing details needs to be collected from wallet
+ /// connector only if it is required field for connector (Eg. Apple Pay, Google Pay etc)
#[schema(default = false, example = false)]
- pub collect_billing_details_from_wallet_connector: Option<bool>,
+ pub collect_billing_details_from_wallet_connector_if_required: Option<bool>,
+
+ /// A boolean value to indicate if customer shipping details needs to be collected from wallet
+ /// connector irrespective of connector required fields (Eg. Apple pay, Google pay etc)
+ #[schema(default = false, example = false)]
+ pub always_collect_shipping_details_from_wallet_connector: Option<bool>,
+
+ /// A boolean value to indicate if customer billing details needs to be collected from wallet
+ /// connector irrespective of connector required fields (Eg. Apple pay, Google pay etc)
+ #[schema(default = false, example = false)]
+ pub always_collect_billing_details_from_wallet_connector: Option<bool>,
/// Indicates if the MIT (merchant initiated transaction) payments can be made connector
/// agnostic, i.e., MITs may be processed through different connector than CIT (customer
@@ -2283,14 +2331,26 @@ pub struct BusinessProfileUpdate {
// Whether to use the billing details passed when creating the intent as payment method billing
pub use_billing_as_payment_method_billing: Option<bool>,
- /// A boolean value to indicate if customer shipping details needs to be collected from wallet connector (Eg. Apple Pay, Google Pay, etc.)
+ /// A boolean value to indicate if customer shipping details needs to be collected from wallet
+ /// connector only if it is required field for connector (Eg. Apple Pay, Google Pay etc)
#[schema(default = false, example = false)]
pub collect_shipping_details_from_wallet_connector: Option<bool>,
- /// A boolean value to indicate if customer billing details needs to be collected from wallet connector (Eg. Apple Pay, Google Pay, etc.)
+ /// A boolean value to indicate if customer billing details needs to be collected from wallet
+ /// connector only if it is required field for connector (Eg. Apple Pay, Google Pay etc)
#[schema(default = false, example = false)]
pub collect_billing_details_from_wallet_connector: Option<bool>,
+ /// A boolean value to indicate if customer shipping details needs to be collected from wallet
+ /// connector irrespective of connector required fields (Eg. Apple pay, Google pay etc)
+ #[schema(default = false, example = false)]
+ pub always_collect_shipping_details_from_wallet_connector: Option<bool>,
+
+ /// A boolean value to indicate if customer billing details needs to be collected from wallet
+ /// connector irrespective of connector required fields (Eg. Apple pay, Google pay etc)
+ #[schema(default = false, example = false)]
+ pub always_collect_billing_details_from_wallet_connector: Option<bool>,
+
/// Indicates if the MIT (merchant initiated transaction) payments can be made connector
/// agnostic, i.e., MITs may be processed through different connector than CIT (customer
/// initiated transaction) based on the routing rules.
@@ -2363,13 +2423,25 @@ pub struct BusinessProfileUpdate {
// Whether to use the billing details passed when creating the intent as payment method billing
pub use_billing_as_payment_method_billing: Option<bool>,
- /// A boolean value to indicate if customer shipping details needs to be collected from wallet connector (Eg. Apple Pay, Google Pay, etc.)
+ /// A boolean value to indicate if customer shipping details needs to be collected from wallet
+ /// connector only if it is required field for connector (Eg. Apple Pay, Google Pay etc)
#[schema(default = false, example = false)]
- pub collect_shipping_details_from_wallet_connector: Option<bool>,
+ pub collect_shipping_details_from_wallet_connector_if_required: Option<bool>,
- /// A boolean value to indicate if customer billing details needs to be collected from wallet connector (Eg. Apple Pay, Google Pay, etc.)
+ /// A boolean value to indicate if customer billing details needs to be collected from wallet
+ /// connector only if it is required field for connector (Eg. Apple Pay, Google Pay etc)
#[schema(default = false, example = false)]
- pub collect_billing_details_from_wallet_connector: Option<bool>,
+ pub collect_billing_details_from_wallet_connector_if_required: Option<bool>,
+
+ /// A boolean value to indicate if customer shipping details needs to be collected from wallet
+ /// connector irrespective of connector required fields (Eg. Apple pay, Google pay etc)
+ #[schema(default = false, example = false)]
+ pub always_collect_shipping_details_from_wallet_connector: Option<bool>,
+
+ /// A boolean value to indicate if customer billing details needs to be collected from wallet
+ /// connector irrespective of connector required fields (Eg. Apple pay, Google pay etc)
+ #[schema(default = false, example = false)]
+ pub always_collect_billing_details_from_wallet_connector: Option<bool>,
/// Indicates if the MIT (merchant initiated transaction) payments can be made connector
/// agnostic, i.e., MITs may be processed through different connector than CIT (customer
diff --git a/crates/diesel_models/src/business_profile.rs b/crates/diesel_models/src/business_profile.rs
index 08778597375..23061c9e7ad 100644
--- a/crates/diesel_models/src/business_profile.rs
+++ b/crates/diesel_models/src/business_profile.rs
@@ -54,6 +54,8 @@ pub struct BusinessProfile {
pub collect_shipping_details_from_wallet_connector: Option<bool>,
pub collect_billing_details_from_wallet_connector: Option<bool>,
pub outgoing_webhook_custom_http_headers: Option<Encryption>,
+ pub always_collect_billing_details_from_wallet_connector: Option<bool>,
+ pub always_collect_shipping_details_from_wallet_connector: Option<bool>,
}
#[cfg(all(
@@ -92,6 +94,8 @@ pub struct BusinessProfileNew {
pub collect_shipping_details_from_wallet_connector: Option<bool>,
pub collect_billing_details_from_wallet_connector: Option<bool>,
pub outgoing_webhook_custom_http_headers: Option<Encryption>,
+ pub always_collect_billing_details_from_wallet_connector: Option<bool>,
+ pub always_collect_shipping_details_from_wallet_connector: Option<bool>,
}
#[cfg(all(
@@ -127,6 +131,8 @@ pub struct BusinessProfileUpdateInternal {
pub collect_shipping_details_from_wallet_connector: Option<bool>,
pub collect_billing_details_from_wallet_connector: Option<bool>,
pub outgoing_webhook_custom_http_headers: Option<Encryption>,
+ pub always_collect_billing_details_from_wallet_connector: Option<bool>,
+ pub always_collect_shipping_details_from_wallet_connector: Option<bool>,
}
#[cfg(all(
@@ -161,6 +167,8 @@ impl BusinessProfileUpdateInternal {
collect_shipping_details_from_wallet_connector,
collect_billing_details_from_wallet_connector,
outgoing_webhook_custom_http_headers,
+ always_collect_billing_details_from_wallet_connector,
+ always_collect_shipping_details_from_wallet_connector,
} = self;
BusinessProfile {
profile_id: source.profile_id,
@@ -205,6 +213,12 @@ impl BusinessProfileUpdateInternal {
.or(source.collect_billing_details_from_wallet_connector),
outgoing_webhook_custom_http_headers: outgoing_webhook_custom_http_headers
.or(source.outgoing_webhook_custom_http_headers),
+ always_collect_billing_details_from_wallet_connector:
+ always_collect_billing_details_from_wallet_connector
+ .or(source.always_collect_billing_details_from_wallet_connector),
+ always_collect_shipping_details_from_wallet_connector:
+ always_collect_shipping_details_from_wallet_connector
+ .or(source.always_collect_shipping_details_from_wallet_connector),
}
}
}
@@ -243,6 +257,8 @@ pub struct BusinessProfile {
pub collect_shipping_details_from_wallet_connector: Option<bool>,
pub collect_billing_details_from_wallet_connector: Option<bool>,
pub outgoing_webhook_custom_http_headers: Option<Encryption>,
+ pub always_collect_billing_details_from_wallet_connector: Option<bool>,
+ pub always_collect_shipping_details_from_wallet_connector: Option<bool>,
pub routing_algorithm_id: Option<String>,
pub order_fulfillment_time: Option<i64>,
pub order_fulfillment_time_origin: Option<common_enums::OrderFulfillmentTimeOrigin>,
@@ -280,6 +296,8 @@ pub struct BusinessProfileNew {
pub collect_shipping_details_from_wallet_connector: Option<bool>,
pub collect_billing_details_from_wallet_connector: Option<bool>,
pub outgoing_webhook_custom_http_headers: Option<Encryption>,
+ pub always_collect_billing_details_from_wallet_connector: Option<bool>,
+ pub always_collect_shipping_details_from_wallet_connector: Option<bool>,
pub routing_algorithm_id: Option<String>,
pub order_fulfillment_time: Option<i64>,
pub order_fulfillment_time_origin: Option<common_enums::OrderFulfillmentTimeOrigin>,
@@ -314,6 +332,8 @@ pub struct BusinessProfileUpdateInternal {
pub collect_shipping_details_from_wallet_connector: Option<bool>,
pub collect_billing_details_from_wallet_connector: Option<bool>,
pub outgoing_webhook_custom_http_headers: Option<Encryption>,
+ pub always_collect_billing_details_from_wallet_connector: Option<bool>,
+ pub always_collect_shipping_details_from_wallet_connector: Option<bool>,
pub routing_algorithm_id: Option<String>,
pub order_fulfillment_time: Option<i64>,
pub order_fulfillment_time_origin: Option<common_enums::OrderFulfillmentTimeOrigin>,
@@ -347,6 +367,8 @@ impl BusinessProfileUpdateInternal {
collect_shipping_details_from_wallet_connector,
collect_billing_details_from_wallet_connector,
outgoing_webhook_custom_http_headers,
+ always_collect_billing_details_from_wallet_connector,
+ always_collect_shipping_details_from_wallet_connector,
routing_algorithm_id,
order_fulfillment_time,
order_fulfillment_time_origin,
@@ -393,6 +415,12 @@ impl BusinessProfileUpdateInternal {
.or(source.collect_billing_details_from_wallet_connector),
outgoing_webhook_custom_http_headers: outgoing_webhook_custom_http_headers
.or(source.outgoing_webhook_custom_http_headers),
+ always_collect_billing_details_from_wallet_connector:
+ always_collect_billing_details_from_wallet_connector
+ .or(always_collect_billing_details_from_wallet_connector),
+ always_collect_shipping_details_from_wallet_connector:
+ always_collect_shipping_details_from_wallet_connector
+ .or(always_collect_shipping_details_from_wallet_connector),
routing_algorithm_id: routing_algorithm_id.or(source.routing_algorithm_id),
order_fulfillment_time: order_fulfillment_time.or(source.order_fulfillment_time),
order_fulfillment_time_origin: order_fulfillment_time_origin
@@ -439,6 +467,10 @@ impl From<BusinessProfileNew> for BusinessProfile {
.collect_billing_details_from_wallet_connector,
outgoing_webhook_custom_http_headers: new.outgoing_webhook_custom_http_headers,
routing_algorithm_id: new.routing_algorithm_id,
+ always_collect_billing_details_from_wallet_connector: new
+ .always_collect_billing_details_from_wallet_connector,
+ always_collect_shipping_details_from_wallet_connector: new
+ .always_collect_shipping_details_from_wallet_connector,
order_fulfillment_time: new.order_fulfillment_time,
order_fulfillment_time_origin: new.order_fulfillment_time_origin,
frm_routing_algorithm_id: new.frm_routing_algorithm_id,
diff --git a/crates/diesel_models/src/schema.rs b/crates/diesel_models/src/schema.rs
index 9cada3e1b41..f751c8bcaf2 100644
--- a/crates/diesel_models/src/schema.rs
+++ b/crates/diesel_models/src/schema.rs
@@ -203,6 +203,8 @@ diesel::table! {
collect_shipping_details_from_wallet_connector -> Nullable<Bool>,
collect_billing_details_from_wallet_connector -> Nullable<Bool>,
outgoing_webhook_custom_http_headers -> Nullable<Bytea>,
+ always_collect_billing_details_from_wallet_connector -> Nullable<Bool>,
+ always_collect_shipping_details_from_wallet_connector -> Nullable<Bool>,
}
}
diff --git a/crates/diesel_models/src/schema_v2.rs b/crates/diesel_models/src/schema_v2.rs
index 3b8c04e4cac..bf7341a10d7 100644
--- a/crates/diesel_models/src/schema_v2.rs
+++ b/crates/diesel_models/src/schema_v2.rs
@@ -201,6 +201,8 @@ diesel::table! {
collect_shipping_details_from_wallet_connector -> Nullable<Bool>,
collect_billing_details_from_wallet_connector -> Nullable<Bool>,
outgoing_webhook_custom_http_headers -> Nullable<Bytea>,
+ always_collect_billing_details_from_wallet_connector -> Nullable<Bool>,
+ always_collect_shipping_details_from_wallet_connector -> Nullable<Bool>,
#[max_length = 64]
routing_algorithm_id -> Nullable<Varchar>,
order_fulfillment_time -> Nullable<Int8>,
diff --git a/crates/hyperswitch_domain_models/src/business_profile.rs b/crates/hyperswitch_domain_models/src/business_profile.rs
index b47dc19217a..70f541391be 100644
--- a/crates/hyperswitch_domain_models/src/business_profile.rs
+++ b/crates/hyperswitch_domain_models/src/business_profile.rs
@@ -51,6 +51,8 @@ pub struct BusinessProfile {
pub collect_shipping_details_from_wallet_connector: Option<bool>,
pub collect_billing_details_from_wallet_connector: Option<bool>,
pub outgoing_webhook_custom_http_headers: OptionalEncryptableValue,
+ pub always_collect_billing_details_from_wallet_connector: Option<bool>,
+ pub always_collect_shipping_details_from_wallet_connector: Option<bool>,
}
#[cfg(all(
@@ -81,6 +83,8 @@ pub struct BusinessProfileGeneralUpdate {
pub collect_billing_details_from_wallet_connector: Option<bool>,
pub is_connector_agnostic_mit_enabled: Option<bool>,
pub outgoing_webhook_custom_http_headers: OptionalEncryptableValue,
+ pub always_collect_billing_details_from_wallet_connector: Option<bool>,
+ pub always_collect_shipping_details_from_wallet_connector: Option<bool>,
}
#[cfg(all(
@@ -135,6 +139,8 @@ impl From<BusinessProfileUpdate> for BusinessProfileUpdateInternal {
collect_billing_details_from_wallet_connector,
is_connector_agnostic_mit_enabled,
outgoing_webhook_custom_http_headers,
+ always_collect_billing_details_from_wallet_connector,
+ always_collect_shipping_details_from_wallet_connector,
} = *update;
Self {
@@ -164,6 +170,8 @@ impl From<BusinessProfileUpdate> for BusinessProfileUpdateInternal {
collect_billing_details_from_wallet_connector,
outgoing_webhook_custom_http_headers: outgoing_webhook_custom_http_headers
.map(Encryption::from),
+ always_collect_billing_details_from_wallet_connector,
+ always_collect_shipping_details_from_wallet_connector,
}
}
BusinessProfileUpdate::RoutingAlgorithmUpdate {
@@ -195,6 +203,8 @@ impl From<BusinessProfileUpdate> for BusinessProfileUpdateInternal {
collect_shipping_details_from_wallet_connector: None,
collect_billing_details_from_wallet_connector: None,
outgoing_webhook_custom_http_headers: None,
+ always_collect_billing_details_from_wallet_connector: None,
+ always_collect_shipping_details_from_wallet_connector: None,
},
BusinessProfileUpdate::ExtendedCardInfoUpdate {
is_extended_card_info_enabled,
@@ -224,6 +234,8 @@ impl From<BusinessProfileUpdate> for BusinessProfileUpdateInternal {
collect_shipping_details_from_wallet_connector: None,
collect_billing_details_from_wallet_connector: None,
outgoing_webhook_custom_http_headers: None,
+ always_collect_billing_details_from_wallet_connector: None,
+ always_collect_shipping_details_from_wallet_connector: None,
},
BusinessProfileUpdate::ConnectorAgnosticMitUpdate {
is_connector_agnostic_mit_enabled,
@@ -253,6 +265,8 @@ impl From<BusinessProfileUpdate> for BusinessProfileUpdateInternal {
collect_shipping_details_from_wallet_connector: None,
collect_billing_details_from_wallet_connector: None,
outgoing_webhook_custom_http_headers: None,
+ always_collect_billing_details_from_wallet_connector: None,
+ always_collect_shipping_details_from_wallet_connector: None,
},
}
}
@@ -301,6 +315,10 @@ impl super::behaviour::Conversion for BusinessProfile {
outgoing_webhook_custom_http_headers: self
.outgoing_webhook_custom_http_headers
.map(Encryption::from),
+ always_collect_billing_details_from_wallet_connector: self
+ .always_collect_billing_details_from_wallet_connector,
+ always_collect_shipping_details_from_wallet_connector: self
+ .always_collect_shipping_details_from_wallet_connector,
})
}
@@ -344,6 +362,10 @@ impl super::behaviour::Conversion for BusinessProfile {
.collect_shipping_details_from_wallet_connector,
collect_billing_details_from_wallet_connector: item
.collect_billing_details_from_wallet_connector,
+ always_collect_billing_details_from_wallet_connector: item
+ .always_collect_billing_details_from_wallet_connector,
+ always_collect_shipping_details_from_wallet_connector: item
+ .always_collect_shipping_details_from_wallet_connector,
outgoing_webhook_custom_http_headers: item
.outgoing_webhook_custom_http_headers
.async_lift(|inner| async {
@@ -400,6 +422,10 @@ impl super::behaviour::Conversion for BusinessProfile {
outgoing_webhook_custom_http_headers: self
.outgoing_webhook_custom_http_headers
.map(Encryption::from),
+ always_collect_billing_details_from_wallet_connector: self
+ .always_collect_billing_details_from_wallet_connector,
+ always_collect_shipping_details_from_wallet_connector: self
+ .always_collect_shipping_details_from_wallet_connector,
})
}
}
@@ -431,6 +457,8 @@ pub struct BusinessProfile {
pub collect_shipping_details_from_wallet_connector: Option<bool>,
pub collect_billing_details_from_wallet_connector: Option<bool>,
pub outgoing_webhook_custom_http_headers: OptionalEncryptableValue,
+ pub always_collect_billing_details_from_wallet_connector: Option<bool>,
+ pub always_collect_shipping_details_from_wallet_connector: Option<bool>,
pub routing_algorithm_id: Option<String>,
pub order_fulfillment_time: Option<i64>,
pub order_fulfillment_time_origin: Option<common_enums::OrderFulfillmentTimeOrigin>,
@@ -475,6 +503,8 @@ pub struct BusinessProfileGeneralUpdate {
pub collect_billing_details_from_wallet_connector: Option<bool>,
pub is_connector_agnostic_mit_enabled: Option<bool>,
pub outgoing_webhook_custom_http_headers: OptionalEncryptableValue,
+ pub always_collect_billing_details_from_wallet_connector: Option<bool>,
+ pub always_collect_shipping_details_from_wallet_connector: Option<bool>,
pub order_fulfillment_time: Option<i64>,
pub order_fulfillment_time_origin: Option<common_enums::OrderFulfillmentTimeOrigin>,
}
@@ -524,6 +554,8 @@ impl From<BusinessProfileUpdate> for BusinessProfileUpdateInternal {
collect_billing_details_from_wallet_connector,
is_connector_agnostic_mit_enabled,
outgoing_webhook_custom_http_headers,
+ always_collect_billing_details_from_wallet_connector,
+ always_collect_shipping_details_from_wallet_connector,
order_fulfillment_time,
order_fulfillment_time_origin,
} = *update;
@@ -551,6 +583,8 @@ impl From<BusinessProfileUpdate> for BusinessProfileUpdateInternal {
outgoing_webhook_custom_http_headers: outgoing_webhook_custom_http_headers
.map(Encryption::from),
routing_algorithm_id: None,
+ always_collect_billing_details_from_wallet_connector,
+ always_collect_shipping_details_from_wallet_connector,
order_fulfillment_time,
order_fulfillment_time_origin,
frm_routing_algorithm_id: None,
@@ -584,6 +618,8 @@ impl From<BusinessProfileUpdate> for BusinessProfileUpdateInternal {
collect_billing_details_from_wallet_connector: None,
outgoing_webhook_custom_http_headers: None,
routing_algorithm_id,
+ always_collect_billing_details_from_wallet_connector: None,
+ always_collect_shipping_details_from_wallet_connector: None,
order_fulfillment_time: None,
order_fulfillment_time_origin: None,
frm_routing_algorithm_id: None,
@@ -614,6 +650,8 @@ impl From<BusinessProfileUpdate> for BusinessProfileUpdateInternal {
collect_shipping_details_from_wallet_connector: None,
collect_billing_details_from_wallet_connector: None,
outgoing_webhook_custom_http_headers: None,
+ always_collect_billing_details_from_wallet_connector: None,
+ always_collect_shipping_details_from_wallet_connector: None,
routing_algorithm_id: None,
payout_routing_algorithm_id: None,
order_fulfillment_time: None,
@@ -645,6 +683,8 @@ impl From<BusinessProfileUpdate> for BusinessProfileUpdateInternal {
collect_shipping_details_from_wallet_connector: None,
collect_billing_details_from_wallet_connector: None,
outgoing_webhook_custom_http_headers: None,
+ always_collect_billing_details_from_wallet_connector: None,
+ always_collect_shipping_details_from_wallet_connector: None,
routing_algorithm_id: None,
payout_routing_algorithm_id: None,
order_fulfillment_time: None,
@@ -676,6 +716,8 @@ impl From<BusinessProfileUpdate> for BusinessProfileUpdateInternal {
collect_shipping_details_from_wallet_connector: None,
collect_billing_details_from_wallet_connector: None,
outgoing_webhook_custom_http_headers: None,
+ always_collect_billing_details_from_wallet_connector: None,
+ always_collect_shipping_details_from_wallet_connector: None,
routing_algorithm_id: None,
payout_routing_algorithm_id: None,
order_fulfillment_time: None,
@@ -724,6 +766,10 @@ impl super::behaviour::Conversion for BusinessProfile {
.outgoing_webhook_custom_http_headers
.map(Encryption::from),
routing_algorithm_id: self.routing_algorithm_id,
+ always_collect_billing_details_from_wallet_connector: self
+ .always_collect_billing_details_from_wallet_connector,
+ always_collect_shipping_details_from_wallet_connector: self
+ .always_collect_shipping_details_from_wallet_connector,
payout_routing_algorithm_id: self.payout_routing_algorithm_id,
order_fulfillment_time: self.order_fulfillment_time,
order_fulfillment_time_origin: self.order_fulfillment_time_origin,
@@ -783,6 +829,10 @@ impl super::behaviour::Conversion for BusinessProfile {
})
.await?,
routing_algorithm_id: item.routing_algorithm_id,
+ always_collect_billing_details_from_wallet_connector: item
+ .always_collect_billing_details_from_wallet_connector,
+ always_collect_shipping_details_from_wallet_connector: item
+ .always_collect_shipping_details_from_wallet_connector,
order_fulfillment_time: item.order_fulfillment_time,
order_fulfillment_time_origin: item.order_fulfillment_time_origin,
frm_routing_algorithm_id: item.frm_routing_algorithm_id,
@@ -827,6 +877,10 @@ impl super::behaviour::Conversion for BusinessProfile {
.outgoing_webhook_custom_http_headers
.map(Encryption::from),
routing_algorithm_id: self.routing_algorithm_id,
+ always_collect_billing_details_from_wallet_connector: self
+ .always_collect_billing_details_from_wallet_connector,
+ always_collect_shipping_details_from_wallet_connector: self
+ .always_collect_shipping_details_from_wallet_connector,
order_fulfillment_time: self.order_fulfillment_time,
order_fulfillment_time_origin: self.order_fulfillment_time_origin,
frm_routing_algorithm_id: self.frm_routing_algorithm_id,
diff --git a/crates/router/src/configs.rs b/crates/router/src/configs.rs
index f7514a312a4..8c6dd28b521 100644
--- a/crates/router/src/configs.rs
+++ b/crates/router/src/configs.rs
@@ -1,6 +1,6 @@
use hyperswitch_interfaces::secrets_interface::secret_state::RawSecret;
-mod defaults;
+pub(crate) mod defaults;
pub mod secrets_transformers;
pub mod settings;
mod validations;
diff --git a/crates/router/src/configs/defaults.rs b/crates/router/src/configs/defaults.rs
index c34c00599a5..b2d9707d0b4 100644
--- a/crates/router/src/configs/defaults.rs
+++ b/crates/router/src/configs/defaults.rs
@@ -7343,74 +7343,7 @@ impl Default for super::settings::RequiredFields {
field_type: enums::FieldType::UserAddressLine1,
value: None,
}
- ),
- (
- "shipping.address.first_name".to_string(),
- RequiredFieldInfo {
- required_field: "shipping.address.first_name".to_string(),
- display_name: "shipping_first_name".to_string(),
- field_type: enums::FieldType::UserShippingName,
- value: None,
- }
- ),
- (
- "shipping.address.last_name".to_string(),
- RequiredFieldInfo {
- required_field: "shipping.address.last_name".to_string(),
- display_name: "shipping_last_name".to_string(),
- field_type: enums::FieldType::UserShippingName,
- value: None,
- }
- ),
- (
- "shipping.address.city".to_string(),
- RequiredFieldInfo {
- required_field: "shipping.address.city".to_string(),
- display_name: "city".to_string(),
- field_type: enums::FieldType::UserShippingAddressCity,
- value: None,
- }
- ),
- (
- "shipping.address.state".to_string(),
- RequiredFieldInfo {
- required_field: "shipping.address.state".to_string(),
- display_name: "state".to_string(),
- field_type: enums::FieldType::UserShippingAddressState,
- value: None,
- }
- ),
- (
- "shipping.address.zip".to_string(),
- RequiredFieldInfo {
- required_field: "shipping.address.zip".to_string(),
- display_name: "zip".to_string(),
- field_type: enums::FieldType::UserShippingAddressPincode,
- value: None,
- }
- ),
- (
- "shipping.address.country".to_string(),
- RequiredFieldInfo {
- required_field: "shipping.address.country".to_string(),
- display_name: "country".to_string(),
- field_type: enums::FieldType::UserShippingAddressCountry{
- options: vec![
- "ALL".to_string(),
- ]
- },
- value: None,
- }
- ),
- (
- "shipping.address.line1".to_string(),
- RequiredFieldInfo {
- required_field: "shipping.address.line1".to_string(),
- display_name: "line1".to_string(),
- field_type: enums::FieldType::UserShippingAddressLine1,
- value: None,
- }
- ),
+ )
]
),
common: HashMap::new(),
@@ -7497,74 +7430,7 @@ impl Default for super::settings::RequiredFields {
field_type: enums::FieldType::UserAddressLine1,
value: None,
}
- ),
- (
- "shipping.address.first_name".to_string(),
- RequiredFieldInfo {
- required_field: "shipping.address.first_name".to_string(),
- display_name: "shipping_first_name".to_string(),
- field_type: enums::FieldType::UserShippingName,
- value: None,
- }
- ),
- (
- "shipping.address.last_name".to_string(),
- RequiredFieldInfo {
- required_field: "shipping.address.last_name".to_string(),
- display_name: "shipping_last_name".to_string(),
- field_type: enums::FieldType::UserShippingName,
- value: None,
- }
- ),
- (
- "shipping.address.city".to_string(),
- RequiredFieldInfo {
- required_field: "shipping.address.city".to_string(),
- display_name: "city".to_string(),
- field_type: enums::FieldType::UserShippingAddressCity,
- value: None,
- }
- ),
- (
- "shipping.address.state".to_string(),
- RequiredFieldInfo {
- required_field: "shipping.address.state".to_string(),
- display_name: "state".to_string(),
- field_type: enums::FieldType::UserShippingAddressState,
- value: None,
- }
- ),
- (
- "shipping.address.zip".to_string(),
- RequiredFieldInfo {
- required_field: "shipping.address.zip".to_string(),
- display_name: "zip".to_string(),
- field_type: enums::FieldType::UserShippingAddressPincode,
- value: None,
- }
- ),
- (
- "shipping.address.country".to_string(),
- RequiredFieldInfo {
- required_field: "shipping.address.country".to_string(),
- display_name: "country".to_string(),
- field_type: enums::FieldType::UserShippingAddressCountry{
- options: vec![
- "ALL".to_string(),
- ]
- },
- value: None,
- }
- ),
- (
- "shipping.address.line1".to_string(),
- RequiredFieldInfo {
- required_field: "shipping.address.line1".to_string(),
- display_name: "line1".to_string(),
- field_type: enums::FieldType::UserShippingAddressLine1,
- value: None,
- }
- ),
+ )
]
),
common: HashMap::new(),
@@ -7820,74 +7686,7 @@ impl Default for super::settings::RequiredFields {
field_type: enums::FieldType::UserAddressLine1,
value: None,
}
- ),
- (
- "shipping.address.first_name".to_string(),
- RequiredFieldInfo {
- required_field: "shipping.address.first_name".to_string(),
- display_name: "shipping_first_name".to_string(),
- field_type: enums::FieldType::UserShippingName,
- value: None,
- }
- ),
- (
- "shipping.address.last_name".to_string(),
- RequiredFieldInfo {
- required_field: "shipping.address.last_name".to_string(),
- display_name: "shipping_last_name".to_string(),
- field_type: enums::FieldType::UserShippingName,
- value: None,
- }
- ),
- (
- "shipping.address.city".to_string(),
- RequiredFieldInfo {
- required_field: "shipping.address.city".to_string(),
- display_name: "city".to_string(),
- field_type: enums::FieldType::UserShippingAddressCity,
- value: None,
- }
- ),
- (
- "shipping.address.state".to_string(),
- RequiredFieldInfo {
- required_field: "shipping.address.state".to_string(),
- display_name: "state".to_string(),
- field_type: enums::FieldType::UserShippingAddressState,
- value: None,
- }
- ),
- (
- "shipping.address.zip".to_string(),
- RequiredFieldInfo {
- required_field: "shipping.address.zip".to_string(),
- display_name: "zip".to_string(),
- field_type: enums::FieldType::UserShippingAddressPincode,
- value: None,
- }
- ),
- (
- "shipping.address.country".to_string(),
- RequiredFieldInfo {
- required_field: "shipping.address.country".to_string(),
- display_name: "country".to_string(),
- field_type: enums::FieldType::UserShippingAddressCountry{
- options: vec![
- "ALL".to_string(),
- ]
- },
- value: None,
- }
- ),
- (
- "shipping.address.line1".to_string(),
- RequiredFieldInfo {
- required_field: "shipping.address.line1".to_string(),
- display_name: "line1".to_string(),
- field_type: enums::FieldType::UserShippingAddressLine1,
- value: None,
- }
- ),
+ )
]
),
common: HashMap::new(),
@@ -8097,187 +7896,50 @@ impl Default for super::settings::RequiredFields {
"billing.address.country".to_string(),
RequiredFieldInfo {
required_field: "payment_method_data.billing.address.country".to_string(),
- display_name: "country".to_string(),
- field_type: enums::FieldType::UserAddressCountry{
- options: vec![
- "ALL".to_string(),
- ]
- },
- value: None,
- }
- ),
- (
- "billing.address.line1".to_string(),
- RequiredFieldInfo {
- required_field: "payment_method_data.billing.address.line1".to_string(),
- display_name: "line1".to_string(),
- field_type: enums::FieldType::UserAddressLine1,
- value: None,
- }
- ),
- (
- "shipping.address.first_name".to_string(),
- RequiredFieldInfo {
- required_field: "shipping.address.first_name".to_string(),
- display_name: "shipping_first_name".to_string(),
- field_type: enums::FieldType::UserShippingName,
- value: None,
- }
- ),
- (
- "shipping.address.last_name".to_string(),
- RequiredFieldInfo {
- required_field: "shipping.address.last_name".to_string(),
- display_name: "shipping_last_name".to_string(),
- field_type: enums::FieldType::UserShippingName,
- value: None,
- }
- ),
- (
- "shipping.address.city".to_string(),
- RequiredFieldInfo {
- required_field: "shipping.address.city".to_string(),
- display_name: "city".to_string(),
- field_type: enums::FieldType::UserShippingAddressCity,
- value: None,
- }
- ),
- (
- "shipping.address.state".to_string(),
- RequiredFieldInfo {
- required_field: "shipping.address.state".to_string(),
- display_name: "state".to_string(),
- field_type: enums::FieldType::UserShippingAddressState,
- value: None,
- }
- ),
- (
- "shipping.address.zip".to_string(),
- RequiredFieldInfo {
- required_field: "shipping.address.zip".to_string(),
- display_name: "zip".to_string(),
- field_type: enums::FieldType::UserShippingAddressPincode,
- value: None,
- }
- ),
- (
- "shipping.address.country".to_string(),
- RequiredFieldInfo {
- required_field: "shipping.address.country".to_string(),
- display_name: "country".to_string(),
- field_type: enums::FieldType::UserShippingAddressCountry{
- options: vec![
- "ALL".to_string(),
- ]
- },
- value: None,
- }
- ),
- (
- "shipping.address.line1".to_string(),
- RequiredFieldInfo {
- required_field: "shipping.address.line1".to_string(),
- display_name: "line1".to_string(),
- field_type: enums::FieldType::UserShippingAddressLine1,
- value: None,
- }
- ),
- ]
- ),
- common: HashMap::new(),
- }
- ),
- (
- enums::Connector::Payu,
- RequiredFieldFinal {
- mandate: HashMap::new(),
- non_mandate: HashMap::new(),
- common: HashMap::new(),
- }
- ),
- (
- enums::Connector::Rapyd,
- RequiredFieldFinal {
- mandate: HashMap::new(),
- non_mandate: HashMap::new(),
- common: HashMap::new(),
- }
- ),
- (
- enums::Connector::Stripe,
- RequiredFieldFinal {
- mandate: HashMap::new(),
- non_mandate: HashMap::from(
- [
- (
- "shipping.address.first_name".to_string(),
- RequiredFieldInfo {
- required_field: "shipping.address.first_name".to_string(),
- display_name: "shipping_first_name".to_string(),
- field_type: enums::FieldType::UserShippingName,
- value: None,
- }
- ),
- (
- "shipping.address.last_name".to_string(),
- RequiredFieldInfo {
- required_field: "shipping.address.last_name".to_string(),
- display_name: "shipping_last_name".to_string(),
- field_type: enums::FieldType::UserShippingName,
- value: None,
- }
- ),
- (
- "shipping.address.city".to_string(),
- RequiredFieldInfo {
- required_field: "shipping.address.city".to_string(),
- display_name: "city".to_string(),
- field_type: enums::FieldType::UserShippingAddressCity,
- value: None,
- }
- ),
- (
- "shipping.address.state".to_string(),
- RequiredFieldInfo {
- required_field: "shipping.address.state".to_string(),
- display_name: "state".to_string(),
- field_type: enums::FieldType::UserShippingAddressState,
- value: None,
- }
- ),
- (
- "shipping.address.zip".to_string(),
- RequiredFieldInfo {
- required_field: "shipping.address.zip".to_string(),
- display_name: "zip".to_string(),
- field_type: enums::FieldType::UserShippingAddressPincode,
- value: None,
- }
- ),
- (
- "shipping.address.country".to_string(),
- RequiredFieldInfo {
- required_field: "shipping.address.country".to_string(),
- display_name: "country".to_string(),
- field_type: enums::FieldType::UserShippingAddressCountry{
- options: vec![
- "ALL".to_string(),
- ]
- },
- value: None,
- }
- ),
- (
- "shipping.address.line1".to_string(),
- RequiredFieldInfo {
- required_field: "shipping.address.line1".to_string(),
- display_name: "line1".to_string(),
- field_type: enums::FieldType::UserShippingAddressLine1,
- value: None,
- }
+ display_name: "country".to_string(),
+ field_type: enums::FieldType::UserAddressCountry{
+ options: vec![
+ "ALL".to_string(),
+ ]
+ },
+ value: None,
+ }
+ ),
+ (
+ "billing.address.line1".to_string(),
+ RequiredFieldInfo {
+ required_field: "payment_method_data.billing.address.line1".to_string(),
+ display_name: "line1".to_string(),
+ field_type: enums::FieldType::UserAddressLine1,
+ value: None,
+ }
+ )
+ ]
),
- ]
- ),
+ common: HashMap::new(),
+ }
+ ),
+ (
+ enums::Connector::Payu,
+ RequiredFieldFinal {
+ mandate: HashMap::new(),
+ non_mandate: HashMap::new(),
+ common: HashMap::new(),
+ }
+ ),
+ (
+ enums::Connector::Rapyd,
+ RequiredFieldFinal {
+ mandate: HashMap::new(),
+ non_mandate: HashMap::new(),
+ common: HashMap::new(),
+ }
+ ),
+ (
+ enums::Connector::Stripe,
+ RequiredFieldFinal {
+ mandate: HashMap::new(),
+ non_mandate: HashMap::new(),
common: HashMap::new(),
}
),
@@ -8487,75 +8149,7 @@ impl Default for super::settings::RequiredFields {
RequiredFieldFinal {
mandate: HashMap::new(),
non_mandate: HashMap::new(),
- common: HashMap::from([
- (
- "shipping.address.first_name".to_string(),
- RequiredFieldInfo {
- required_field: "shipping.address.first_name".to_string(),
- display_name: "shipping_first_name".to_string(),
- field_type: enums::FieldType::UserShippingName,
- value: None,
- }
- ),
- (
- "shipping.address.last_name".to_string(),
- RequiredFieldInfo {
- required_field: "shipping.address.last_name".to_string(),
- display_name: "shipping_last_name".to_string(),
- field_type: enums::FieldType::UserShippingName,
- value: None,
- }
- ),
- (
- "shipping.address.city".to_string(),
- RequiredFieldInfo {
- required_field: "shipping.address.city".to_string(),
- display_name: "city".to_string(),
- field_type: enums::FieldType::UserShippingAddressCity,
- value: None,
- }
- ),
- (
- "shipping.address.state".to_string(),
- RequiredFieldInfo {
- required_field: "shipping.address.state".to_string(),
- display_name: "state".to_string(),
- field_type: enums::FieldType::UserShippingAddressState,
- value: None,
- }
- ),
- (
- "shipping.address.zip".to_string(),
- RequiredFieldInfo {
- required_field: "shipping.address.zip".to_string(),
- display_name: "zip".to_string(),
- field_type: enums::FieldType::UserShippingAddressPincode,
- value: None,
- }
- ),
- (
- "shipping.address.country".to_string(),
- RequiredFieldInfo {
- required_field: "shipping.address.country".to_string(),
- display_name: "country".to_string(),
- field_type: enums::FieldType::UserShippingAddressCountry{
- options: vec![
- "ALL".to_string(),
- ]
- },
- value: None,
- }
- ),
- (
- "shipping.address.line1".to_string(),
- RequiredFieldInfo {
- required_field: "shipping.address.line1".to_string(),
- display_name: "line1".to_string(),
- field_type: enums::FieldType::UserShippingAddressLine1,
- value: None,
- }
- ),
- ]),
+ common: HashMap::new(),
}
),
(
@@ -8564,77 +8158,7 @@ impl Default for super::settings::RequiredFields {
mandate: HashMap::new(),
non_mandate: HashMap::new(
),
- common: HashMap::from(
- [
- (
- "shipping.address.first_name".to_string(),
- RequiredFieldInfo {
- required_field: "shipping.address.first_name".to_string(),
- display_name: "shipping_first_name".to_string(),
- field_type: enums::FieldType::UserShippingName,
- value: None,
- }
- ),
- (
- "shipping.address.last_name".to_string(),
- RequiredFieldInfo {
- required_field: "shipping.address.last_name".to_string(),
- display_name: "shipping_last_name".to_string(),
- field_type: enums::FieldType::UserShippingName,
- value: None,
- }
- ),
- (
- "shipping.address.city".to_string(),
- RequiredFieldInfo {
- required_field: "shipping.address.city".to_string(),
- display_name: "city".to_string(),
- field_type: enums::FieldType::UserShippingAddressCity,
- value: None,
- }
- ),
- (
- "shipping.address.state".to_string(),
- RequiredFieldInfo {
- required_field: "shipping.address.state".to_string(),
- display_name: "state".to_string(),
- field_type: enums::FieldType::UserShippingAddressState,
- value: None,
- }
- ),
- (
- "shipping.address.zip".to_string(),
- RequiredFieldInfo {
- required_field: "shipping.address.zip".to_string(),
- display_name: "zip".to_string(),
- field_type: enums::FieldType::UserShippingAddressPincode,
- value: None,
- }
- ),
- (
- "shipping.address.country".to_string(),
- RequiredFieldInfo {
- required_field: "shipping.address.country".to_string(),
- display_name: "country".to_string(),
- field_type: enums::FieldType::UserShippingAddressCountry{
- options: vec![
- "ALL".to_string(),
- ]
- },
- value: None,
- }
- ),
- (
- "shipping.address.line1".to_string(),
- RequiredFieldInfo {
- required_field: "shipping.address.line1".to_string(),
- display_name: "line1".to_string(),
- field_type: enums::FieldType::UserShippingAddressLine1,
- value: None,
- }
- ),
- ]
- ),
+ common: HashMap::new(),
}
),
]),
@@ -9002,130 +8526,6 @@ impl Default for super::settings::RequiredFields {
mandate: HashMap::new(),
non_mandate: HashMap::new(),
common: HashMap::from([
- (
- "shipping.address.first_name".to_string(),
- RequiredFieldInfo {
- required_field: "shipping.address.first_name".to_string(),
- display_name: "shipping_first_name".to_string(),
- field_type: enums::FieldType::UserShippingName,
- value: None,
- }
- ),
- (
- "shipping.address.last_name".to_string(),
- RequiredFieldInfo {
- required_field: "shipping.address.last_name".to_string(),
- display_name: "shipping_last_name".to_string(),
- field_type: enums::FieldType::UserShippingName,
- value: None,
- }
- ),
- (
- "shipping.address.city".to_string(),
- RequiredFieldInfo {
- required_field: "shipping.address.city".to_string(),
- display_name: "city".to_string(),
- field_type: enums::FieldType::UserShippingAddressCity,
- value: None,
- }
- ),
- (
- "shipping.address.line1".to_string(),
- RequiredFieldInfo {
- required_field: "shipping.address.line1".to_string(),
- display_name: "line1".to_string(),
- field_type: enums::FieldType::UserShippingAddressLine1,
- value: None,
- }
- ),
- (
- "shipping.address.line2".to_string(),
- RequiredFieldInfo {
- required_field: "shipping.address.line2".to_string(),
- display_name: "line2".to_string(),
- field_type: enums::FieldType::UserShippingAddressLine2,
- value: None,
- }
- ),
- (
- "shipping.address.zip".to_string(),
- RequiredFieldInfo {
- required_field: "shipping.address.zip".to_string(),
- display_name: "zip".to_string(),
- field_type: enums::FieldType::UserShippingAddressPincode,
- value: None,
- }
- ),
- (
- "shipping.address.state".to_string(),
- RequiredFieldInfo {
- required_field: "shipping.address.state".to_string(),
- display_name: "state".to_string(),
- field_type: enums::FieldType::UserShippingAddressState,
- value: None,
- }
- ),
- (
- "shipping.email".to_string(),
- RequiredFieldInfo {
- required_field: "shipping.email".to_string(),
- display_name: "email".to_string(),
- field_type: enums::FieldType::UserEmailAddress,
- value: None,
- }
- ),
- (
- "shipping.phone.number".to_string(),
- RequiredFieldInfo {
- required_field: "shipping.phone.number".to_string(),
- display_name: "phone_number".to_string(),
- field_type: enums::FieldType::UserPhoneNumber,
- value: None,
- }
- ),
- (
- "shipping.phone.country_code".to_string(),
- RequiredFieldInfo {
- required_field: "shipping.phone.country_code".to_string(),
- display_name: "phone_country_code".to_string(),
- field_type: enums::FieldType::UserPhoneNumberCountryCode,
- value: None,
- }
- ),
- (
- "shipping.address.country".to_string(),
- RequiredFieldInfo {
- required_field: "shipping.address.country".to_string(),
- display_name: "country".to_string(),
- field_type: enums::FieldType::UserShippingAddressCountry{
- options: vec![
- "AU".to_string(),
- "AT".to_string(),
- "BE".to_string(),
- "CA".to_string(),
- "CZ".to_string(),
- "DK".to_string(),
- "FI".to_string(),
- "FR".to_string(),
- "DE".to_string(),
- "GR".to_string(),
- "IE".to_string(),
- "IT".to_string(),
- "NL".to_string(),
- "NZ".to_string(),
- "NO".to_string(),
- "PL".to_string(),
- "PT".to_string(),
- "ES".to_string(),
- "SE".to_string(),
- "CH".to_string(),
- "GB".to_string(),
- "US".to_string(),
- ]
- },
- value: None,
- }
- ),
(
"billing.address.country".to_string(),
RequiredFieldInfo {
@@ -9497,6 +8897,155 @@ impl Default for super::settings::ApiKeys {
}
}
+pub fn get_billing_required_fields() -> HashMap<String, RequiredFieldInfo> {
+ HashMap::from([
+ (
+ "billing.address.first_name".to_string(),
+ RequiredFieldInfo {
+ required_field: "payment_method_data.billing.address.first_name".to_string(),
+ display_name: "billing_first_name".to_string(),
+ field_type: enums::FieldType::UserBillingName,
+ value: None,
+ },
+ ),
+ (
+ "billing.address.last_name".to_string(),
+ RequiredFieldInfo {
+ required_field: "payment_method_data.billing.address.last_name".to_string(),
+ display_name: "billing_last_name".to_string(),
+ field_type: enums::FieldType::UserBillingName,
+ value: None,
+ },
+ ),
+ (
+ "billing.address.city".to_string(),
+ RequiredFieldInfo {
+ required_field: "payment_method_data.billing.address.city".to_string(),
+ display_name: "city".to_string(),
+ field_type: enums::FieldType::UserAddressCity,
+ value: None,
+ },
+ ),
+ (
+ "billing.address.state".to_string(),
+ RequiredFieldInfo {
+ required_field: "payment_method_data.billing.address.state".to_string(),
+ display_name: "state".to_string(),
+ field_type: enums::FieldType::UserAddressState,
+ value: None,
+ },
+ ),
+ (
+ "billing.address.zip".to_string(),
+ RequiredFieldInfo {
+ required_field: "payment_method_data.billing.address.zip".to_string(),
+ display_name: "zip".to_string(),
+ field_type: enums::FieldType::UserAddressPincode,
+ value: None,
+ },
+ ),
+ (
+ "billing.address.country".to_string(),
+ RequiredFieldInfo {
+ required_field: "payment_method_data.billing.address.country".to_string(),
+ display_name: "country".to_string(),
+ field_type: enums::FieldType::UserAddressCountry {
+ options: vec!["ALL".to_string()],
+ },
+ value: None,
+ },
+ ),
+ (
+ "billing.address.line1".to_string(),
+ RequiredFieldInfo {
+ required_field: "payment_method_data.billing.address.line1".to_string(),
+ display_name: "line1".to_string(),
+ field_type: enums::FieldType::UserAddressLine1,
+ value: None,
+ },
+ ),
+ (
+ "billing.address.line2".to_string(),
+ RequiredFieldInfo {
+ required_field: "payment_method_data.billing.address.line2".to_string(),
+ display_name: "line2".to_string(),
+ field_type: enums::FieldType::UserAddressLine2,
+ value: None,
+ },
+ ),
+ ])
+}
+
+pub fn get_shipping_required_fields() -> HashMap<String, RequiredFieldInfo> {
+ HashMap::from([
+ (
+ "shipping.address.first_name".to_string(),
+ RequiredFieldInfo {
+ required_field: "shipping.address.first_name".to_string(),
+ display_name: "shipping_first_name".to_string(),
+ field_type: enums::FieldType::UserShippingName,
+ value: None,
+ },
+ ),
+ (
+ "shipping.address.last_name".to_string(),
+ RequiredFieldInfo {
+ required_field: "shipping.address.last_name".to_string(),
+ display_name: "shipping_last_name".to_string(),
+ field_type: enums::FieldType::UserShippingName,
+ value: None,
+ },
+ ),
+ (
+ "shipping.address.city".to_string(),
+ RequiredFieldInfo {
+ required_field: "shipping.address.city".to_string(),
+ display_name: "city".to_string(),
+ field_type: enums::FieldType::UserShippingAddressCity,
+ value: None,
+ },
+ ),
+ (
+ "shipping.address.state".to_string(),
+ RequiredFieldInfo {
+ required_field: "shipping.address.state".to_string(),
+ display_name: "state".to_string(),
+ field_type: enums::FieldType::UserShippingAddressState,
+ value: None,
+ },
+ ),
+ (
+ "shipping.address.zip".to_string(),
+ RequiredFieldInfo {
+ required_field: "shipping.address.zip".to_string(),
+ display_name: "zip".to_string(),
+ field_type: enums::FieldType::UserShippingAddressPincode,
+ value: None,
+ },
+ ),
+ (
+ "shipping.address.country".to_string(),
+ RequiredFieldInfo {
+ required_field: "shipping.address.country".to_string(),
+ display_name: "country".to_string(),
+ field_type: enums::FieldType::UserShippingAddressCountry {
+ options: vec!["ALL".to_string()],
+ },
+ value: None,
+ },
+ ),
+ (
+ "shipping.address.line1".to_string(),
+ RequiredFieldInfo {
+ required_field: "shipping.address.line1".to_string(),
+ display_name: "line1".to_string(),
+ field_type: enums::FieldType::UserShippingAddressLine1,
+ value: None,
+ },
+ ),
+ ])
+}
+
impl Default for super::settings::KeyManagerConfig {
fn default() -> Self {
Self {
diff --git a/crates/router/src/core/admin.rs b/crates/router/src/core/admin.rs
index ca1b24a06fb..9362094c459 100644
--- a/crates/router/src/core/admin.rs
+++ b/crates/router/src/core/admin.rs
@@ -3451,6 +3451,10 @@ impl BusinessProfileCreateBridge for api::BusinessProfileCreate {
.or(Some(false)),
outgoing_webhook_custom_http_headers: outgoing_webhook_custom_http_headers
.map(Into::into),
+ always_collect_billing_details_from_wallet_connector: self
+ .always_collect_billing_details_from_wallet_connector,
+ always_collect_shipping_details_from_wallet_connector: self
+ .always_collect_shipping_details_from_wallet_connector,
})
}
@@ -3531,13 +3535,17 @@ impl BusinessProfileCreateBridge for api::BusinessProfileCreate {
.use_billing_as_payment_method_billing
.or(Some(true)),
collect_shipping_details_from_wallet_connector: self
- .collect_shipping_details_from_wallet_connector
+ .collect_shipping_details_from_wallet_connector_if_required
.or(Some(false)),
collect_billing_details_from_wallet_connector: self
- .collect_billing_details_from_wallet_connector
+ .collect_billing_details_from_wallet_connector_if_required
.or(Some(false)),
outgoing_webhook_custom_http_headers: outgoing_webhook_custom_http_headers
.map(Into::into),
+ always_collect_billing_details_from_wallet_connector: self
+ .always_collect_billing_details_from_wallet_connector,
+ always_collect_shipping_details_from_wallet_connector: self
+ .always_collect_shipping_details_from_wallet_connector,
routing_algorithm_id: None,
frm_routing_algorithm_id: None,
payout_routing_algorithm_id: None,
@@ -3809,6 +3817,10 @@ impl BusinessProfileUpdateBridge for api::BusinessProfileUpdate {
is_connector_agnostic_mit_enabled: self.is_connector_agnostic_mit_enabled,
outgoing_webhook_custom_http_headers: outgoing_webhook_custom_http_headers
.map(Into::into),
+ always_collect_billing_details_from_wallet_connector: self
+ .always_collect_billing_details_from_wallet_connector,
+ always_collect_shipping_details_from_wallet_connector: self
+ .always_collect_shipping_details_from_wallet_connector,
},
)))
}
@@ -3887,9 +3899,9 @@ impl BusinessProfileUpdateBridge for api::BusinessProfileUpdate {
extended_card_info_config,
use_billing_as_payment_method_billing: self.use_billing_as_payment_method_billing,
collect_shipping_details_from_wallet_connector: self
- .collect_shipping_details_from_wallet_connector,
+ .collect_shipping_details_from_wallet_connector_if_required,
collect_billing_details_from_wallet_connector: self
- .collect_billing_details_from_wallet_connector,
+ .collect_billing_details_from_wallet_connector_if_required,
is_connector_agnostic_mit_enabled: self.is_connector_agnostic_mit_enabled,
outgoing_webhook_custom_http_headers: outgoing_webhook_custom_http_headers
.map(Into::into),
@@ -3897,6 +3909,10 @@ impl BusinessProfileUpdateBridge for api::BusinessProfileUpdate {
.order_fulfillment_time
.map(|order_fulfillment_time| order_fulfillment_time.into_inner()),
order_fulfillment_time_origin: self.order_fulfillment_time_origin,
+ always_collect_billing_details_from_wallet_connector: self
+ .always_collect_billing_details_from_wallet_connector,
+ always_collect_shipping_details_from_wallet_connector: self
+ .always_collect_shipping_details_from_wallet_connector,
},
)))
}
diff --git a/crates/router/src/core/payment_methods/cards.rs b/crates/router/src/core/payment_methods/cards.rs
index 3ce9c9ab5af..cc4e5ebd2b9 100644
--- a/crates/router/src/core/payment_methods/cards.rs
+++ b/crates/router/src/core/payment_methods/cards.rs
@@ -60,7 +60,10 @@ use crate::types::domain::types::AsyncLift;
#[cfg(all(any(feature = "v1", feature = "v2"), not(feature = "customer_v2")))]
use crate::utils::{self};
use crate::{
- configs::settings,
+ configs::{
+ defaults::{get_billing_required_fields, get_shipping_required_fields},
+ settings,
+ },
core::{
errors::{self, StorageErrorExt},
payment_methods::{
@@ -2897,29 +2900,12 @@ pub async fn list_payment_methods(
}
}
- let should_send_shipping_details =
- business_profile.clone().and_then(|business_profile| {
- business_profile
- .collect_shipping_details_from_wallet_connector
- });
-
- // Remove shipping fields from required fields based on business profile configuration
- if should_send_shipping_details != Some(true) {
- let shipping_variants =
- api_enums::FieldType::get_shipping_variants();
-
- let keys_to_be_removed = required_fields_hs
- .iter()
- .filter(|(_key, value)| {
- shipping_variants.contains(&value.field_type)
- })
- .map(|(key, _value)| key.to_string())
- .collect::<Vec<_>>();
-
- keys_to_be_removed.iter().for_each(|key_to_be_removed| {
- required_fields_hs.remove(key_to_be_removed);
- });
- }
+ required_fields_hs = should_collect_shipping_or_billing_details_from_wallet_connector(
+ &payment_method,
+ element.payment_experience.as_ref(),
+ business_profile.as_ref(),
+ required_fields_hs.clone(),
+ );
// get the config, check the enums while adding
{
@@ -3270,11 +3256,22 @@ pub async fn list_payment_methods(
let collect_shipping_details_from_wallets = business_profile
.as_ref()
- .and_then(|bp| bp.collect_shipping_details_from_wallet_connector);
+ .and_then(|business_profile| {
+ business_profile.always_collect_shipping_details_from_wallet_connector
+ })
+ .or(business_profile.as_ref().and_then(|business_profile| {
+ business_profile.collect_shipping_details_from_wallet_connector
+ }));
let collect_billing_details_from_wallets = business_profile
.as_ref()
- .and_then(|bp| bp.collect_billing_details_from_wallet_connector);
+ .and_then(|business_profile| {
+ business_profile.always_collect_billing_details_from_wallet_connector
+ })
+ .or(business_profile.as_ref().and_then(|business_profile| {
+ business_profile.collect_billing_details_from_wallet_connector
+ }));
+
Ok(services::ApplicationResponse::Json(
api::PaymentMethodListResponse {
redirect_url: business_profile
@@ -3319,6 +3316,37 @@ pub async fn list_payment_methods(
))
}
+fn should_collect_shipping_or_billing_details_from_wallet_connector(
+ payment_method: &api_enums::PaymentMethod,
+ payment_experience_optional: Option<&api_enums::PaymentExperience>,
+ business_profile: Option<&BusinessProfile>,
+ mut required_fields_hs: HashMap<String, RequiredFieldInfo>,
+) -> HashMap<String, RequiredFieldInfo> {
+ match (payment_method, payment_experience_optional) {
+ (api_enums::PaymentMethod::Wallet, Some(api_enums::PaymentExperience::InvokeSdkClient)) => {
+ let always_send_billing_details = business_profile.and_then(|business_profile| {
+ business_profile.always_collect_billing_details_from_wallet_connector
+ });
+
+ let always_send_shipping_details = business_profile.and_then(|business_profile| {
+ business_profile.always_collect_shipping_details_from_wallet_connector
+ });
+
+ if always_send_billing_details == Some(true) {
+ let billing_details = get_billing_required_fields();
+ required_fields_hs.extend(billing_details)
+ };
+ if always_send_shipping_details == Some(true) {
+ let shipping_details = get_shipping_required_fields();
+ required_fields_hs.extend(shipping_details)
+ };
+
+ required_fields_hs
+ }
+ _ => required_fields_hs,
+ }
+}
+
async fn validate_payment_method_and_client_secret(
cs: &String,
db: &dyn db::StorageInterface,
diff --git a/crates/router/src/core/payments/flows/session_flow.rs b/crates/router/src/core/payments/flows/session_flow.rs
index 4a1d57cda34..1dee6842360 100644
--- a/crates/router/src/core/payments/flows/session_flow.rs
+++ b/crates/router/src/core/payments/flows/session_flow.rs
@@ -316,43 +316,61 @@ async fn create_applepay_session_token(
router_data.request.to_owned(),
)?;
- let required_billing_contact_fields = business_profile
+ let required_billing_contact_fields = if business_profile
+ .always_collect_billing_details_from_wallet_connector
+ .unwrap_or(false)
+ {
+ Some(payment_types::ApplePayBillingContactFields(vec![
+ payment_types::ApplePayAddressParameters::PostalAddress,
+ ]))
+ } else if business_profile
.collect_billing_details_from_wallet_connector
.unwrap_or(false)
- .then_some({
- let billing_variants = enums::FieldType::get_billing_variants();
- is_dynamic_fields_required(
- &state.conf.required_fields,
- enums::PaymentMethod::Wallet,
- enums::PaymentMethodType::ApplePay,
- &connector.connector_name,
- billing_variants,
- )
- .then_some(payment_types::ApplePayBillingContactFields(vec![
- payment_types::ApplePayAddressParameters::PostalAddress,
- ]))
- })
- .flatten();
+ {
+ let billing_variants = enums::FieldType::get_billing_variants();
+ is_dynamic_fields_required(
+ &state.conf.required_fields,
+ enums::PaymentMethod::Wallet,
+ enums::PaymentMethodType::ApplePay,
+ &connector.connector_name,
+ billing_variants,
+ )
+ .then_some(payment_types::ApplePayBillingContactFields(vec![
+ payment_types::ApplePayAddressParameters::PostalAddress,
+ ]))
+ } else {
+ None
+ };
- let required_shipping_contact_fields = business_profile
+ let required_shipping_contact_fields = if business_profile
+ .always_collect_shipping_details_from_wallet_connector
+ .unwrap_or(false)
+ {
+ Some(payment_types::ApplePayShippingContactFields(vec![
+ payment_types::ApplePayAddressParameters::PostalAddress,
+ payment_types::ApplePayAddressParameters::Phone,
+ payment_types::ApplePayAddressParameters::Email,
+ ]))
+ } else if business_profile
.collect_shipping_details_from_wallet_connector
.unwrap_or(false)
- .then_some({
- let shipping_variants = enums::FieldType::get_shipping_variants();
- is_dynamic_fields_required(
- &state.conf.required_fields,
- enums::PaymentMethod::Wallet,
- enums::PaymentMethodType::ApplePay,
- &connector.connector_name,
- shipping_variants,
- )
- .then_some(payment_types::ApplePayShippingContactFields(vec![
- payment_types::ApplePayAddressParameters::PostalAddress,
- payment_types::ApplePayAddressParameters::Phone,
- payment_types::ApplePayAddressParameters::Email,
- ]))
- })
- .flatten();
+ {
+ let shipping_variants = enums::FieldType::get_shipping_variants();
+ is_dynamic_fields_required(
+ &state.conf.required_fields,
+ enums::PaymentMethod::Wallet,
+ enums::PaymentMethodType::ApplePay,
+ &connector.connector_name,
+ shipping_variants,
+ )
+ .then_some(payment_types::ApplePayShippingContactFields(vec![
+ payment_types::ApplePayAddressParameters::PostalAddress,
+ payment_types::ApplePayAddressParameters::Phone,
+ payment_types::ApplePayAddressParameters::Email,
+ ]))
+ } else {
+ None
+ };
// If collect_shipping_details_from_wallet_connector is false, we check if
// collect_billing_details_from_wallet_connector is true. If it is, then we pass the Email and Phone in
@@ -655,20 +673,27 @@ fn create_gpay_session_token(
expected_format: "gpay_metadata_format".to_string(),
})?;
- let is_billing_details_required =
- if business_profile.collect_billing_details_from_wallet_connector == Some(true) {
- let billing_variants = enums::FieldType::get_billing_variants();
+ let always_collect_billing_details_from_wallet_connector = business_profile
+ .always_collect_billing_details_from_wallet_connector
+ .unwrap_or(false);
- is_dynamic_fields_required(
- &state.conf.required_fields,
- enums::PaymentMethod::Wallet,
- enums::PaymentMethodType::GooglePay,
- &connector.connector_name,
- billing_variants,
- )
- } else {
- false
- };
+ let is_billing_details_required = if always_collect_billing_details_from_wallet_connector {
+ always_collect_billing_details_from_wallet_connector
+ } else if business_profile
+ .collect_billing_details_from_wallet_connector
+ .unwrap_or(false)
+ {
+ let billing_variants = enums::FieldType::get_billing_variants();
+ is_dynamic_fields_required(
+ &state.conf.required_fields,
+ enums::PaymentMethod::Wallet,
+ enums::PaymentMethodType::GooglePay,
+ &connector.connector_name,
+ billing_variants,
+ )
+ } else {
+ false
+ };
let billing_address_parameters =
is_billing_details_required.then_some(payment_types::GpayBillingAddressParameters {
@@ -708,8 +733,17 @@ fn create_gpay_session_token(
total_price: google_pay_amount,
};
+ let always_collect_shipping_details_from_wallet_connector = business_profile
+ .always_collect_shipping_details_from_wallet_connector
+ .unwrap_or(false);
+
let required_shipping_contact_fields =
- if business_profile.collect_shipping_details_from_wallet_connector == Some(true) {
+ if always_collect_shipping_details_from_wallet_connector {
+ true
+ } else if business_profile
+ .collect_shipping_details_from_wallet_connector
+ .unwrap_or(false)
+ {
let shipping_variants = enums::FieldType::get_shipping_variants();
is_dynamic_fields_required(
diff --git a/crates/router/src/core/payments/transformers.rs b/crates/router/src/core/payments/transformers.rs
index 24f5ffdca9a..df61b8809a7 100644
--- a/crates/router/src/core/payments/transformers.rs
+++ b/crates/router/src/core/payments/transformers.rs
@@ -18,6 +18,7 @@ use crate::{
connector::{Helcim, Nexinets},
core::{
errors::{self, RouterResponse, RouterResult},
+ payment_methods::cards::decrypt_generic_data,
payments::{self, helpers},
utils as core_utils,
},
@@ -25,8 +26,8 @@ use crate::{
routes::{metrics, SessionState},
services::{self, RedirectForm},
types::{
- self, api,
- api::ConnectorTransactionId,
+ self,
+ api::{self, ConnectorTransactionId},
domain,
storage::{self, enums},
transformers::{ForeignFrom, ForeignInto, ForeignTryFrom},
@@ -137,14 +138,13 @@ where
let unified_address =
if let Some(payment_method_info) = payment_data.payment_method_info.clone() {
- let payment_method_billing =
- crate::core::payment_methods::cards::decrypt_generic_data::<Address>(
- state,
- payment_method_info.payment_method_billing_address,
- key_store,
- )
- .await
- .attach_printable("unable to decrypt payment method billing address details")?;
+ let payment_method_billing = decrypt_generic_data::<Address>(
+ state,
+ payment_method_info.payment_method_billing_address,
+ key_store,
+ )
+ .await
+ .attach_printable("unable to decrypt payment method billing address details")?;
payment_data
.address
.clone()
diff --git a/crates/router/src/types/api/admin.rs b/crates/router/src/types/api/admin.rs
index 11b27a583bc..2d986d2c686 100644
--- a/crates/router/src/types/api/admin.rs
+++ b/crates/router/src/types/api/admin.rs
@@ -160,6 +160,10 @@ impl ForeignTryFrom<domain::BusinessProfile> for BusinessProfileResponse {
.collect_shipping_details_from_wallet_connector,
collect_billing_details_from_wallet_connector: item
.collect_billing_details_from_wallet_connector,
+ always_collect_billing_details_from_wallet_connector: item
+ .always_collect_billing_details_from_wallet_connector,
+ always_collect_shipping_details_from_wallet_connector: item
+ .always_collect_shipping_details_from_wallet_connector,
is_connector_agnostic_mit_enabled: item.is_connector_agnostic_mit_enabled,
outgoing_webhook_custom_http_headers,
})
@@ -211,10 +215,14 @@ impl ForeignTryFrom<domain::BusinessProfile> for BusinessProfileResponse {
.extended_card_info_config
.map(|config| config.expose().parse_value("ExtendedCardInfoConfig"))
.transpose()?,
- collect_shipping_details_from_wallet_connector: item
+ collect_shipping_details_from_wallet_connector_if_required: item
.collect_shipping_details_from_wallet_connector,
- collect_billing_details_from_wallet_connector: item
+ collect_billing_details_from_wallet_connector_if_required: item
.collect_billing_details_from_wallet_connector,
+ always_collect_shipping_details_from_wallet_connector: item
+ .always_collect_shipping_details_from_wallet_connector,
+ always_collect_billing_details_from_wallet_connector: item
+ .always_collect_billing_details_from_wallet_connector,
is_connector_agnostic_mit_enabled: item.is_connector_agnostic_mit_enabled,
outgoing_webhook_custom_http_headers,
order_fulfillment_time,
@@ -330,6 +338,12 @@ pub async fn create_business_profile_from_merchant_account(
collect_billing_details_from_wallet_connector: request
.collect_billing_details_from_wallet_connector
.or(Some(false)),
+ always_collect_billing_details_from_wallet_connector: request
+ .always_collect_billing_details_from_wallet_connector
+ .or(Some(false)),
+ always_collect_shipping_details_from_wallet_connector: request
+ .always_collect_shipping_details_from_wallet_connector
+ .or(Some(false)),
outgoing_webhook_custom_http_headers: outgoing_webhook_custom_http_headers.map(Into::into),
})
}
diff --git a/migrations/2024-07-23-060446_always_collect_billing_details_from_wallet_connector/down.sql b/migrations/2024-07-23-060446_always_collect_billing_details_from_wallet_connector/down.sql
new file mode 100644
index 00000000000..2cc1119dacc
--- /dev/null
+++ b/migrations/2024-07-23-060446_always_collect_billing_details_from_wallet_connector/down.sql
@@ -0,0 +1,3 @@
+-- This file should undo anything in `up.sql`
+
+ALTER TABLE business_profile DROP COLUMN IF EXISTS always_collect_billing_details_from_wallet_connector;
\ No newline at end of file
diff --git a/migrations/2024-07-23-060446_always_collect_billing_details_from_wallet_connector/up.sql b/migrations/2024-07-23-060446_always_collect_billing_details_from_wallet_connector/up.sql
new file mode 100644
index 00000000000..ee94a6224d2
--- /dev/null
+++ b/migrations/2024-07-23-060446_always_collect_billing_details_from_wallet_connector/up.sql
@@ -0,0 +1,3 @@
+-- Your SQL goes here
+
+ALTER TABLE business_profile ADD COLUMN IF NOT EXISTS always_collect_billing_details_from_wallet_connector BOOLEAN DEFAULT FALSE;
\ No newline at end of file
diff --git a/migrations/2024-07-23-060936_always_collect_shipping_details_from_wallet_connector/down.sql b/migrations/2024-07-23-060936_always_collect_shipping_details_from_wallet_connector/down.sql
new file mode 100644
index 00000000000..b277b3122f3
--- /dev/null
+++ b/migrations/2024-07-23-060936_always_collect_shipping_details_from_wallet_connector/down.sql
@@ -0,0 +1,3 @@
+-- This file should undo anything in `up.sql`
+
+ALTER TABLE business_profile DROP COLUMN IF EXISTS always_collect_shipping_details_from_wallet_connector;
\ No newline at end of file
diff --git a/migrations/2024-07-23-060936_always_collect_shipping_details_from_wallet_connector/up.sql b/migrations/2024-07-23-060936_always_collect_shipping_details_from_wallet_connector/up.sql
new file mode 100644
index 00000000000..2ac4d7c28b7
--- /dev/null
+++ b/migrations/2024-07-23-060936_always_collect_shipping_details_from_wallet_connector/up.sql
@@ -0,0 +1,3 @@
+-- Your SQL goes here
+
+ALTER TABLE business_profile ADD COLUMN IF NOT EXISTS always_collect_shipping_details_from_wallet_connector BOOLEAN DEFAULT FALSE;
\ No newline at end of file
|
2024-07-23T12:29:54Z
|
## Type of Change
<!-- Put an `x` in the boxes that apply -->
- [ ] Bugfix
- [x] New feature
- [ ] Enhancement
- [ ] Refactoring
- [ ] Dependency updates
- [ ] Documentation
- [ ] CI/CD
## Description
<!-- Describe your changes in detail -->
Always collect address details | Collect address details only if required by connector | Connector required fields | payment method list | Session call
-- | -- | -- | -- | --
False | False | False | False | False
False | False | True | True | False
False | True | True | True | True
False | True | False | False | False
True | True | False | True | True
True | True | True | True | True
True | False | False | True | True
True | False | True | True | True
Currently, we have business profile fields (`collect_shipping_details_from_wallet_connector` and `collect_billing_details_from_wallet_connector`) which will collect the address details from the wallet during the session call. Additionally, the address fields will be added to the payment method list, but only if these flags are enabled and the connector requires it.
This change is to collect address details (both billing and shipping) based on the merchant's requirements, regardless of the connector's required fields. The above details describes the behaviour of the payment method list and the session call based on the `Always collect address details`, `Collect address details only if required by connector`, and `Connector required fields`.
- `Always collect address details` fields for this are `always_collect_shipping_details_from_wallet_connector` and `always_collect_billing_details_from_wallet_connector`
- `Collect address details only if required by connector` fields for this are `collect_shipping_details_from_wallet_connector` and `collect_billing_details_from_wallet_connector`
### Additional Changes
- [x] This PR modifies the API contract
- [x] This PR modifies the database schema
- [ ] This PR modifies application configuration/environment variables
<!--
Provide links to the files with corresponding changes.
Following are the paths where you can find config files:
1. `config`
2. `crates/router/src/configs`
3. `loadtest/config`
-->
## Motivation and Context
<!--
Why is this change required? What problem does it solve?
If it fixes an open issue, please link to the issue here.
If you don't have an issue, we'd recommend starting with one first so the PR
can focus on the implementation (unless it is an obvious bug or documentation fix
that will have little conversation).
-->
## How did you test it?
<!--
Did you write an integration/unit/API test to verify the code changes?
Or did you test this change manually (provide relevant screenshots)?
-->
-> Create a merchant connector account for cybersource and enable the below payment method
```
"payment_methods_enabled": [
{
"payment_method": "pay_later",
"payment_method_types": [
{
"minimum_amount": 1,
"maximum_amount": 68607706,
"recurring_enabled": true,
"installment_payment_enabled": true,
"payment_experience": "invoke_sdk_client",
"payment_method_type": "klarna"
}
]
},
{
"payment_method": "pay_later",
"payment_method_types": [
{
"minimum_amount": 1,
"maximum_amount": 68607706,
"recurring_enabled": true,
"installment_payment_enabled": true,
"payment_experience": "redirect_to_url",
"payment_method_type": "klarna"
}
]
},
{
"payment_method": "card",
"payment_method_types": [
{
"payment_method_type": "credit",
"payment_experience": null,
"card_networks": [
"Visa",
"Mastercard",
"Discover",
"DinersClub"
],
"accepted_currencies": null,
"accepted_countries": null,
"minimum_amount": 1,
"maximum_amount": 68607706,
"recurring_enabled": true,
"installment_payment_enabled": true
},
{
"payment_method_type": "debit",
"payment_experience": null,
"card_networks": [
"Visa",
"Mastercard"
],
"accepted_currencies": null,
"accepted_countries": null,
"minimum_amount": 1,
"maximum_amount": 68607706,
"recurring_enabled": true,
"installment_payment_enabled": true
}
]
},
{
"payment_method": "bank_debit",
"payment_method_types": [
{
"payment_method_type": "ach",
"recurring_enabled": true,
"installment_payment_enabled": true,
"minimum_amount": 0,
"maximum_amount": 10000
}
]
},
{
"payment_method": "wallet",
"payment_method_types": [
{
"payment_method_type": "google_pay",
"payment_experience": "invoke_sdk_client",
"card_networks": null,
"accepted_currencies": null,
"accepted_countries": null,
"minimum_amount": 1,
"maximum_amount": 68607706,
"recurring_enabled": true,
"installment_payment_enabled": true
},
{
"payment_method_type": "apple_pay",
"payment_experience": "invoke_sdk_client",
"card_networks": null,
"accepted_currencies": null,
"accepted_countries": null,
"minimum_amount": 1,
"maximum_amount": 68607706,
"recurring_enabled": true,
"installment_payment_enabled": true
},
{
"payment_method_type": "paypal",
"payment_experience": "redirect_to_url",
"card_networks": null,
"accepted_currencies": null,
"accepted_countries": null,
"minimum_amount": 1,
"maximum_amount": 68607706,
"recurring_enabled": true,
"installment_payment_enabled": true
}
]
}
],
```
-> Create a payment with confirm false
```
curl --location 'http://localhost:8080/payments' \
--header 'Content-Type: application/json' \
--header 'Accept: application/json' \
--header 'api-key: dev_01Z3SBQylw8CnKOSkONabUTtrnFZ7PiR3FwnADNQynfZFoYy9de3QmGWaeEmiblD' \
--data '{
"amount": 10000,
"currency": "USD",
"capture_method": "automatic",
"authentication_type": "no_three_ds",
"confirm": false,
"customer_id": "cu_1721237981"
}'
```
<img width="876" alt="image" src="https://github.com/user-attachments/assets/62f0dc74-0486-4b38-b172-06957d83abe5">
#### Test case 1
```
curl --location 'http://localhost:8080/account/merchant_1721741844/business_profile/pro_vtlWLmrVdh8d3nYGqHFi' \
--header 'Content-Type: application/json' \
--header 'Accept: application/json' \
--header 'api-key: test_admin' \
--data '{
"collect_shipping_details_from_wallet_connector": false,
"collect_billing_details_from_wallet_connector": false,
"always_collect_shipping_details_from_wallet_connector": false,
"always_collect_billing_details_from_wallet_connector": false,
"is_connector_agnostic_mit_enabled": false
}'
```
-> Perform merchant payment method list
```
curl --location 'http://localhost:8080/account/payment_methods?client_secret=pay_gxXOqEflgTHCFXDSe4gw_secret_BX8QNVYb6TEWG9Td2b4O' \
--header 'Accept: application/json' \
--header 'api-key: pk_dev_cf008d4c3c134125ac1d1a1b8175d288'
```
```
{
"redirect_url": "https://google.com/success",
"currency": "USD",
"payment_methods": [
{
"payment_method": "pay_later",
"payment_method_types": [
{
"payment_method_type": "klarna",
"payment_experience": [
{
"payment_experience_type": "redirect_to_url",
"eligible_connectors": [
"cybersource"
]
},
{
"payment_experience_type": "invoke_sdk_client",
"eligible_connectors": [
"cybersource"
]
}
],
"card_networks": null,
"bank_names": null,
"bank_debits": null,
"bank_transfers": null,
"required_fields": null,
"surcharge_details": null,
"pm_auth_connector": null
}
]
},
{
"payment_method": "wallet",
"payment_method_types": [
{
"payment_method_type": "paypal",
"payment_experience": [
{
"payment_experience_type": "redirect_to_url",
"eligible_connectors": [
"cybersource"
]
}
],
"card_networks": null,
"bank_names": null,
"bank_debits": null,
"bank_transfers": null,
"required_fields": null,
"surcharge_details": null,
"pm_auth_connector": null
},
{
"payment_method_type": "google_pay",
"payment_experience": [
{
"payment_experience_type": "invoke_sdk_client",
"eligible_connectors": [
"cybersource"
]
}
],
"card_networks": null,
"bank_names": null,
"bank_debits": null,
"bank_transfers": null,
"required_fields": {
"billing.address.line1": {
"required_field": "payment_method_data.billing.address.line1",
"display_name": "line1",
"field_type": "user_address_line1",
"value": null
},
"billing.address.last_name": {
"required_field": "payment_method_data.billing.address.last_name",
"display_name": "billing_last_name",
"field_type": "user_billing_name",
"value": null
},
"billing.address.country": {
"required_field": "payment_method_data.billing.address.country",
"display_name": "country",
"field_type": {
"user_address_country": {
"options": [
"ALL"
]
}
},
"value": null
},
"billing.address.first_name": {
"required_field": "payment_method_data.billing.address.first_name",
"display_name": "billing_first_name",
"field_type": "user_billing_name",
"value": null
},
"email": {
"required_field": "email",
"display_name": "email",
"field_type": "user_email_address",
"value": null
},
"billing.address.state": {
"required_field": "payment_method_data.billing.address.state",
"display_name": "state",
"field_type": "user_address_state",
"value": null
},
"billing.address.zip": {
"required_field": "payment_method_data.billing.address.zip",
"display_name": "zip",
"field_type": "user_address_pincode",
"value": null
},
"billing.address.city": {
"required_field": "payment_method_data.billing.address.city",
"display_name": "city",
"field_type": "user_address_city",
"value": null
}
},
"surcharge_details": null,
"pm_auth_connector": null
},
{
"payment_method_type": "apple_pay",
"payment_experience": [
{
"payment_experience_type": "invoke_sdk_client",
"eligible_connectors": [
"cybersource"
]
}
],
"card_networks": null,
"bank_names": null,
"bank_debits": null,
"bank_transfers": null,
"required_fields": {
"billing.address.state": {
"required_field": "payment_method_data.billing.address.state",
"display_name": "state",
"field_type": "user_address_state",
"value": null
},
"email": {
"required_field": "email",
"display_name": "email",
"field_type": "user_email_address",
"value": null
},
"billing.address.country": {
"required_field": "payment_method_data.billing.address.country",
"display_name": "country",
"field_type": {
"user_address_country": {
"options": [
"ALL"
]
}
},
"value": null
},
"billing.address.city": {
"required_field": "payment_method_data.billing.address.city",
"display_name": "city",
"field_type": "user_address_city",
"value": null
},
"billing.address.last_name": {
"required_field": "payment_method_data.billing.address.last_name",
"display_name": "billing_last_name",
"field_type": "user_billing_name",
"value": null
},
"billing.address.line1": {
"required_field": "payment_method_data.billing.address.line1",
"display_name": "line1",
"field_type": "user_address_line1",
"value": null
},
"billing.address.first_name": {
"required_field": "payment_method_data.billing.address.first_name",
"display_name": "billing_first_name",
"field_type": "user_billing_name",
"value": null
},
"billing.address.zip": {
"required_field": "payment_method_data.billing.address.zip",
"display_name": "zip",
"field_type": "user_address_pincode",
"value": null
}
},
"surcharge_details": null,
"pm_auth_connector": null
}
]
},
{
"payment_method": "card",
"payment_method_types": [
{
"payment_method_type": "credit",
"payment_experience": null,
"card_networks": [
{
"card_network": "Discover",
"surcharge_details": null,
"eligible_connectors": [
"cybersource"
]
},
{
"card_network": "DinersClub",
"surcharge_details": null,
"eligible_connectors": [
"cybersource"
]
},
{
"card_network": "Mastercard",
"surcharge_details": null,
"eligible_connectors": [
"cybersource"
]
},
{
"card_network": "Visa",
"surcharge_details": null,
"eligible_connectors": [
"cybersource"
]
}
],
"bank_names": null,
"bank_debits": null,
"bank_transfers": null,
"required_fields": {
"payment_method_data.card.card_cvc": {
"required_field": "payment_method_data.card.card_cvc",
"display_name": "card_cvc",
"field_type": "user_card_cvc",
"value": null
},
"billing.address.city": {
"required_field": "payment_method_data.billing.address.city",
"display_name": "city",
"field_type": "user_address_city",
"value": null
},
"billing.address.line1": {
"required_field": "payment_method_data.billing.address.line1",
"display_name": "line1",
"field_type": "user_address_line1",
"value": null
},
"billing.address.country": {
"required_field": "payment_method_data.billing.address.country",
"display_name": "country",
"field_type": {
"user_address_country": {
"options": [
"ALL"
]
}
},
"value": null
},
"billing.address.last_name": {
"required_field": "payment_method_data.billing.address.last_name",
"display_name": "card_holder_name",
"field_type": "user_full_name",
"value": null
},
"billing.address.zip": {
"required_field": "payment_method_data.billing.address.zip",
"display_name": "zip",
"field_type": "user_address_pincode",
"value": null
},
"payment_method_data.card.card_exp_month": {
"required_field": "payment_method_data.card.card_exp_month",
"display_name": "card_exp_month",
"field_type": "user_card_expiry_month",
"value": null
},
"email": {
"required_field": "email",
"display_name": "email",
"field_type": "user_email_address",
"value": null
},
"billing.address.first_name": {
"required_field": "payment_method_data.billing.address.first_name",
"display_name": "card_holder_name",
"field_type": "user_full_name",
"value": null
},
"payment_method_data.card.card_number": {
"required_field": "payment_method_data.card.card_number",
"display_name": "card_number",
"field_type": "user_card_number",
"value": null
},
"billing.address.state": {
"required_field": "payment_method_data.billing.address.state",
"display_name": "state",
"field_type": "user_address_state",
"value": null
},
"payment_method_data.card.card_exp_year": {
"required_field": "payment_method_data.card.card_exp_year",
"display_name": "card_exp_year",
"field_type": "user_card_expiry_year",
"value": null
}
},
"surcharge_details": null,
"pm_auth_connector": null
},
{
"payment_method_type": "debit",
"payment_experience": null,
"card_networks": [
{
"card_network": "Visa",
"surcharge_details": null,
"eligible_connectors": [
"cybersource"
]
},
{
"card_network": "Mastercard",
"surcharge_details": null,
"eligible_connectors": [
"cybersource"
]
}
],
"bank_names": null,
"bank_debits": null,
"bank_transfers": null,
"required_fields": {
"payment_method_data.card.card_exp_month": {
"required_field": "payment_method_data.card.card_exp_month",
"display_name": "card_exp_month",
"field_type": "user_card_expiry_month",
"value": null
},
"billing.address.last_name": {
"required_field": "payment_method_data.billing.address.last_name",
"display_name": "card_holder_name",
"field_type": "user_full_name",
"value": null
},
"billing.address.line1": {
"required_field": "payment_method_data.billing.address.line1",
"display_name": "line1",
"field_type": "user_address_line1",
"value": null
},
"billing.address.country": {
"required_field": "payment_method_data.billing.address.country",
"display_name": "country",
"field_type": {
"user_address_country": {
"options": [
"ALL"
]
}
},
"value": null
},
"payment_method_data.card.card_exp_year": {
"required_field": "payment_method_data.card.card_exp_year",
"display_name": "card_exp_year",
"field_type": "user_card_expiry_year",
"value": null
},
"payment_method_data.card.card_cvc": {
"required_field": "payment_method_data.card.card_cvc",
"display_name": "card_cvc",
"field_type": "user_card_cvc",
"value": null
},
"billing.address.city": {
"required_field": "payment_method_data.billing.address.city",
"display_name": "city",
"field_type": "user_address_city",
"value": null
},
"billing.address.first_name": {
"required_field": "payment_method_data.billing.address.first_name",
"display_name": "card_holder_name",
"field_type": "user_full_name",
"value": null
},
"billing.address.state": {
"required_field": "payment_method_data.billing.address.state",
"display_name": "state",
"field_type": "user_address_state",
"value": null
},
"payment_method_data.card.card_number": {
"required_field": "payment_method_data.card.card_number",
"display_name": "card_number",
"field_type": "user_card_number",
"value": null
},
"billing.address.zip": {
"required_field": "payment_method_data.billing.address.zip",
"display_name": "zip",
"field_type": "user_address_pincode",
"value": null
},
"email": {
"required_field": "email",
"display_name": "email",
"field_type": "user_email_address",
"value": null
}
},
"surcharge_details": null,
"pm_auth_connector": null
}
]
},
{
"payment_method": "bank_debit",
"payment_method_types": [
{
"payment_method_type": "ach",
"payment_experience": null,
"card_networks": null,
"bank_names": null,
"bank_debits": {
"eligible_connectors": [
"cybersource"
]
},
"bank_transfers": null,
"required_fields": null,
"surcharge_details": null,
"pm_auth_connector": null
}
]
}
],
"mandate_payment": null,
"merchant_name": "NewAge Retailer",
"show_surcharge_breakup_screen": false,
"payment_type": "normal",
"request_external_three_ds_authentication": false,
"collect_shipping_details_from_wallets": false,
"collect_billing_details_from_wallets": false
}
```
-> Session call
```
curl --location 'http://localhost:8080/payments/session_tokens' \
--header 'Content-Type: application/json' \
--header 'x-merchant-domain: sdk-test-app.netlify.app' \
--header 'api-key: pk_dev_cf008d4c3c134125ac1d1a1b8175d288' \
--data '{
"payment_id": "pay_gxXOqEflgTHCFXDSe4gw",
"wallets": [],
"client_secret": "pay_gxXOqEflgTHCFXDSe4gw_secret_BX8QNVYb6TEWG9Td2b4O"
}'
```
```
{
"payment_id": "pay_gxXOqEflgTHCFXDSe4gw",
"client_secret": "pay_gxXOqEflgTHCFXDSe4gw_secret_BX8QNVYb6TEWG9Td2b4O",
"session_token": [
{
"wallet_name": "google_pay",
"merchant_info": {
"merchant_name": "Stripe"
},
"shipping_address_required": false,
"email_required": false,
"shipping_address_parameters": {
"phone_number_required": false
},
"allowed_payment_methods": [
{
"type": "CARD",
"parameters": {
"allowed_auth_methods": [
"PAN_ONLY",
"CRYPTOGRAM_3DS"
],
"allowed_card_networks": [
"AMEX",
"DISCOVER",
"INTERAC",
"JCB",
"MASTERCARD",
"VISA"
],
"billing_address_required": false
},
"tokenization_specification": {
"type": "PAYMENT_GATEWAY",
"parameters": {
"gateway": "stripe",
"stripe:version": "2018-10-31",
"stripe:publishableKey": "pk_test_51Msk2GAGHc77EJXX78h549SX2uaOnEkUYqBfjcoD05PIpAnDkYxMn8nQ4d19im85NQuX4Z6WDyHaUw2fFTPBWsIY00Wa7oNerO"
}
}
}
],
"transaction_info": {
"country_code": "US",
"currency_code": "USD",
"total_price_status": "Final",
"total_price": "100.00"
},
"delayed_session_token": false,
"connector": "cybersource",
"sdk_next_action": {
"next_action": "confirm"
},
"secrets": null
},
{
"wallet_name": "apple_pay",
"session_token_data": {
"epoch_timestamp": 1721742967477,
"expires_at": 1721746567477,
"merchant_session_identifier": "SSH31A9B315225043E7B9F8526D7EF8E03D_C23A0D3024FAB8B12CBB67660B4C1B48ABF1272EC8B61399E3A647290C8BE67A",
"nonce": "f927f51c",
"merchant_identifier": "76B79A8E91F4D365B0B636C8F75CB207D52532E82C2C085DE79D6D8135EF3813",
"domain_name": "sdk-test-app.netlify.app",
"display_name": "applepay",
"signature": "308006092a864886f70d010702a0803080020101310d300b0609608648016503040201308006092a864886f70d0107010000a080308203e330820388a003020102020816634c8b0e305717300a06082a8648ce3d040302307a312e302c06035504030c254170706c65204170706c69636174696f6e20496e746567726174696f6e204341202d20473331263024060355040b0c1d4170706c652043657274696669636174696f6e20417574686f7269747931133011060355040a0c0a4170706c6520496e632e310b3009060355040613025553301e170d3234303432393137343732375a170d3239303432383137343732365a305f3125302306035504030c1c6563632d736d702d62726f6b65722d7369676e5f5543342d50524f4431143012060355040b0c0b694f532053797374656d7331133011060355040a0c0a4170706c6520496e632e310b30090603550406130255533059301306072a8648ce3d020106082a8648ce3d03010703420004c21577edebd6c7b2218f68dd7090a1218dc7b0bd6f2c283d846095d94af4a5411b83420ed811f3407e83331f1c54c3f7eb3220d6bad5d4eff49289893e7c0f13a38202113082020d300c0603551d130101ff04023000301f0603551d2304183016801423f249c44f93e4ef27e6c4f6286c3fa2bbfd2e4b304506082b0601050507010104393037303506082b060105050730018629687474703a2f2f6f6373702e6170706c652e636f6d2f6f63737030342d6170706c65616963613330323082011d0603551d2004820114308201103082010c06092a864886f7636405013081fe3081c306082b060105050702023081b60c81b352656c69616e6365206f6e207468697320636572746966696361746520627920616e7920706172747920617373756d657320616363657074616e6365206f6620746865207468656e206170706c696361626c65207374616e64617264207465726d7320616e6420636f6e646974696f6e73206f66207573652c20636572746966696361746520706f6c69637920616e642063657274696669636174696f6e2070726163746963652073746174656d656e74732e303606082b06010505070201162a687474703a2f2f7777772e6170706c652e636f6d2f6365727469666963617465617574686f726974792f30340603551d1f042d302b3029a027a0258623687474703a2f2f63726c2e6170706c652e636f6d2f6170706c6561696361332e63726c301d0603551d0e041604149457db6fd57481868989762f7e578507e79b5824300e0603551d0f0101ff040403020780300f06092a864886f76364061d04020500300a06082a8648ce3d0403020349003046022100c6f023cb2614bb303888a162983e1a93f1056f50fa78cdb9ba4ca241cc14e25e022100be3cd0dfd16247f6494475380e9d44c228a10890a3a1dc724b8b4cb8889818bc308202ee30820275a0030201020208496d2fbf3a98da97300a06082a8648ce3d0403023067311b301906035504030c124170706c6520526f6f74204341202d20473331263024060355040b0c1d4170706c652043657274696669636174696f6e20417574686f7269747931133011060355040a0c0a4170706c6520496e632e310b3009060355040613025553301e170d3134303530363233343633305a170d3239303530363233343633305a307a312e302c06035504030c254170706c65204170706c69636174696f6e20496e746567726174696f6e204341202d20473331263024060355040b0c1d4170706c652043657274696669636174696f6e20417574686f7269747931133011060355040a0c0a4170706c6520496e632e310b30090603550406130255533059301306072a8648ce3d020106082a8648ce3d03010703420004f017118419d76485d51a5e25810776e880a2efde7bae4de08dfc4b93e13356d5665b35ae22d097760d224e7bba08fd7617ce88cb76bb6670bec8e82984ff5445a381f73081f4304606082b06010505070101043a3038303606082b06010505073001862a687474703a2f2f6f6373702e6170706c652e636f6d2f6f63737030342d6170706c65726f6f7463616733301d0603551d0e0416041423f249c44f93e4ef27e6c4f6286c3fa2bbfd2e4b300f0603551d130101ff040530030101ff301f0603551d23041830168014bbb0dea15833889aa48a99debebdebafdacb24ab30370603551d1f0430302e302ca02aa0288626687474703a2f2f63726c2e6170706c652e636f6d2f6170706c65726f6f74636167332e63726c300e0603551d0f0101ff0404030201063010060a2a864886f7636406020e04020500300a06082a8648ce3d040302036700306402303acf7283511699b186fb35c356ca62bff417edd90f754da28ebef19c815e42b789f898f79b599f98d5410d8f9de9c2fe0230322dd54421b0a305776c5df3383b9067fd177c2c216d964fc6726982126f54f87a7d1b99cb9b0989216106990f09921d00003182018830820184020101308186307a312e302c06035504030c254170706c65204170706c69636174696f6e20496e746567726174696f6e204341202d20473331263024060355040b0c1d4170706c652043657274696669636174696f6e20417574686f7269747931133011060355040a0c0a4170706c6520496e632e310b3009060355040613025553020816634c8b0e305717300b0609608648016503040201a08193301806092a864886f70d010903310b06092a864886f70d010701301c06092a864886f70d010905310f170d3234303732333133353630375a302806092a864886f70d010934311b3019300b0609608648016503040201a10a06082a8648ce3d040302302f06092a864886f70d0109043122042069535b60ec3dc589325bd95773f7ba7378c9f05a4b39e65efb030b27dfefc758300a06082a8648ce3d04030204473045022100b96c88ebb717e2622fc4519f8aa0957209aacce31a617798bac56e0b522c14610220150efef71f2b557775a2ed2ccb274ce32d64d28e07bd84be39a9fb9ba53404b3000000000000",
"operational_analytics_identifier": "applepay:76B79A8E91F4D365B0B636C8F75CB207D52532E82C2C085DE79D6D8135EF3813",
"retries": 0,
"psp_id": "76B79A8E91F4D365B0B636C8F75CB207D52532E82C2C085DE79D6D8135EF3813"
},
"payment_request_data": {
"country_code": "US",
"currency_code": "USD",
"total": {
"label": "applepay",
"type": "final",
"amount": "100.00"
},
"merchant_capabilities": [
"supports3DS"
],
"supported_networks": [
"visa",
"masterCard",
"amex",
"discover"
],
"merchant_identifier": "merchant.com.hyperswitch.checkout"
},
"connector": "cybersource",
"delayed_session_token": false,
"sdk_next_action": {
"next_action": "confirm"
},
"connector_reference_id": null,
"connector_sdk_public_key": null,
"connector_merchant_id": null
}
]
}
```
-> For test purpose I have kept the shipping details in the connector required fields of apple pay boa
```
{
"payment_id": "pay_6aOv0gxeNHFFqSw2Einn",
"client_secret": "pay_6aOv0gxeNHFFqSw2Einn_secret_flyrD784FhtVfM68gT5J",
"session_token": [
{
"wallet_name": "google_pay",
"merchant_info": {
"merchant_name": "Stripe"
},
"shipping_address_required": false,
"email_required": false,
"shipping_address_parameters": {
"phone_number_required": false
},
"allowed_payment_methods": [
{
"type": "CARD",
"parameters": {
"allowed_auth_methods": [
"PAN_ONLY",
"CRYPTOGRAM_3DS"
],
"allowed_card_networks": [
"AMEX",
"DISCOVER",
"INTERAC",
"JCB",
"MASTERCARD",
"VISA"
],
"billing_address_required": false
},
"tokenization_specification": {
"type": "PAYMENT_GATEWAY",
"parameters": {
"gateway": "stripe",
"stripe:version": "2018-10-31",
"stripe:publishableKey": "pk_test_51Msk2GAGHc77EJXX78h549SX2uaOnEkUYqBfjcoD05PIpAnDkYxMn8nQ4d19im85NQuX4Z6WDyHaUw2fFTPBWsIY00Wa7oNerO"
}
}
}
],
"transaction_info": {
"country_code": "US",
"currency_code": "USD",
"total_price_status": "Final",
"total_price": "100.00"
},
"delayed_session_token": false,
"connector": "bankofamerica",
"sdk_next_action": {
"next_action": "confirm"
},
"secrets": null
},
{
"wallet_name": "apple_pay",
"session_token_data": {
"epoch_timestamp": 1721743409181,
"expires_at": 1721747009181,
"merchant_session_identifier": "SSHDCB45B020BFE4ABDA530581D199F4727_7E0DD1295E42A30B376B18CB4E6B9B9FB4C5E36B3EDF9FB0DEA51F9419420173",
"nonce": "7a73d676",
"merchant_identifier": "E43BADB7A30AB6630A49626B7181746F79AF44AE982581E52A78E1E2D8E126AC",
"domain_name": "sdk-test-app.netlify.app",
"display_name": "Apple pay",
"signature": "308006092a864886f70d010702a0803080020101310d300b0609608648016503040201308006092a864886f70d0107010000a080308203e330820388a003020102020816634c8b0e305717300a06082a8648ce3d040302307a312e302c06035504030c254170706c65204170706c69636174696f6e20496e746567726174696f6e204341202d20473331263024060355040b0c1d4170706c652043657274696669636174696f6e20417574686f7269747931133011060355040a0c0a4170706c6520496e632e310b3009060355040613025553301e170d3234303432393137343732375a170d3239303432383137343732365a305f3125302306035504030c1c6563632d736d702d62726f6b65722d7369676e5f5543342d50524f4431143012060355040b0c0b694f532053797374656d7331133011060355040a0c0a4170706c6520496e632e310b30090603550406130255533059301306072a8648ce3d020106082a8648ce3d03010703420004c21577edebd6c7b2218f68dd7090a1218dc7b0bd6f2c283d846095d94af4a5411b83420ed811f3407e83331f1c54c3f7eb3220d6bad5d4eff49289893e7c0f13a38202113082020d300c0603551d130101ff04023000301f0603551d2304183016801423f249c44f93e4ef27e6c4f6286c3fa2bbfd2e4b304506082b0601050507010104393037303506082b060105050730018629687474703a2f2f6f6373702e6170706c652e636f6d2f6f63737030342d6170706c65616963613330323082011d0603551d2004820114308201103082010c06092a864886f7636405013081fe3081c306082b060105050702023081b60c81b352656c69616e6365206f6e207468697320636572746966696361746520627920616e7920706172747920617373756d657320616363657074616e6365206f6620746865207468656e206170706c696361626c65207374616e64617264207465726d7320616e6420636f6e646974696f6e73206f66207573652c20636572746966696361746520706f6c69637920616e642063657274696669636174696f6e2070726163746963652073746174656d656e74732e303606082b06010505070201162a687474703a2f2f7777772e6170706c652e636f6d2f6365727469666963617465617574686f726974792f30340603551d1f042d302b3029a027a0258623687474703a2f2f63726c2e6170706c652e636f6d2f6170706c6561696361332e63726c301d0603551d0e041604149457db6fd57481868989762f7e578507e79b5824300e0603551d0f0101ff040403020780300f06092a864886f76364061d04020500300a06082a8648ce3d0403020349003046022100c6f023cb2614bb303888a162983e1a93f1056f50fa78cdb9ba4ca241cc14e25e022100be3cd0dfd16247f6494475380e9d44c228a10890a3a1dc724b8b4cb8889818bc308202ee30820275a0030201020208496d2fbf3a98da97300a06082a8648ce3d0403023067311b301906035504030c124170706c6520526f6f74204341202d20473331263024060355040b0c1d4170706c652043657274696669636174696f6e20417574686f7269747931133011060355040a0c0a4170706c6520496e632e310b3009060355040613025553301e170d3134303530363233343633305a170d3239303530363233343633305a307a312e302c06035504030c254170706c65204170706c69636174696f6e20496e746567726174696f6e204341202d20473331263024060355040b0c1d4170706c652043657274696669636174696f6e20417574686f7269747931133011060355040a0c0a4170706c6520496e632e310b30090603550406130255533059301306072a8648ce3d020106082a8648ce3d03010703420004f017118419d76485d51a5e25810776e880a2efde7bae4de08dfc4b93e13356d5665b35ae22d097760d224e7bba08fd7617ce88cb76bb6670bec8e82984ff5445a381f73081f4304606082b06010505070101043a3038303606082b06010505073001862a687474703a2f2f6f6373702e6170706c652e636f6d2f6f63737030342d6170706c65726f6f7463616733301d0603551d0e0416041423f249c44f93e4ef27e6c4f6286c3fa2bbfd2e4b300f0603551d130101ff040530030101ff301f0603551d23041830168014bbb0dea15833889aa48a99debebdebafdacb24ab30370603551d1f0430302e302ca02aa0288626687474703a2f2f63726c2e6170706c652e636f6d2f6170706c65726f6f74636167332e63726c300e0603551d0f0101ff0404030201063010060a2a864886f7636406020e04020500300a06082a8648ce3d040302036700306402303acf7283511699b186fb35c356ca62bff417edd90f754da28ebef19c815e42b789f898f79b599f98d5410d8f9de9c2fe0230322dd54421b0a305776c5df3383b9067fd177c2c216d964fc6726982126f54f87a7d1b99cb9b0989216106990f09921d00003182018830820184020101308186307a312e302c06035504030c254170706c65204170706c69636174696f6e20496e746567726174696f6e204341202d20473331263024060355040b0c1d4170706c652043657274696669636174696f6e20417574686f7269747931133011060355040a0c0a4170706c6520496e632e310b3009060355040613025553020816634c8b0e305717300b0609608648016503040201a08193301806092a864886f70d010903310b06092a864886f70d010701301c06092a864886f70d010905310f170d3234303732333134303332395a302806092a864886f70d010934311b3019300b0609608648016503040201a10a06082a8648ce3d040302302f06092a864886f70d01090431220420b8b2688d17da2a59fe8f951f6b12a68d0a985eff11e908a3aad7104d6f5125dc300a06082a8648ce3d0403020447304502210082190f7a78e98aad3254aff0ecb8a15090aeec33f382e84e79f9cde054f40d94022050a13095afe1346d8bed6759d54076b38f1131ac70b4332306c70ff151692ea0000000000000",
"operational_analytics_identifier": "Apple pay:E43BADB7A30AB6630A49626B7181746F79AF44AE982581E52A78E1E2D8E126AC",
"retries": 0,
"psp_id": "E43BADB7A30AB6630A49626B7181746F79AF44AE982581E52A78E1E2D8E126AC"
},
"payment_request_data": {
"country_code": "US",
"currency_code": "USD",
"total": {
"label": "applepay",
"type": "final",
"amount": "100.00"
},
"merchant_capabilities": [
"supports3DS"
],
"supported_networks": [
"visa",
"masterCard",
"amex",
"discover"
],
"merchant_identifier": "merchant.com.noon.juspay"
},
"connector": "bankofamerica",
"delayed_session_token": false,
"sdk_next_action": {
"next_action": "confirm"
},
"connector_reference_id": null,
"connector_sdk_public_key": null,
"connector_merchant_id": null
}
]
}
```
```
{
"redirect_url": "https://google.com/success",
"currency": "USD",
"payment_methods": [
{
"payment_method": "pay_later",
"payment_method_types": [
{
"payment_method_type": "klarna",
"payment_experience": [
{
"payment_experience_type": "redirect_to_url",
"eligible_connectors": [
"bankofamerica"
]
}
],
"card_networks": null,
"bank_names": null,
"bank_debits": null,
"bank_transfers": null,
"required_fields": null,
"surcharge_details": null,
"pm_auth_connector": null
},
{
"payment_method_type": "afterpay_clearpay",
"payment_experience": [
{
"payment_experience_type": "redirect_to_url",
"eligible_connectors": [
"bankofamerica"
]
}
],
"card_networks": null,
"bank_names": null,
"bank_debits": null,
"bank_transfers": null,
"required_fields": null,
"surcharge_details": null,
"pm_auth_connector": null
},
{
"payment_method_type": "affirm",
"payment_experience": [
{
"payment_experience_type": "redirect_to_url",
"eligible_connectors": [
"bankofamerica"
]
}
],
"card_networks": null,
"bank_names": null,
"bank_debits": null,
"bank_transfers": null,
"required_fields": null,
"surcharge_details": null,
"pm_auth_connector": null
}
]
},
{
"payment_method": "wallet",
"payment_method_types": [
{
"payment_method_type": "paypal",
"payment_experience": [
{
"payment_experience_type": "redirect_to_url",
"eligible_connectors": [
"bankofamerica"
]
}
],
"card_networks": null,
"bank_names": null,
"bank_debits": null,
"bank_transfers": null,
"required_fields": null,
"surcharge_details": null,
"pm_auth_connector": null
},
{
"payment_method_type": "apple_pay",
"payment_experience": [
{
"payment_experience_type": "invoke_sdk_client",
"eligible_connectors": [
"bankofamerica"
]
}
],
"card_networks": null,
"bank_names": null,
"bank_debits": null,
"bank_transfers": null,
"required_fields": {
"billing.address.first_name": {
"required_field": "payment_method_data.billing.address.first_name",
"display_name": "billing_first_name",
"field_type": "user_billing_name",
"value": null
},
"shipping.address.line1": {
"required_field": "shipping.address.line1",
"display_name": "line1",
"field_type": "user_shipping_address_line1",
"value": null
},
"billing.address.line1": {
"required_field": "payment_method_data.billing.address.line1",
"display_name": "line1",
"field_type": "user_address_line1",
"value": null
},
"billing.address.state": {
"required_field": "payment_method_data.billing.address.state",
"display_name": "state",
"field_type": "user_address_state",
"value": null
},
"shipping.address.city": {
"required_field": "shipping.address.city",
"display_name": "city",
"field_type": "user_shipping_address_city",
"value": null
},
"email": {
"required_field": "email",
"display_name": "email",
"field_type": "user_email_address",
"value": null
},
"billing.address.country": {
"required_field": "payment_method_data.billing.address.country",
"display_name": "country",
"field_type": {
"user_address_country": {
"options": [
"ALL"
]
}
},
"value": null
},
"shipping.address.last_name": {
"required_field": "shipping.address.last_name",
"display_name": "shipping_last_name",
"field_type": "user_shipping_name",
"value": null
},
"shipping.address.zip": {
"required_field": "shipping.address.zip",
"display_name": "zip",
"field_type": "user_shipping_address_pincode",
"value": null
},
"billing.address.last_name": {
"required_field": "payment_method_data.billing.address.last_name",
"display_name": "billing_last_name",
"field_type": "user_billing_name",
"value": null
},
"shipping.address.first_name": {
"required_field": "shipping.address.first_name",
"display_name": "shipping_first_name",
"field_type": "user_shipping_name",
"value": null
},
"billing.address.city": {
"required_field": "payment_method_data.billing.address.city",
"display_name": "city",
"field_type": "user_address_city",
"value": null
},
"shipping.address.country": {
"required_field": "shipping.address.country",
"display_name": "country",
"field_type": {
"user_shipping_address_country": {
"options": [
"ALL"
]
}
},
"value": null
},
"billing.address.zip": {
"required_field": "payment_method_data.billing.address.zip",
"display_name": "zip",
"field_type": "user_address_pincode",
"value": null
},
"shipping.address.state": {
"required_field": "shipping.address.state",
"display_name": "state",
"field_type": "user_shipping_address_state",
"value": null
}
},
"surcharge_details": null,
"pm_auth_connector": null
},
{
"payment_method_type": "google_pay",
"payment_experience": [
{
"payment_experience_type": "invoke_sdk_client",
"eligible_connectors": [
"bankofamerica"
]
}
],
"card_networks": null,
"bank_names": null,
"bank_debits": null,
"bank_transfers": null,
"required_fields": {
"billing.address.first_name": {
"required_field": "payment_method_data.billing.address.first_name",
"display_name": "billing_first_name",
"field_type": "user_billing_name",
"value": null
},
"billing.address.country": {
"required_field": "payment_method_data.billing.address.country",
"display_name": "country",
"field_type": {
"user_address_country": {
"options": [
"ALL"
]
}
},
"value": null
},
"billing.address.state": {
"required_field": "payment_method_data.billing.address.state",
"display_name": "state",
"field_type": "user_address_state",
"value": null
},
"email": {
"required_field": "email",
"display_name": "email",
"field_type": "user_email_address",
"value": null
},
"billing.address.line1": {
"required_field": "payment_method_data.billing.address.line1",
"display_name": "line1",
"field_type": "user_address_line1",
"value": null
},
"billing.address.city": {
"required_field": "payment_method_data.billing.address.city",
"display_name": "city",
"field_type": "user_address_city",
"value": null
},
"billing.address.zip": {
"required_field": "payment_method_data.billing.address.zip",
"display_name": "zip",
"field_type": "user_address_pincode",
"value": null
},
"billing.address.last_name": {
"required_field": "payment_method_data.billing.address.last_name",
"display_name": "billing_last_name",
"field_type": "user_billing_name",
"value": null
}
},
"surcharge_details": null,
"pm_auth_connector": null
}
]
},
{
"payment_method": "card",
"payment_method_types": [
{
"payment_method_type": "debit",
"payment_experience": null,
"card_networks": [
{
"card_network": "Visa",
"surcharge_details": null,
"eligible_connectors": [
"bankofamerica"
]
},
{
"card_network": "Mastercard",
"surcharge_details": null,
"eligible_connectors": [
"bankofamerica"
]
}
],
"bank_names": null,
"bank_debits": null,
"bank_transfers": null,
"required_fields": {
"billing.address.city": {
"required_field": "payment_method_data.billing.address.city",
"display_name": "city",
"field_type": "user_address_city",
"value": null
},
"billing.address.country": {
"required_field": "payment_method_data.billing.address.country",
"display_name": "country",
"field_type": {
"user_address_country": {
"options": [
"ALL"
]
}
},
"value": null
},
"billing.address.last_name": {
"required_field": "payment_method_data.billing.address.last_name",
"display_name": "card_holder_name",
"field_type": "user_full_name",
"value": null
},
"payment_method_data.card.card_number": {
"required_field": "payment_method_data.card.card_number",
"display_name": "card_number",
"field_type": "user_card_number",
"value": null
},
"billing.address.line1": {
"required_field": "payment_method_data.billing.address.line1",
"display_name": "line1",
"field_type": "user_address_line1",
"value": null
},
"billing.address.first_name": {
"required_field": "payment_method_data.billing.address.first_name",
"display_name": "card_holder_name",
"field_type": "user_full_name",
"value": null
},
"payment_method_data.card.card_cvc": {
"required_field": "payment_method_data.card.card_cvc",
"display_name": "card_cvc",
"field_type": "user_card_cvc",
"value": null
},
"billing.address.state": {
"required_field": "payment_method_data.billing.address.state",
"display_name": "state",
"field_type": "user_address_state",
"value": null
},
"billing.address.zip": {
"required_field": "payment_method_data.billing.address.zip",
"display_name": "zip",
"field_type": "user_address_pincode",
"value": null
},
"email": {
"required_field": "email",
"display_name": "email",
"field_type": "user_email_address",
"value": null
},
"payment_method_data.card.card_exp_year": {
"required_field": "payment_method_data.card.card_exp_year",
"display_name": "card_exp_year",
"field_type": "user_card_expiry_year",
"value": null
},
"payment_method_data.card.card_exp_month": {
"required_field": "payment_method_data.card.card_exp_month",
"display_name": "card_exp_month",
"field_type": "user_card_expiry_month",
"value": null
}
},
"surcharge_details": null,
"pm_auth_connector": null
},
{
"payment_method_type": "credit",
"payment_experience": null,
"card_networks": [
{
"card_network": "Mastercard",
"surcharge_details": null,
"eligible_connectors": [
"bankofamerica"
]
},
{
"card_network": "Visa",
"surcharge_details": null,
"eligible_connectors": [
"bankofamerica"
]
}
],
"bank_names": null,
"bank_debits": null,
"bank_transfers": null,
"required_fields": {
"billing.address.zip": {
"required_field": "payment_method_data.billing.address.zip",
"display_name": "zip",
"field_type": "user_address_pincode",
"value": null
},
"payment_method_data.card.card_exp_year": {
"required_field": "payment_method_data.card.card_exp_year",
"display_name": "card_exp_year",
"field_type": "user_card_expiry_year",
"value": null
},
"billing.address.first_name": {
"required_field": "payment_method_data.billing.address.first_name",
"display_name": "card_holder_name",
"field_type": "user_full_name",
"value": null
},
"billing.address.country": {
"required_field": "payment_method_data.billing.address.country",
"display_name": "country",
"field_type": {
"user_address_country": {
"options": [
"ALL"
]
}
},
"value": null
},
"billing.address.state": {
"required_field": "payment_method_data.billing.address.state",
"display_name": "state",
"field_type": "user_address_state",
"value": null
},
"payment_method_data.card.card_exp_month": {
"required_field": "payment_method_data.card.card_exp_month",
"display_name": "card_exp_month",
"field_type": "user_card_expiry_month",
"value": null
},
"billing.address.line1": {
"required_field": "payment_method_data.billing.address.line1",
"display_name": "line1",
"field_type": "user_address_line1",
"value": null
},
"billing.address.city": {
"required_field": "payment_method_data.billing.address.city",
"display_name": "city",
"field_type": "user_address_city",
"value": null
},
"email": {
"required_field": "email",
"display_name": "email",
"field_type": "user_email_address",
"value": null
},
"payment_method_data.card.card_cvc": {
"required_field": "payment_method_data.card.card_cvc",
"display_name": "card_cvc",
"field_type": "user_card_cvc",
"value": null
},
"billing.address.last_name": {
"required_field": "payment_method_data.billing.address.last_name",
"display_name": "card_holder_name",
"field_type": "user_full_name",
"value": null
},
"payment_method_data.card.card_number": {
"required_field": "payment_method_data.card.card_number",
"display_name": "card_number",
"field_type": "user_card_number",
"value": null
}
},
"surcharge_details": null,
"pm_auth_connector": null
}
]
}
],
"mandate_payment": null,
"merchant_name": "NewAge Retailer",
"show_surcharge_breakup_screen": false,
"payment_type": "normal",
"request_external_three_ds_authentication": false,
"collect_shipping_details_from_wallets": false,
"collect_billing_details_from_wallets": false
}
```
### Test case 2
```
curl --location 'http://localhost:8080/account/merchant_1721744553/business_profile/pro_UbvlkhzFe49CKOC2Cp6A' \
--header 'Content-Type: application/json' \
--header 'Accept: application/json' \
--header 'api-key: test_admin' \
--data '{
"collect_shipping_details_from_wallet_connector": false,
"collect_billing_details_from_wallet_connector": false,
"always_collect_shipping_details_from_wallet_connector": true,
"always_collect_billing_details_from_wallet_connector": true,
"is_connector_agnostic_mit_enabled": false
}'
```
```
{
"merchant_id": "merchant_1721744553",
"profile_id": "pro_UbvlkhzFe49CKOC2Cp6A",
"profile_name": "US_default",
"return_url": "https://google.com/success",
"enable_payment_response_hash": true,
"payment_response_hash_key": "VcvWuegeCGmK3fPk1Wy9mkkGtYxXgbrtzr4CEbPkMcrgDaD4ULbxxGTvSNf1ZIuE",
"redirect_to_merchant_with_http_post": false,
"webhook_details": {
"webhook_version": "1.0.1",
"webhook_username": "ekart_retail",
"webhook_password": "password_ekart@123",
"webhook_url": null,
"payment_created_enabled": true,
"payment_succeeded_enabled": true,
"payment_failed_enabled": true
},
"metadata": null,
"routing_algorithm": {
"algorithm_id": null,
"timestamp": 0
},
"intent_fulfillment_time": 900,
"frm_routing_algorithm": null,
"payout_routing_algorithm": null,
"applepay_verified_domains": null,
"session_expiry": 900,
"payment_link_config": null,
"authentication_connector_details": null,
"use_billing_as_payment_method_billing": true,
"extended_card_info_config": null,
"collect_shipping_details_from_wallet_connector": false,
"collect_billing_details_from_wallet_connector": false,
"always_collect_shipping_details_from_wallet_connector": true,
"always_collect_billing_details_from_wallet_connector": true,
"is_connector_agnostic_mit_enabled": false,
"payout_link_config": null,
"outgoing_webhook_custom_http_headers": null
}
```
```
curl --location 'http://localhost:8080/payments' \
--header 'Content-Type: application/json' \
--header 'Accept: application/json' \
--header 'api-key: dev_dL6Ns79GbmbVgvowsPH5ih58Yq0HsUUW4DNk1Uot6U1VgdViqIHKddecSjs1WK6J' \
--data '{
"amount": 10000,
"currency": "USD",
"capture_method": "automatic",
"authentication_type": "no_three_ds",
"confirm": false,
"customer_id": "cu_1721237981"
}'
```
```
{
"payment_id": "pay_wtUNM2Q9VsQRgh1gmzRS",
"merchant_id": "merchant_1721743299",
"status": "requires_payment_method",
"amount": 10000,
"net_amount": 10000,
"amount_capturable": 0,
"amount_received": null,
"connector": null,
"client_secret": "pay_wtUNM2Q9VsQRgh1gmzRS_secret_ZQbTBMQpjkfM2UU1XtW6",
"created": "2024-07-23T14:09:06.140Z",
"currency": "USD",
"customer_id": "cu_1721237981",
"customer": {
"id": "cu_1721237981",
"name": null,
"email": null,
"phone": null,
"phone_country_code": null
},
"description": null,
"refunds": null,
"disputes": null,
"mandate_id": null,
"mandate_data": null,
"setup_future_usage": null,
"off_session": null,
"capture_on": null,
"capture_method": "automatic",
"payment_method": null,
"payment_method_data": null,
"payment_token": null,
"shipping": null,
"billing": null,
"order_details": null,
"email": null,
"name": null,
"phone": null,
"return_url": null,
"authentication_type": "no_three_ds",
"statement_descriptor_name": null,
"statement_descriptor_suffix": null,
"next_action": null,
"cancellation_reason": null,
"error_code": null,
"error_message": null,
"unified_code": null,
"unified_message": null,
"payment_experience": null,
"payment_method_type": null,
"connector_label": null,
"business_country": null,
"business_label": "default",
"business_sub_label": null,
"allowed_payment_method_types": null,
"ephemeral_key": {
"customer_id": "cu_1721237981",
"created_at": 1721743746,
"expires": 1721747346,
"secret": "epk_4cdfcb3480614ee6a18924a90581c293"
},
"manual_retry_allowed": null,
"connector_transaction_id": null,
"frm_message": null,
"metadata": null,
"connector_metadata": null,
"feature_metadata": null,
"reference_id": null,
"payment_link": null,
"profile_id": "pro_6HWsZd9W2UzInY0YWvjG",
"surcharge_details": null,
"attempt_count": 1,
"merchant_decision": null,
"merchant_connector_id": null,
"incremental_authorization_allowed": null,
"authorization_count": null,
"incremental_authorizations": null,
"external_authentication_details": null,
"external_3ds_authentication_attempted": false,
"expires_on": "2024-07-23T14:24:06.140Z",
"fingerprint": null,
"browser_info": null,
"payment_method_id": null,
"payment_method_status": null,
"updated": "2024-07-23T14:09:06.157Z",
"charges": null,
"frm_metadata": null,
"merchant_order_reference_id": null
}
```
-> Session call
```
curl --location 'http://localhost:8080/payments/session_tokens' \
--header 'Content-Type: application/json' \
--header 'x-merchant-domain: sdk-test-app.netlify.app' \
--header 'api-key: pk_dev_6b6f32cb55244ccb83ef922d20826d91' \
--data '{
"payment_id": "pay_AVV9EBPUwiDrIYMDlC4a",
"wallets": [],
"client_secret": "pay_AVV9EBPUwiDrIYMDlC4a_secret_MZQmLy9CUO3ipa7p2HgW"
}'
```
```
{
"payment_id": "pay_AVV9EBPUwiDrIYMDlC4a",
"client_secret": "pay_AVV9EBPUwiDrIYMDlC4a_secret_MZQmLy9CUO3ipa7p2HgW",
"session_token": [
{
"wallet_name": "google_pay",
"merchant_info": {
"merchant_name": "Stripe"
},
"shipping_address_required": true,
"email_required": true,
"shipping_address_parameters": {
"phone_number_required": true
},
"allowed_payment_methods": [
{
"type": "CARD",
"parameters": {
"allowed_auth_methods": [
"PAN_ONLY",
"CRYPTOGRAM_3DS"
],
"allowed_card_networks": [
"AMEX",
"DISCOVER",
"INTERAC",
"JCB",
"MASTERCARD",
"VISA"
],
"billing_address_required": true,
"billing_address_parameters": {
"phone_number_required": true,
"format": "FULL"
}
},
"tokenization_specification": {
"type": "PAYMENT_GATEWAY",
"parameters": {
"gateway": "stripe",
"stripe:version": "2018-10-31",
"stripe:publishableKey": "pk_test_51Msk2GAGHc77EJXX78h549SX2uaOnEkUYqBfjcoD05PIpAnDkYxMn8nQ4d19im85NQuX4Z6WDyHaUw2fFTPBWsIY00Wa7oNerO"
}
}
}
],
"transaction_info": {
"country_code": "US",
"currency_code": "USD",
"total_price_status": "Final",
"total_price": "100.00"
},
"delayed_session_token": false,
"connector": "cybersource",
"sdk_next_action": {
"next_action": "confirm"
},
"secrets": null
},
{
"wallet_name": "apple_pay",
"session_token_data": {
"epoch_timestamp": 1721744742767,
"expires_at": 1721748342767,
"merchant_session_identifier": "SSHB08C98B29BE949C98D803024EABF86D6_7E0DD1295E42A30B376B18CB4E6B9B9FB4C5E36B3EDF9FB0DEA51F9419420173",
"nonce": "763e0341",
"merchant_identifier": "76B79A8E91F4D365B0B636C8F75CB207D52532E82C2C085DE79D6D8135EF3813",
"domain_name": "sdk-test-app.netlify.app",
"display_name": "applepay",
"signature": "308006092a864886f70d010702a0803080020101310d300b0609608648016503040201308006092a864886f70d0107010000a080308203e330820388a003020102020816634c8b0e305717300a06082a8648ce3d040302307a312e302c06035504030c254170706c65204170706c69636174696f6e20496e746567726174696f6e204341202d20473331263024060355040b0c1d4170706c652043657274696669636174696f6e20417574686f7269747931133011060355040a0c0a4170706c6520496e632e310b3009060355040613025553301e170d3234303432393137343732375a170d3239303432383137343732365a305f3125302306035504030c1c6563632d736d702d62726f6b65722d7369676e5f5543342d50524f4431143012060355040b0c0b694f532053797374656d7331133011060355040a0c0a4170706c6520496e632e310b30090603550406130255533059301306072a8648ce3d020106082a8648ce3d03010703420004c21577edebd6c7b2218f68dd7090a1218dc7b0bd6f2c283d846095d94af4a5411b83420ed811f3407e83331f1c54c3f7eb3220d6bad5d4eff49289893e7c0f13a38202113082020d300c0603551d130101ff04023000301f0603551d2304183016801423f249c44f93e4ef27e6c4f6286c3fa2bbfd2e4b304506082b0601050507010104393037303506082b060105050730018629687474703a2f2f6f6373702e6170706c652e636f6d2f6f63737030342d6170706c65616963613330323082011d0603551d2004820114308201103082010c06092a864886f7636405013081fe3081c306082b060105050702023081b60c81b352656c69616e6365206f6e207468697320636572746966696361746520627920616e7920706172747920617373756d657320616363657074616e6365206f6620746865207468656e206170706c696361626c65207374616e64617264207465726d7320616e6420636f6e646974696f6e73206f66207573652c20636572746966696361746520706f6c69637920616e642063657274696669636174696f6e2070726163746963652073746174656d656e74732e303606082b06010505070201162a687474703a2f2f7777772e6170706c652e636f6d2f6365727469666963617465617574686f726974792f30340603551d1f042d302b3029a027a0258623687474703a2f2f63726c2e6170706c652e636f6d2f6170706c6561696361332e63726c301d0603551d0e041604149457db6fd57481868989762f7e578507e79b5824300e0603551d0f0101ff040403020780300f06092a864886f76364061d04020500300a06082a8648ce3d0403020349003046022100c6f023cb2614bb303888a162983e1a93f1056f50fa78cdb9ba4ca241cc14e25e022100be3cd0dfd16247f6494475380e9d44c228a10890a3a1dc724b8b4cb8889818bc308202ee30820275a0030201020208496d2fbf3a98da97300a06082a8648ce3d0403023067311b301906035504030c124170706c6520526f6f74204341202d20473331263024060355040b0c1d4170706c652043657274696669636174696f6e20417574686f7269747931133011060355040a0c0a4170706c6520496e632e310b3009060355040613025553301e170d3134303530363233343633305a170d3239303530363233343633305a307a312e302c06035504030c254170706c65204170706c69636174696f6e20496e746567726174696f6e204341202d20473331263024060355040b0c1d4170706c652043657274696669636174696f6e20417574686f7269747931133011060355040a0c0a4170706c6520496e632e310b30090603550406130255533059301306072a8648ce3d020106082a8648ce3d03010703420004f017118419d76485d51a5e25810776e880a2efde7bae4de08dfc4b93e13356d5665b35ae22d097760d224e7bba08fd7617ce88cb76bb6670bec8e82984ff5445a381f73081f4304606082b06010505070101043a3038303606082b06010505073001862a687474703a2f2f6f6373702e6170706c652e636f6d2f6f63737030342d6170706c65726f6f7463616733301d0603551d0e0416041423f249c44f93e4ef27e6c4f6286c3fa2bbfd2e4b300f0603551d130101ff040530030101ff301f0603551d23041830168014bbb0dea15833889aa48a99debebdebafdacb24ab30370603551d1f0430302e302ca02aa0288626687474703a2f2f63726c2e6170706c652e636f6d2f6170706c65726f6f74636167332e63726c300e0603551d0f0101ff0404030201063010060a2a864886f7636406020e04020500300a06082a8648ce3d040302036700306402303acf7283511699b186fb35c356ca62bff417edd90f754da28ebef19c815e42b789f898f79b599f98d5410d8f9de9c2fe0230322dd54421b0a305776c5df3383b9067fd177c2c216d964fc6726982126f54f87a7d1b99cb9b0989216106990f09921d00003182018730820183020101308186307a312e302c06035504030c254170706c65204170706c69636174696f6e20496e746567726174696f6e204341202d20473331263024060355040b0c1d4170706c652043657274696669636174696f6e20417574686f7269747931133011060355040a0c0a4170706c6520496e632e310b3009060355040613025553020816634c8b0e305717300b0609608648016503040201a08193301806092a864886f70d010903310b06092a864886f70d010701301c06092a864886f70d010905310f170d3234303732333134323534325a302806092a864886f70d010934311b3019300b0609608648016503040201a10a06082a8648ce3d040302302f06092a864886f70d01090431220420c286a5e158cf0da5837c92848f8fca0d6ca30d544d80ffdf0d45801a6a3462ab300a06082a8648ce3d040302044630440220395f134c29d0952b378978c0ee8e6b38da7bb494526e050c997ed58f61413a9502200cf5f04dcf6e951ffc88dd20d0146c53b8fc0dea40cfa598ae653839fcb55776000000000000",
"operational_analytics_identifier": "applepay:76B79A8E91F4D365B0B636C8F75CB207D52532E82C2C085DE79D6D8135EF3813",
"retries": 0,
"psp_id": "76B79A8E91F4D365B0B636C8F75CB207D52532E82C2C085DE79D6D8135EF3813"
},
"payment_request_data": {
"country_code": "US",
"currency_code": "USD",
"total": {
"label": "applepay",
"type": "final",
"amount": "100.00"
},
"merchant_capabilities": [
"supports3DS"
],
"supported_networks": [
"visa",
"masterCard",
"amex",
"discover"
],
"merchant_identifier": "merchant.com.hyperswitch.checkout",
"required_billing_contact_fields": [
"postalAddress"
],
"required_shipping_contact_fields": [
"postalAddress",
"phone",
"email"
]
},
"connector": "cybersource",
"delayed_session_token": false,
"sdk_next_action": {
"next_action": "confirm"
},
"connector_reference_id": null,
"connector_sdk_public_key": null,
"connector_merchant_id": null
}
]
}
```
-> Pml list
```
curl --location 'http://localhost:8080/account/payment_methods?client_secret=pay_AVV9EBPUwiDrIYMDlC4a_secret_MZQmLy9CUO3ipa7p2HgW' \
--header 'Accept: application/json' \
--header 'api-key: pk_dev_6b6f32cb55244ccb83ef922d20826d91'
```
```
{
"redirect_url": "https://google.com/success",
"currency": "USD",
"payment_methods": [
{
"payment_method": "pay_later",
"payment_method_types": [
{
"payment_method_type": "klarna",
"payment_experience": [
{
"payment_experience_type": "redirect_to_url",
"eligible_connectors": [
"cybersource"
]
},
{
"payment_experience_type": "invoke_sdk_client",
"eligible_connectors": [
"cybersource"
]
}
],
"card_networks": null,
"bank_names": null,
"bank_debits": null,
"bank_transfers": null,
"required_fields": null,
"surcharge_details": null,
"pm_auth_connector": null
}
]
},
{
"payment_method": "wallet",
"payment_method_types": [
{
"payment_method_type": "apple_pay",
"payment_experience": [
{
"payment_experience_type": "invoke_sdk_client",
"eligible_connectors": [
"cybersource"
]
}
],
"card_networks": null,
"bank_names": null,
"bank_debits": null,
"bank_transfers": null,
"required_fields": {
"shipping.address.first_name": {
"required_field": "shipping.address.first_name",
"display_name": "shipping_first_name",
"field_type": "user_shipping_name",
"value": null
},
"shipping.address.zip": {
"required_field": "shipping.address.zip",
"display_name": "zip",
"field_type": "user_shipping_address_pincode",
"value": null
},
"shipping.address.city": {
"required_field": "shipping.address.city",
"display_name": "city",
"field_type": "user_shipping_address_city",
"value": null
},
"email": {
"required_field": "email",
"display_name": "email",
"field_type": "user_email_address",
"value": null
},
"shipping.address.line1": {
"required_field": "shipping.address.line1",
"display_name": "line1",
"field_type": "user_shipping_address_line1",
"value": null
},
"billing.address.last_name": {
"required_field": "payment_method_data.billing.address.last_name",
"display_name": "billing_last_name",
"field_type": "user_billing_name",
"value": null
},
"billing.address.line1": {
"required_field": "payment_method_data.billing.address.line1",
"display_name": "line1",
"field_type": "user_address_line1",
"value": null
},
"billing.address.city": {
"required_field": "payment_method_data.billing.address.city",
"display_name": "city",
"field_type": "user_address_city",
"value": null
},
"shipping.address.last_name": {
"required_field": "shipping.address.last_name",
"display_name": "shipping_last_name",
"field_type": "user_shipping_name",
"value": null
},
"billing.address.line2": {
"required_field": "payment_method_data.billing.address.line2",
"display_name": "line2",
"field_type": "user_address_line2",
"value": null
},
"shipping.address.country": {
"required_field": "shipping.address.country",
"display_name": "country",
"field_type": {
"user_shipping_address_country": {
"options": [
"ALL"
]
}
},
"value": null
},
"shipping.address.state": {
"required_field": "shipping.address.state",
"display_name": "state",
"field_type": "user_shipping_address_state",
"value": null
},
"billing.address.zip": {
"required_field": "payment_method_data.billing.address.zip",
"display_name": "zip",
"field_type": "user_address_pincode",
"value": null
},
"billing.address.first_name": {
"required_field": "payment_method_data.billing.address.first_name",
"display_name": "billing_first_name",
"field_type": "user_billing_name",
"value": null
},
"billing.address.country": {
"required_field": "payment_method_data.billing.address.country",
"display_name": "country",
"field_type": {
"user_address_country": {
"options": [
"ALL"
]
}
},
"value": null
},
"billing.address.state": {
"required_field": "payment_method_data.billing.address.state",
"display_name": "state",
"field_type": "user_address_state",
"value": null
}
},
"surcharge_details": null,
"pm_auth_connector": null
},
{
"payment_method_type": "paypal",
"payment_experience": [
{
"payment_experience_type": "redirect_to_url",
"eligible_connectors": [
"cybersource"
]
}
],
"card_networks": null,
"bank_names": null,
"bank_debits": null,
"bank_transfers": null,
"required_fields": null,
"surcharge_details": null,
"pm_auth_connector": null
},
{
"payment_method_type": "google_pay",
"payment_experience": [
{
"payment_experience_type": "invoke_sdk_client",
"eligible_connectors": [
"cybersource"
]
}
],
"card_networks": null,
"bank_names": null,
"bank_debits": null,
"bank_transfers": null,
"required_fields": {
"shipping.address.state": {
"required_field": "shipping.address.state",
"display_name": "state",
"field_type": "user_shipping_address_state",
"value": null
},
"billing.address.line1": {
"required_field": "payment_method_data.billing.address.line1",
"display_name": "line1",
"field_type": "user_address_line1",
"value": null
},
"email": {
"required_field": "email",
"display_name": "email",
"field_type": "user_email_address",
"value": null
},
"shipping.address.city": {
"required_field": "shipping.address.city",
"display_name": "city",
"field_type": "user_shipping_address_city",
"value": null
},
"shipping.address.country": {
"required_field": "shipping.address.country",
"display_name": "country",
"field_type": {
"user_shipping_address_country": {
"options": [
"ALL"
]
}
},
"value": null
},
"billing.address.country": {
"required_field": "payment_method_data.billing.address.country",
"display_name": "country",
"field_type": {
"user_address_country": {
"options": [
"ALL"
]
}
},
"value": null
},
"billing.address.city": {
"required_field": "payment_method_data.billing.address.city",
"display_name": "city",
"field_type": "user_address_city",
"value": null
},
"billing.address.zip": {
"required_field": "payment_method_data.billing.address.zip",
"display_name": "zip",
"field_type": "user_address_pincode",
"value": null
},
"shipping.address.line1": {
"required_field": "shipping.address.line1",
"display_name": "line1",
"field_type": "user_shipping_address_line1",
"value": null
},
"billing.address.line2": {
"required_field": "payment_method_data.billing.address.line2",
"display_name": "line2",
"field_type": "user_address_line2",
"value": null
},
"billing.address.state": {
"required_field": "payment_method_data.billing.address.state",
"display_name": "state",
"field_type": "user_address_state",
"value": null
},
"shipping.address.first_name": {
"required_field": "shipping.address.first_name",
"display_name": "shipping_first_name",
"field_type": "user_shipping_name",
"value": null
},
"shipping.address.zip": {
"required_field": "shipping.address.zip",
"display_name": "zip",
"field_type": "user_shipping_address_pincode",
"value": null
},
"billing.address.first_name": {
"required_field": "payment_method_data.billing.address.first_name",
"display_name": "billing_first_name",
"field_type": "user_billing_name",
"value": null
},
"billing.address.last_name": {
"required_field": "payment_method_data.billing.address.last_name",
"display_name": "billing_last_name",
"field_type": "user_billing_name",
"value": null
},
"shipping.address.last_name": {
"required_field": "shipping.address.last_name",
"display_name": "shipping_last_name",
"field_type": "user_shipping_name",
"value": null
}
},
"surcharge_details": null,
"pm_auth_connector": null
}
]
},
{
"payment_method": "card",
"payment_method_types": [
{
"payment_method_type": "credit",
"payment_experience": null,
"card_networks": [
{
"card_network": "Visa",
"surcharge_details": null,
"eligible_connectors": [
"cybersource"
]
},
{
"card_network": "Discover",
"surcharge_details": null,
"eligible_connectors": [
"cybersource"
]
},
{
"card_network": "DinersClub",
"surcharge_details": null,
"eligible_connectors": [
"cybersource"
]
},
{
"card_network": "Mastercard",
"surcharge_details": null,
"eligible_connectors": [
"cybersource"
]
}
],
"bank_names": null,
"bank_debits": null,
"bank_transfers": null,
"required_fields": {
"billing.address.city": {
"required_field": "payment_method_data.billing.address.city",
"display_name": "city",
"field_type": "user_address_city",
"value": null
},
"billing.address.country": {
"required_field": "payment_method_data.billing.address.country",
"display_name": "country",
"field_type": {
"user_address_country": {
"options": [
"ALL"
]
}
},
"value": null
},
"shipping.address.zip": {
"required_field": "shipping.address.zip",
"display_name": "zip",
"field_type": "user_shipping_address_pincode",
"value": null
},
"email": {
"required_field": "email",
"display_name": "email",
"field_type": "user_email_address",
"value": null
},
"billing.address.line1": {
"required_field": "payment_method_data.billing.address.line1",
"display_name": "line1",
"field_type": "user_address_line1",
"value": null
},
"shipping.address.city": {
"required_field": "shipping.address.city",
"display_name": "city",
"field_type": "user_shipping_address_city",
"value": null
},
"payment_method_data.card.card_exp_year": {
"required_field": "payment_method_data.card.card_exp_year",
"display_name": "card_exp_year",
"field_type": "user_card_expiry_year",
"value": null
},
"billing.address.line2": {
"required_field": "payment_method_data.billing.address.line2",
"display_name": "line2",
"field_type": "user_address_line2",
"value": null
},
"billing.address.zip": {
"required_field": "payment_method_data.billing.address.zip",
"display_name": "zip",
"field_type": "user_address_pincode",
"value": null
},
"shipping.address.last_name": {
"required_field": "shipping.address.last_name",
"display_name": "shipping_last_name",
"field_type": "user_shipping_name",
"value": null
},
"shipping.address.country": {
"required_field": "shipping.address.country",
"display_name": "country",
"field_type": {
"user_shipping_address_country": {
"options": [
"ALL"
]
}
},
"value": null
},
"billing.address.first_name": {
"required_field": "payment_method_data.billing.address.first_name",
"display_name": "billing_first_name",
"field_type": "user_billing_name",
"value": null
},
"payment_method_data.card.card_exp_month": {
"required_field": "payment_method_data.card.card_exp_month",
"display_name": "card_exp_month",
"field_type": "user_card_expiry_month",
"value": null
},
"billing.address.state": {
"required_field": "payment_method_data.billing.address.state",
"display_name": "state",
"field_type": "user_address_state",
"value": null
},
"shipping.address.state": {
"required_field": "shipping.address.state",
"display_name": "state",
"field_type": "user_shipping_address_state",
"value": null
},
"shipping.address.line1": {
"required_field": "shipping.address.line1",
"display_name": "line1",
"field_type": "user_shipping_address_line1",
"value": null
},
"payment_method_data.card.card_number": {
"required_field": "payment_method_data.card.card_number",
"display_name": "card_number",
"field_type": "user_card_number",
"value": null
},
"shipping.address.first_name": {
"required_field": "shipping.address.first_name",
"display_name": "shipping_first_name",
"field_type": "user_shipping_name",
"value": null
},
"billing.address.last_name": {
"required_field": "payment_method_data.billing.address.last_name",
"display_name": "billing_last_name",
"field_type": "user_billing_name",
"value": null
},
"payment_method_data.card.card_cvc": {
"required_field": "payment_method_data.card.card_cvc",
"display_name": "card_cvc",
"field_type": "user_card_cvc",
"value": null
}
},
"surcharge_details": null,
"pm_auth_connector": null
},
{
"payment_method_type": "debit",
"payment_experience": null,
"card_networks": [
{
"card_network": "Mastercard",
"surcharge_details": null,
"eligible_connectors": [
"cybersource"
]
},
{
"card_network": "Visa",
"surcharge_details": null,
"eligible_connectors": [
"cybersource"
]
}
],
"bank_names": null,
"bank_debits": null,
"bank_transfers": null,
"required_fields": {
"payment_method_data.card.card_exp_year": {
"required_field": "payment_method_data.card.card_exp_year",
"display_name": "card_exp_year",
"field_type": "user_card_expiry_year",
"value": null
},
"billing.address.last_name": {
"required_field": "payment_method_data.billing.address.last_name",
"display_name": "billing_last_name",
"field_type": "user_billing_name",
"value": null
},
"shipping.address.state": {
"required_field": "shipping.address.state",
"display_name": "state",
"field_type": "user_shipping_address_state",
"value": null
},
"shipping.address.zip": {
"required_field": "shipping.address.zip",
"display_name": "zip",
"field_type": "user_shipping_address_pincode",
"value": null
},
"billing.address.state": {
"required_field": "payment_method_data.billing.address.state",
"display_name": "state",
"field_type": "user_address_state",
"value": null
},
"payment_method_data.card.card_exp_month": {
"required_field": "payment_method_data.card.card_exp_month",
"display_name": "card_exp_month",
"field_type": "user_card_expiry_month",
"value": null
},
"billing.address.line2": {
"required_field": "payment_method_data.billing.address.line2",
"display_name": "line2",
"field_type": "user_address_line2",
"value": null
},
"billing.address.first_name": {
"required_field": "payment_method_data.billing.address.first_name",
"display_name": "billing_first_name",
"field_type": "user_billing_name",
"value": null
},
"billing.address.city": {
"required_field": "payment_method_data.billing.address.city",
"display_name": "city",
"field_type": "user_address_city",
"value": null
},
"billing.address.country": {
"required_field": "payment_method_data.billing.address.country",
"display_name": "country",
"field_type": {
"user_address_country": {
"options": [
"ALL"
]
}
},
"value": null
},
"payment_method_data.card.card_number": {
"required_field": "payment_method_data.card.card_number",
"display_name": "card_number",
"field_type": "user_card_number",
"value": null
},
"shipping.address.line1": {
"required_field": "shipping.address.line1",
"display_name": "line1",
"field_type": "user_shipping_address_line1",
"value": null
},
"billing.address.line1": {
"required_field": "payment_method_data.billing.address.line1",
"display_name": "line1",
"field_type": "user_address_line1",
"value": null
},
"shipping.address.city": {
"required_field": "shipping.address.city",
"display_name": "city",
"field_type": "user_shipping_address_city",
"value": null
},
"shipping.address.first_name": {
"required_field": "shipping.address.first_name",
"display_name": "shipping_first_name",
"field_type": "user_shipping_name",
"value": null
},
"email": {
"required_field": "email",
"display_name": "email",
"field_type": "user_email_address",
"value": null
},
"payment_method_data.card.card_cvc": {
"required_field": "payment_method_data.card.card_cvc",
"display_name": "card_cvc",
"field_type": "user_card_cvc",
"value": null
},
"billing.address.zip": {
"required_field": "payment_method_data.billing.address.zip",
"display_name": "zip",
"field_type": "user_address_pincode",
"value": null
},
"shipping.address.last_name": {
"required_field": "shipping.address.last_name",
"display_name": "shipping_last_name",
"field_type": "user_shipping_name",
"value": null
},
"shipping.address.country": {
"required_field": "shipping.address.country",
"display_name": "country",
"field_type": {
"user_shipping_address_country": {
"options": [
"ALL"
]
}
},
"value": null
}
},
"surcharge_details": null,
"pm_auth_connector": null
}
]
},
{
"payment_method": "bank_debit",
"payment_method_types": [
{
"payment_method_type": "ach",
"payment_experience": null,
"card_networks": null,
"bank_names": null,
"bank_debits": {
"eligible_connectors": [
"cybersource"
]
},
"bank_transfers": null,
"required_fields": null,
"surcharge_details": null,
"pm_auth_connector": null
}
]
}
],
"mandate_payment": null,
"merchant_name": "NewAge Retailer",
"show_surcharge_breakup_screen": false,
"payment_type": "normal",
"request_external_three_ds_authentication": false,
"collect_shipping_details_from_wallets": true,
"collect_billing_details_from_wallets": true
}
```
#### Test case 3
```
curl --location 'http://localhost:8080/account/merchant_1721744553/business_profile/pro_UbvlkhzFe49CKOC2Cp6A' \
--header 'Content-Type: application/json' \
--header 'Accept: application/json' \
--header 'api-key: test_admin' \
--data '{
"collect_shipping_details_from_wallet_connector": false,
"collect_billing_details_from_wallet_connector": false,
"always_collect_shipping_details_from_wallet_connector": false,
"always_collect_billing_details_from_wallet_connector": true,
"is_connector_agnostic_mit_enabled": false
}'
```
```
{
"merchant_id": "merchant_1721744553",
"profile_id": "pro_UbvlkhzFe49CKOC2Cp6A",
"profile_name": "US_default",
"return_url": "https://google.com/success",
"enable_payment_response_hash": true,
"payment_response_hash_key": "VcvWuegeCGmK3fPk1Wy9mkkGtYxXgbrtzr4CEbPkMcrgDaD4ULbxxGTvSNf1ZIuE",
"redirect_to_merchant_with_http_post": false,
"webhook_details": {
"webhook_version": "1.0.1",
"webhook_username": "ekart_retail",
"webhook_password": "password_ekart@123",
"webhook_url": null,
"payment_created_enabled": true,
"payment_succeeded_enabled": true,
"payment_failed_enabled": true
},
"metadata": null,
"routing_algorithm": {
"algorithm_id": null,
"timestamp": 0
},
"intent_fulfillment_time": 900,
"frm_routing_algorithm": null,
"payout_routing_algorithm": null,
"applepay_verified_domains": null,
"session_expiry": 900,
"payment_link_config": null,
"authentication_connector_details": null,
"use_billing_as_payment_method_billing": true,
"extended_card_info_config": null,
"collect_shipping_details_from_wallet_connector": false,
"collect_billing_details_from_wallet_connector": false,
"always_collect_shipping_details_from_wallet_connector": false,
"always_collect_billing_details_from_wallet_connector": true,
"is_connector_agnostic_mit_enabled": false,
"payout_link_config": null,
"outgoing_webhook_custom_http_headers": null
}
```
-> Create payment with confirm false
```
curl --location 'http://localhost:8080/payments' \
--header 'Content-Type: application/json' \
--header 'Accept: application/json' \
--header 'api-key: dev_JUigpqaxc3JIsB3n6tKy1SyUqCOiwMlh8g1jhSl4ogy94UjG9cophbqUD7DNU2dc' \
--data '{
"amount": 10000,
"currency": "USD",
"capture_method": "automatic",
"authentication_type": "no_three_ds",
"confirm": false,
"customer_id": "cu_1721237981"
}'
```
-> Session call
```
curl --location 'http://localhost:8080/payments/session_tokens' \
--header 'Content-Type: application/json' \
--header 'x-merchant-domain: sdk-test-app.netlify.app' \
--header 'api-key: pk_dev_6b6f32cb55244ccb83ef922d20826d91' \
--data '{
"payment_id": "pay_6iSqUbkVLMCe92hQKlXb",
"wallets": [],
"client_secret": "pay_6iSqUbkVLMCe92hQKlXb_secret_mpvCuTcZayG421BWwvDR"
}'
```
```
{
"payment_id": "pay_6iSqUbkVLMCe92hQKlXb",
"client_secret": "pay_6iSqUbkVLMCe92hQKlXb_secret_mpvCuTcZayG421BWwvDR",
"session_token": [
{
"wallet_name": "google_pay",
"merchant_info": {
"merchant_name": "Stripe"
},
"shipping_address_required": false,
"email_required": true,
"shipping_address_parameters": {
"phone_number_required": false
},
"allowed_payment_methods": [
{
"type": "CARD",
"parameters": {
"allowed_auth_methods": [
"PAN_ONLY",
"CRYPTOGRAM_3DS"
],
"allowed_card_networks": [
"AMEX",
"DISCOVER",
"INTERAC",
"JCB",
"MASTERCARD",
"VISA"
],
"billing_address_required": true,
"billing_address_parameters": {
"phone_number_required": true,
"format": "FULL"
}
},
"tokenization_specification": {
"type": "PAYMENT_GATEWAY",
"parameters": {
"gateway": "stripe",
"stripe:version": "2018-10-31",
"stripe:publishableKey": "pk_test_51Msk2GAGHc77EJXX78h549SX2uaOnEkUYqBfjcoD05PIpAnDkYxMn8nQ4d19im85NQuX4Z6WDyHaUw2fFTPBWsIY00Wa7oNerO"
}
}
}
],
"transaction_info": {
"country_code": "US",
"currency_code": "USD",
"total_price_status": "Final",
"total_price": "100.00"
},
"delayed_session_token": false,
"connector": "cybersource",
"sdk_next_action": {
"next_action": "confirm"
},
"secrets": null
},
{
"wallet_name": "apple_pay",
"session_token_data": {
"epoch_timestamp": 1721745064490,
"expires_at": 1721748664490,
"merchant_session_identifier": "SSH8822ED4B4D484361A81AB71EF1A016D1_7E0DD1295E42A30B376B18CB4E6B9B9FB4C5E36B3EDF9FB0DEA51F9419420173",
"nonce": "90cda932",
"merchant_identifier": "76B79A8E91F4D365B0B636C8F75CB207D52532E82C2C085DE79D6D8135EF3813",
"domain_name": "sdk-test-app.netlify.app",
"display_name": "applepay",
"signature": "308006092a864886f70d010702a0803080020101310d300b0609608648016503040201308006092a864886f70d0107010000a080308203e330820388a003020102020816634c8b0e305717300a06082a8648ce3d040302307a312e302c06035504030c254170706c65204170706c69636174696f6e20496e746567726174696f6e204341202d20473331263024060355040b0c1d4170706c652043657274696669636174696f6e20417574686f7269747931133011060355040a0c0a4170706c6520496e632e310b3009060355040613025553301e170d3234303432393137343732375a170d3239303432383137343732365a305f3125302306035504030c1c6563632d736d702d62726f6b65722d7369676e5f5543342d50524f4431143012060355040b0c0b694f532053797374656d7331133011060355040a0c0a4170706c6520496e632e310b30090603550406130255533059301306072a8648ce3d020106082a8648ce3d03010703420004c21577edebd6c7b2218f68dd7090a1218dc7b0bd6f2c283d846095d94af4a5411b83420ed811f3407e83331f1c54c3f7eb3220d6bad5d4eff49289893e7c0f13a38202113082020d300c0603551d130101ff04023000301f0603551d2304183016801423f249c44f93e4ef27e6c4f6286c3fa2bbfd2e4b304506082b0601050507010104393037303506082b060105050730018629687474703a2f2f6f6373702e6170706c652e636f6d2f6f63737030342d6170706c65616963613330323082011d0603551d2004820114308201103082010c06092a864886f7636405013081fe3081c306082b060105050702023081b60c81b352656c69616e6365206f6e207468697320636572746966696361746520627920616e7920706172747920617373756d657320616363657074616e6365206f6620746865207468656e206170706c696361626c65207374616e64617264207465726d7320616e6420636f6e646974696f6e73206f66207573652c20636572746966696361746520706f6c69637920616e642063657274696669636174696f6e2070726163746963652073746174656d656e74732e303606082b06010505070201162a687474703a2f2f7777772e6170706c652e636f6d2f6365727469666963617465617574686f726974792f30340603551d1f042d302b3029a027a0258623687474703a2f2f63726c2e6170706c652e636f6d2f6170706c6561696361332e63726c301d0603551d0e041604149457db6fd57481868989762f7e578507e79b5824300e0603551d0f0101ff040403020780300f06092a864886f76364061d04020500300a06082a8648ce3d0403020349003046022100c6f023cb2614bb303888a162983e1a93f1056f50fa78cdb9ba4ca241cc14e25e022100be3cd0dfd16247f6494475380e9d44c228a10890a3a1dc724b8b4cb8889818bc308202ee30820275a0030201020208496d2fbf3a98da97300a06082a8648ce3d0403023067311b301906035504030c124170706c6520526f6f74204341202d20473331263024060355040b0c1d4170706c652043657274696669636174696f6e20417574686f7269747931133011060355040a0c0a4170706c6520496e632e310b3009060355040613025553301e170d3134303530363233343633305a170d3239303530363233343633305a307a312e302c06035504030c254170706c65204170706c69636174696f6e20496e746567726174696f6e204341202d20473331263024060355040b0c1d4170706c652043657274696669636174696f6e20417574686f7269747931133011060355040a0c0a4170706c6520496e632e310b30090603550406130255533059301306072a8648ce3d020106082a8648ce3d03010703420004f017118419d76485d51a5e25810776e880a2efde7bae4de08dfc4b93e13356d5665b35ae22d097760d224e7bba08fd7617ce88cb76bb6670bec8e82984ff5445a381f73081f4304606082b06010505070101043a3038303606082b06010505073001862a687474703a2f2f6f6373702e6170706c652e636f6d2f6f63737030342d6170706c65726f6f7463616733301d0603551d0e0416041423f249c44f93e4ef27e6c4f6286c3fa2bbfd2e4b300f0603551d130101ff040530030101ff301f0603551d23041830168014bbb0dea15833889aa48a99debebdebafdacb24ab30370603551d1f0430302e302ca02aa0288626687474703a2f2f63726c2e6170706c652e636f6d2f6170706c65726f6f74636167332e63726c300e0603551d0f0101ff0404030201063010060a2a864886f7636406020e04020500300a06082a8648ce3d040302036700306402303acf7283511699b186fb35c356ca62bff417edd90f754da28ebef19c815e42b789f898f79b599f98d5410d8f9de9c2fe0230322dd54421b0a305776c5df3383b9067fd177c2c216d964fc6726982126f54f87a7d1b99cb9b0989216106990f09921d00003182018830820184020101308186307a312e302c06035504030c254170706c65204170706c69636174696f6e20496e746567726174696f6e204341202d20473331263024060355040b0c1d4170706c652043657274696669636174696f6e20417574686f7269747931133011060355040a0c0a4170706c6520496e632e310b3009060355040613025553020816634c8b0e305717300b0609608648016503040201a08193301806092a864886f70d010903310b06092a864886f70d010701301c06092a864886f70d010905310f170d3234303732333134333130345a302806092a864886f70d010934311b3019300b0609608648016503040201a10a06082a8648ce3d040302302f06092a864886f70d01090431220420a4ea1ed1a14f7fa5230876d6645d9c0617ad16770e93acf3fc0281ad1c2d8ded300a06082a8648ce3d0403020447304502205a8cfb5be613ca26b68b23558903deec7c9cb2940fe32f2cdc0d5c7041a02d57022100a526ae63fd2837cace3e085b4f890411055f35194c9b085b02fc060052f928cc000000000000",
"operational_analytics_identifier": "applepay:76B79A8E91F4D365B0B636C8F75CB207D52532E82C2C085DE79D6D8135EF3813",
"retries": 0,
"psp_id": "76B79A8E91F4D365B0B636C8F75CB207D52532E82C2C085DE79D6D8135EF3813"
},
"payment_request_data": {
"country_code": "US",
"currency_code": "USD",
"total": {
"label": "applepay",
"type": "final",
"amount": "100.00"
},
"merchant_capabilities": [
"supports3DS"
],
"supported_networks": [
"visa",
"masterCard",
"amex",
"discover"
],
"merchant_identifier": "merchant.com.hyperswitch.checkout",
"required_billing_contact_fields": [
"postalAddress"
],
"required_shipping_contact_fields": [
"phone",
"email"
]
},
"connector": "cybersource",
"delayed_session_token": false,
"sdk_next_action": {
"next_action": "confirm"
},
"connector_reference_id": null,
"connector_sdk_public_key": null,
"connector_merchant_id": null
}
]
}
```
-> Pml
```
curl --location 'http://localhost:8080/account/payment_methods?client_secret=pay_6iSqUbkVLMCe92hQKlXb_secret_mpvCuTcZayG421BWwvDR' \
--header 'Accept: application/json' \
--header 'api-key: pk_dev_6b6f32cb55244ccb83ef922d20826d91'
```
```
{
"redirect_url": "https://google.com/success",
"currency": "USD",
"payment_methods": [
{
"payment_method": "pay_later",
"payment_method_types": [
{
"payment_method_type": "klarna",
"payment_experience": [
{
"payment_experience_type": "invoke_sdk_client",
"eligible_connectors": [
"cybersource"
]
},
{
"payment_experience_type": "redirect_to_url",
"eligible_connectors": [
"cybersource"
]
}
],
"card_networks": null,
"bank_names": null,
"bank_debits": null,
"bank_transfers": null,
"required_fields": null,
"surcharge_details": null,
"pm_auth_connector": null
}
]
},
{
"payment_method": "wallet",
"payment_method_types": [
{
"payment_method_type": "google_pay",
"payment_experience": [
{
"payment_experience_type": "invoke_sdk_client",
"eligible_connectors": [
"cybersource"
]
}
],
"card_networks": null,
"bank_names": null,
"bank_debits": null,
"bank_transfers": null,
"required_fields": {
"billing.address.country": {
"required_field": "payment_method_data.billing.address.country",
"display_name": "country",
"field_type": {
"user_address_country": {
"options": [
"ALL"
]
}
},
"value": null
},
"billing.address.city": {
"required_field": "payment_method_data.billing.address.city",
"display_name": "city",
"field_type": "user_address_city",
"value": null
},
"billing.address.zip": {
"required_field": "payment_method_data.billing.address.zip",
"display_name": "zip",
"field_type": "user_address_pincode",
"value": null
},
"billing.address.line2": {
"required_field": "payment_method_data.billing.address.line2",
"display_name": "line2",
"field_type": "user_address_line2",
"value": null
},
"billing.address.state": {
"required_field": "payment_method_data.billing.address.state",
"display_name": "state",
"field_type": "user_address_state",
"value": null
},
"billing.address.first_name": {
"required_field": "payment_method_data.billing.address.first_name",
"display_name": "billing_first_name",
"field_type": "user_billing_name",
"value": null
},
"billing.address.line1": {
"required_field": "payment_method_data.billing.address.line1",
"display_name": "line1",
"field_type": "user_address_line1",
"value": null
},
"email": {
"required_field": "email",
"display_name": "email",
"field_type": "user_email_address",
"value": null
},
"billing.address.last_name": {
"required_field": "payment_method_data.billing.address.last_name",
"display_name": "billing_last_name",
"field_type": "user_billing_name",
"value": null
}
},
"surcharge_details": null,
"pm_auth_connector": null
},
{
"payment_method_type": "apple_pay",
"payment_experience": [
{
"payment_experience_type": "invoke_sdk_client",
"eligible_connectors": [
"cybersource"
]
}
],
"card_networks": null,
"bank_names": null,
"bank_debits": null,
"bank_transfers": null,
"required_fields": {
"billing.address.city": {
"required_field": "payment_method_data.billing.address.city",
"display_name": "city",
"field_type": "user_address_city",
"value": null
},
"billing.address.state": {
"required_field": "payment_method_data.billing.address.state",
"display_name": "state",
"field_type": "user_address_state",
"value": null
},
"billing.address.line2": {
"required_field": "payment_method_data.billing.address.line2",
"display_name": "line2",
"field_type": "user_address_line2",
"value": null
},
"email": {
"required_field": "email",
"display_name": "email",
"field_type": "user_email_address",
"value": null
},
"billing.address.zip": {
"required_field": "payment_method_data.billing.address.zip",
"display_name": "zip",
"field_type": "user_address_pincode",
"value": null
},
"billing.address.first_name": {
"required_field": "payment_method_data.billing.address.first_name",
"display_name": "billing_first_name",
"field_type": "user_billing_name",
"value": null
},
"billing.address.last_name": {
"required_field": "payment_method_data.billing.address.last_name",
"display_name": "billing_last_name",
"field_type": "user_billing_name",
"value": null
},
"billing.address.country": {
"required_field": "payment_method_data.billing.address.country",
"display_name": "country",
"field_type": {
"user_address_country": {
"options": [
"ALL"
]
}
},
"value": null
},
"billing.address.line1": {
"required_field": "payment_method_data.billing.address.line1",
"display_name": "line1",
"field_type": "user_address_line1",
"value": null
}
},
"surcharge_details": null,
"pm_auth_connector": null
},
{
"payment_method_type": "paypal",
"payment_experience": [
{
"payment_experience_type": "redirect_to_url",
"eligible_connectors": [
"cybersource"
]
}
],
"card_networks": null,
"bank_names": null,
"bank_debits": null,
"bank_transfers": null,
"required_fields": null,
"surcharge_details": null,
"pm_auth_connector": null
}
]
},
{
"payment_method": "card",
"payment_method_types": [
{
"payment_method_type": "debit",
"payment_experience": null,
"card_networks": [
{
"card_network": "Visa",
"surcharge_details": null,
"eligible_connectors": [
"cybersource"
]
},
{
"card_network": "Mastercard",
"surcharge_details": null,
"eligible_connectors": [
"cybersource"
]
}
],
"bank_names": null,
"bank_debits": null,
"bank_transfers": null,
"required_fields": {
"payment_method_data.card.card_exp_year": {
"required_field": "payment_method_data.card.card_exp_year",
"display_name": "card_exp_year",
"field_type": "user_card_expiry_year",
"value": null
},
"billing.address.last_name": {
"required_field": "payment_method_data.billing.address.last_name",
"display_name": "billing_last_name",
"field_type": "user_billing_name",
"value": null
},
"billing.address.state": {
"required_field": "payment_method_data.billing.address.state",
"display_name": "state",
"field_type": "user_address_state",
"value": null
},
"payment_method_data.card.card_exp_month": {
"required_field": "payment_method_data.card.card_exp_month",
"display_name": "card_exp_month",
"field_type": "user_card_expiry_month",
"value": null
},
"billing.address.line2": {
"required_field": "payment_method_data.billing.address.line2",
"display_name": "line2",
"field_type": "user_address_line2",
"value": null
},
"billing.address.first_name": {
"required_field": "payment_method_data.billing.address.first_name",
"display_name": "billing_first_name",
"field_type": "user_billing_name",
"value": null
},
"billing.address.city": {
"required_field": "payment_method_data.billing.address.city",
"display_name": "city",
"field_type": "user_address_city",
"value": null
},
"billing.address.country": {
"required_field": "payment_method_data.billing.address.country",
"display_name": "country",
"field_type": {
"user_address_country": {
"options": [
"ALL"
]
}
},
"value": null
},
"payment_method_data.card.card_number": {
"required_field": "payment_method_data.card.card_number",
"display_name": "card_number",
"field_type": "user_card_number",
"value": null
},
"billing.address.line1": {
"required_field": "payment_method_data.billing.address.line1",
"display_name": "line1",
"field_type": "user_address_line1",
"value": null
},
"email": {
"required_field": "email",
"display_name": "email",
"field_type": "user_email_address",
"value": null
},
"payment_method_data.card.card_cvc": {
"required_field": "payment_method_data.card.card_cvc",
"display_name": "card_cvc",
"field_type": "user_card_cvc",
"value": null
},
"billing.address.zip": {
"required_field": "payment_method_data.billing.address.zip",
"display_name": "zip",
"field_type": "user_address_pincode",
"value": null
}
},
"surcharge_details": null,
"pm_auth_connector": null
},
{
"payment_method_type": "credit",
"payment_experience": null,
"card_networks": [
{
"card_network": "Mastercard",
"surcharge_details": null,
"eligible_connectors": [
"cybersource"
]
},
{
"card_network": "DinersClub",
"surcharge_details": null,
"eligible_connectors": [
"cybersource"
]
},
{
"card_network": "Visa",
"surcharge_details": null,
"eligible_connectors": [
"cybersource"
]
},
{
"card_network": "Discover",
"surcharge_details": null,
"eligible_connectors": [
"cybersource"
]
}
],
"bank_names": null,
"bank_debits": null,
"bank_transfers": null,
"required_fields": {
"billing.address.city": {
"required_field": "payment_method_data.billing.address.city",
"display_name": "city",
"field_type": "user_address_city",
"value": null
},
"billing.address.country": {
"required_field": "payment_method_data.billing.address.country",
"display_name": "country",
"field_type": {
"user_address_country": {
"options": [
"ALL"
]
}
},
"value": null
},
"email": {
"required_field": "email",
"display_name": "email",
"field_type": "user_email_address",
"value": null
},
"billing.address.line1": {
"required_field": "payment_method_data.billing.address.line1",
"display_name": "line1",
"field_type": "user_address_line1",
"value": null
},
"payment_method_data.card.card_exp_year": {
"required_field": "payment_method_data.card.card_exp_year",
"display_name": "card_exp_year",
"field_type": "user_card_expiry_year",
"value": null
},
"billing.address.line2": {
"required_field": "payment_method_data.billing.address.line2",
"display_name": "line2",
"field_type": "user_address_line2",
"value": null
},
"billing.address.zip": {
"required_field": "payment_method_data.billing.address.zip",
"display_name": "zip",
"field_type": "user_address_pincode",
"value": null
},
"billing.address.first_name": {
"required_field": "payment_method_data.billing.address.first_name",
"display_name": "billing_first_name",
"field_type": "user_billing_name",
"value": null
},
"payment_method_data.card.card_exp_month": {
"required_field": "payment_method_data.card.card_exp_month",
"display_name": "card_exp_month",
"field_type": "user_card_expiry_month",
"value": null
},
"billing.address.state": {
"required_field": "payment_method_data.billing.address.state",
"display_name": "state",
"field_type": "user_address_state",
"value": null
},
"payment_method_data.card.card_number": {
"required_field": "payment_method_data.card.card_number",
"display_name": "card_number",
"field_type": "user_card_number",
"value": null
},
"billing.address.last_name": {
"required_field": "payment_method_data.billing.address.last_name",
"display_name": "billing_last_name",
"field_type": "user_billing_name",
"value": null
},
"payment_method_data.card.card_cvc": {
"required_field": "payment_method_data.card.card_cvc",
"display_name": "card_cvc",
"field_type": "user_card_cvc",
"value": null
}
},
"surcharge_details": null,
"pm_auth_connector": null
}
]
},
{
"payment_method": "bank_debit",
"payment_method_types": [
{
"payment_method_type": "ach",
"payment_experience": null,
"card_networks": null,
"bank_names": null,
"bank_debits": {
"eligible_connectors": [
"cybersource"
]
},
"bank_transfers": null,
"required_fields": null,
"surcharge_details": null,
"pm_auth_connector": null
}
]
}
],
"mandate_payment": null,
"merchant_name": "NewAge Retailer",
"show_surcharge_breakup_screen": false,
"payment_type": "normal",
"request_external_three_ds_authentication": false,
"collect_shipping_details_from_wallets": false,
"collect_billing_details_from_wallets": true
}
```
#### Test case 4
```
curl --location 'http://localhost:8080/account/merchant_1721744553/business_profile/pro_UbvlkhzFe49CKOC2Cp6A' \
--header 'Content-Type: application/json' \
--header 'Accept: application/json' \
--header 'api-key: test_admin' \
--data '{
"collect_shipping_details_from_wallet_connector": true,
"collect_billing_details_from_wallet_connector": true,
"always_collect_shipping_details_from_wallet_connector": true,
"always_collect_billing_details_from_wallet_connector": true,
"is_connector_agnostic_mit_enabled": false
}'
```
-> Create payment with confirm false
```
curl --location 'http://localhost:8080/payments' \
--header 'Content-Type: application/json' \
--header 'Accept: application/json' \
--header 'api-key: dev_JUigpqaxc3JIsB3n6tKy1SyUqCOiwMlh8g1jhSl4ogy94UjG9cophbqUD7DNU2dc' \
--data '{
"amount": 10000,
"currency": "USD",
"capture_method": "automatic",
"authentication_type": "no_three_ds",
"confirm": false,
"customer_id": "cu_1721237981"
}'
```
-> Session call
```
curl --location 'http://localhost:8080/payments/session_tokens' \
--header 'Content-Type: application/json' \
--header 'x-merchant-domain: sdk-test-app.netlify.app' \
--header 'api-key: pk_dev_6b6f32cb55244ccb83ef922d20826d91' \
--data '{
"payment_id": "pay_mUhoyp7LPvaPKQAqIdDI",
"wallets": [],
"client_secret": "pay_mUhoyp7LPvaPKQAqIdDI_secret_xwVdPWdwTEjbexPM7aYS"
}'
```
```
{
"payment_id": "pay_mUhoyp7LPvaPKQAqIdDI",
"client_secret": "pay_mUhoyp7LPvaPKQAqIdDI_secret_xwVdPWdwTEjbexPM7aYS",
"session_token": [
{
"wallet_name": "google_pay",
"merchant_info": {
"merchant_name": "Stripe"
},
"shipping_address_required": true,
"email_required": true,
"shipping_address_parameters": {
"phone_number_required": true
},
"allowed_payment_methods": [
{
"type": "CARD",
"parameters": {
"allowed_auth_methods": [
"PAN_ONLY",
"CRYPTOGRAM_3DS"
],
"allowed_card_networks": [
"AMEX",
"DISCOVER",
"INTERAC",
"JCB",
"MASTERCARD",
"VISA"
],
"billing_address_required": true,
"billing_address_parameters": {
"phone_number_required": true,
"format": "FULL"
}
},
"tokenization_specification": {
"type": "PAYMENT_GATEWAY",
"parameters": {
"gateway": "stripe",
"stripe:version": "2018-10-31",
"stripe:publishableKey": "pk_test_51Msk2GAGHc77EJXX78h549SX2uaOnEkUYqBfjcoD05PIpAnDkYxMn8nQ4d19im85NQuX4Z6WDyHaUw2fFTPBWsIY00Wa7oNerO"
}
}
}
],
"transaction_info": {
"country_code": "US",
"currency_code": "USD",
"total_price_status": "Final",
"total_price": "100.00"
},
"delayed_session_token": false,
"connector": "cybersource",
"sdk_next_action": {
"next_action": "confirm"
},
"secrets": null
},
{
"wallet_name": "apple_pay",
"session_token_data": {
"epoch_timestamp": 1721745482229,
"expires_at": 1721749082229,
"merchant_session_identifier": "SSH0A58E32F13C74163977F0DDE274249C1_BB8E62003687F8FCC159B2B83AAFC02DB625F1F1E3997CCC2FE2CFD11F636558",
"nonce": "c9553225",
"merchant_identifier": "76B79A8E91F4D365B0B636C8F75CB207D52532E82C2C085DE79D6D8135EF3813",
"domain_name": "sdk-test-app.netlify.app",
"display_name": "applepay",
"signature": "308006092a864886f70d010702a0803080020101310d300b0609608648016503040201308006092a864886f70d0107010000a080308203e330820388a003020102020816634c8b0e305717300a06082a8648ce3d040302307a312e302c06035504030c254170706c65204170706c69636174696f6e20496e746567726174696f6e204341202d20473331263024060355040b0c1d4170706c652043657274696669636174696f6e20417574686f7269747931133011060355040a0c0a4170706c6520496e632e310b3009060355040613025553301e170d3234303432393137343732375a170d3239303432383137343732365a305f3125302306035504030c1c6563632d736d702d62726f6b65722d7369676e5f5543342d50524f4431143012060355040b0c0b694f532053797374656d7331133011060355040a0c0a4170706c6520496e632e310b30090603550406130255533059301306072a8648ce3d020106082a8648ce3d03010703420004c21577edebd6c7b2218f68dd7090a1218dc7b0bd6f2c283d846095d94af4a5411b83420ed811f3407e83331f1c54c3f7eb3220d6bad5d4eff49289893e7c0f13a38202113082020d300c0603551d130101ff04023000301f0603551d2304183016801423f249c44f93e4ef27e6c4f6286c3fa2bbfd2e4b304506082b0601050507010104393037303506082b060105050730018629687474703a2f2f6f6373702e6170706c652e636f6d2f6f63737030342d6170706c65616963613330323082011d0603551d2004820114308201103082010c06092a864886f7636405013081fe3081c306082b060105050702023081b60c81b352656c69616e6365206f6e207468697320636572746966696361746520627920616e7920706172747920617373756d657320616363657074616e6365206f6620746865207468656e206170706c696361626c65207374616e64617264207465726d7320616e6420636f6e646974696f6e73206f66207573652c20636572746966696361746520706f6c69637920616e642063657274696669636174696f6e2070726163746963652073746174656d656e74732e303606082b06010505070201162a687474703a2f2f7777772e6170706c652e636f6d2f6365727469666963617465617574686f726974792f30340603551d1f042d302b3029a027a0258623687474703a2f2f63726c2e6170706c652e636f6d2f6170706c6561696361332e63726c301d0603551d0e041604149457db6fd57481868989762f7e578507e79b5824300e0603551d0f0101ff040403020780300f06092a864886f76364061d04020500300a06082a8648ce3d0403020349003046022100c6f023cb2614bb303888a162983e1a93f1056f50fa78cdb9ba4ca241cc14e25e022100be3cd0dfd16247f6494475380e9d44c228a10890a3a1dc724b8b4cb8889818bc308202ee30820275a0030201020208496d2fbf3a98da97300a06082a8648ce3d0403023067311b301906035504030c124170706c6520526f6f74204341202d20473331263024060355040b0c1d4170706c652043657274696669636174696f6e20417574686f7269747931133011060355040a0c0a4170706c6520496e632e310b3009060355040613025553301e170d3134303530363233343633305a170d3239303530363233343633305a307a312e302c06035504030c254170706c65204170706c69636174696f6e20496e746567726174696f6e204341202d20473331263024060355040b0c1d4170706c652043657274696669636174696f6e20417574686f7269747931133011060355040a0c0a4170706c6520496e632e310b30090603550406130255533059301306072a8648ce3d020106082a8648ce3d03010703420004f017118419d76485d51a5e25810776e880a2efde7bae4de08dfc4b93e13356d5665b35ae22d097760d224e7bba08fd7617ce88cb76bb6670bec8e82984ff5445a381f73081f4304606082b06010505070101043a3038303606082b06010505073001862a687474703a2f2f6f6373702e6170706c652e636f6d2f6f63737030342d6170706c65726f6f7463616733301d0603551d0e0416041423f249c44f93e4ef27e6c4f6286c3fa2bbfd2e4b300f0603551d130101ff040530030101ff301f0603551d23041830168014bbb0dea15833889aa48a99debebdebafdacb24ab30370603551d1f0430302e302ca02aa0288626687474703a2f2f63726c2e6170706c652e636f6d2f6170706c65726f6f74636167332e63726c300e0603551d0f0101ff0404030201063010060a2a864886f7636406020e04020500300a06082a8648ce3d040302036700306402303acf7283511699b186fb35c356ca62bff417edd90f754da28ebef19c815e42b789f898f79b599f98d5410d8f9de9c2fe0230322dd54421b0a305776c5df3383b9067fd177c2c216d964fc6726982126f54f87a7d1b99cb9b0989216106990f09921d00003182018930820185020101308186307a312e302c06035504030c254170706c65204170706c69636174696f6e20496e746567726174696f6e204341202d20473331263024060355040b0c1d4170706c652043657274696669636174696f6e20417574686f7269747931133011060355040a0c0a4170706c6520496e632e310b3009060355040613025553020816634c8b0e305717300b0609608648016503040201a08193301806092a864886f70d010903310b06092a864886f70d010701301c06092a864886f70d010905310f170d3234303732333134333830325a302806092a864886f70d010934311b3019300b0609608648016503040201a10a06082a8648ce3d040302302f06092a864886f70d01090431220420eb0c1b6240e97eb0eceac7447bb4b83520e33f1ee58255666c4b2ff49df587de300a06082a8648ce3d04030204483046022100b391fdb2d99154a8a11e8a60f1311c494f478efbfb19e1c366bed1092357cdfa022100ab34f9f53721da59d5bbb5f12f00b1b8204b44f027c1d046ec3197957a40b773000000000000",
"operational_analytics_identifier": "applepay:76B79A8E91F4D365B0B636C8F75CB207D52532E82C2C085DE79D6D8135EF3813",
"retries": 0,
"psp_id": "76B79A8E91F4D365B0B636C8F75CB207D52532E82C2C085DE79D6D8135EF3813"
},
"payment_request_data": {
"country_code": "US",
"currency_code": "USD",
"total": {
"label": "applepay",
"type": "final",
"amount": "100.00"
},
"merchant_capabilities": [
"supports3DS"
],
"supported_networks": [
"visa",
"masterCard",
"amex",
"discover"
],
"merchant_identifier": "merchant.com.hyperswitch.checkout",
"required_billing_contact_fields": [
"postalAddress"
],
"required_shipping_contact_fields": [
"postalAddress",
"phone",
"email"
]
},
"connector": "cybersource",
"delayed_session_token": false,
"sdk_next_action": {
"next_action": "confirm"
},
"connector_reference_id": null,
"connector_sdk_public_key": null,
"connector_merchant_id": null
}
]
}
```
-> pml
```
curl --location 'http://localhost:8080/account/payment_methods?client_secret=pay_mUhoyp7LPvaPKQAqIdDI_secret_xwVdPWdwTEjbexPM7aYS' \
--header 'Accept: application/json' \
--header 'api-key: pk_dev_6b6f32cb55244ccb83ef922d20826d91'
```
```
{
"redirect_url": "https://google.com/success",
"currency": "USD",
"payment_methods": [
{
"payment_method": "pay_later",
"payment_method_types": [
{
"payment_method_type": "klarna",
"payment_experience": [
{
"payment_experience_type": "redirect_to_url",
"eligible_connectors": [
"cybersource"
]
},
{
"payment_experience_type": "invoke_sdk_client",
"eligible_connectors": [
"cybersource"
]
}
],
"card_networks": null,
"bank_names": null,
"bank_debits": null,
"bank_transfers": null,
"required_fields": null,
"surcharge_details": null,
"pm_auth_connector": null
}
]
},
{
"payment_method": "wallet",
"payment_method_types": [
{
"payment_method_type": "google_pay",
"payment_experience": [
{
"payment_experience_type": "invoke_sdk_client",
"eligible_connectors": [
"cybersource"
]
}
],
"card_networks": null,
"bank_names": null,
"bank_debits": null,
"bank_transfers": null,
"required_fields": {
"shipping.address.state": {
"required_field": "shipping.address.state",
"display_name": "state",
"field_type": "user_shipping_address_state",
"value": null
},
"billing.address.line1": {
"required_field": "payment_method_data.billing.address.line1",
"display_name": "line1",
"field_type": "user_address_line1",
"value": null
},
"email": {
"required_field": "email",
"display_name": "email",
"field_type": "user_email_address",
"value": null
},
"shipping.address.city": {
"required_field": "shipping.address.city",
"display_name": "city",
"field_type": "user_shipping_address_city",
"value": null
},
"shipping.address.country": {
"required_field": "shipping.address.country",
"display_name": "country",
"field_type": {
"user_shipping_address_country": {
"options": [
"ALL"
]
}
},
"value": null
},
"billing.address.country": {
"required_field": "payment_method_data.billing.address.country",
"display_name": "country",
"field_type": {
"user_address_country": {
"options": [
"ALL"
]
}
},
"value": null
},
"billing.address.city": {
"required_field": "payment_method_data.billing.address.city",
"display_name": "city",
"field_type": "user_address_city",
"value": null
},
"billing.address.zip": {
"required_field": "payment_method_data.billing.address.zip",
"display_name": "zip",
"field_type": "user_address_pincode",
"value": null
},
"shipping.address.first_name": {
"required_field": "shipping.address.first_name",
"display_name": "shipping_first_name",
"field_type": "user_shipping_name",
"value": null
},
"billing.address.line2": {
"required_field": "payment_method_data.billing.address.line2",
"display_name": "line2",
"field_type": "user_address_line2",
"value": null
},
"billing.address.state": {
"required_field": "payment_method_data.billing.address.state",
"display_name": "state",
"field_type": "user_address_state",
"value": null
},
"shipping.address.line1": {
"required_field": "shipping.address.line1",
"display_name": "line1",
"field_type": "user_shipping_address_line1",
"value": null
},
"shipping.address.zip": {
"required_field": "shipping.address.zip",
"display_name": "zip",
"field_type": "user_shipping_address_pincode",
"value": null
},
"billing.address.first_name": {
"required_field": "payment_method_data.billing.address.first_name",
"display_name": "billing_first_name",
"field_type": "user_billing_name",
"value": null
},
"billing.address.last_name": {
"required_field": "payment_method_data.billing.address.last_name",
"display_name": "billing_last_name",
"field_type": "user_billing_name",
"value": null
},
"shipping.address.last_name": {
"required_field": "shipping.address.last_name",
"display_name": "shipping_last_name",
"field_type": "user_shipping_name",
"value": null
}
},
"surcharge_details": null,
"pm_auth_connector": null
},
{
"payment_method_type": "paypal",
"payment_experience": [
{
"payment_experience_type": "redirect_to_url",
"eligible_connectors": [
"cybersource"
]
}
],
"card_networks": null,
"bank_names": null,
"bank_debits": null,
"bank_transfers": null,
"required_fields": null,
"surcharge_details": null,
"pm_auth_connector": null
},
{
"payment_method_type": "apple_pay",
"payment_experience": [
{
"payment_experience_type": "invoke_sdk_client",
"eligible_connectors": [
"cybersource"
]
}
],
"card_networks": null,
"bank_names": null,
"bank_debits": null,
"bank_transfers": null,
"required_fields": {
"shipping.address.first_name": {
"required_field": "shipping.address.first_name",
"display_name": "shipping_first_name",
"field_type": "user_shipping_name",
"value": null
},
"shipping.address.zip": {
"required_field": "shipping.address.zip",
"display_name": "zip",
"field_type": "user_shipping_address_pincode",
"value": null
},
"shipping.address.city": {
"required_field": "shipping.address.city",
"display_name": "city",
"field_type": "user_shipping_address_city",
"value": null
},
"email": {
"required_field": "email",
"display_name": "email",
"field_type": "user_email_address",
"value": null
},
"shipping.address.line1": {
"required_field": "shipping.address.line1",
"display_name": "line1",
"field_type": "user_shipping_address_line1",
"value": null
},
"billing.address.last_name": {
"required_field": "payment_method_data.billing.address.last_name",
"display_name": "billing_last_name",
"field_type": "user_billing_name",
"value": null
},
"billing.address.line1": {
"required_field": "payment_method_data.billing.address.line1",
"display_name": "line1",
"field_type": "user_address_line1",
"value": null
},
"billing.address.city": {
"required_field": "payment_method_data.billing.address.city",
"display_name": "city",
"field_type": "user_address_city",
"value": null
},
"shipping.address.last_name": {
"required_field": "shipping.address.last_name",
"display_name": "shipping_last_name",
"field_type": "user_shipping_name",
"value": null
},
"billing.address.line2": {
"required_field": "payment_method_data.billing.address.line2",
"display_name": "line2",
"field_type": "user_address_line2",
"value": null
},
"shipping.address.country": {
"required_field": "shipping.address.country",
"display_name": "country",
"field_type": {
"user_shipping_address_country": {
"options": [
"ALL"
]
}
},
"value": null
},
"shipping.address.state": {
"required_field": "shipping.address.state",
"display_name": "state",
"field_type": "user_shipping_address_state",
"value": null
},
"billing.address.zip": {
"required_field": "payment_method_data.billing.address.zip",
"display_name": "zip",
"field_type": "user_address_pincode",
"value": null
},
"billing.address.first_name": {
"required_field": "payment_method_data.billing.address.first_name",
"display_name": "billing_first_name",
"field_type": "user_billing_name",
"value": null
},
"billing.address.country": {
"required_field": "payment_method_data.billing.address.country",
"display_name": "country",
"field_type": {
"user_address_country": {
"options": [
"ALL"
]
}
},
"value": null
},
"billing.address.state": {
"required_field": "payment_method_data.billing.address.state",
"display_name": "state",
"field_type": "user_address_state",
"value": null
}
},
"surcharge_details": null,
"pm_auth_connector": null
}
]
},
{
"payment_method": "card",
"payment_method_types": [
{
"payment_method_type": "debit",
"payment_experience": null,
"card_networks": [
{
"card_network": "Visa",
"surcharge_details": null,
"eligible_connectors": [
"cybersource"
]
},
{
"card_network": "Mastercard",
"surcharge_details": null,
"eligible_connectors": [
"cybersource"
]
}
],
"bank_names": null,
"bank_debits": null,
"bank_transfers": null,
"required_fields": {
"payment_method_data.card.card_exp_year": {
"required_field": "payment_method_data.card.card_exp_year",
"display_name": "card_exp_year",
"field_type": "user_card_expiry_year",
"value": null
},
"billing.address.last_name": {
"required_field": "payment_method_data.billing.address.last_name",
"display_name": "billing_last_name",
"field_type": "user_billing_name",
"value": null
},
"shipping.address.state": {
"required_field": "shipping.address.state",
"display_name": "state",
"field_type": "user_shipping_address_state",
"value": null
},
"shipping.address.zip": {
"required_field": "shipping.address.zip",
"display_name": "zip",
"field_type": "user_shipping_address_pincode",
"value": null
},
"billing.address.state": {
"required_field": "payment_method_data.billing.address.state",
"display_name": "state",
"field_type": "user_address_state",
"value": null
},
"payment_method_data.card.card_exp_month": {
"required_field": "payment_method_data.card.card_exp_month",
"display_name": "card_exp_month",
"field_type": "user_card_expiry_month",
"value": null
},
"billing.address.line2": {
"required_field": "payment_method_data.billing.address.line2",
"display_name": "line2",
"field_type": "user_address_line2",
"value": null
},
"billing.address.first_name": {
"required_field": "payment_method_data.billing.address.first_name",
"display_name": "billing_first_name",
"field_type": "user_billing_name",
"value": null
},
"billing.address.city": {
"required_field": "payment_method_data.billing.address.city",
"display_name": "city",
"field_type": "user_address_city",
"value": null
},
"billing.address.country": {
"required_field": "payment_method_data.billing.address.country",
"display_name": "country",
"field_type": {
"user_address_country": {
"options": [
"ALL"
]
}
},
"value": null
},
"payment_method_data.card.card_number": {
"required_field": "payment_method_data.card.card_number",
"display_name": "card_number",
"field_type": "user_card_number",
"value": null
},
"shipping.address.city": {
"required_field": "shipping.address.city",
"display_name": "city",
"field_type": "user_shipping_address_city",
"value": null
},
"billing.address.line1": {
"required_field": "payment_method_data.billing.address.line1",
"display_name": "line1",
"field_type": "user_address_line1",
"value": null
},
"shipping.address.line1": {
"required_field": "shipping.address.line1",
"display_name": "line1",
"field_type": "user_shipping_address_line1",
"value": null
},
"shipping.address.country": {
"required_field": "shipping.address.country",
"display_name": "country",
"field_type": {
"user_shipping_address_country": {
"options": [
"ALL"
]
}
},
"value": null
},
"email": {
"required_field": "email",
"display_name": "email",
"field_type": "user_email_address",
"value": null
},
"payment_method_data.card.card_cvc": {
"required_field": "payment_method_data.card.card_cvc",
"display_name": "card_cvc",
"field_type": "user_card_cvc",
"value": null
},
"billing.address.zip": {
"required_field": "payment_method_data.billing.address.zip",
"display_name": "zip",
"field_type": "user_address_pincode",
"value": null
},
"shipping.address.first_name": {
"required_field": "shipping.address.first_name",
"display_name": "shipping_first_name",
"field_type": "user_shipping_name",
"value": null
},
"shipping.address.last_name": {
"required_field": "shipping.address.last_name",
"display_name": "shipping_last_name",
"field_type": "user_shipping_name",
"value": null
}
},
"surcharge_details": null,
"pm_auth_connector": null
},
{
"payment_method_type": "credit",
"payment_experience": null,
"card_networks": [
{
"card_network": "Discover",
"surcharge_details": null,
"eligible_connectors": [
"cybersource"
]
},
{
"card_network": "DinersClub",
"surcharge_details": null,
"eligible_connectors": [
"cybersource"
]
},
{
"card_network": "Mastercard",
"surcharge_details": null,
"eligible_connectors": [
"cybersource"
]
},
{
"card_network": "Visa",
"surcharge_details": null,
"eligible_connectors": [
"cybersource"
]
}
],
"bank_names": null,
"bank_debits": null,
"bank_transfers": null,
"required_fields": {
"billing.address.city": {
"required_field": "payment_method_data.billing.address.city",
"display_name": "city",
"field_type": "user_address_city",
"value": null
},
"billing.address.country": {
"required_field": "payment_method_data.billing.address.country",
"display_name": "country",
"field_type": {
"user_address_country": {
"options": [
"ALL"
]
}
},
"value": null
},
"shipping.address.zip": {
"required_field": "shipping.address.zip",
"display_name": "zip",
"field_type": "user_shipping_address_pincode",
"value": null
},
"email": {
"required_field": "email",
"display_name": "email",
"field_type": "user_email_address",
"value": null
},
"billing.address.line1": {
"required_field": "payment_method_data.billing.address.line1",
"display_name": "line1",
"field_type": "user_address_line1",
"value": null
},
"shipping.address.city": {
"required_field": "shipping.address.city",
"display_name": "city",
"field_type": "user_shipping_address_city",
"value": null
},
"payment_method_data.card.card_exp_year": {
"required_field": "payment_method_data.card.card_exp_year",
"display_name": "card_exp_year",
"field_type": "user_card_expiry_year",
"value": null
},
"billing.address.line2": {
"required_field": "payment_method_data.billing.address.line2",
"display_name": "line2",
"field_type": "user_address_line2",
"value": null
},
"billing.address.zip": {
"required_field": "payment_method_data.billing.address.zip",
"display_name": "zip",
"field_type": "user_address_pincode",
"value": null
},
"shipping.address.last_name": {
"required_field": "shipping.address.last_name",
"display_name": "shipping_last_name",
"field_type": "user_shipping_name",
"value": null
},
"shipping.address.country": {
"required_field": "shipping.address.country",
"display_name": "country",
"field_type": {
"user_shipping_address_country": {
"options": [
"ALL"
]
}
},
"value": null
},
"billing.address.first_name": {
"required_field": "payment_method_data.billing.address.first_name",
"display_name": "billing_first_name",
"field_type": "user_billing_name",
"value": null
},
"payment_method_data.card.card_exp_month": {
"required_field": "payment_method_data.card.card_exp_month",
"display_name": "card_exp_month",
"field_type": "user_card_expiry_month",
"value": null
},
"billing.address.state": {
"required_field": "payment_method_data.billing.address.state",
"display_name": "state",
"field_type": "user_address_state",
"value": null
},
"shipping.address.state": {
"required_field": "shipping.address.state",
"display_name": "state",
"field_type": "user_shipping_address_state",
"value": null
},
"shipping.address.line1": {
"required_field": "shipping.address.line1",
"display_name": "line1",
"field_type": "user_shipping_address_line1",
"value": null
},
"payment_method_data.card.card_number": {
"required_field": "payment_method_data.card.card_number",
"display_name": "card_number",
"field_type": "user_card_number",
"value": null
},
"shipping.address.first_name": {
"required_field": "shipping.address.first_name",
"display_name": "shipping_first_name",
"field_type": "user_shipping_name",
"value": null
},
"billing.address.last_name": {
"required_field": "payment_method_data.billing.address.last_name",
"display_name": "billing_last_name",
"field_type": "user_billing_name",
"value": null
},
"payment_method_data.card.card_cvc": {
"required_field": "payment_method_data.card.card_cvc",
"display_name": "card_cvc",
"field_type": "user_card_cvc",
"value": null
}
},
"surcharge_details": null,
"pm_auth_connector": null
}
]
},
{
"payment_method": "bank_debit",
"payment_method_types": [
{
"payment_method_type": "ach",
"payment_experience": null,
"card_networks": null,
"bank_names": null,
"bank_debits": {
"eligible_connectors": [
"cybersource"
]
},
"bank_transfers": null,
"required_fields": null,
"surcharge_details": null,
"pm_auth_connector": null
}
]
}
],
"mandate_payment": null,
"merchant_name": "NewAge Retailer",
"show_surcharge_breakup_screen": false,
"payment_type": "normal",
"request_external_three_ds_authentication": false,
"collect_shipping_details_from_wallets": true,
"collect_billing_details_from_wallets": true
}
```
#### Test case 6
```
curl --location 'http://localhost:8080/account/merchant_1721744553/business_profile/pro_UbvlkhzFe49CKOC2Cp6A' \
--header 'Content-Type: application/json' \
--header 'Accept: application/json' \
--header 'api-key: test_admin' \
--data '{
"collect_shipping_details_from_wallet_connector": true,
"collect_billing_details_from_wallet_connector": true,
"always_collect_shipping_details_from_wallet_connector": false,
"always_collect_billing_details_from_wallet_connector": true,
"is_connector_agnostic_mit_enabled": false
}'
```
-> Payment create with confirm false
```
curl --location 'http://localhost:8080/payments' \
--header 'Content-Type: application/json' \
--header 'Accept: application/json' \
--header 'api-key: dev_JUigpqaxc3JIsB3n6tKy1SyUqCOiwMlh8g1jhSl4ogy94UjG9cophbqUD7DNU2dc' \
--data '{
"amount": 10000,
"currency": "USD",
"capture_method": "automatic",
"authentication_type": "no_three_ds",
"confirm": false,
"customer_id": "cu_1721237981"
}'
```
session call
```
curl --location 'http://localhost:8080/payments/session_tokens' \
--header 'Content-Type: application/json' \
--header 'x-merchant-domain: sdk-test-app.netlify.app' \
--header 'api-key: pk_dev_6b6f32cb55244ccb83ef922d20826d91' \
--data '{
"payment_id": "pay_dCVD5EqoFRHbEcJ0tv5y",
"wallets": [],
"client_secret": "pay_dCVD5EqoFRHbEcJ0tv5y_secret_nSYbyiGZeR7PqQzTdUZk"
}'
```
```
{
"payment_id": "pay_dCVD5EqoFRHbEcJ0tv5y",
"client_secret": "pay_dCVD5EqoFRHbEcJ0tv5y_secret_nSYbyiGZeR7PqQzTdUZk",
"session_token": [
{
"wallet_name": "google_pay",
"merchant_info": {
"merchant_name": "Stripe"
},
"shipping_address_required": false,
"email_required": true,
"shipping_address_parameters": {
"phone_number_required": false
},
"allowed_payment_methods": [
{
"type": "CARD",
"parameters": {
"allowed_auth_methods": [
"PAN_ONLY",
"CRYPTOGRAM_3DS"
],
"allowed_card_networks": [
"AMEX",
"DISCOVER",
"INTERAC",
"JCB",
"MASTERCARD",
"VISA"
],
"billing_address_required": true,
"billing_address_parameters": {
"phone_number_required": true,
"format": "FULL"
}
},
"tokenization_specification": {
"type": "PAYMENT_GATEWAY",
"parameters": {
"gateway": "stripe",
"stripe:version": "2018-10-31",
"stripe:publishableKey": "pk_test_51Msk2GAGHc77EJXX78h549SX2uaOnEkUYqBfjcoD05PIpAnDkYxMn8nQ4d19im85NQuX4Z6WDyHaUw2fFTPBWsIY00Wa7oNerO"
}
}
}
],
"transaction_info": {
"country_code": "US",
"currency_code": "USD",
"total_price_status": "Final",
"total_price": "100.00"
},
"delayed_session_token": false,
"connector": "cybersource",
"sdk_next_action": {
"next_action": "confirm"
},
"secrets": null
},
{
"wallet_name": "apple_pay",
"session_token_data": {
"epoch_timestamp": 1721746230537,
"expires_at": 1721749830537,
"merchant_session_identifier": "SSH8124D93142F541A0B86AAD933575175A_CCE257A9D27B42513B2C3CA67DB49F602F3450D996C0811ED462EDCA0D7477FD",
"nonce": "e3b5f1b3",
"merchant_identifier": "76B79A8E91F4D365B0B636C8F75CB207D52532E82C2C085DE79D6D8135EF3813",
"domain_name": "sdk-test-app.netlify.app",
"display_name": "applepay",
"signature": "308006092a864886f70d010702a0803080020101310d300b0609608648016503040201308006092a864886f70d0107010000a080308203e330820388a003020102020816634c8b0e305717300a06082a8648ce3d040302307a312e302c06035504030c254170706c65204170706c69636174696f6e20496e746567726174696f6e204341202d20473331263024060355040b0c1d4170706c652043657274696669636174696f6e20417574686f7269747931133011060355040a0c0a4170706c6520496e632e310b3009060355040613025553301e170d3234303432393137343732375a170d3239303432383137343732365a305f3125302306035504030c1c6563632d736d702d62726f6b65722d7369676e5f5543342d50524f4431143012060355040b0c0b694f532053797374656d7331133011060355040a0c0a4170706c6520496e632e310b30090603550406130255533059301306072a8648ce3d020106082a8648ce3d03010703420004c21577edebd6c7b2218f68dd7090a1218dc7b0bd6f2c283d846095d94af4a5411b83420ed811f3407e83331f1c54c3f7eb3220d6bad5d4eff49289893e7c0f13a38202113082020d300c0603551d130101ff04023000301f0603551d2304183016801423f249c44f93e4ef27e6c4f6286c3fa2bbfd2e4b304506082b0601050507010104393037303506082b060105050730018629687474703a2f2f6f6373702e6170706c652e636f6d2f6f63737030342d6170706c65616963613330323082011d0603551d2004820114308201103082010c06092a864886f7636405013081fe3081c306082b060105050702023081b60c81b352656c69616e6365206f6e207468697320636572746966696361746520627920616e7920706172747920617373756d657320616363657074616e6365206f6620746865207468656e206170706c696361626c65207374616e64617264207465726d7320616e6420636f6e646974696f6e73206f66207573652c20636572746966696361746520706f6c69637920616e642063657274696669636174696f6e2070726163746963652073746174656d656e74732e303606082b06010505070201162a687474703a2f2f7777772e6170706c652e636f6d2f6365727469666963617465617574686f726974792f30340603551d1f042d302b3029a027a0258623687474703a2f2f63726c2e6170706c652e636f6d2f6170706c6561696361332e63726c301d0603551d0e041604149457db6fd57481868989762f7e578507e79b5824300e0603551d0f0101ff040403020780300f06092a864886f76364061d04020500300a06082a8648ce3d0403020349003046022100c6f023cb2614bb303888a162983e1a93f1056f50fa78cdb9ba4ca241cc14e25e022100be3cd0dfd16247f6494475380e9d44c228a10890a3a1dc724b8b4cb8889818bc308202ee30820275a0030201020208496d2fbf3a98da97300a06082a8648ce3d0403023067311b301906035504030c124170706c6520526f6f74204341202d20473331263024060355040b0c1d4170706c652043657274696669636174696f6e20417574686f7269747931133011060355040a0c0a4170706c6520496e632e310b3009060355040613025553301e170d3134303530363233343633305a170d3239303530363233343633305a307a312e302c06035504030c254170706c65204170706c69636174696f6e20496e746567726174696f6e204341202d20473331263024060355040b0c1d4170706c652043657274696669636174696f6e20417574686f7269747931133011060355040a0c0a4170706c6520496e632e310b30090603550406130255533059301306072a8648ce3d020106082a8648ce3d03010703420004f017118419d76485d51a5e25810776e880a2efde7bae4de08dfc4b93e13356d5665b35ae22d097760d224e7bba08fd7617ce88cb76bb6670bec8e82984ff5445a381f73081f4304606082b06010505070101043a3038303606082b06010505073001862a687474703a2f2f6f6373702e6170706c652e636f6d2f6f63737030342d6170706c65726f6f7463616733301d0603551d0e0416041423f249c44f93e4ef27e6c4f6286c3fa2bbfd2e4b300f0603551d130101ff040530030101ff301f0603551d23041830168014bbb0dea15833889aa48a99debebdebafdacb24ab30370603551d1f0430302e302ca02aa0288626687474703a2f2f63726c2e6170706c652e636f6d2f6170706c65726f6f74636167332e63726c300e0603551d0f0101ff0404030201063010060a2a864886f7636406020e04020500300a06082a8648ce3d040302036700306402303acf7283511699b186fb35c356ca62bff417edd90f754da28ebef19c815e42b789f898f79b599f98d5410d8f9de9c2fe0230322dd54421b0a305776c5df3383b9067fd177c2c216d964fc6726982126f54f87a7d1b99cb9b0989216106990f09921d00003182018830820184020101308186307a312e302c06035504030c254170706c65204170706c69636174696f6e20496e746567726174696f6e204341202d20473331263024060355040b0c1d4170706c652043657274696669636174696f6e20417574686f7269747931133011060355040a0c0a4170706c6520496e632e310b3009060355040613025553020816634c8b0e305717300b0609608648016503040201a08193301806092a864886f70d010903310b06092a864886f70d010701301c06092a864886f70d010905310f170d3234303732333134353033305a302806092a864886f70d010934311b3019300b0609608648016503040201a10a06082a8648ce3d040302302f06092a864886f70d010904312204202fa422ef92b9dade1b318617c4d96a8ee1ed2e306f2ce73fb997f9ee8f60fe5e300a06082a8648ce3d04030204473045022100f85fc317ee62108fbba6bf99a694496396b6f25b372f7347020a1d20664a725d022040558be009cadd743bac1428197c3b21c0f6cb6f7c02cdd7cf960296d0dff910000000000000",
"operational_analytics_identifier": "applepay:76B79A8E91F4D365B0B636C8F75CB207D52532E82C2C085DE79D6D8135EF3813",
"retries": 0,
"psp_id": "76B79A8E91F4D365B0B636C8F75CB207D52532E82C2C085DE79D6D8135EF3813"
},
"payment_request_data": {
"country_code": "US",
"currency_code": "USD",
"total": {
"label": "applepay",
"type": "final",
"amount": "100.00"
},
"merchant_capabilities": [
"supports3DS"
],
"supported_networks": [
"visa",
"masterCard",
"amex",
"discover"
],
"merchant_identifier": "merchant.com.hyperswitch.checkout",
"required_billing_contact_fields": [
"postalAddress"
],
"required_shipping_contact_fields": [
"phone",
"email"
]
},
"connector": "cybersource",
"delayed_session_token": false,
"sdk_next_action": {
"next_action": "confirm"
},
"connector_reference_id": null,
"connector_sdk_public_key": null,
"connector_merchant_id": null
}
]
}
```
-> pml
```
curl --location 'http://localhost:8080/account/payment_methods?client_secret=pay_dCVD5EqoFRHbEcJ0tv5y_secret_nSYbyiGZeR7PqQzTdUZk' \
--header 'Accept: application/json' \
--header 'api-key: pk_dev_6b6f32cb55244ccb83ef922d20826d91'
```
```
{
"redirect_url": "https://google.com/success",
"currency": "USD",
"payment_methods": [
{
"payment_method": "wallet",
"payment_method_types": [
{
"payment_method_type": "paypal",
"payment_experience": [
{
"payment_experience_type": "redirect_to_url",
"eligible_connectors": [
"cybersource"
]
}
],
"card_networks": null,
"bank_names": null,
"bank_debits": null,
"bank_transfers": null,
"required_fields": null,
"surcharge_details": null,
"pm_auth_connector": null
},
{
"payment_method_type": "apple_pay",
"payment_experience": [
{
"payment_experience_type": "invoke_sdk_client",
"eligible_connectors": [
"cybersource"
]
}
],
"card_networks": null,
"bank_names": null,
"bank_debits": null,
"bank_transfers": null,
"required_fields": {
"billing.address.city": {
"required_field": "payment_method_data.billing.address.city",
"display_name": "city",
"field_type": "user_address_city",
"value": null
},
"billing.address.state": {
"required_field": "payment_method_data.billing.address.state",
"display_name": "state",
"field_type": "user_address_state",
"value": null
},
"billing.address.line2": {
"required_field": "payment_method_data.billing.address.line2",
"display_name": "line2",
"field_type": "user_address_line2",
"value": null
},
"email": {
"required_field": "email",
"display_name": "email",
"field_type": "user_email_address",
"value": null
},
"billing.address.zip": {
"required_field": "payment_method_data.billing.address.zip",
"display_name": "zip",
"field_type": "user_address_pincode",
"value": null
},
"billing.address.first_name": {
"required_field": "payment_method_data.billing.address.first_name",
"display_name": "billing_first_name",
"field_type": "user_billing_name",
"value": null
},
"billing.address.last_name": {
"required_field": "payment_method_data.billing.address.last_name",
"display_name": "billing_last_name",
"field_type": "user_billing_name",
"value": null
},
"billing.address.country": {
"required_field": "payment_method_data.billing.address.country",
"display_name": "country",
"field_type": {
"user_address_country": {
"options": [
"ALL"
]
}
},
"value": null
},
"billing.address.line1": {
"required_field": "payment_method_data.billing.address.line1",
"display_name": "line1",
"field_type": "user_address_line1",
"value": null
}
},
"surcharge_details": null,
"pm_auth_connector": null
},
{
"payment_method_type": "google_pay",
"payment_experience": [
{
"payment_experience_type": "invoke_sdk_client",
"eligible_connectors": [
"cybersource"
]
}
],
"card_networks": null,
"bank_names": null,
"bank_debits": null,
"bank_transfers": null,
"required_fields": {
"billing.address.country": {
"required_field": "payment_method_data.billing.address.country",
"display_name": "country",
"field_type": {
"user_address_country": {
"options": [
"ALL"
]
}
},
"value": null
},
"billing.address.city": {
"required_field": "payment_method_data.billing.address.city",
"display_name": "city",
"field_type": "user_address_city",
"value": null
},
"billing.address.zip": {
"required_field": "payment_method_data.billing.address.zip",
"display_name": "zip",
"field_type": "user_address_pincode",
"value": null
},
"billing.address.line2": {
"required_field": "payment_method_data.billing.address.line2",
"display_name": "line2",
"field_type": "user_address_line2",
"value": null
},
"billing.address.state": {
"required_field": "payment_method_data.billing.address.state",
"display_name": "state",
"field_type": "user_address_state",
"value": null
},
"billing.address.first_name": {
"required_field": "payment_method_data.billing.address.first_name",
"display_name": "billing_first_name",
"field_type": "user_billing_name",
"value": null
},
"billing.address.line1": {
"required_field": "payment_method_data.billing.address.line1",
"display_name": "line1",
"field_type": "user_address_line1",
"value": null
},
"email": {
"required_field": "email",
"display_name": "email",
"field_type": "user_email_address",
"value": null
},
"billing.address.last_name": {
"required_field": "payment_method_data.billing.address.last_name",
"display_name": "billing_last_name",
"field_type": "user_billing_name",
"value": null
}
},
"surcharge_details": null,
"pm_auth_connector": null
}
]
},
{
"payment_method": "pay_later",
"payment_method_types": [
{
"payment_method_type": "klarna",
"payment_experience": [
{
"payment_experience_type": "redirect_to_url",
"eligible_connectors": [
"cybersource"
]
},
{
"payment_experience_type": "invoke_sdk_client",
"eligible_connectors": [
"cybersource"
]
}
],
"card_networks": null,
"bank_names": null,
"bank_debits": null,
"bank_transfers": null,
"required_fields": null,
"surcharge_details": null,
"pm_auth_connector": null
}
]
},
{
"payment_method": "card",
"payment_method_types": [
{
"payment_method_type": "debit",
"payment_experience": null,
"card_networks": [
{
"card_network": "Visa",
"surcharge_details": null,
"eligible_connectors": [
"cybersource"
]
},
{
"card_network": "Mastercard",
"surcharge_details": null,
"eligible_connectors": [
"cybersource"
]
}
],
"bank_names": null,
"bank_debits": null,
"bank_transfers": null,
"required_fields": {
"payment_method_data.card.card_exp_year": {
"required_field": "payment_method_data.card.card_exp_year",
"display_name": "card_exp_year",
"field_type": "user_card_expiry_year",
"value": null
},
"billing.address.last_name": {
"required_field": "payment_method_data.billing.address.last_name",
"display_name": "billing_last_name",
"field_type": "user_billing_name",
"value": null
},
"billing.address.state": {
"required_field": "payment_method_data.billing.address.state",
"display_name": "state",
"field_type": "user_address_state",
"value": null
},
"payment_method_data.card.card_exp_month": {
"required_field": "payment_method_data.card.card_exp_month",
"display_name": "card_exp_month",
"field_type": "user_card_expiry_month",
"value": null
},
"billing.address.line2": {
"required_field": "payment_method_data.billing.address.line2",
"display_name": "line2",
"field_type": "user_address_line2",
"value": null
},
"billing.address.first_name": {
"required_field": "payment_method_data.billing.address.first_name",
"display_name": "billing_first_name",
"field_type": "user_billing_name",
"value": null
},
"billing.address.city": {
"required_field": "payment_method_data.billing.address.city",
"display_name": "city",
"field_type": "user_address_city",
"value": null
},
"billing.address.country": {
"required_field": "payment_method_data.billing.address.country",
"display_name": "country",
"field_type": {
"user_address_country": {
"options": [
"ALL"
]
}
},
"value": null
},
"payment_method_data.card.card_number": {
"required_field": "payment_method_data.card.card_number",
"display_name": "card_number",
"field_type": "user_card_number",
"value": null
},
"billing.address.line1": {
"required_field": "payment_method_data.billing.address.line1",
"display_name": "line1",
"field_type": "user_address_line1",
"value": null
},
"email": {
"required_field": "email",
"display_name": "email",
"field_type": "user_email_address",
"value": null
},
"payment_method_data.card.card_cvc": {
"required_field": "payment_method_data.card.card_cvc",
"display_name": "card_cvc",
"field_type": "user_card_cvc",
"value": null
},
"billing.address.zip": {
"required_field": "payment_method_data.billing.address.zip",
"display_name": "zip",
"field_type": "user_address_pincode",
"value": null
}
},
"surcharge_details": null,
"pm_auth_connector": null
},
{
"payment_method_type": "credit",
"payment_experience": null,
"card_networks": [
{
"card_network": "DinersClub",
"surcharge_details": null,
"eligible_connectors": [
"cybersource"
]
},
{
"card_network": "Visa",
"surcharge_details": null,
"eligible_connectors": [
"cybersource"
]
},
{
"card_network": "Mastercard",
"surcharge_details": null,
"eligible_connectors": [
"cybersource"
]
},
{
"card_network": "Discover",
"surcharge_details": null,
"eligible_connectors": [
"cybersource"
]
}
],
"bank_names": null,
"bank_debits": null,
"bank_transfers": null,
"required_fields": {
"billing.address.city": {
"required_field": "payment_method_data.billing.address.city",
"display_name": "city",
"field_type": "user_address_city",
"value": null
},
"billing.address.country": {
"required_field": "payment_method_data.billing.address.country",
"display_name": "country",
"field_type": {
"user_address_country": {
"options": [
"ALL"
]
}
},
"value": null
},
"email": {
"required_field": "email",
"display_name": "email",
"field_type": "user_email_address",
"value": null
},
"billing.address.line1": {
"required_field": "payment_method_data.billing.address.line1",
"display_name": "line1",
"field_type": "user_address_line1",
"value": null
},
"payment_method_data.card.card_exp_year": {
"required_field": "payment_method_data.card.card_exp_year",
"display_name": "card_exp_year",
"field_type": "user_card_expiry_year",
"value": null
},
"billing.address.line2": {
"required_field": "payment_method_data.billing.address.line2",
"display_name": "line2",
"field_type": "user_address_line2",
"value": null
},
"billing.address.zip": {
"required_field": "payment_method_data.billing.address.zip",
"display_name": "zip",
"field_type": "user_address_pincode",
"value": null
},
"billing.address.first_name": {
"required_field": "payment_method_data.billing.address.first_name",
"display_name": "billing_first_name",
"field_type": "user_billing_name",
"value": null
},
"payment_method_data.card.card_exp_month": {
"required_field": "payment_method_data.card.card_exp_month",
"display_name": "card_exp_month",
"field_type": "user_card_expiry_month",
"value": null
},
"billing.address.state": {
"required_field": "payment_method_data.billing.address.state",
"display_name": "state",
"field_type": "user_address_state",
"value": null
},
"payment_method_data.card.card_number": {
"required_field": "payment_method_data.card.card_number",
"display_name": "card_number",
"field_type": "user_card_number",
"value": null
},
"billing.address.last_name": {
"required_field": "payment_method_data.billing.address.last_name",
"display_name": "billing_last_name",
"field_type": "user_billing_name",
"value": null
},
"payment_method_data.card.card_cvc": {
"required_field": "payment_method_data.card.card_cvc",
"display_name": "card_cvc",
"field_type": "user_card_cvc",
"value": null
}
},
"surcharge_details": null,
"pm_auth_connector": null
}
]
},
{
"payment_method": "bank_debit",
"payment_method_types": [
{
"payment_method_type": "ach",
"payment_experience": null,
"card_networks": null,
"bank_names": null,
"bank_debits": {
"eligible_connectors": [
"cybersource"
]
},
"bank_transfers": null,
"required_fields": null,
"surcharge_details": null,
"pm_auth_connector": null
}
]
}
],
"mandate_payment": null,
"merchant_name": "NewAge Retailer",
"show_surcharge_breakup_screen": false,
"payment_type": "normal",
"request_external_three_ds_authentication": false,
"collect_shipping_details_from_wallets": false,
"collect_billing_details_from_wallets": true
}
```
## Checklist
<!-- Put an `x` in the boxes that apply -->
- [x] I formatted the code `cargo +nightly fmt --all`
- [x] I addressed lints thrown by `cargo clippy`
- [x] I reviewed the submitted code
- [ ] I added unit tests for my changes where possible
|
ca72fedae82194abb7216854c7dd61c64d57b1d6
|
|
juspay/hyperswitch
|
juspay__hyperswitch-5377
|
Bug: refactor: change primary keys in user, user_roles & roles tables
## Description
Previously our tables namely:
users
user_roles
roles
has primary key as ID.
we are refactoring them as follows:
users => user_id
user_roles => (user_id, merchant_id)
roles => role_id
|
diff --git a/crates/diesel_models/src/schema.rs b/crates/diesel_models/src/schema.rs
index 4b5f4a8ad49..b8c5344cbbb 100644
--- a/crates/diesel_models/src/schema.rs
+++ b/crates/diesel_models/src/schema.rs
@@ -1168,7 +1168,7 @@ diesel::table! {
use diesel::sql_types::*;
use crate::enums::diesel_exports::*;
- roles (id) {
+ roles (role_id) {
id -> Int4,
#[max_length = 64]
role_name -> Varchar,
@@ -1251,7 +1251,7 @@ diesel::table! {
use diesel::sql_types::*;
use crate::enums::diesel_exports::*;
- user_roles (id) {
+ user_roles (user_id, merchant_id) {
id -> Int4,
#[max_length = 64]
user_id -> Varchar,
@@ -1275,7 +1275,7 @@ diesel::table! {
use diesel::sql_types::*;
use crate::enums::diesel_exports::*;
- users (id) {
+ users (user_id) {
id -> Int4,
#[max_length = 64]
user_id -> Varchar,
diff --git a/crates/diesel_models/src/schema_v2.rs b/crates/diesel_models/src/schema_v2.rs
index a2e35a6d6a9..c831bbfa709 100644
--- a/crates/diesel_models/src/schema_v2.rs
+++ b/crates/diesel_models/src/schema_v2.rs
@@ -1166,7 +1166,7 @@ diesel::table! {
use diesel::sql_types::*;
use crate::enums::diesel_exports::*;
- roles (id) {
+ roles (role_id) {
id -> Int4,
#[max_length = 64]
role_name -> Varchar,
@@ -1249,7 +1249,7 @@ diesel::table! {
use diesel::sql_types::*;
use crate::enums::diesel_exports::*;
- user_roles (id) {
+ user_roles (user_id, merchant_id) {
id -> Int4,
#[max_length = 64]
user_id -> Varchar,
@@ -1273,7 +1273,7 @@ diesel::table! {
use diesel::sql_types::*;
use crate::enums::diesel_exports::*;
- users (id) {
+ users (user_id) {
id -> Int4,
#[max_length = 64]
user_id -> Varchar,
diff --git a/migrations/2024-07-19-095541_change_primary_key_for_users/down.sql b/migrations/2024-07-19-095541_change_primary_key_for_users/down.sql
new file mode 100644
index 00000000000..6ba57be2af4
--- /dev/null
+++ b/migrations/2024-07-19-095541_change_primary_key_for_users/down.sql
@@ -0,0 +1,5 @@
+-- This file should undo anything in `up.sql`
+ALTER TABLE users DROP CONSTRAINT users_pkey;
+
+ALTER TABLE users
+ADD PRIMARY KEY (id);
diff --git a/migrations/2024-07-19-095541_change_primary_key_for_users/up.sql b/migrations/2024-07-19-095541_change_primary_key_for_users/up.sql
new file mode 100644
index 00000000000..3d53115c172
--- /dev/null
+++ b/migrations/2024-07-19-095541_change_primary_key_for_users/up.sql
@@ -0,0 +1,12 @@
+-- Your SQL goes here
+-- The below query will lock the users table
+-- Running this query is not necessary on higher environments
+-- as the application will work fine without these queries being run
+-- This query should be run after the new version of application is deployed
+ALTER TABLE users DROP CONSTRAINT users_pkey;
+
+-- Use the `user_id` columns as primary key
+-- These are already unique, not null column
+-- So this query should not fail for not null or duplicate value reasons
+ALTER TABLE users
+ADD PRIMARY KEY (user_id);
diff --git a/migrations/2024-07-19-100016_change_primary_key_for_user_roles/down.sql b/migrations/2024-07-19-100016_change_primary_key_for_user_roles/down.sql
new file mode 100644
index 00000000000..47b9f679c40
--- /dev/null
+++ b/migrations/2024-07-19-100016_change_primary_key_for_user_roles/down.sql
@@ -0,0 +1,5 @@
+-- This file should undo anything in `up.sql`
+ALTER TABLE user_roles DROP CONSTRAINT user_roles_pkey;
+
+ALTER TABLE user_roles
+ADD PRIMARY KEY (id);
diff --git a/migrations/2024-07-19-100016_change_primary_key_for_user_roles/up.sql b/migrations/2024-07-19-100016_change_primary_key_for_user_roles/up.sql
new file mode 100644
index 00000000000..65d9c61fcb8
--- /dev/null
+++ b/migrations/2024-07-19-100016_change_primary_key_for_user_roles/up.sql
@@ -0,0 +1,12 @@
+-- Your SQL goes here
+-- The below query will lock the user_roles table
+-- Running this query is not necessary on higher environments
+-- as the application will work fine without these queries being run
+-- This query should be run after the new version of application is deployed
+ALTER TABLE user_roles DROP CONSTRAINT user_roles_pkey;
+
+-- Use the `user_id, merchant_id` columns as primary key
+-- These are already unique, not null columns
+-- So this query should not fail for not null or duplicate value reasons
+ALTER TABLE user_roles
+ADD PRIMARY KEY (user_id, merchant_id);
diff --git a/migrations/2024-07-19-100936_change_primary_key_for_roles/down.sql b/migrations/2024-07-19-100936_change_primary_key_for_roles/down.sql
new file mode 100644
index 00000000000..70e4d1674af
--- /dev/null
+++ b/migrations/2024-07-19-100936_change_primary_key_for_roles/down.sql
@@ -0,0 +1,5 @@
+-- This file should undo anything in `up.sql`
+ALTER TABLE roles DROP CONSTRAINT roles_pkey;
+
+ALTER TABLE roles
+ADD PRIMARY KEY (id);
diff --git a/migrations/2024-07-19-100936_change_primary_key_for_roles/up.sql b/migrations/2024-07-19-100936_change_primary_key_for_roles/up.sql
new file mode 100644
index 00000000000..8bde2a3b426
--- /dev/null
+++ b/migrations/2024-07-19-100936_change_primary_key_for_roles/up.sql
@@ -0,0 +1,12 @@
+-- Your SQL goes here
+-- The below query will lock the user_roles table
+-- Running this query is not necessary on higher environments
+-- as the application will work fine without these queries being run
+-- This query should be run after the new version of application is deployed
+ALTER TABLE roles DROP CONSTRAINT roles_pkey;
+
+-- Use the `role_id` column as primary key
+-- These are already unique, not null column
+-- So this query should not fail for not null or duplicate value reasons
+ALTER TABLE roles
+ADD PRIMARY KEY (role_id);
|
2024-07-19T10:27:39Z
|
## Type of Change
<!-- Put an `x` in the boxes that apply -->
- [ ] Bugfix
- [ ] New feature
- [ ] Enhancement
- [x] Refactoring
- [ ] Dependency updates
- [ ] Documentation
- [ ] CI/CD
## Description
<!-- Describe your changes in detail -->
Changing the primary key of the following table from (id) to the specified new keys:
users => user_id
user_roles => (user_id, merchant_id)
roles => role_id
### Additional Changes
- [ ] This PR modifies the API contract
- [x] This PR modifies the database schema
- [ ] This PR modifies application configuration/environment variables
<!--
Provide links to the files with corresponding changes.
Following are the paths where you can find config files:
1. `config`
2. `crates/router/src/configs`
3. `loadtest/config`
-->
## Motivation and Context
<!--
Why is this change required? What problem does it solve?
If it fixes an open issue, please link to the issue here.
If you don't have an issue, we'd recommend starting with one first so the PR
can focus on the implementation (unless it is an obvious bug or documentation fix
that will have little conversation).
-->
Required for api_v2
## How did you test it?
<!--
Did you write an integration/unit/API test to verify the code changes?
Or did you test this change manually (provide relevant screenshots)?
-->
Checked by compiling the code
## Checklist
<!-- Put an `x` in the boxes that apply -->
- [x] I formatted the code `cargo +nightly fmt --all`
- [x] I addressed lints thrown by `cargo clippy`
- [x] I reviewed the submitted code
- [ ] I added unit tests for my changes where possible
|
476aed5036eb41671c0736887d02dcac7f3573c6
|
|
juspay/hyperswitch
|
juspay__hyperswitch-5371
|
Bug: Make `original_payment_authorized_currency` and `original_payment_authorized_amount` mandatory fields for `Discover` cards and `Cybersource` connector during payment method migration.
Make original_payment_authorized_currency and original_payment_authorized_amount mandatory fields for Discover cards and Cybersource connector during payment method migration.
|
diff --git a/crates/api_models/src/payment_methods.rs b/crates/api_models/src/payment_methods.rs
index 7799cc24df2..1ca01114dd5 100644
--- a/crates/api_models/src/payment_methods.rs
+++ b/crates/api_models/src/payment_methods.rs
@@ -1428,12 +1428,8 @@ impl From<PaymentMethodRecord> for PaymentMethodMigrate {
PaymentsMandateReferenceRecord {
connector_mandate_id: record.payment_instrument_id.peek().to_string(),
payment_method_type: record.payment_method_type,
- original_payment_authorized_amount: record
- .original_transaction_amount
- .or(Some(1000)),
- original_payment_authorized_currency: record
- .original_transaction_currency
- .or(Some(common_enums::Currency::USD)),
+ original_payment_authorized_amount: record.original_transaction_amount,
+ original_payment_authorized_currency: record.original_transaction_currency,
},
);
Self {
diff --git a/crates/router/src/core/payment_methods/cards.rs b/crates/router/src/core/payment_methods/cards.rs
index 0a3007b572c..5f5e59a89a5 100644
--- a/crates/router/src/core/payment_methods/cards.rs
+++ b/crates/router/src/core/payment_methods/cards.rs
@@ -278,17 +278,30 @@ pub async fn migrate_payment_method(
merchant_account: &domain::MerchantAccount,
key_store: &domain::MerchantKeyStore,
) -> errors::RouterResponse<api::PaymentMethodResponse> {
+ let mut req = req;
let card_details = req.card.as_ref().get_required_value("card")?;
let card_number_validation_result =
cards::CardNumber::from_str(card_details.card_number.peek());
+ let card_bin_details =
+ populate_bin_details_for_masked_card(card_details, &*state.store).await?;
+
+ req.card = Some(api_models::payment_methods::MigrateCardDetail {
+ card_issuing_country: card_bin_details.issuer_country.clone(),
+ card_network: card_bin_details.card_network.clone(),
+ card_issuer: card_bin_details.card_issuer.clone(),
+ card_type: card_bin_details.card_type.clone(),
+ ..card_details.clone()
+ });
+
if let Some(connector_mandate_details) = &req.connector_mandate_details {
helpers::validate_merchant_connector_ids_in_connector_mandate_details(
&state,
key_store,
connector_mandate_details,
merchant_id,
+ card_bin_details.card_network.clone(),
)
.await?;
};
@@ -316,18 +329,130 @@ pub async fn migrate_payment_method(
merchant_id.into(),
key_store,
merchant_account,
+ card_bin_details.clone(),
)
.await
}
}
}
+pub async fn populate_bin_details_for_masked_card(
+ card_details: &api_models::payment_methods::MigrateCardDetail,
+ db: &dyn db::StorageInterface,
+) -> errors::CustomResult<api::CardDetailFromLocker, errors::ApiErrorResponse> {
+ helpers::validate_card_expiry(&card_details.card_exp_month, &card_details.card_exp_year)?;
+ let card_number = card_details.card_number.clone();
+
+ let (card_isin, _last4_digits) = get_card_bin_and_last4_digits_for_masked_card(
+ card_number.peek(),
+ )
+ .change_context(errors::ApiErrorResponse::InvalidRequestData {
+ message: "Invalid card number".to_string(),
+ })?;
+
+ let card_bin_details = if card_details.card_issuer.is_some()
+ && card_details.card_network.is_some()
+ && card_details.card_type.is_some()
+ && card_details.card_issuing_country.is_some()
+ {
+ api_models::payment_methods::CardDetailFromLocker::foreign_try_from((card_details, None))?
+ } else {
+ let card_info = db
+ .get_card_info(&card_isin)
+ .await
+ .map_err(|error| services::logger::error!(card_info_error=?error))
+ .ok()
+ .flatten();
+
+ api_models::payment_methods::CardDetailFromLocker::foreign_try_from((
+ card_details,
+ card_info,
+ ))?
+ };
+ Ok(card_bin_details)
+}
+
+impl
+ ForeignTryFrom<(
+ &api_models::payment_methods::MigrateCardDetail,
+ Option<diesel_models::CardInfo>,
+ )> for api_models::payment_methods::CardDetailFromLocker
+{
+ type Error = error_stack::Report<errors::ApiErrorResponse>;
+ fn foreign_try_from(
+ (card_details, card_info): (
+ &api_models::payment_methods::MigrateCardDetail,
+ Option<diesel_models::CardInfo>,
+ ),
+ ) -> Result<Self, Self::Error> {
+ let (card_isin, last4_digits) =
+ get_card_bin_and_last4_digits_for_masked_card(card_details.card_number.peek())
+ .change_context(errors::ApiErrorResponse::InvalidRequestData {
+ message: "Invalid card number".to_string(),
+ })?;
+ if let Some(card_bin_info) = card_info {
+ Ok(Self {
+ scheme: card_details
+ .card_network
+ .clone()
+ .or(card_bin_info.card_network.clone())
+ .map(|card_network| card_network.to_string()),
+ last4_digits: Some(last4_digits.clone()),
+ issuer_country: card_details
+ .card_issuing_country
+ .clone()
+ .or(card_bin_info.card_issuing_country),
+ card_number: None,
+ expiry_month: Some(card_details.card_exp_month.clone()),
+ expiry_year: Some(card_details.card_exp_year.clone()),
+ card_token: None,
+ card_fingerprint: None,
+ card_holder_name: card_details.card_holder_name.clone(),
+ nick_name: card_details.nick_name.clone(),
+ card_isin: Some(card_isin.clone()),
+ card_issuer: card_details
+ .card_issuer
+ .clone()
+ .or(card_bin_info.card_issuer),
+ card_network: card_details
+ .card_network
+ .clone()
+ .or(card_bin_info.card_network),
+ card_type: card_details.card_type.clone().or(card_bin_info.card_type),
+ saved_to_locker: false,
+ })
+ } else {
+ Ok(Self {
+ scheme: card_details
+ .card_network
+ .clone()
+ .map(|card_network| card_network.to_string()),
+ last4_digits: Some(last4_digits.clone()),
+ issuer_country: card_details.card_issuing_country.clone(),
+ card_number: None,
+ expiry_month: Some(card_details.card_exp_month.clone()),
+ expiry_year: Some(card_details.card_exp_year.clone()),
+ card_token: None,
+ card_fingerprint: None,
+ card_holder_name: card_details.card_holder_name.clone(),
+ nick_name: card_details.nick_name.clone(),
+ card_isin: Some(card_isin.clone()),
+ card_issuer: card_details.card_issuer.clone(),
+ card_network: card_details.card_network.clone(),
+ card_type: card_details.card_type.clone(),
+ saved_to_locker: false,
+ })
+ }
+ }
+}
+
pub async fn skip_locker_call_and_migrate_payment_method(
state: routes::SessionState,
req: &api::PaymentMethodMigrate,
merchant_id: String,
key_store: &domain::MerchantKeyStore,
merchant_account: &domain::MerchantAccount,
+ card: api_models::payment_methods::CardDetailFromLocker,
) -> errors::RouterResponse<api::PaymentMethodResponse> {
let db = &*state.store;
let customer_id = req.customer_id.clone().get_required_value("customer_id")?;
@@ -362,132 +487,15 @@ pub async fn skip_locker_call_and_migrate_payment_method(
.await
.to_not_found_response(errors::ApiErrorResponse::CustomerNotFound)?;
- let card = if let Some(card_details) = &req.card {
- helpers::validate_card_expiry(&card_details.card_exp_month, &card_details.card_exp_year)?;
- let card_number = card_details.card_number.clone();
-
- let (card_isin, last4_digits) = get_card_bin_and_last4_digits_for_masked_card(
- card_number.peek(),
- )
- .change_context(errors::ApiErrorResponse::InvalidRequestData {
- message: "Invalid card number".to_string(),
- })?;
-
- if card_details.card_issuer.is_some()
- && card_details.card_network.is_some()
- && card_details.card_type.is_some()
- && card_details.card_issuing_country.is_some()
- {
- Some(api::CardDetailFromLocker {
- scheme: card_details
- .card_network
- .clone()
- .or(card_details.card_network.clone())
- .map(|card_network| card_network.to_string()),
- last4_digits: Some(last4_digits.clone()),
- issuer_country: card_details
- .card_issuing_country
- .clone()
- .or(card_details.card_issuing_country.clone()),
- card_number: None,
- expiry_month: Some(card_details.card_exp_month.clone()),
- expiry_year: Some(card_details.card_exp_year.clone()),
- card_token: None,
- card_fingerprint: None,
- card_holder_name: card_details.card_holder_name.clone(),
- nick_name: card_details.nick_name.clone(),
- card_isin: Some(card_isin.clone()),
- card_issuer: card_details
- .card_issuer
- .clone()
- .or(card_details.card_issuer.clone()),
- card_network: card_details
- .card_network
- .clone()
- .or(card_details.card_network.clone()),
- card_type: card_details
- .card_type
- .clone()
- .or(card_details.card_type.clone()),
- saved_to_locker: false,
- })
- } else {
- Some(
- db.get_card_info(&card_isin)
- .await
- .map_err(|error| services::logger::error!(card_info_error=?error))
- .ok()
- .flatten()
- .map(|card_info| {
- logger::debug!("Fetching bin details");
- api::CardDetailFromLocker {
- scheme: card_details
- .card_network
- .clone()
- .or(card_info.card_network.clone())
- .map(|card_network| card_network.to_string()),
- last4_digits: Some(last4_digits.clone()),
- issuer_country: card_details
- .card_issuing_country
- .clone()
- .or(card_info.card_issuing_country),
- card_number: None,
- expiry_month: Some(card_details.card_exp_month.clone()),
- expiry_year: Some(card_details.card_exp_year.clone()),
- card_token: None,
- card_fingerprint: None,
- card_holder_name: card_details.card_holder_name.clone(),
- nick_name: card_details.nick_name.clone(),
- card_isin: Some(card_isin.clone()),
- card_issuer: card_details.card_issuer.clone().or(card_info.card_issuer),
- card_network: card_details
- .card_network
- .clone()
- .or(card_info.card_network),
- card_type: card_details.card_type.clone().or(card_info.card_type),
- saved_to_locker: false,
- }
- })
- .unwrap_or_else(|| {
- logger::debug!("Failed to fetch bin details");
- api::CardDetailFromLocker {
- scheme: card_details
- .card_network
- .clone()
- .map(|card_network| card_network.to_string()),
- last4_digits: Some(last4_digits.clone()),
- issuer_country: card_details.card_issuing_country.clone(),
- card_number: None,
- expiry_month: Some(card_details.card_exp_month.clone()),
- expiry_year: Some(card_details.card_exp_year.clone()),
- card_token: None,
- card_fingerprint: None,
- card_holder_name: card_details.card_holder_name.clone(),
- nick_name: card_details.nick_name.clone(),
- card_isin: Some(card_isin.clone()),
- card_issuer: card_details.card_issuer.clone(),
- card_network: card_details.card_network.clone(),
- card_type: card_details.card_type.clone(),
- saved_to_locker: false,
- }
- }),
- )
- }
- } else {
- None
- };
-
- let payment_method_card_details = card
- .as_ref()
- .map(|card| PaymentMethodsData::Card(CardDetailsPaymentMethod::from(card.clone())));
+ let payment_method_card_details =
+ PaymentMethodsData::Card(CardDetailsPaymentMethod::from(card.clone()));
- let payment_method_data_encrypted: Option<Encryptable<Secret<serde_json::Value>>> =
- payment_method_card_details
- .async_map(|card_details| create_encrypted_data(&state, key_store, card_details))
+ let payment_method_data_encrypted: Option<Encryptable<Secret<serde_json::Value>>> = Some(
+ create_encrypted_data(&state, key_store, payment_method_card_details)
.await
- .transpose()
.change_context(errors::ApiErrorResponse::InternalServerError)
- .attach_printable("Unable to encrypt Payment method card details")?;
+ .attach_printable("Unable to encrypt Payment method card details")?,
+ );
let payment_method_metadata: Option<serde_json::Value> =
req.metadata.as_ref().map(|data| data.peek()).cloned();
@@ -506,10 +514,7 @@ pub async fn skip_locker_call_and_migrate_payment_method(
payment_method: req.payment_method,
payment_method_type: req.payment_method_type,
payment_method_issuer: req.payment_method_issuer.clone(),
- scheme: req
- .card_network
- .clone()
- .or(card.clone().and_then(|card| card.scheme.clone())),
+ scheme: req.card_network.clone().or(card.scheme.clone()),
metadata: payment_method_metadata.map(Secret::new),
payment_method_data: payment_method_data_encrypted.map(Into::into),
connector_mandate_details: Some(connector_mandate_details),
@@ -554,7 +559,7 @@ pub async fn skip_locker_call_and_migrate_payment_method(
.map_err(|error| logger::error!(?error, "Failed to set the payment method as default"));
}
Ok(services::api::ApplicationResponse::Json(
- api::PaymentMethodResponse::foreign_from((card, response)),
+ api::PaymentMethodResponse::foreign_from((Some(card), response)),
))
}
diff --git a/crates/router/src/core/payments/helpers.rs b/crates/router/src/core/payments/helpers.rs
index ecf8ff0c40d..aa630ad9835 100644
--- a/crates/router/src/core/payments/helpers.rs
+++ b/crates/router/src/core/payments/helpers.rs
@@ -5085,6 +5085,7 @@ pub async fn validate_merchant_connector_ids_in_connector_mandate_details(
key_store: &domain::MerchantKeyStore,
connector_mandate_details: &api_models::payment_methods::PaymentsMandateReference,
merchant_id: &str,
+ card_network: Option<api_enums::CardNetwork>,
) -> CustomResult<(), errors::ApiErrorResponse> {
let db = &*state.store;
let merchant_connector_account_list = db
@@ -5097,20 +5098,49 @@ pub async fn validate_merchant_connector_ids_in_connector_mandate_details(
.await
.to_not_found_response(errors::ApiErrorResponse::InternalServerError)?;
- let merchant_connector_ids: Vec<String> = merchant_connector_account_list
+ let merchant_connector_account_details_hash_map: std::collections::HashMap<
+ String,
+ domain::MerchantConnectorAccount,
+ > = merchant_connector_account_list
.iter()
- .map(|merchant_connector_account| merchant_connector_account.merchant_connector_id.clone())
+ .map(|merchant_connector_account| {
+ (
+ merchant_connector_account.merchant_connector_id.clone(),
+ merchant_connector_account.clone(),
+ )
+ })
.collect();
- for merchant_connector_id in connector_mandate_details.0.keys() {
- if !merchant_connector_ids.contains(merchant_connector_id) {
- Err(errors::ApiErrorResponse::InvalidDataValue {
- field_name: "merchant_connector_id",
- })
- .attach_printable_lazy(|| {
- format!("{merchant_connector_id} invalid merchant connector id in connector_mandate_details")
- })?
- }
+ for (migrating_merchant_connector_id, migrating_connector_mandate_details) in
+ connector_mandate_details.0.clone()
+ {
+ match (card_network.clone() ,merchant_connector_account_details_hash_map.get(&migrating_merchant_connector_id)) {
+ (Some(enums::CardNetwork::Discover),Some(merchant_connector_account_details)) => if let ("cybersource", None) = (
+ merchant_connector_account_details.connector_name.as_str(),
+ migrating_connector_mandate_details
+ .original_payment_authorized_amount
+ .zip(
+ migrating_connector_mandate_details
+ .original_payment_authorized_currency,
+ ),
+ ) {
+ Err(errors::ApiErrorResponse::MissingRequiredFields {
+ field_names: vec![
+ "original_payment_authorized_currency",
+ "original_payment_authorized_amount",
+ ],
+ }).attach_printable(format!("Invalid connector_mandate_details provided for connector {migrating_merchant_connector_id}"))?
+ },
+ (_, Some(_)) => (),
+ (_, None) => {
+ Err(errors::ApiErrorResponse::InvalidDataValue {
+ field_name: "merchant_connector_id",
+ })
+ .attach_printable_lazy(|| {
+ format!("{migrating_merchant_connector_id} invalid merchant connector id in connector_mandate_details")
+ })?
+ },
+ }
}
Ok(())
}
|
2024-07-19T08:01:57Z
|
## Type of Change
<!-- Put an `x` in the boxes that apply -->
- [ ] Bugfix
- [ ] New feature
- [ ] Enhancement
- [x] Refactoring
- [ ] Dependency updates
- [ ] Documentation
- [ ] CI/CD
## Description
<!-- Describe your changes in detail -->
Make `original_payment_authorized_currency` and `original_payment_authorized_amount` mandatory fields for Discover cards and `Cybersource` connector during payment method migration.
### Additional Changes
- [ ] This PR modifies the API contract
- [ ] This PR modifies the database schema
- [ ] This PR modifies application configuration/environment variables
<!--
Provide links to the files with corresponding changes.
Following are the paths where you can find config files:
1. `config`
2. `crates/router/src/configs`
3. `loadtest/config`
-->
## Motivation and Context
<!--
Why is this change required? What problem does it solve?
If it fixes an open issue, please link to the issue here.
If you don't have an issue, we'd recommend starting with one first so the PR
can focus on the implementation (unless it is an obvious bug or documentation fix
that will have little conversation).
-->
## How did you test it?
<!--
Did you write an integration/unit/API test to verify the code changes?
Or did you test this change manually (provide relevant screenshots)?
-->
-> Create a merchant connector account for cybersource
-> Create a customer
```
curl --location 'http://localhost:8080/customers' \
--header 'Content-Type: application/json' \
--header 'Accept: application/json' \
--header 'api-key: dev_1oC3ReWVy4AaGA8ORA6EMm8JHS5WTlsmBtfRnNp2LLemMxZEJXfZ9hLYsd9wmWtg' \
--data-raw '{
"customer_id": "cu_1721377355",
"email": "guest@example.com",
"name": "John Doe",
"phone": "999999999",
"phone_country_code": "+65",
"description": "First customer",
"address": {
"line1": "1467",
"line2": "Harrison Street",
"line3": "Harrison Street",
"city": "San Fransico",
"state": "California",
"zip": "94122",
"country": "US",
"first_name": "John",
"last_name": "Doe"
},
"metadata": {
"udf1": "value1",
"new_customer": "true",
"login_date": "2019-09-10T10:11:12Z"
}
}'
```
```
{
"customer_id": "cu_1721377384",
"name": "John Doe",
"email": "guest@example.com",
"phone": "999999999",
"phone_country_code": "+65",
"description": "First customer",
"address": {
"city": "San Fransico",
"country": "US",
"line1": "1467",
"line2": "Harrison Street",
"line3": "Harrison Street",
"zip": "94122",
"state": "California",
"first_name": "John",
"last_name": "Doe"
},
"created_at": "2024-07-19T08:23:04.632Z",
"metadata": {
"udf1": "value1",
"new_customer": "true",
"login_date": "2019-09-10T10:11:12Z"
},
"default_payment_method_id": null
}
```
-> Migrate the payment method without the `original_payment_authorized_amount` and `original_payment_authorized_currency` for `discover` card
```
curl --location 'http://localhost:8080/payment_methods/migrate' \
--header 'api-key: test_admin' \
--header 'Content-Type: application/json' \
--data '{
"payment_method": "card",
"merchant_id": "merchant_1721375416",
"card": {
"card_number": "6011111111111117",
"card_exp_month": "10",
"card_exp_year": "33",
"nick_name": "Joh"
},
"customer_id": "cu_1721375441",
"connector_mandate_details": {
"mca_k9zWJaOP2XzQbygmkerU": {
"connector_mandate_id": "juaghfija"
}
}
}
'
```
```
{
"error": {
"type": "invalid_request",
"message": "Missing required params",
"code": "IR_21",
"data": [
"original_payment_authorized_currency",
"original_payment_authorized_amount"
]
}
}
```
-> With the `original_payment_authorized_amount` and `original_payment_authorized_currency` for `discover` card
```
curl --location 'http://localhost:8080/payment_methods/migrate' \
--header 'api-key: test_admin' \
--header 'Content-Type: application/json' \
--data '{
"payment_method": "card",
"merchant_id": "merchant_1721375416",
"card": {
"card_number": "601111xxxxxx1117",
"card_exp_month": "10",
"card_exp_year": "33",
"nick_name": "Joh"
},
"customer_id": "cu_1721375441",
"connector_mandate_details": {
"mca_k9zWJaOP2XzQbygmkerU": {
"connector_mandate_id": "khaifhq",
"original_payment_authorized_amount": 6560,
"original_payment_authorized_currency": "USD"
}
}
}
'
```
-> without the `original_payment_authorized_amount` and `original_payment_authorized_currency` for `visa`
```
curl --location 'http://localhost:8080/payment_methods/migrate' \
--header 'api-key: test_admin' \
--header 'Content-Type: application/json' \
--data '{
"payment_method": "card",
"merchant_id": "merchant_1721375416",
"card": {
"card_number": "424242xxxxxx4242",
"card_exp_month": "10",
"card_exp_year": "33",
"nick_name": "Joh"
},
"customer_id": "cu_1721375441",
"connector_mandate_details": {
"mca_k9zWJaOP2XzQbygmkerU": {
"connector_mandate_id": "1BF10FB47729ADD7E063AF598E0A9908"
}
}
}
'
```
```
{
"merchant_id": "merchant_1721375416",
"customer_id": "cu_1721375441",
"payment_method_id": "pm_ZwoZZ11YSzX8iGECSUe1",
"payment_method": "card",
"payment_method_type": null,
"card": {
"scheme": "Visa",
"issuer_country": "UNITEDKINGDOM",
"last4_digits": "4242",
"expiry_month": "10",
"expiry_year": "33",
"card_token": null,
"card_holder_name": null,
"card_fingerprint": null,
"nick_name": "Joh",
"card_network": "Visa",
"card_isin": "424242",
"card_issuer": "STRIPE PAYMENTS UK LIMITED",
"card_type": "CREDIT",
"saved_to_locker": false
},
"recurring_enabled": false,
"installment_payment_enabled": false,
"payment_experience": null,
"metadata": null,
"created": "2024-07-19T08:28:28.586Z",
"last_used_at": null,
"client_secret": null
}
```
-> Make a MIT with the migrated payment method details
```
curl --location 'http://localhost:8080/payment_methods/migrate' \
--header 'api-key: test_admin' \
--header 'Content-Type: application/json' \
--data '{
"payment_method": "card",
"merchant_id": "merchant_1721375416",
"card": {
"card_number": "424242xxxxxx4242",
"card_exp_month": "10",
"card_exp_year": "33",
"nick_name": "Joh"
},
"customer_id": "cu_1721375441",
"connector_mandate_details": {
"mca_k9zWJaOP2XzQbygmkerU": {
"connector_mandate_id": "hiahfi"
}
}
}
'
```
```
{
"merchant_id": "merchant_1721375416",
"customer_id": "cu_1721375441",
"payment_method_id": "pm_MQkdTmCFjDcuSoDsaNQY",
"payment_method": "card",
"payment_method_type": null,
"card": {
"scheme": "Visa",
"issuer_country": "UNITEDKINGDOM",
"last4_digits": "4242",
"expiry_month": "10",
"expiry_year": "33",
"card_token": null,
"card_holder_name": null,
"card_fingerprint": null,
"nick_name": "Joh",
"card_network": "Visa",
"card_isin": "424242",
"card_issuer": "STRIPE PAYMENTS UK LIMITED",
"card_type": "CREDIT",
"saved_to_locker": false
},
"recurring_enabled": false,
"installment_payment_enabled": false,
"payment_experience": null,
"metadata": null,
"created": "2024-07-19T09:10:00.443Z",
"last_used_at": null,
"client_secret": null
}
```
-> Create a payment with confirm false with the above customer id
```
curl --location 'http://localhost:8080/payments' \
--header 'Accept: application/json' \
--header 'api-key: dev_1oC3ReWVy4AaGA8ORA6EMm8JHS5WTlsmBtfRnNp2LLemMxZEJXfZ9hLYsd9wmWtg' \
--header 'Content-Type: application/json' \
--data '{
"amount": 10000,
"currency": "USD",
"capture_method": "automatic",
"authentication_type": "no_three_ds",
"confirm": false,
"setup_future_usage": "off_session",
"customer_id": "cu_1721375441"
}'
```
```
{
"payment_id": "pay_j5a3ywnN1phsL3wzUAcm",
"merchant_id": "merchant_1721375416",
"status": "requires_payment_method",
"amount": 10000,
"net_amount": 10000,
"amount_capturable": 0,
"amount_received": null,
"connector": null,
"client_secret": "pay_j5a3ywnN1phsL3wzUAcm_secret_5rlnu9oeMJmtgXb3ZBLq",
"created": "2024-07-19T09:12:34.290Z",
"currency": "USD",
"customer_id": "cu_1721375441",
"customer": {
"id": "cu_1721375441",
"name": "John Doe",
"email": "guest@example.com",
"phone": "999999999",
"phone_country_code": "+65"
},
"description": null,
"refunds": null,
"disputes": null,
"mandate_id": null,
"mandate_data": null,
"setup_future_usage": "off_session",
"off_session": null,
"capture_on": null,
"capture_method": "automatic",
"payment_method": null,
"payment_method_data": null,
"payment_token": null,
"shipping": null,
"billing": null,
"order_details": null,
"email": "guest@example.com",
"name": "John Doe",
"phone": "999999999",
"return_url": null,
"authentication_type": "no_three_ds",
"statement_descriptor_name": null,
"statement_descriptor_suffix": null,
"next_action": null,
"cancellation_reason": null,
"error_code": null,
"error_message": null,
"unified_code": null,
"unified_message": null,
"payment_experience": null,
"payment_method_type": null,
"connector_label": null,
"business_country": null,
"business_label": "default",
"business_sub_label": null,
"allowed_payment_method_types": null,
"ephemeral_key": {
"customer_id": "cu_1721375441",
"created_at": 1721380354,
"expires": 1721383954,
"secret": "epk_8e71524230c54b8c93aad028cefbee53"
},
"manual_retry_allowed": null,
"connector_transaction_id": null,
"frm_message": null,
"metadata": null,
"connector_metadata": null,
"feature_metadata": null,
"reference_id": null,
"payment_link": null,
"profile_id": "pro_Xr0FZLrIrMhCcomCOWSh",
"surcharge_details": null,
"attempt_count": 1,
"merchant_decision": null,
"merchant_connector_id": null,
"incremental_authorization_allowed": null,
"authorization_count": null,
"incremental_authorizations": null,
"external_authentication_details": null,
"external_3ds_authentication_attempted": false,
"expires_on": "2024-07-19T09:27:34.290Z",
"fingerprint": null,
"browser_info": null,
"payment_method_id": null,
"payment_method_status": null,
"updated": "2024-07-19T09:12:34.317Z",
"charges": null,
"frm_metadata": null,
"merchant_order_reference_id": null
}
```
-> List payment methods
```
curl --location 'http://localhost:8080/customers/payment_methods?client_secret=pay_j5a3ywnN1phsL3wzUAcm_secret_5rlnu9oeMJmtgXb3ZBLq' \
--header 'Accept: application/json' \
--header 'api-key: '
```
```
{
"customer_payment_methods": [
{
"payment_token": "token_pNplvKAPorPIvbXwefUW",
"payment_method_id": "pm_MQkdTmCFjDcuSoDsaNQY",
"customer_id": "cu_1721375441",
"payment_method": "card",
"payment_method_type": null,
"payment_method_issuer": null,
"payment_method_issuer_code": null,
"recurring_enabled": true,
"installment_payment_enabled": false,
"payment_experience": [
"redirect_to_url"
],
"card": {
"scheme": "Visa",
"issuer_country": "UNITEDKINGDOM",
"last4_digits": "4242",
"expiry_month": "10",
"expiry_year": "33",
"card_token": null,
"card_holder_name": null,
"card_fingerprint": null,
"nick_name": "Joh",
"card_network": "Visa",
"card_isin": "424242",
"card_issuer": "STRIPE PAYMENTS UK LIMITED",
"card_type": "CREDIT",
"saved_to_locker": false
},
"metadata": null,
"created": "2024-07-19T09:10:00.443Z",
"bank": null,
"surcharge_details": null,
"requires_cvv": false,
"last_used_at": "2024-07-19T09:10:00.443Z",
"default_payment_method_set": false,
"billing": null
}
"is_guest_customer": false
]
}
```
-> Confirm the payment
```
curl --location 'http://localhost:8080/payments/pay_j5a3ywnN1phsL3wzUAcm/confirm' \
--header 'api-key: pk_dev_032d2d2b7ccf4013b41cfcb815a331c4' \
--header 'Content-Type: application/json' \
--data '{
"payment_token": "token_pNplvKAPorPIvbXwefUW",
"client_secret": "pay_j5a3ywnN1phsL3wzUAcm_secret_5rlnu9oeMJmtgXb3ZBLq",
"payment_method": "card",
"billing": {
"address": {
"line1": "1467",
"line2": "Harrison Street",
"line3": "Harrison Street",
"city": "San Fransico",
"state": "California",
"zip": "94122",
"country": "US",
"first_name": "PiX",
"last_name": "ss"
}
}
}'
```
```
{
"payment_id": "pay_j5a3ywnN1phsL3wzUAcm",
"merchant_id": "merchant_1721375416",
"status": "succeeded",
"amount": 10000,
"net_amount": 10000,
"amount_capturable": 0,
"amount_received": 10000,
"connector": "cybersource",
"client_secret": "pay_j5a3ywnN1phsL3wzUAcm_secret_5rlnu9oeMJmtgXb3ZBLq",
"created": "2024-07-19T09:12:34.290Z",
"currency": "USD",
"customer_id": "cu_1721375441",
"customer": {
"id": "cu_1721375441",
"name": "John Doe",
"email": "guest@example.com",
"phone": "999999999",
"phone_country_code": "+65"
},
"description": null,
"refunds": null,
"disputes": null,
"mandate_id": null,
"mandate_data": null,
"setup_future_usage": "off_session",
"off_session": null,
"capture_on": null,
"capture_method": "automatic",
"payment_method": null,
"payment_method_data": null,
"payment_token": "token_pNplvKAPorPIvbXwefUW",
"shipping": null,
"billing": {
"address": {
"city": "San Fransico",
"country": "US",
"line1": "1467",
"line2": "Harrison Street",
"line3": "Harrison Street",
"zip": "94122",
"state": "California",
"first_name": "PiX",
"last_name": "ss"
},
"phone": null,
"email": null
},
"order_details": null,
"email": "guest@example.com",
"name": "John Doe",
"phone": "999999999",
"return_url": null,
"authentication_type": "no_three_ds",
"statement_descriptor_name": null,
"statement_descriptor_suffix": null,
"next_action": null,
"cancellation_reason": null,
"error_code": null,
"error_message": null,
"unified_code": null,
"unified_message": null,
"payment_experience": null,
"payment_method_type": null,
"connector_label": null,
"business_country": null,
"business_label": "default",
"business_sub_label": null,
"allowed_payment_method_types": null,
"ephemeral_key": null,
"manual_retry_allowed": false,
"connector_transaction_id": "7213805477216373003954",
"frm_message": null,
"metadata": null,
"connector_metadata": null,
"feature_metadata": null,
"reference_id": "pay_j5a3ywnN1phsL3wzUAcm_1",
"payment_link": null,
"profile_id": "pro_Xr0FZLrIrMhCcomCOWSh",
"surcharge_details": null,
"attempt_count": 1,
"merchant_decision": null,
"merchant_connector_id": "mca_k9zWJaOP2XzQbygmkerU",
"incremental_authorization_allowed": false,
"authorization_count": null,
"incremental_authorizations": null,
"external_authentication_details": null,
"external_3ds_authentication_attempted": false,
"expires_on": "2024-07-19T09:27:34.290Z",
"fingerprint": null,
"browser_info": {
"language": null,
"time_zone": null,
"ip_address": "::1",
"user_agent": null,
"color_depth": null,
"java_enabled": null,
"screen_width": null,
"accept_header": null,
"screen_height": null,
"java_script_enabled": null
},
"payment_method_id": "pm_MQkdTmCFjDcuSoDsaNQY",
"payment_method_status": "active",
"updated": "2024-07-19T09:15:48.395Z",
"charges": null,
"frm_metadata": null,
"merchant_order_reference_id": null
}
```
-> Connector request
```
raw_connector_request: Object {"processingInformation": Object {"actionList": Null, "actionTokenTypes": Null, "authorizationOptions": Object {"initiator": Null, "merchantIntitiatedTransaction": Object {"reason": Null, "previousTransactionId": Null, "originalAuthorizedAmount": Null}}, "commerceIndicator": String("internet"), "capture": Bool(true), "captureOptions": Null, "paymentSolution": Null}, "paymentInformation": Object {"paymentInstrument": Object {"id": String("*** alloc::string::String ***")}}, "orderInformation": Object {"amountDetails": Object {"totalAmount": String("100.00"), "currency": String("USD")}, "billTo": Object {"firstName": String("*** alloc::string::String ***"), "lastName": String("*** alloc::string::String ***"), "address1": String("*** alloc::string::String ***"), "locality": String("San Fransico"), "administrativeArea": String("*** alloc::string::String ***"), "postalCode": String("*** alloc::string::String ***"), "country": String("US"), "email": String("*****@example.com")}}, "clientReferenceInformation": Object {"code": String("pay_j5a3ywnN1phsL3wzUAcm_1")}}
```
-> Payment with migrated discover card
```
curl --location 'http://localhost:8080/payment_methods/migrate' \
--header 'api-key: test_admin' \
--header 'Content-Type: application/json' \
--data '{
"payment_method": "card",
"merchant_id": "merchant_1721375416",
"card": {
"card_number": "601111xxxxxx1117",
"card_exp_month": "10",
"card_exp_year": "33",
"nick_name": "Joh"
},
"customer_id": "cu_1721380681",
"connector_mandate_details": {
"mca_k9zWJaOP2XzQbygmkerU": {
"connector_mandate_id": "1BF10FB47729ADD7E063AF598E0A9908",
"original_payment_authorized_amount": 6560,
"original_payment_authorized_currency": "USD"
}
}
}
'
```
```
{
"merchant_id": "merchant_1721375416",
"customer_id": "cu_1721380681",
"payment_method_id": "pm_9cRR2r6E8cL69tpJnaNj",
"payment_method": "card",
"payment_method_type": null,
"card": {
"scheme": "Discover",
"issuer_country": null,
"last4_digits": "1117",
"expiry_month": "10",
"expiry_year": "33",
"card_token": null,
"card_holder_name": null,
"card_fingerprint": null,
"nick_name": "Joh",
"card_network": "Discover",
"card_isin": "601111",
"card_issuer": null,
"card_type": "CREDIT",
"saved_to_locker": false
},
"recurring_enabled": false,
"installment_payment_enabled": false,
"payment_experience": null,
"metadata": null,
"created": "2024-07-19T09:18:06.867Z",
"last_used_at": null,
"client_secret": null
}
```
```
curl --location 'http://localhost:8080/payments' \
--header 'Accept: application/json' \
--header 'api-key: dev_1oC3ReWVy4AaGA8ORA6EMm8JHS5WTlsmBtfRnNp2LLemMxZEJXfZ9hLYsd9wmWtg' \
--header 'Content-Type: application/json' \
--data '{
"amount": 10000,
"currency": "USD",
"capture_method": "automatic",
"authentication_type": "no_three_ds",
"confirm": false,
"setup_future_usage": "off_session",
"customer_id": "cu_1721380681"
}'
```
```
{
"payment_id": "pay_Lk545qXsXo4LdMgMLoDJ",
"merchant_id": "merchant_1721375416",
"status": "requires_payment_method",
"amount": 10000,
"net_amount": 10000,
"amount_capturable": 0,
"amount_received": null,
"connector": null,
"client_secret": "pay_Lk545qXsXo4LdMgMLoDJ_secret_kIFzEWppjSudovmGPpSb",
"created": "2024-07-19T09:18:15.484Z",
"currency": "USD",
"customer_id": "cu_1721380681",
"customer": {
"id": "cu_1721380681",
"name": "John Doe",
"email": "guest@example.com",
"phone": "999999999",
"phone_country_code": "+65"
},
"description": null,
"refunds": null,
"disputes": null,
"mandate_id": null,
"mandate_data": null,
"setup_future_usage": "off_session",
"off_session": null,
"capture_on": null,
"capture_method": "automatic",
"payment_method": null,
"payment_method_data": null,
"payment_token": null,
"shipping": null,
"billing": null,
"order_details": null,
"email": "guest@example.com",
"name": "John Doe",
"phone": "999999999",
"return_url": null,
"authentication_type": "no_three_ds",
"statement_descriptor_name": null,
"statement_descriptor_suffix": null,
"next_action": null,
"cancellation_reason": null,
"error_code": null,
"error_message": null,
"unified_code": null,
"unified_message": null,
"payment_experience": null,
"payment_method_type": null,
"connector_label": null,
"business_country": null,
"business_label": "default",
"business_sub_label": null,
"allowed_payment_method_types": null,
"ephemeral_key": {
"customer_id": "cu_1721380681",
"created_at": 1721380695,
"expires": 1721384295,
"secret": "epk_cdb56ad452eb4c11b1d7d8256683a3dc"
},
"manual_retry_allowed": null,
"connector_transaction_id": null,
"frm_message": null,
"metadata": null,
"connector_metadata": null,
"feature_metadata": null,
"reference_id": null,
"payment_link": null,
"profile_id": "pro_Xr0FZLrIrMhCcomCOWSh",
"surcharge_details": null,
"attempt_count": 1,
"merchant_decision": null,
"merchant_connector_id": null,
"incremental_authorization_allowed": null,
"authorization_count": null,
"incremental_authorizations": null,
"external_authentication_details": null,
"external_3ds_authentication_attempted": false,
"expires_on": "2024-07-19T09:33:15.484Z",
"fingerprint": null,
"browser_info": null,
"payment_method_id": null,
"payment_method_status": null,
"updated": "2024-07-19T09:18:15.505Z",
"charges": null,
"frm_metadata": null,
"merchant_order_reference_id": null
}
```
```
curl --location 'http://localhost:8080/customers/payment_methods?client_secret=pay_Lk545qXsXo4LdMgMLoDJ_secret_kIFzEWppjSudovmGPpSb' \
--header 'Accept: application/json' \
--header 'api-key: pk_dev_032d2d2b7ccf4013b41cfcb815a331c4'
```
```
{
"customer_payment_methods": [
{
"payment_token": "token_GgtGSli2dsvjLKdDCdN1",
"payment_method_id": "pm_9cRR2r6E8cL69tpJnaNj",
"customer_id": "cu_1721380681",
"payment_method": "card",
"payment_method_type": null,
"payment_method_issuer": null,
"payment_method_issuer_code": null,
"recurring_enabled": true,
"installment_payment_enabled": false,
"payment_experience": [
"redirect_to_url"
],
"card": {
"scheme": "Discover",
"issuer_country": null,
"last4_digits": "1117",
"expiry_month": "10",
"expiry_year": "33",
"card_token": null,
"card_holder_name": null,
"card_fingerprint": null,
"nick_name": "Joh",
"card_network": "Discover",
"card_isin": "601111",
"card_issuer": null,
"card_type": "CREDIT",
"saved_to_locker": false
},
"metadata": null,
"created": "2024-07-19T09:18:06.867Z",
"bank": null,
"surcharge_details": null,
"requires_cvv": false,
"last_used_at": "2024-07-19T09:18:06.867Z",
"default_payment_method_set": true,
"billing": null
}
],
"is_guest_customer": false
}
```
```
curl --location 'http://localhost:8080/payments/pay_Lk545qXsXo4LdMgMLoDJ/confirm' \
--header 'api-key: pk_dev_032d2d2b7ccf4013b41cfcb815a331c4' \
--header 'Content-Type: application/json' \
--data '{
"payment_token": "token_GgtGSli2dsvjLKdDCdN1",
"client_secret": "pay_Lk545qXsXo4LdMgMLoDJ_secret_kIFzEWppjSudovmGPpSb",
"payment_method": "card",
"billing": {
"address": {
"line1": "1467",
"line2": "Harrison Street",
"line3": "Harrison Street",
"city": "San Fransico",
"state": "California",
"zip": "94122",
"country": "US",
"first_name": "PiX",
"last_name": "ss"
}
}
}'
```
```
{
"payment_id": "pay_Lk545qXsXo4LdMgMLoDJ",
"merchant_id": "merchant_1721375416",
"status": "succeeded",
"amount": 10000,
"net_amount": 10000,
"amount_capturable": 0,
"amount_received": 10000,
"connector": "cybersource",
"client_secret": "pay_Lk545qXsXo4LdMgMLoDJ_secret_kIFzEWppjSudovmGPpSb",
"created": "2024-07-19T09:18:15.484Z",
"currency": "USD",
"customer_id": "cu_1721380681",
"customer": {
"id": "cu_1721380681",
"name": "John Doe",
"email": "guest@example.com",
"phone": "999999999",
"phone_country_code": "+65"
},
"description": null,
"refunds": null,
"disputes": null,
"mandate_id": null,
"mandate_data": null,
"setup_future_usage": "off_session",
"off_session": null,
"capture_on": null,
"capture_method": "automatic",
"payment_method": null,
"payment_method_data": null,
"payment_token": "token_GgtGSli2dsvjLKdDCdN1",
"shipping": null,
"billing": {
"address": {
"city": "San Fransico",
"country": "US",
"line1": "1467",
"line2": "Harrison Street",
"line3": "Harrison Street",
"zip": "94122",
"state": "California",
"first_name": "PiX",
"last_name": "ss"
},
"phone": null,
"email": null
},
"order_details": null,
"email": "guest@example.com",
"name": "John Doe",
"phone": "999999999",
"return_url": null,
"authentication_type": "no_three_ds",
"statement_descriptor_name": null,
"statement_descriptor_suffix": null,
"next_action": null,
"cancellation_reason": null,
"error_code": null,
"error_message": null,
"unified_code": null,
"unified_message": null,
"payment_experience": null,
"payment_method_type": null,
"connector_label": null,
"business_country": null,
"business_label": "default",
"business_sub_label": null,
"allowed_payment_method_types": null,
"ephemeral_key": null,
"manual_retry_allowed": false,
"connector_transaction_id": "7213807255186401603954",
"frm_message": null,
"metadata": null,
"connector_metadata": null,
"feature_metadata": null,
"reference_id": "pay_Lk545qXsXo4LdMgMLoDJ_1",
"payment_link": null,
"profile_id": "pro_Xr0FZLrIrMhCcomCOWSh",
"surcharge_details": null,
"attempt_count": 1,
"merchant_decision": null,
"merchant_connector_id": "mca_k9zWJaOP2XzQbygmkerU",
"incremental_authorization_allowed": false,
"authorization_count": null,
"incremental_authorizations": null,
"external_authentication_details": null,
"external_3ds_authentication_attempted": false,
"expires_on": "2024-07-19T09:33:15.484Z",
"fingerprint": null,
"browser_info": {
"language": null,
"time_zone": null,
"ip_address": "::1",
"user_agent": null,
"color_depth": null,
"java_enabled": null,
"screen_width": null,
"accept_header": null,
"screen_height": null,
"java_script_enabled": null
},
"payment_method_id": "pm_9cRR2r6E8cL69tpJnaNj",
"payment_method_status": "active",
"updated": "2024-07-19T09:18:46.232Z",
"charges": null,
"frm_metadata": null,
"merchant_order_reference_id": null
}
```
```
raw_connector_request: Object {"processingInformation": Object {"actionList": Null, "actionTokenTypes": Null, "authorizationOptions": Object {"initiator": Null, "merchantIntitiatedTransaction": Object {"reason": Null, "previousTransactionId": Null, "originalAuthorizedAmount": String("65.60")}}, "commerceIndicator": String("internet"), "capture": Bool(true), "captureOptions": Null, "paymentSolution": Null}, "paymentInformation": Object {"paymentInstrument": Object {"id": String("*** alloc::string::String ***")}}, "orderInformation": Object {"amountDetails": Object {"totalAmount": String("100.00"), "currency": String("USD")}, "billTo": Object {"firstName": String("*** alloc::string::String ***"), "lastName": String("*** alloc::string::String ***"), "address1": String("*** alloc::string::String ***"), "locality": String("San Fransico"), "administrativeArea": String("*** alloc::string::String ***"), "postalCode": String("*** alloc::string::String ***"), "country": String("US"), "email": String("*****@example.com")}}, "clientReferenceInformation": Object {"code": String("pay_Lk545qXsXo4LdMgMLoDJ_1")}}
```
-> Migrate the discover card for stripe without the `original_payment_authorized_amount` and `original_payment_authorized_currency`
```
curl --location 'http://localhost:8080/payment_methods/migrate' \
--header 'api-key: test_admin' \
--header 'Content-Type: application/json' \
--data '{
"payment_method": "card",
"merchant_id": "merchant_1721375416",
"card": {
"card_number": "601111xxxxxx1117",
"card_exp_month": "10",
"card_exp_year": "33",
"nick_name": "Joh"
},
"customer_id": "cu_1721380681",
"connector_mandate_details": {
"mca_tuuwWnqTVvyk5DOS8tO7": {
"connector_mandate_id": "aaaaa"
}
}
}
'
```
```
{
"merchant_id": "merchant_1721375416",
"customer_id": "cu_1721380681",
"payment_method_id": "pm_1sfzvLMBw0SVAdKRZcA2",
"payment_method": "card",
"payment_method_type": null,
"card": {
"scheme": "Discover",
"issuer_country": null,
"last4_digits": "1117",
"expiry_month": "10",
"expiry_year": "33",
"card_token": null,
"card_holder_name": null,
"card_fingerprint": null,
"nick_name": "Joh",
"card_network": "Discover",
"card_isin": "601111",
"card_issuer": null,
"card_type": "CREDIT",
"saved_to_locker": false
},
"recurring_enabled": false,
"installment_payment_enabled": false,
"payment_experience": null,
"metadata": null,
"created": "2024-07-19T09:22:42.387Z",
"last_used_at": null,
"client_secret": null
}
```
## Checklist
<!-- Put an `x` in the boxes that apply -->
- [x] I formatted the code `cargo +nightly fmt --all`
- [x] I addressed lints thrown by `cargo clippy`
- [x] I reviewed the submitted code
- [ ] I added unit tests for my changes where possible
|
1c825f465a42c71568db994c5d05ba72d8680564
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.