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
test_instructions
stringlengths
0
232k
juspay/hyperswitch
juspay__hyperswitch-3799
Bug: [BUG]: connector request is being built twice ### Bug Description When a payment is confirmed, the `connector_request` log is being printed twice ### Expected Behavior It should be printed only once ### Actual Behavior Two instances of the log line can be found ### Steps To Reproduce - Create a payment with `confirm` = `true` - Search for log with `connector_request` tag ### Context For The Bug _No response_ ### Environment Are you using hyperswitch hosted version? No ### 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/services/api.rs b/crates/router/src/services/api.rs index 1c4d1810c88..45decfd451d 100644 --- a/crates/router/src/services/api.rs +++ b/crates/router/src/services/api.rs @@ -338,30 +338,31 @@ where ], ); - let connector_request = connector_request.or(connector_integration - .build_request(req, &state.conf.connectors) - .map_err(|error| { - if matches!( - error.current_context(), - &errors::ConnectorError::RequestEncodingFailed - | &errors::ConnectorError::RequestEncodingFailedWithReason(_) - ) { - metrics::REQUEST_BUILD_FAILURE.add( - &metrics::CONTEXT, - 1, - &[metrics::request::add_attributes( - "connector", - req.connector.to_string(), - )], - ) - } - error - })?); + let connector_request = match connector_request { + Some(connector_request) => Some(connector_request), + None => connector_integration + .build_request(req, &state.conf.connectors) + .map_err(|error| { + if matches!( + error.current_context(), + &errors::ConnectorError::RequestEncodingFailed + | &errors::ConnectorError::RequestEncodingFailedWithReason(_) + ) { + metrics::REQUEST_BUILD_FAILURE.add( + &metrics::CONTEXT, + 1, + &[metrics::request::add_attributes( + "connector", + req.connector.to_string(), + )], + ) + } + error + })?, + }; match connector_request { Some(request) => { - logger::debug!(connector_request=?request); - let masked_request_body = match &request.body { Some(request) => match request { RequestContent::Json(i) @@ -1828,7 +1829,7 @@ pub fn build_redirection_form( threeDSsecureInterface.on('challenge', function(e) {{ console.log('Challenged'); - document.getElementById('loader-wrapper').style.display = 'none'; + document.getElementById('loader-wrapper').style.display = 'none'; }}); threeDSsecureInterface.on('complete', function(e) {{
2024-02-26T13:04:52Z
## Type of Change <!-- Put an `x` in the boxes that apply --> - [x] Bugfix ## Description <!-- Describe your changes in detail --> This PR fixes the duplicate request that was being constructed even if the connector_request already exists. ## 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). --> The `or()` function does eager evaluation. This means that even if there is Some(val) the part of code in the or part is evaluated. This is causing the request to be constructed twice. Fixes #3799 ## 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)? --> - Manual, compiler guided. - Create a payment and check if `connector_request` is logged only once. ## 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
75c633fc7c37341177597041ccbcdfc3cf9e236f
- Manual, compiler guided. - Create a payment and check if `connector_request` is logged only once.
juspay/hyperswitch
juspay__hyperswitch-3781
Bug: create api for custom roles Create apis for - create custom role - update custom role
diff --git a/crates/api_models/src/events/user_role.rs b/crates/api_models/src/events/user_role.rs index 2b8d0221497..f19ff95f9ed 100644 --- a/crates/api_models/src/events/user_role.rs +++ b/crates/api_models/src/events/user_role.rs @@ -1,8 +1,11 @@ use common_utils::events::{ApiEventMetric, ApiEventsType}; use crate::user_role::{ - AcceptInvitationRequest, AuthorizationInfoResponse, DeleteUserRoleRequest, GetRoleRequest, - ListRolesResponse, RoleInfoResponse, TransferOrgOwnershipRequest, UpdateUserRoleRequest, + role::{ + CreateRoleRequest, GetRoleRequest, ListRolesResponse, RoleInfoResponse, UpdateRoleRequest, + }, + AcceptInvitationRequest, AuthorizationInfoResponse, DeleteUserRoleRequest, + TransferOrgOwnershipRequest, UpdateUserRoleRequest, }; common_utils::impl_misc_api_event_type!( @@ -13,5 +16,7 @@ common_utils::impl_misc_api_event_type!( UpdateUserRoleRequest, AcceptInvitationRequest, DeleteUserRoleRequest, - TransferOrgOwnershipRequest + TransferOrgOwnershipRequest, + CreateRoleRequest, + UpdateRoleRequest ); diff --git a/crates/api_models/src/user_role.rs b/crates/api_models/src/user_role.rs index 1c4c28aa993..ed0838adc24 100644 --- a/crates/api_models/src/user_role.rs +++ b/crates/api_models/src/user_role.rs @@ -1,23 +1,8 @@ -use common_enums::RoleScope; use common_utils::pii; use crate::user::DashboardEntryResponse; -#[derive(Debug, serde::Serialize)] -pub struct ListRolesResponse(pub Vec<RoleInfoResponse>); - -#[derive(Debug, serde::Serialize)] -pub struct RoleInfoResponse { - pub role_id: String, - pub permissions: Vec<Permission>, - pub role_name: String, - pub role_scope: RoleScope, -} - -#[derive(Debug, serde::Deserialize, serde::Serialize)] -pub struct GetRoleRequest { - pub role_id: String, -} +pub mod role; #[derive(Debug, serde::Serialize)] pub enum Permission { diff --git a/crates/api_models/src/user_role/role.rs b/crates/api_models/src/user_role/role.rs new file mode 100644 index 00000000000..4a767cfa723 --- /dev/null +++ b/crates/api_models/src/user_role/role.rs @@ -0,0 +1,30 @@ +use common_enums::{PermissionGroup, RoleScope}; + +#[derive(Debug, serde::Deserialize, serde::Serialize)] +pub struct CreateRoleRequest { + pub role_name: String, + pub groups: Vec<PermissionGroup>, + pub role_scope: RoleScope, +} + +#[derive(Debug, serde::Deserialize, serde::Serialize)] +pub struct UpdateRoleRequest { + pub groups: Option<Vec<PermissionGroup>>, + pub role_name: Option<String>, +} + +#[derive(Debug, serde::Serialize)] +pub struct ListRolesResponse(pub Vec<RoleInfoResponse>); + +#[derive(Debug, serde::Serialize)] +pub struct RoleInfoResponse { + pub role_id: String, + pub permissions: Vec<super::Permission>, + pub role_name: String, + pub role_scope: RoleScope, +} + +#[derive(Debug, serde::Deserialize, serde::Serialize)] +pub struct GetRoleRequest { + pub role_id: String, +} diff --git a/crates/diesel_models/src/role.rs b/crates/diesel_models/src/role.rs index 6b21b1461cd..075d0602554 100644 --- a/crates/diesel_models/src/role.rs +++ b/crates/diesel_models/src/role.rs @@ -46,35 +46,25 @@ pub struct RoleUpdateInternal { } pub enum RoleUpdate { - UpdateGroup { - groups: Vec<enums::PermissionGroup>, - last_modified_by: String, - }, - UpdateRoleName { - role_name: String, + UpdateDetails { + groups: Option<Vec<enums::PermissionGroup>>, + role_name: Option<String>, + last_modified_at: PrimitiveDateTime, last_modified_by: String, }, } impl From<RoleUpdate> for RoleUpdateInternal { fn from(value: RoleUpdate) -> Self { - let last_modified_at = common_utils::date_time::now(); match value { - RoleUpdate::UpdateGroup { + RoleUpdate::UpdateDetails { groups, - last_modified_by, - } => Self { - groups: Some(groups), - role_name: None, - last_modified_at, - last_modified_by, - }, - RoleUpdate::UpdateRoleName { role_name, last_modified_by, + last_modified_at, } => Self { - groups: None, - role_name: Some(role_name), + groups, + role_name, last_modified_at, last_modified_by, }, diff --git a/crates/router/src/consts/user_role.rs b/crates/router/src/consts/user_role.rs index ae1436bcd67..0a5d6556a11 100644 --- a/crates/router/src/consts/user_role.rs +++ b/crates/router/src/consts/user_role.rs @@ -9,3 +9,4 @@ pub const ROLE_ID_MERCHANT_DEVELOPER: &str = "merchant_developer"; pub const ROLE_ID_MERCHANT_OPERATOR: &str = "merchant_operator"; pub const ROLE_ID_MERCHANT_CUSTOMER_SUPPORT: &str = "merchant_customer_support"; pub const INTERNAL_USER_MERCHANT_ID: &str = "juspay000"; +pub const MAX_ROLE_NAME_LENGTH: usize = 64; diff --git a/crates/router/src/core/errors/user.rs b/crates/router/src/core/errors/user.rs index c837fd7c20f..8a7d77cdbc9 100644 --- a/crates/router/src/core/errors/user.rs +++ b/crates/router/src/core/errors/user.rs @@ -62,6 +62,10 @@ pub enum UserErrors { RoleNotFound, #[error("InvalidRoleOperationWithMessage")] InvalidRoleOperationWithMessage(String), + #[error("RoleNameParsingError")] + RoleNameParsingError, + #[error("RoleNameAlreadyExists")] + RoleNameAlreadyExists, } impl common_utils::errors::ErrorSwitch<api_models::errors::types::ApiErrorResponse> for UserErrors { @@ -159,6 +163,12 @@ impl common_utils::errors::ErrorSwitch<api_models::errors::types::ApiErrorRespon Self::InvalidRoleOperationWithMessage(_) => { AER::BadRequest(ApiError::new(sub_code, 33, self.get_error_message(), None)) } + Self::RoleNameParsingError => { + AER::BadRequest(ApiError::new(sub_code, 34, self.get_error_message(), None)) + } + Self::RoleNameAlreadyExists => { + AER::BadRequest(ApiError::new(sub_code, 35, self.get_error_message(), None)) + } } } } @@ -193,6 +203,8 @@ impl UserErrors { Self::MaxInvitationsError => "Maximum invite count per request exceeded", Self::RoleNotFound => "Role Not Found", Self::InvalidRoleOperationWithMessage(error_message) => error_message, + Self::RoleNameParsingError => "Invalid Role Name", + Self::RoleNameAlreadyExists => "Role name already exists", } } } diff --git a/crates/router/src/core/user_role.rs b/crates/router/src/core/user_role.rs index c2dfd34322c..b954e0df6c6 100644 --- a/crates/router/src/core/user_role.rs +++ b/crates/router/src/core/user_role.rs @@ -17,6 +17,8 @@ use crate::{ utils, }; +pub mod role; + pub async fn get_authorization_info( _state: AppState, ) -> UserResponse<user_role_api::AuthorizationInfoResponse> { @@ -30,98 +32,6 @@ pub async fn get_authorization_info( )) } -pub async fn list_invitable_roles( - state: AppState, - user_from_token: auth::UserFromToken, -) -> UserResponse<user_role_api::ListRolesResponse> { - let predefined_roles_map = roles::predefined_roles::PREDEFINED_ROLES - .iter() - .filter(|(_, role_info)| role_info.is_invitable()) - .map(|(role_id, role_info)| user_role_api::RoleInfoResponse { - 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() - .map(roles::RoleInfo::from) - .filter(|role_info| role_info.is_invitable()) - .map(|role_info| user_role_api::RoleInfoResponse { - 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(user_role_api::ListRolesResponse( - predefined_roles_map.chain(custom_roles_map).collect(), - ))) -} - -pub async fn get_role( - state: AppState, - user_from_token: auth::UserFromToken, - role: user_role_api::GetRoleRequest, -) -> UserResponse<user_role_api::RoleInfoResponse> { - let role_info = roles::get_role_info_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(user_role_api::RoleInfoResponse { - 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_from_token( - state: AppState, - user_from_token: auth::UserFromToken, -) -> UserResponse<Vec<user_role_api::Permission>> { - 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(permissions)) -} - pub async fn update_user_role( state: AppState, user_from_token: auth::UserFromToken, diff --git a/crates/router/src/core/user_role/role.rs b/crates/router/src/core/user_role/role.rs new file mode 100644 index 00000000000..7ce72779bbb --- /dev/null +++ b/crates/router/src/core/user_role/role.rs @@ -0,0 +1,223 @@ +use api_models::user_role::{ + role::{self as role_api}, + Permission, +}; +use common_enums::RoleScope; +use common_utils::generate_id_with_default_len; +use diesel_models::role::{RoleNew, RoleUpdate}; +use error_stack::ResultExt; + +use crate::{ + consts, + core::errors::{StorageErrorExt, UserErrors, UserResponse}, + routes::AppState, + services::{ + authentication::UserFromToken, + authorization::roles::{self, predefined_roles::PREDEFINED_ROLES}, + ApplicationResponse, + }, + types::domain::user::RoleName, + utils, +}; + +pub async fn get_role_from_token( + state: AppState, + user_from_token: UserFromToken, +) -> UserResponse<Vec<Permission>> { + 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(permissions)) +} + +pub async fn create_role( + state: AppState, + user_from_token: UserFromToken, + req: role_api::CreateRoleRequest, +) -> UserResponse<()> { + let now = common_utils::date_time::now(); + let role_name = RoleName::new(req.role_name)?.get_role_name(); + + if req.groups.is_empty() { + return Err(UserErrors::InvalidRoleOperation.into()) + .attach_printable("Role groups cannot be empty"); + } + + if matches!(req.role_scope, RoleScope::Organization) + && user_from_token.role_id != consts::user_role::ROLE_ID_ORGANIZATION_ADMIN + { + return Err(UserErrors::InvalidRoleOperation.into()) + .attach_printable("Non org admin user creating org level role"); + } + + utils::user_role::is_role_name_already_present_for_merchant( + &state, + &role_name, + &user_from_token.merchant_id, + &user_from_token.org_id, + ) + .await?; + + state + .store + .insert_role(RoleNew { + role_id: generate_id_with_default_len("role"), + role_name, + merchant_id: user_from_token.merchant_id, + org_id: user_from_token.org_id, + groups: req.groups, + scope: req.role_scope, + created_by: user_from_token.user_id.clone(), + last_modified_by: user_from_token.user_id, + created_at: now, + last_modified_at: now, + }) + .await + .to_duplicate_response(UserErrors::RoleNameAlreadyExists)?; + + Ok(ApplicationResponse::StatusOk) +} + +pub async fn list_invitable_roles( + state: AppState, + 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_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() + .map(roles::RoleInfo::from) + .filter(|role_info| role_info.is_invitable()) + .map(|role_info| role_api::RoleInfoResponse { + 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 get_role( + state: AppState, + user_from_token: UserFromToken, + role: role_api::GetRoleRequest, +) -> UserResponse<role_api::RoleInfoResponse> { + let role_info = roles::get_role_info_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_id: role.role_id, + role_name: role_info.get_role_name().to_string(), + role_scope: role_info.get_scope(), + })) +} + +pub async fn update_role( + state: AppState, + user_from_token: UserFromToken, + req: role_api::UpdateRoleRequest, + role_id: &str, +) -> UserResponse<()> { + let role_name = req + .role_name + .map(RoleName::new) + .transpose()? + .map(RoleName::get_role_name); + + if let Some(ref role_name) = role_name { + utils::user_role::is_role_name_already_present_for_merchant( + &state, + role_name, + &user_from_token.merchant_id, + &user_from_token.org_id, + ) + .await?; + } + + let role_info = roles::get_role_info_from_role_id( + &state, + role_id, + &user_from_token.merchant_id, + &user_from_token.org_id, + ) + .await + .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 + { + return Err(UserErrors::InvalidRoleOperation.into()) + .attach_printable("Non org admin user creating org level role"); + } + + if let Some(ref groups) = req.groups { + if groups.is_empty() { + return Err(UserErrors::InvalidRoleOperation.into()) + .attach_printable("role groups cannot be empty"); + } + } + + state + .store + .update_role_by_role_id( + role_id, + RoleUpdate::UpdateDetails { + groups: req.groups, + role_name, + last_modified_at: common_utils::date_time::now(), + last_modified_by: user_from_token.user_id, + }, + ) + .await + .to_duplicate_response(UserErrors::RoleNameAlreadyExists)?; + + Ok(ApplicationResponse::StatusOk) +} diff --git a/crates/router/src/db/role.rs b/crates/router/src/db/role.rs index 90e1e97e377..111b531e2f4 100644 --- a/crates/router/src/db/role.rs +++ b/crates/router/src/db/role.rs @@ -200,29 +200,21 @@ impl RoleInterface for MockDb { role_update: storage::RoleUpdate, ) -> CustomResult<storage::Role, errors::StorageError> { let mut roles = self.roles.lock().await; - let last_modified_at = common_utils::date_time::now(); - roles .iter_mut() .find(|role| role.role_id == role_id) .map(|role| { *role = match role_update { - storage::RoleUpdate::UpdateGroup { - groups, - last_modified_by, - } => storage::Role { + storage::RoleUpdate::UpdateDetails { groups, - last_modified_by, - last_modified_at, - ..role.to_owned() - }, - storage::RoleUpdate::UpdateRoleName { role_name, + last_modified_at, last_modified_by, } => storage::Role { - role_name, - last_modified_at, + groups: groups.unwrap_or(role.groups.to_owned()), + role_name: role_name.unwrap_or(role.role_name.to_owned()), last_modified_by, + last_modified_at, ..role.to_owned() }, }; diff --git a/crates/router/src/routes/app.rs b/crates/router/src/routes/app.rs index 26f5b528072..a11265fde80 100644 --- a/crates/router/src/routes/app.rs +++ b/crates/router/src/routes/app.rs @@ -1052,9 +1052,17 @@ impl User { // Role information route = route.service( web::scope("/role") - .service(web::resource("").route(web::get().to(get_role_from_token))) + .service( + web::resource("") + .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("/{role_id}").route(web::get().to(get_role))), + .service( + web::resource("/{role_id}") + .route(web::get().to(get_role)) + .route(web::put().to(update_role)), + ), ); #[cfg(feature = "dummy_connector")] diff --git a/crates/router/src/routes/lock_utils.rs b/crates/router/src/routes/lock_utils.rs index e3b04bd3f73..0214d3b5e3d 100644 --- a/crates/router/src/routes/lock_utils.rs +++ b/crates/router/src/routes/lock_utils.rs @@ -29,6 +29,7 @@ pub enum ApiIdentifier { Forex, RustLockerMigration, Gsm, + Role, User, UserRole, ConnectorOnboarding, @@ -200,7 +201,9 @@ impl From<Flow> for ApiIdentifier { | Flow::GetAuthorizationInfo | Flow::AcceptInvitation | Flow::DeleteUserRole - | Flow::TransferOrgOwnership => Self::UserRole, + | Flow::TransferOrgOwnership + | Flow::CreateRole + | Flow::UpdateRole => 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 63e2ce37269..52e739c36e1 100644 --- a/crates/router/src/routes/user_role.rs +++ b/crates/router/src/routes/user_role.rs @@ -7,7 +7,7 @@ use crate::{ core::{api_locking, user_role as user_role_core}, services::{ api, - authentication::{self as auth, UserFromToken}, + authentication::{self as auth}, authorization::permissions::Permission, }, }; @@ -29,6 +29,38 @@ pub async fn get_authorization_info( .await } +pub async fn get_role_from_token(state: web::Data<AppState>, req: HttpRequest) -> HttpResponse { + let flow = Flow::GetRoleFromToken; + Box::pin(api::server_wrap( + flow, + state.clone(), + &req, + (), + |state, user, _| user_role_core::role::get_role_from_token(state, user), + &auth::DashboardNoPermissionAuth, + api_locking::LockAction::NotApplicable, + )) + .await +} + +pub async fn create_role( + state: web::Data<AppState>, + req: HttpRequest, + json_payload: web::Json<user_role_api::role::CreateRoleRequest>, +) -> HttpResponse { + let flow = Flow::CreateRole; + Box::pin(api::server_wrap( + flow, + state.clone(), + &req, + json_payload.into_inner(), + user_role_core::role::create_role, + &auth::JWTAuth(Permission::UsersWrite), + api_locking::LockAction::NotApplicable, + )) + .await +} + pub async fn list_all_roles(state: web::Data<AppState>, req: HttpRequest) -> HttpResponse { let flow = Flow::ListRoles; Box::pin(api::server_wrap( @@ -36,7 +68,7 @@ pub async fn list_all_roles(state: web::Data<AppState>, req: HttpRequest) -> Htt state.clone(), &req, (), - |state, user, _| user_role_core::list_invitable_roles(state, user), + |state, user, _| user_role_core::role::list_invitable_roles(state, user), &auth::JWTAuth(Permission::UsersRead), api_locking::LockAction::NotApplicable, )) @@ -49,7 +81,7 @@ pub async fn get_role( path: web::Path<String>, ) -> HttpResponse { let flow = Flow::GetRole; - let request_payload = user_role_api::GetRoleRequest { + let request_payload = user_role_api::role::GetRoleRequest { role_id: path.into_inner(), }; Box::pin(api::server_wrap( @@ -57,22 +89,29 @@ pub async fn get_role( state.clone(), &req, request_payload, - user_role_core::get_role, + user_role_core::role::get_role, &auth::JWTAuth(Permission::UsersRead), api_locking::LockAction::NotApplicable, )) .await } -pub async fn get_role_from_token(state: web::Data<AppState>, req: HttpRequest) -> HttpResponse { - let flow = Flow::GetRoleFromToken; +pub async fn update_role( + state: web::Data<AppState>, + req: HttpRequest, + json_payload: web::Json<user_role_api::role::UpdateRoleRequest>, + path: web::Path<String>, +) -> HttpResponse { + let flow = Flow::UpdateRole; + let role_id = path.into_inner(); + Box::pin(api::server_wrap( flow, state.clone(), &req, - (), - |state, user: UserFromToken, _| user_role_core::get_role_from_token(state, user), - &auth::DashboardNoPermissionAuth, + json_payload.into_inner(), + |state, user, req| user_role_core::role::update_role(state, user, req, &role_id), + &auth::JWTAuth(Permission::UsersWrite), api_locking::LockAction::NotApplicable, )) .await diff --git a/crates/router/src/types/domain/user.rs b/crates/router/src/types/domain/user.rs index 263b0e52b8a..a759bf00806 100644 --- a/crates/router/src/types/domain/user.rs +++ b/crates/router/src/types/domain/user.rs @@ -926,3 +926,23 @@ impl ForeignFrom<UserStatus> for user_role_api::UserStatus { } } } + +#[derive(Clone)] +pub struct RoleName(String); + +impl RoleName { + pub fn new(name: String) -> UserResult<Self> { + let is_empty_or_whitespace = name.trim().is_empty(); + let is_too_long = name.graphemes(true).count() > consts::user_role::MAX_ROLE_NAME_LENGTH; + + if is_empty_or_whitespace || is_too_long || name.contains(' ') { + Err(UserErrors::RoleNameParsingError.into()) + } else { + Ok(Self(name.to_lowercase())) + } + } + + pub fn get_role_name(self) -> String { + self.0 + } +} diff --git a/crates/router/src/utils/user_role.rs b/crates/router/src/utils/user_role.rs index ef69219b4c9..8ae65ce86e0 100644 --- a/crates/router/src/utils/user_role.rs +++ b/crates/router/src/utils/user_role.rs @@ -1,6 +1,11 @@ use api_models::user_role as user_role_api; +use error_stack::ResultExt; -use crate::services::authorization::permissions::Permission; +use crate::{ + core::errors::{UserErrors, UserResult}, + routes::AppState, + services::authorization::permissions::Permission, +}; impl From<Permission> for user_role_api::Permission { fn from(value: Permission) -> Self { @@ -34,3 +39,24 @@ impl From<Permission> for user_role_api::Permission { } } } + +pub async fn is_role_name_already_present_for_merchant( + state: &AppState, + role_name: &str, + merchant_id: &str, + org_id: &str, +) -> UserResult<()> { + let role_name_list: Vec<String> = state + .store + .list_all_roles(merchant_id, org_id) + .await + .change_context(UserErrors::InternalServerError)? + .iter() + .map(|role| role.role_name.to_owned()) + .collect(); + + if role_name_list.contains(&role_name.to_string()) { + return Err(UserErrors::RoleNameAlreadyExists.into()); + } + Ok(()) +} diff --git a/crates/router_env/src/logger/types.rs b/crates/router_env/src/logger/types.rs index b2e665059e7..4af81ae49ca 100644 --- a/crates/router_env/src/logger/types.rs +++ b/crates/router_env/src/logger/types.rs @@ -363,6 +363,10 @@ pub enum Flow { UpdateUserAccountDetails, /// Accept user invitation AcceptInvitation, + /// Create Role + CreateRole, + /// Update Role + UpdateRole, } /// diff --git a/migrations/2024-02-22-100718_role_name_org_id_constraint/down.sql b/migrations/2024-02-22-100718_role_name_org_id_constraint/down.sql new file mode 100644 index 00000000000..3fcac875de6 --- /dev/null +++ b/migrations/2024-02-22-100718_role_name_org_id_constraint/down.sql @@ -0,0 +1,3 @@ +-- This file should undo anything in `up.sql` +DROP INDEX role_name_org_id_org_scope_index; +DROP INDEX role_name_merchant_id_merchant_scope_index; diff --git a/migrations/2024-02-22-100718_role_name_org_id_constraint/up.sql b/migrations/2024-02-22-100718_role_name_org_id_constraint/up.sql new file mode 100644 index 00000000000..9780e01b772 --- /dev/null +++ b/migrations/2024-02-22-100718_role_name_org_id_constraint/up.sql @@ -0,0 +1,3 @@ +-- Your SQL goes here +CREATE UNIQUE INDEX role_name_org_id_org_scope_index ON roles(org_id, role_name) WHERE scope='organization'; +CREATE UNIQUE INDEX role_name_merchant_id_merchant_scope_index ON roles(merchant_id, role_name) WHERE scope='merchant';
2024-02-21T21:19:02Z
## Type of Change <!-- Put an `x` in the boxes that apply --> - [ ] Bugfix - [x] New feature - [ ] Enhancement - [ ] Refactoring - [ ] Dependency updates - [ ] Documentation - [ ] CI/CD ## Description Add functionality for - create role api - update role api ### 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 User should be allowed to create/update custom roles. ## How did you test it? Create role ``` curl --location --request PUT 'http://localhost:8080/user/role' \ --header 'Authorization: Bearer eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJ1c2VyX2lkIjoiOGJiZGM4YWUtZDlhYS00NGUxLWFkYzYtYjEyMjZiYjkxZDliIiwibWVyY2hhbnRfaWQiOiJtZXJjaGFudF8xNzA4NjAxMTE3Iiwicm9sZV9pZCI6Im9yZ19hZG1pbiIsImV4cCI6MTcwODc3MzkxNywib3JnX2lkIjoib3JnX1dFN1Z3emNITWRaS01hTzYzeW9pIn0.l5tcWpOqgTVxGKw6zQvx-4iBBmOietj1-drGgzqFYBg' \ --header 'Content-Type: application/json' \ --data '{ "role_name": "test_x", "groups": ["operations_view"], "role_scope": "organization" }' ``` Update ``` curl --location --request PUT 'http://localhost:8080/user/role/role_cau2w3YVoakCr30XWeJi' \ --header 'Authorization: Bearer eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJ1c2VyX2lkIjoiOGJiZGM4YWUtZDlhYS00NGUxLWFkYzYtYjEyMjZiYjkxZDliIiwibWVyY2hhbnRfaWQiOiJtZXJjaGFudF8xNzA4NjAxMTE3Iiwicm9sZV9pZCI6Im9yZ19hZG1pbiIsImV4cCI6MTcwODc3MzkxNywib3JnX2lkIjoib3JnX1dFN1Z3emNITWRaS01hTzYzeW9pIn0.l5tcWpOqgTVxGKw6zQvx-4iBBmOietj1-drGgzqFYBg' \ --header 'Content-Type: application/json' \ --data '{ "role_name": "test", "groups": ["workflows_manage"] }' ``` Response will be 200 Ok. ## 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 - [ ] I added a [CHANGELOG](/CHANGELOG.md) entry if applicable
bbb3d3d1e26f303964a495606dece7958f6c40fc
Create role ``` curl --location --request PUT 'http://localhost:8080/user/role' \ --header 'Authorization: Bearer eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJ1c2VyX2lkIjoiOGJiZGM4YWUtZDlhYS00NGUxLWFkYzYtYjEyMjZiYjkxZDliIiwibWVyY2hhbnRfaWQiOiJtZXJjaGFudF8xNzA4NjAxMTE3Iiwicm9sZV9pZCI6Im9yZ19hZG1pbiIsImV4cCI6MTcwODc3MzkxNywib3JnX2lkIjoib3JnX1dFN1Z3emNITWRaS01hTzYzeW9pIn0.l5tcWpOqgTVxGKw6zQvx-4iBBmOietj1-drGgzqFYBg' \ --header 'Content-Type: application/json' \ --data '{ "role_name": "test_x", "groups": ["operations_view"], "role_scope": "organization" }' ``` Update ``` curl --location --request PUT 'http://localhost:8080/user/role/role_cau2w3YVoakCr30XWeJi' \ --header 'Authorization: Bearer eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJ1c2VyX2lkIjoiOGJiZGM4YWUtZDlhYS00NGUxLWFkYzYtYjEyMjZiYjkxZDliIiwibWVyY2hhbnRfaWQiOiJtZXJjaGFudF8xNzA4NjAxMTE3Iiwicm9sZV9pZCI6Im9yZ19hZG1pbiIsImV4cCI6MTcwODc3MzkxNywib3JnX2lkIjoib3JnX1dFN1Z3emNITWRaS01hTzYzeW9pIn0.l5tcWpOqgTVxGKw6zQvx-4iBBmOietj1-drGgzqFYBg' \ --header 'Content-Type: application/json' \ --data '{ "role_name": "test", "groups": ["workflows_manage"] }' ``` Response will be 200 Ok.
juspay/hyperswitch
juspay__hyperswitch-3778
Bug: [FEATURE] : [Braintree] mask pii information in connector request and response ### Feature Description Mask pii information passed and received in the connector request and response ### Possible Implementation Refactor all sensitive response and request fields secret ### 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/braintree/braintree_graphql_transformers.rs b/crates/router/src/connector/braintree/braintree_graphql_transformers.rs index 436cd8dfa36..190cd276572 100644 --- a/crates/router/src/connector/braintree/braintree_graphql_transformers.rs +++ b/crates/router/src/connector/braintree/braintree_graphql_transformers.rs @@ -54,7 +54,7 @@ impl<T> #[derive(Debug, Serialize)] #[serde(rename_all = "camelCase")] pub struct PaymentInput { - payment_method_id: String, + payment_method_id: Secret<String>, transaction: TransactionBody, } @@ -899,7 +899,7 @@ impl TryFrom<&types::TokenizationRouterData> for BraintreeTokenRequest { #[derive(Default, Debug, Clone, Deserialize, Serialize)] pub struct TokenizePaymentMethodData { - id: String, + id: Secret<String>, } #[derive(Default, Debug, Clone, Deserialize, Serialize)] @@ -969,6 +969,7 @@ impl<F, T> .tokenize_credit_card .payment_method .id + .expose() .clone(), }) } @@ -1277,7 +1278,7 @@ impl<F, T> #[derive(Debug, Deserialize)] #[serde(rename_all = "camelCase")] pub struct BraintreeThreeDsResponse { - pub nonce: String, + pub nonce: Secret<String>, pub liability_shifted: bool, pub liability_shift_possible: bool, } @@ -1332,7 +1333,7 @@ impl variables: VariablePaymentInput { input: PaymentInput { payment_method_id: match item.router_data.get_payment_method_token()? { - types::PaymentMethodToken::Token(token) => token, + types::PaymentMethodToken::Token(token) => token.into(), types::PaymentMethodToken::ApplePayDecrypt(_) => { Err(errors::ConnectorError::InvalidWalletToken)? } diff --git a/crates/router/src/connector/braintree/transformers.rs b/crates/router/src/connector/braintree/transformers.rs index 8846753117c..9201bc9e4cc 100644 --- a/crates/router/src/connector/braintree/transformers.rs +++ b/crates/router/src/connector/braintree/transformers.rs @@ -1,6 +1,6 @@ use api_models::payments; use base64::Engine; -use masking::{PeekInterface, Secret}; +use masking::{ExposeInterface, PeekInterface, Secret}; use serde::{Deserialize, Serialize}; use crate::{ @@ -77,7 +77,7 @@ pub enum PaymentMethodType { #[derive(Default, Debug, Serialize, Eq, PartialEq)] pub struct Nonce { - payment_method_nonce: String, + payment_method_nonce: Secret<String>, } #[derive(Default, Debug, Serialize, Eq, PartialEq)] @@ -130,7 +130,8 @@ impl TryFrom<&types::PaymentsAuthorizeRouterData> for BraintreePaymentsRequest { Ok(wallet_data.token.to_owned()) } _ => Err(errors::ConnectorError::InvalidWallet), - }?, + }? + .into(), })) } _ => Err(errors::ConnectorError::NotImplemented(format!( @@ -263,7 +264,7 @@ impl<F, T> response: Ok(types::PaymentsResponseData::SessionResponse { session_token: types::api::SessionToken::Paypal(Box::new( payments::PaypalSessionTokenResponse { - session_token: item.response.client_token.value, + session_token: item.response.client_token.value.expose(), }, )), }), @@ -281,7 +282,7 @@ pub struct BraintreePaymentsResponse { #[derive(Default, Debug, Clone, Deserialize, Serialize)] #[serde(rename_all = "camelCase")] pub struct ClientToken { - pub value: String, + pub value: Secret<String>, } #[derive(Default, Debug, Clone, Deserialize, Serialize)]
2024-02-21T15:12:03Z
## Type of Change <!-- Put an `x` in the boxes that apply --> - [ ] Bugfix - [ ] New feature - [x] Enhancement - [x] Refactoring - [ ] Dependency updates - [ ] Documentation - [ ] CI/CD ## Description <!-- Describe your changes in detail --> Mask pii information passed and received in the connector request and response for Braintree. ## Test Case Check if sensitive fields within connector request and response is masked in the click house for Braintree Test for both graphQL and the normal version Sanity test 1. Payment create - 3ds card ``` curl --location 'http://localhost:8080/payments' \ --header 'Content-Type: application/json' \ --header 'Accept: application/json' \ --header 'api-key: {{api_key}}' \ --data-raw '{ "amount": 2000, "currency": "GBP", "confirm": true, "capture_method": "automatic", "capture_on": "2022-09-10T10:11:12Z", "customer_id": "StripeCustomer", "email": "abcdef123@gmail.com", "name": "John Doe", "phone": "999999999", "phone_country_code": "+65", "description": "Its my first payment request", "authentication_type": "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": "US", "first_name": "John", "last_name": "Doe" } }, "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_method": "card", "payment_method_data": { "card": { "card_number": "5123456789012346", "card_exp_month": "10", "card_exp_year": "30", "card_holder_name": "Joseph Doe", "card_cvc": "123" } } }' ``` response ``` ClientTokenResponse(ClientTokenResponse { data: ClientTokenData { create_client_token: ClientToken { client_token: *** alloc::string::String *** } } }) ``` ``` router::connector::braintree: connector_response: TokenResponse(TokenResponse { data: TokenizeCreditCard { tokenize_credit_card: TokenizeCreditCardData { payment_method: TokenizePaymentMethodData { id: *** alloc::string::String *** } } } }) ``` In logs check for `topic = "hyperswitch-outgoing-connector-events" ` ## 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 - [ ] I added a [CHANGELOG](/CHANGELOG.md) entry if applicable
ef5e886ab1abdf50254343be8c6c48100ec2ec2d
juspay/hyperswitch
juspay__hyperswitch-3772
Bug: [FEATURE] : [Checkout] mask pii information in connector request and response ### Feature Description Mask pii information passed and received in the connector request and response ### Possible Implementation Refactor all sensitive response and request fields secret ### 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/checkout/transformers.rs b/crates/router/src/connector/checkout/transformers.rs index f96bd50ffc8..591e1aa31c7 100644 --- a/crates/router/src/connector/checkout/transformers.rs +++ b/crates/router/src/connector/checkout/transformers.rs @@ -188,7 +188,7 @@ pub struct CardSource { pub struct WalletSource { #[serde(rename = "type")] pub source_type: CheckoutSourceTypes, - pub token: String, + pub token: Secret<String>, } #[derive(Debug, Serialize)] @@ -301,7 +301,7 @@ impl TryFrom<&CheckoutRouterData<&types::PaymentsAuthorizeRouterData>> for Payme Ok(PaymentSource::Wallets(WalletSource { source_type: CheckoutSourceTypes::Token, token: match item.router_data.get_payment_method_token()? { - types::PaymentMethodToken::Token(token) => token, + types::PaymentMethodToken::Token(token) => token.into(), types::PaymentMethodToken::ApplePayDecrypt(_) => { Err(errors::ConnectorError::InvalidWalletToken)? } @@ -314,7 +314,7 @@ impl TryFrom<&CheckoutRouterData<&types::PaymentsAuthorizeRouterData>> for Payme types::PaymentMethodToken::Token(apple_pay_payment_token) => { Ok(PaymentSource::Wallets(WalletSource { source_type: CheckoutSourceTypes::Token, - token: apple_pay_payment_token, + token: apple_pay_payment_token.into(), })) } types::PaymentMethodToken::ApplePayDecrypt(decrypt_data) => {
2024-02-22T10:22: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 <!-- Describe your changes in detail --> Mask pii information passed and received in the connector request and response for Checkout. ## Test cases 1. Create a payment with Apple pay 2. Create a payment with Google pay Generate Google pay token from: https://jsfiddle.net/1agu74ve/     `'gateway': 'checkoutltd'`,     `'gatewayMerchantId': 'public_key'` ``` curl --location 'http://localhost:8080/payments' \ --header 'Content-Type: application/json' \ --header 'Accept: application/json' \ --header 'api-key:{{api_key}}' \ --data-raw '{ "amount": 7000, "currency": "USD", "confirm": true, "capture_method": "manual", "capture_on": "2022-09-10T10:11:12Z", "customer_id": "StripeCustomer", "email": "abcdef123@gmail.com", "name": "John Doe", "phone": "999999999", "phone_country_code": "+65", "description": "Its my first payment request", "authentication_type": "three_ds", "return_url": "https://hs-payments-test.netlify.app/payments", "billing": { "address": { "line1": "1467", "line2": "Harrison Street", "line3": "Harrison Street", "city": "San Fransico", "state": "California", "zip": "94122", "country": "US" } }, "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_method": "wallet", "payment_method_type": "google_pay", "payment_method_data": { "wallet": { "google_pay": { "description": "Visa •••• 1111", "tokenization_data": { "type": "PAYMENT_GATEWAY", "token": "{token_generated_from_above_step}" }, "type": "CARD", "info": { "card_network": "VISA", "card_details": "1111" } } } } }' ``` 4. Check if all the sensitive data in the `masked_response` is masked ``` curl --location '{{base_url}}/analytics/v1/connector_event_logs?type=Payment&payment_id={{payment_id}}' \ --header 'sec-ch-ua: "Not A(Brand";v="99", "Google Chrome";v="121", "Chromium";v="121"' \ --header 'sec-ch-ua-mobile: ?0' \ --header 'authorization: Bearer JWT_token' \ --header 'User-Agent: Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/121.0.0.0 Safari/537.36' \ --header 'Content-Type: application/json' \ --header 'Referer: https://integ.hyperswitch.io/' \ --header 'api-key: {{api-key}}' \ --header 'sec-ch-ua-platform: "macOS"' ``` Response for Googlepay ``` "masked_response\":\"{\\\"token\\\":\\\"*** alloc::string::String ***\\\"} ``` ## Impact Area > Create payment: Applepay and Googlepay ## 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 - [ ] I added a [CHANGELOG](/CHANGELOG.md) entry if applicable
d000847b938952de6ff9c2e01bdd06b4ede60e69
juspay/hyperswitch
juspay__hyperswitch-3769
Bug: [FEATURE] : [BOA] mask pii information in connector request and response ### Feature Description Mask pii information passed and received in the connector request and response ### Possible Implementation Refactor all sensitive response and request fields secret ### 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/bankofamerica.rs b/crates/router/src/connector/bankofamerica.rs index 706532c5d18..fefc80f806c 100644 --- a/crates/router/src/connector/bankofamerica.rs +++ b/crates/router/src/connector/bankofamerica.rs @@ -1079,8 +1079,10 @@ impl ConnectorIntegration<api::Execute, types::RefundsData, types::RefundsRespon .response .parse_struct("bankofamerica 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(), diff --git a/crates/router/src/connector/bankofamerica/transformers.rs b/crates/router/src/connector/bankofamerica/transformers.rs index b2a9f14ccce..235321f1ac6 100644 --- a/crates/router/src/connector/bankofamerica/transformers.rs +++ b/crates/router/src/connector/bankofamerica/transformers.rs @@ -2,7 +2,7 @@ use api_models::payments; use base64::Engine; use common_utils::{ext_traits::ValueExt, pii}; use error_stack::{IntoReport, ResultExt}; -use masking::{PeekInterface, Secret}; +use masking::{ExposeInterface, PeekInterface, Secret}; use serde::{Deserialize, Serialize}; use serde_json::Value; @@ -113,9 +113,9 @@ pub struct MerchantDefinedInformation { pub struct BankOfAmericaConsumerAuthInformation { ucaf_collection_indicator: Option<String>, cavv: Option<String>, - ucaf_authentication_data: Option<String>, + ucaf_authentication_data: Option<Secret<String>>, xid: Option<String>, - directory_server_transaction_id: Option<String>, + directory_server_transaction_id: Option<Secret<String>>, specification_version: Option<String>, } @@ -213,7 +213,7 @@ pub struct BillTo { first_name: Secret<String>, last_name: Secret<String>, address1: Secret<String>, - locality: String, + locality: Secret<String>, administrative_area: Secret<String>, postal_code: Secret<String>, country: api_enums::CountryAlpha2, @@ -235,7 +235,7 @@ fn build_bill_to( first_name: address.get_first_name()?.to_owned(), last_name: address.get_last_name()?.to_owned(), address1: address.get_line1()?.to_owned(), - locality: address.get_city()?.to_owned(), + locality: Secret::new(address.get_city()?.to_owned()), administrative_area: Secret::from(state), postal_code: address.get_zip()?.to_owned(), country: address.get_country()?.to_owned(), @@ -435,7 +435,7 @@ pub struct ClientRiskInformation { #[derive(Debug, Clone, Deserialize, Serialize)] pub struct ClientRiskInformationRules { - name: String, + name: Secret<String>, } #[derive(Debug, Clone, Serialize, Deserialize)] @@ -889,8 +889,8 @@ impl ForeignFrom<(BankofamericaPaymentStatus, bool)> for enums::AttemptStatus { #[derive(Debug, Deserialize, Serialize)] #[serde(rename_all = "camelCase")] pub struct BankOfAmericaConsumerAuthInformationResponse { - access_token: String, - device_data_collection_url: String, + access_token: Secret<String>, + device_data_collection_url: Secret<String>, reference_id: String, } @@ -1066,10 +1066,12 @@ impl<F> redirection_data: Some(services::RedirectForm::CybersourceAuthSetup { access_token: info_response .consumer_authentication_information - .access_token, + .access_token + .expose(), ddc_url: info_response .consumer_authentication_information - .device_data_collection_url, + .device_data_collection_url + .expose(), reference_id: info_response .consumer_authentication_information .reference_id, @@ -1322,10 +1324,10 @@ pub enum BankOfAmericaAuthEnrollmentStatus { pub struct BankOfAmericaConsumerAuthValidateResponse { ucaf_collection_indicator: Option<String>, cavv: Option<String>, - ucaf_authentication_data: Option<String>, + ucaf_authentication_data: Option<Secret<String>>, xid: Option<String>, specification_version: Option<String>, - directory_server_transaction_id: Option<String>, + directory_server_transaction_id: Option<Secret<String>>, indicator: Option<String>, } @@ -1337,7 +1339,7 @@ pub struct BankOfAmericaThreeDSMetadata { #[derive(Debug, Deserialize, Serialize)] #[serde(rename_all = "camelCase")] pub struct BankOfAmericaConsumerAuthInformationEnrollmentResponse { - access_token: Option<String>, + access_token: Option<Secret<String>>, step_up_url: Option<String>, //Added to segregate the three_ds_data in a separate struct #[serde(flatten)] @@ -1420,7 +1422,8 @@ impl<F> let redirection_data = match ( info_response .consumer_authentication_information - .access_token, + .access_token + .map(|access_token| access_token.expose()), info_response .consumer_authentication_information .step_up_url, @@ -2023,7 +2026,7 @@ impl client_risk_information.rules.map(|rules| { rules .iter() - .map(|risk_info| format!(" , {}", risk_info.name)) + .map(|risk_info| format!(" , {}", risk_info.name.clone().expose())) .collect::<Vec<String>>() .join("") })
2024-02-19T12:20:16Z
## Type of Change <!-- Put an `x` in the boxes that apply --> - [ ] Bugfix - [ ] New feature - [x] Enhancement - [x] Refactoring - [ ] Dependency updates - [ ] Documentation - [ ] CI/CD ## Description <!-- Describe your changes in detail --> Mask pii information passed and received in the connector request and response for BOA ## Test Case Check if sensitive fields within connector request and response is masked in the click house for BOA Sanity test 1. Payment create - card 3ds ``` curl --location 'http://localhost:8080/payments' \ --header 'Content-Type: application/json' \ --header 'Accept: application/json' \ --header 'api-key: {{api_key}}' \ --data-raw '{ "amount": 2000, "currency": "GBP", "confirm": true, "capture_method": "automatic", "capture_on": "2022-09-10T10:11:12Z", "customer_id": "StripeCustomer", "email": "abcdef123@gmail.com", "name": "John Doe", "phone": "999999999", "phone_country_code": "+65", "description": "Its my first payment request", "authentication_type": "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": "US", "first_name": "John", "last_name": "Doe" } }, "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_method": "card", "payment_method_data": { "card": { "card_number": "5123456789012346", "card_exp_month": "10", "card_exp_year": "30", "card_holder_name": "Joseph Doe", "card_cvc": "123" } } }' ``` response ``` NFO router::events::event_logger: event: "{\"connector_name\":\"bankofamerica\",\"flow\":\"PreProcessing\",\"request\":\"{\\\"paymentInformation\\\":{\\\"card\\\":{\\\"number\\\":\\\"512345**********\\\",\\\"expirationMonth\\\":\\\"*** alloc::string::String ***\\\",\\\"expirationYear\\\":\\\"*** alloc::string::String ***\\\",\\\"securityCode\\\":\\\"*** alloc::string::String ***\\\",\\\"type\\\":\\\"002\\\"}},\\\"clientReferenceInformation\\\":{\\\"code\\\":\\\"pay_yHo8Y3B8atd40rrClRkx_1\\\"},\\\"consumerAuthenticationInformation\\\":{\\\"returnUrl\\\":\\\"http://localhost:8080/payments/pay_yHo8Y3B8atd40rrClRkx/merchant_1708425554/redirect/complete/bankofamerica\\\",\\\"referenceId\\\":\\\"1901aba7-33de-49bb-afa0-001a14f95448\\\"},\\\"orderInformation\\\":{\\\"amountDetails\\\":{\\\"totalAmount\\\":\\\"20.00\\\",\\\"currency\\\":\\\"GBP\\\"},\\\"billTo\\\":{\\\"firstName\\\":\\\"*** alloc::string::String ***\\\",\\\"lastName\\\":\\\"*** alloc::string::String ***\\\",\\\"address1\\\":\\\"*** alloc::string::String ***\\\",\\\"locality\\\":\\\"*** alloc::string::String ***\\\",\\\"administrativeArea\\\":\\\"*** alloc::string::String ***\\\",\\\"postalCode\\\":\\\"*** alloc::string::String ***\\\",\\\"country\\\":\\\"US\\\",\\\"email\\\":\\\"*********@gmail.com\\\"}}}\",\"masked_response\":\"{\\\"id\\\":\\\"7084255709226701604951\\\",\\\"clientReferenceInformation\\\":{\\\"code\\\":\\\"pay_yHo8Y3B8atd40rrClRkx_1\\\"},\\\"consumerAuthenticationInformation\\\":{\\\"accessToken\\\":null,\\\"stepUpUrl\\\":null,\\\"ucafCollectionIndicator\\\":\\\"2\\\",\\\"cavv\\\":null,\\\"ucafAuthenticationData\\\":\\\"*** alloc::string::String ***\\\",\\\"xid\\\":null,\\\"specificationVersion\\\":\\\"2.1.0\\\",\\\"directoryServerTransactionId\\\":\\\"*** alloc::string::String ***\\\",\\\"indicator\\\":null},\\\"status\\\":\\\"AUTHENTICATION_SUCCESSFUL\\\",\\\"errorInformation\\\":null}\",\"error\":null,\"url\":\"https://apitest.merchant-services.bankofamerica.com/risk/v1/authentications\",\"method\":\"POST\",\"payment_id\":\"pay_yHo8Y3B8atd40rrClRkx\",\"merchant_id\":\"merchant_1708425554\",\"created_at\":1708425571363,\"request_id\":\"018dc619-6993-719c-b539-c698c767a08f\",\"latency\":579,\"refund_id\":null,\"dispute_id\":null,\"status_code\":201}", event_type: ConnectorApiLogs, event_id: "018dc619-6993-719c-b539-c698c767a08f", log_type: "event" ``` In logs check for `topic = "hyperswitch-outgoing-connector-events" ` ## 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 - [ ] I added a [CHANGELOG](/CHANGELOG.md) entry if applicable
cf3c66636ffee30cdd4353b276a89a8f9fc2d9d0
juspay/hyperswitch
juspay__hyperswitch-3770
Bug: [FEATURE] : [Bluesnap] mask pii information in connector request and response ### Feature Description Mask pii information passed and received in the connector request and response ### Possible Implementation Refactor all sensitive response and request fields secret ### 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/bluesnap/transformers.rs b/crates/router/src/connector/bluesnap/transformers.rs index 63ca7750303..201ddc221fc 100644 --- a/crates/router/src/connector/bluesnap/transformers.rs +++ b/crates/router/src/connector/bluesnap/transformers.rs @@ -591,7 +591,7 @@ pub struct BluesnapCompletePaymentsRequest { amount: String, currency: enums::Currency, card_transaction_type: BluesnapTxnType, - pf_token: String, + pf_token: Secret<String>, three_d_secure: Option<BluesnapThreeDSecureInfo>, transaction_fraud_info: Option<TransactionFraudInfo>, card_holder_info: Option<BluesnapCardHolderInfo>, @@ -627,7 +627,7 @@ impl TryFrom<&BluesnapRouterData<&types::PaymentsCompleteAuthorizeRouterData>> meta_data: Vec::<RequestMetadata>::foreign_from(metadata.peek().to_owned()), }); - let pf_token = item + let token = item .router_data .request .redirect_response @@ -673,7 +673,7 @@ impl TryFrom<&BluesnapRouterData<&types::PaymentsCompleteAuthorizeRouterData>> item.router_data.request.get_email()?, )?, merchant_transaction_id: Some(item.router_data.connector_request_reference_id.clone()), - pf_token, + pf_token: Secret::new(token), transaction_meta_data, }) }
2024-02-20T06:20:23Z
## Type of Change <!-- Put an `x` in the boxes that apply --> - [ ] Bugfix - [ ] New feature - [x] Enhancement - [x] Refactoring - [ ] Dependency updates - [ ] Documentation - [ ] CI/CD ## Description <!-- Describe your changes in detail --> Mask pii information passed and received in the connector request and response for Bluesnap. [Bluesnap Doc](https://developers.bluesnap.com/v8976-JSON/reference/bluesnap-payment-api-json) ## Test Case Check if sensitive fields within connector request and response is masked in the click house for Bluesnap Sanity test 1. Payment create - 3ds card ``` curl --location 'http://localhost:8080/payments' \ --header 'Content-Type: application/json' \ --header 'Accept: application/json' \ --header 'api-key: {{api_key}}' \ --data-raw '{ "amount": 2000, "currency": "GBP", "confirm": true, "capture_method": "automatic", "capture_on": "2022-09-10T10:11:12Z", "customer_id": "StripeCustomer", "email": "abcdef123@gmail.com", "name": "John Doe", "phone": "999999999", "phone_country_code": "+65", "description": "Its my first payment request", "authentication_type": "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": "US", "first_name": "John", "last_name": "Doe" } }, "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_method": "card", "payment_method_data": { "card": { "card_number": "5123456789012346", "card_exp_month": "10", "card_exp_year": "30", "card_holder_name": "Joseph Doe", "card_cvc": "123" } } }' ``` Response ``` "{\"connector_name\":\"bluesnap\",\"flow\":\"Authorize\",\"request\":\"{\\\"ccNumber\\\":\\\"512345**********\\\",\\\"expDate\\\":\\\"*** alloc::string::String ***\\\"}\",\"masked_response\":\"{\\\"payment_fields_token\\\":\\\"66282e40db55c410dc0689772e171f9d20078a6cd322be81f5b087e550fbbe14_\\\"}\",\"error\":null,\"url\":\"https://sandbox.bluesnap.com/services/2/payment-fields-tokens/prefill\",\"method\":\"POST\",\"payment_id\":\"pay_2QBMshgSXePTr9bKsab1\",\"merchant_id\":\"merchant_1708588739\",\"created_at\":1708588782767,\"request_id\":\"018dcfd3-cdb2-77ea-8cbc-568a736877c5\",\"latency\":1540,\"refund_id\":null,\"dispute_id\":null,\"status_code\":201}", event_type: ConnectorApiLogs, event_id: "018dcfd3-cdb2-77ea-8cbc-568a736877c5", log_type: "event" ``` In logs check for `topic = "hyperswitch-outgoing-connector-events" ` ## 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 - [ ] I added a [CHANGELOG](/CHANGELOG.md) entry if applicable
5aae1798257b5ee0c5a62104e4711748cdb5f935
juspay/hyperswitch
juspay__hyperswitch-3768
Bug: [FEATURE] : [Bambora] mask pii information in connector request and response ### Feature Description Mask pii information passed and received in the connector request and response ### Possible Implementation Refactor all sensitive response and request fields secret ### 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/bambora.rs b/crates/router/src/connector/bambora.rs index e2d9e18ce96..d453677deb6 100644 --- a/crates/router/src/connector/bambora.rs +++ b/crates/router/src/connector/bambora.rs @@ -228,8 +228,10 @@ impl ConnectorIntegration<api::Void, types::PaymentsCancelData, types::PaymentsR .response .parse_struct("bambora PaymentsResponse") .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, @@ -324,8 +326,10 @@ impl ConnectorIntegration<api::PSync, types::PaymentsSyncData, types::PaymentsRe .response .parse_struct("bambora PaymentsResponse") .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, @@ -405,8 +409,10 @@ impl ConnectorIntegration<api::Capture, types::PaymentsCaptureData, types::Payme .response .parse_struct("Bambora PaymentsResponse") .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, @@ -597,8 +603,10 @@ impl ConnectorIntegration<api::Execute, types::RefundsData, types::RefundsRespon .response .parse_struct("bambora RefundResponse") .change_context(errors::ConnectorError::RequestEncodingFailed)?; + event_builder.map(|i| i.set_response_body(&response)); router_env::logger::info!(connector_response=?response); + types::RefundsRouterData::try_from(types::ResponseRouterData { response, data: data.clone(), @@ -669,8 +677,10 @@ impl ConnectorIntegration<api::RSync, types::RefundsData, types::RefundsResponse .response .parse_struct("bambora 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(), diff --git a/crates/router/src/connector/bambora/transformers.rs b/crates/router/src/connector/bambora/transformers.rs index d2c99bbaca0..c47b0718287 100644 --- a/crates/router/src/connector/bambora/transformers.rs +++ b/crates/router/src/connector/bambora/transformers.rs @@ -1,7 +1,7 @@ use base64::Engine; -use common_utils::ext_traits::ValueExt; +use common_utils::{ext_traits::ValueExt, pii::IpAddress}; use error_stack::{IntoReport, ResultExt}; -use masking::{PeekInterface, Secret}; +use masking::{ExposeInterface, PeekInterface, Secret}; use serde::{Deserialize, Deserializer, Serialize}; use crate::{ @@ -51,7 +51,7 @@ pub struct BamboraPaymentsRequest { order_number: String, amount: i64, payment_method: PaymentMethod, - customer_ip: Option<std::net::IpAddr>, + customer_ip: Option<Secret<String, IpAddress>>, term_url: Option<String>, card: BamboraCard, } @@ -133,7 +133,9 @@ impl TryFrom<&types::PaymentsAuthorizeRouterData> for BamboraPaymentsRequest { amount: item.request.amount, payment_method: PaymentMethod::Card, card: bambora_card, - customer_ip: browser_info.ip_address, + customer_ip: browser_info + .ip_address + .map(|ip_address| Secret::new(format!("{ip_address}"))), term_url: item.request.complete_authorize_url.clone(), }) } @@ -235,7 +237,7 @@ impl<F, T> mandate_reference: None, connector_metadata: Some( serde_json::to_value(BamboraMeta { - three_d_session_data: response.three_d_session_data, + three_d_session_data: response.three_d_session_data.expose(), }) .into_report() .change_context(errors::ConnectorError::ResponseHandlingFailed)?, @@ -312,7 +314,7 @@ pub struct BamboraPaymentsResponse { #[derive(Debug, Clone, Deserialize, Serialize)] pub struct Bambora3DsResponse { #[serde(rename = "3d_session_data")] - three_d_session_data: String, + three_d_session_data: Secret<String>, contents: String, } @@ -334,12 +336,12 @@ pub struct CardResponse { #[derive(Default, Debug, Clone, Deserialize, PartialEq, Serialize)] pub struct CardData { - name: Option<String>, - expiry_month: Option<String>, - expiry_year: Option<String>, + name: Option<Secret<String>>, + expiry_month: Option<Secret<String>>, + expiry_year: Option<Secret<String>>, card_type: String, - last_four: String, - card_bin: Option<String>, + last_four: Secret<String>, + card_bin: Option<Secret<String>>, avs_result: String, cvd_result: String, cavv_result: Option<String>, @@ -357,15 +359,15 @@ pub struct AvsObject { #[derive(Default, Debug, Clone, Serialize, Deserialize, PartialEq)] pub struct AddressData { - name: String, - address_line1: String, - address_line2: String, + name: Secret<String>, + address_line1: Secret<String>, + address_line2: Secret<String>, city: String, province: String, country: String, - postal_code: String, - phone_number: String, - email_address: String, + postal_code: Secret<String>, + phone_number: Secret<String>, + email_address: Secret<String>, } #[derive(Default, Debug, Clone, Serialize, Deserialize, PartialEq)]
2024-02-19T08:53:46Z
## Type of Change <!-- Put an `x` in the boxes that apply --> - [ ] Bugfix - [ ] New feature - [x] Enhancement - [x] Refactoring - [ ] Dependency updates - [ ] Documentation - [ ] CI/CD ## Description <!-- Describe your changes in detail --> Mask pii information passed and received in the connector request and response for Bambora ## Test Case Check if sensitive fields within connector request and response is masked in the click house for bambora Sanity test 1. Payment create - Card ``` curl --location 'http://localhost:8080/payments' \ --header 'Content-Type: application/json' \ --header 'Accept: application/json' \ --header 'api-key: {{api_key}}' \ --data-raw '{ "amount": 2000, "currency": "GBP", "confirm": true, "capture_method": "automatic", "capture_on": "2022-09-10T10:11:12Z", "customer_id": "StripeCustomer", "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", "billing": { "address": { "line1": "1467", "line2": "Harrison Street", "line3": "Harrison Street", "city": "San Fransico", "state": "California", "zip": "94122", "country": "US", "first_name": "John", "last_name": "Doe" } }, "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_method": "card", "payment_method_data": { "card": { "card_number": "5123456789012346", "card_exp_month": "10", "card_exp_year": "30", "card_holder_name": "Joseph Doe", "card_cvc": "123" } } }' ``` Card 3ds ``` curl --location 'http://localhost:8080/payments' \ --header 'Content-Type: application/json' \ --header 'Accept: application/json' \ --header 'api-key: {{api_key}}' \ --data-raw '{ "amount": 2000, "currency": "GBP", "confirm": true, "capture_method": "automatic", "capture_on": "2022-09-10T10:11:12Z", "customer_id": "StripeCustomer", "email": "abcdef123@gmail.com", "name": "John Doe", "phone": "999999999", "phone_country_code": "+65", "description": "Its my first payment request", "authentication_type": "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": "US", "first_name": "John", "last_name": "Doe" } }, "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_method": "card", "payment_method_data": { "card": { "card_number": "5123456789012346", "card_exp_month": "10", "card_exp_year": "30", "card_holder_name": "Joseph Doe", "card_cvc": "123" } } }' ``` In logs check for `topic = "hyperswitch-outgoing-connector-events" ` 2. Refund > _Note: There is an existing issue with this connector #3701. That could affect 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 - [ ] I added a [CHANGELOG](/CHANGELOG.md) entry if applicable
073310c1f671ccbb71cc5c8725eca9771e511589
juspay/hyperswitch
juspay__hyperswitch-3766
Bug: Insert `payment_method_id` in redis for wallet tokens To be discussed: In case of wallets, banks what should be the Payment Token equivalent? Note: Update last_used field
diff --git a/crates/router/src/core/payment_methods.rs b/crates/router/src/core/payment_methods.rs index df1fb1e358d..220a28771c8 100644 --- a/crates/router/src/core/payment_methods.rs +++ b/crates/router/src/core/payment_methods.rs @@ -192,6 +192,8 @@ impl PaymentMethodRetrieve for Oss { ) .await } + + storage::PaymentTokenData::WalletToken(_) => Ok(None), } } } diff --git a/crates/router/src/core/payment_methods/cards.rs b/crates/router/src/core/payment_methods/cards.rs index 4fdf957c842..0e45f689d12 100644 --- a/crates/router/src/core/payment_methods/cards.rs +++ b/crates/router/src/core/payment_methods/cards.rs @@ -2757,6 +2757,12 @@ pub async fn list_customer_payment_method( } } + enums::PaymentMethod::Wallet => ( + None, + None, + PaymentTokenData::wallet_token(pm.payment_method_id.clone()), + ), + _ => ( None, None, diff --git a/crates/router/src/types/storage/payment_method.rs b/crates/router/src/types/storage/payment_method.rs index a787a4d932c..17d31ff353d 100644 --- a/crates/router/src/types/storage/payment_method.rs +++ b/crates/router/src/types/storage/payment_method.rs @@ -23,6 +23,11 @@ pub struct GenericTokenData { pub token: String, } +#[derive(Debug, Clone, serde::Serialize, serde::Deserialize)] +pub struct WalletTokenData { + pub payment_method_id: String, +} + #[derive(Debug, serde::Serialize, serde::Deserialize)] #[serde(tag = "kind", rename_all = "snake_case")] pub enum PaymentTokenData { @@ -33,6 +38,7 @@ pub enum PaymentTokenData { Permanent(CardTokenData), PermanentCard(CardTokenData), AuthBankDebit(payment_methods::BankAccountConnectorDetails), + WalletToken(WalletTokenData), } impl PaymentTokenData { @@ -51,4 +57,8 @@ impl PaymentTokenData { pub fn temporary_generic(token: String) -> Self { Self::TemporaryGeneric(GenericTokenData { token }) } + + pub fn wallet_token(payment_method_id: String) -> Self { + Self::WalletToken(WalletTokenData { payment_method_id }) + } }
2024-03-06T12:54:20Z
## 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 support for wallet tokens to be inserted in redis with value being `payment_method_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? <!-- 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 mca with wallets being a payment method ``` curl --location 'http://localhost:8080/account/merchant_1709561576/connectors' \ --header 'Content-Type: application/json' \ --header 'Accept: application/json' \ --header 'api-key: test_admin' \ --data '{ "connector_type": "fiz_operations", "connector_name": "stripe", "connector_account_details": { "auth_type": "HeaderKey", "api_key": "abc" }, "test_mode": false, "disabled": false, "payment_methods_enabled": [ { "payment_method": "card", "payment_method_types": [ { "payment_method_type": "credit", "card_networks": [ "Visa", "Mastercard" ], "minimum_amount": 1, "maximum_amount": 68607706, "recurring_enabled": true, "installment_payment_enabled": true }, { "payment_method_type": "debit", "card_networks": [ "Visa", "Mastercard" ], "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": "apple_pay", "payment_experience": "invoke_sdk_client", "minimum_amount": 1, "maximum_amount": 68607706, "recurring_enabled": true, "installment_payment_enabled": true }, { "payment_method_type": "google_pay", "payment_experience": "invoke_sdk_client", "minimum_amount": 1, "maximum_amount": 68607706, "recurring_enabled": true, "installment_payment_enabled": true } ] } ], "metadata": { "apple_pay_combined": { "manual": { "session_token_data": { "initiative": "web", "certificate": "certificate", "display_name": "applepay", "certificate_keys": "keys", "initiative_context": "sdk-test-app.netlify.app", "merchant_identifier": "xyz" }, "payment_request_data": { "label": "applepay", "supported_networks": [ "visa", "masterCard", "amex", "discover" ], "merchant_capabilities": [ "supports3DS" ] } } }, "google_pay": { "merchant_info": { "merchant_name": "Stripe" }, "allowed_payment_methods": [ { "type": "CARD", "parameters": { "allowed_auth_methods": [ "PAN_ONLY", "CRYPTOGRAM_3DS" ], "allowed_card_networks": [ "AMEX", "DISCOVER", "INTERAC", "JCB", "MASTERCARD", "VISA" ] }, "tokenization_specification": { "type": "PAYMENT_GATEWAY", "parameters": { "gateway": "stripe", "stripe:version": "2018-10-31", "stripe:publishableKey": "abc" } } } ] } }, "connector_webhook_details": { "merchant_secret": "MyWebhookSecret" }, "business_country": "US", "business_label": "default" }' ``` 2. Create a applepay wallet payment so that wallet entry gets saved in `payment_methods` table ``` curl --location 'http://localhost:8080/payments' \ --header 'Content-Type: application/json' \ --header 'Accept: application/json' \ --header 'api-key: dev_UyebBGu4SpiswmyxyM5ISeJO5BoAVQO8yWX20QFoKFBwB7q50t23zvH3xRqQ6auv' \ --data-raw '{ "amount": 650, "currency": "USD", "confirm": true, "business_country": "US", "business_label": "default", "amount_to_capture": 650, "customer_id": "custhype1232", "capture_method": "automatic", "capture_on": "2022-09-10T10:11:12Z", "authentication_type": "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", "statement_descriptor_name": "Juspay", "statement_descriptor_suffix": "Router", "payment_method": "wallet", "payment_method_type": "apple_pay", "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" } }, "payment_method_data": { "wallet": { "apple_pay": { "payment_data":"data", "payment_method": { "display_name": "Visa 0326", "network": "Mastercard", "type": "debit" }, "transaction_identifier": "identifier" } } } }' ``` 3. Check whether payment_methods entry is created in table 4. Now do `list_customer_payment_method` which generates a payment_token When checked in redis for that `payment_token` ![image](https://github.com/juspay/hyperswitch/assets/70657455/95662ab4-fa17-413f-8255-08a65fcb6c83) Cannot be tested in sandbox, as this inserts value in redis. (Could log into redis and check the entry) ## 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 - [ ] I added a [CHANGELOG](/CHANGELOG.md) entry if applicable
d220e815dc81925b205fb57d5d4f05883c1a7cde
1. Create mca with wallets being a payment method ``` curl --location 'http://localhost:8080/account/merchant_1709561576/connectors' \ --header 'Content-Type: application/json' \ --header 'Accept: application/json' \ --header 'api-key: test_admin' \ --data '{ "connector_type": "fiz_operations", "connector_name": "stripe", "connector_account_details": { "auth_type": "HeaderKey", "api_key": "abc" }, "test_mode": false, "disabled": false, "payment_methods_enabled": [ { "payment_method": "card", "payment_method_types": [ { "payment_method_type": "credit", "card_networks": [ "Visa", "Mastercard" ], "minimum_amount": 1, "maximum_amount": 68607706, "recurring_enabled": true, "installment_payment_enabled": true }, { "payment_method_type": "debit", "card_networks": [ "Visa", "Mastercard" ], "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": "apple_pay", "payment_experience": "invoke_sdk_client", "minimum_amount": 1, "maximum_amount": 68607706, "recurring_enabled": true, "installment_payment_enabled": true }, { "payment_method_type": "google_pay", "payment_experience": "invoke_sdk_client", "minimum_amount": 1, "maximum_amount": 68607706, "recurring_enabled": true, "installment_payment_enabled": true } ] } ], "metadata": { "apple_pay_combined": { "manual": { "session_token_data": { "initiative": "web", "certificate": "certificate", "display_name": "applepay", "certificate_keys": "keys", "initiative_context": "sdk-test-app.netlify.app", "merchant_identifier": "xyz" }, "payment_request_data": { "label": "applepay", "supported_networks": [ "visa", "masterCard", "amex", "discover" ], "merchant_capabilities": [ "supports3DS" ] } } }, "google_pay": { "merchant_info": { "merchant_name": "Stripe" }, "allowed_payment_methods": [ { "type": "CARD", "parameters": { "allowed_auth_methods": [ "PAN_ONLY", "CRYPTOGRAM_3DS" ], "allowed_card_networks": [ "AMEX", "DISCOVER", "INTERAC", "JCB", "MASTERCARD", "VISA" ] }, "tokenization_specification": { "type": "PAYMENT_GATEWAY", "parameters": { "gateway": "stripe", "stripe:version": "2018-10-31", "stripe:publishableKey": "abc" } } } ] } }, "connector_webhook_details": { "merchant_secret": "MyWebhookSecret" }, "business_country": "US", "business_label": "default" }' ``` 2. Create a applepay wallet payment so that wallet entry gets saved in `payment_methods` table ``` curl --location 'http://localhost:8080/payments' \ --header 'Content-Type: application/json' \ --header 'Accept: application/json' \ --header 'api-key: dev_UyebBGu4SpiswmyxyM5ISeJO5BoAVQO8yWX20QFoKFBwB7q50t23zvH3xRqQ6auv' \ --data-raw '{ "amount": 650, "currency": "USD", "confirm": true, "business_country": "US", "business_label": "default", "amount_to_capture": 650, "customer_id": "custhype1232", "capture_method": "automatic", "capture_on": "2022-09-10T10:11:12Z", "authentication_type": "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", "statement_descriptor_name": "Juspay", "statement_descriptor_suffix": "Router", "payment_method": "wallet", "payment_method_type": "apple_pay", "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" } }, "payment_method_data": { "wallet": { "apple_pay": { "payment_data":"data", "payment_method": { "display_name": "Visa 0326", "network": "Mastercard", "type": "debit" }, "transaction_identifier": "identifier" } } } }' ``` 3. Check whether payment_methods entry is created in table 4. Now do `list_customer_payment_method` which generates a payment_token When checked in redis for that `payment_token` ![image](https://github.com/juspay/hyperswitch/assets/70657455/95662ab4-fa17-413f-8255-08a65fcb6c83) Cannot be tested in sandbox, as this inserts value in redis. (Could log into redis and check the entry)
juspay/hyperswitch
juspay__hyperswitch-3792
Bug: [BUG] Nuvei payment declined errors are not captured ### Bug Description Nuvei Payments error are captured and handled only for transaction status : "Error" Testing [card declined](https://docs.nuvei.com/documentation/integration/testing/testing-cards/#cards-that-return-declined) is not responding with expected error code and message error_code and error_message is responded as null <img width="615" alt="image" src="https://github.com/juspay/hyperswitch/assets/97145230/220ba157-fb4f-4d79-bd51-74c19fbab0ca"> ### Expected Behavior Expected Response : ``` { "payment_id": "pay_99nCeujKAhTB27glC5Fw", "merchant_id": "mannar_1707830889", "status": "failed", "amount": 100, "net_amount": 100, "amount_capturable": 0, "amount_received": null, "connector": "nuvei", "client_secret": "pay_99nCeujKAhTB27glC5Fw_secret_bTMbuN08o3fvjytYPyEd", "created": "2024-02-23T06:32:16.486Z", "currency": "USD", "customer_id": "futurebilling", "description": "testing", "refunds": null, "disputes": null, "mandate_id": null, "mandate_data": { "update_mandate_id": null, "customer_acceptance": { "acceptance_type": "offline", "accepted_at": "1963-05-03T04:07:52.723Z", "online": { "ip_address": "127.0.0.1", "user_agent": "amet irure esse" } }, "mandate_type": { "multi_use": { "amount": 100, "currency": "USD", "start_date": null, "end_date": "2025-05-03T04:07:52.723Z", "metadata": { "frequency": "1" } } } }, "setup_future_usage": "off_session", "off_session": null, "capture_on": null, "capture_method": "automatic", "payment_method": "card", "payment_method_data": { "card": { "last4": "4872", "card_type": null, "card_network": null, "card_issuer": null, "card_issuing_country": null, "card_isin": "400017", "card_extended_bin": "40001739", "card_exp_month": "12", "card_exp_year": "2030", "card_holder_name": "joseph Doe" } }, "payment_token": "token_EDEFLY9j7GRL5eFlIgoa", "shipping": null, "billing": { "address": { "city": "San Fransico", "country": "JP", "line1": "1467", "line2": "jkjj Street", "line3": "no 1111 Street", "zip": "94122", "state": "California", "first_name": "joseph", "last_name": "Doe" }, "phone": { "number": "8056594427", "country_code": "+91" } }, "order_details": 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": null, "next_action": null, "cancellation_reason": null, "error_code": "-1", "error_message": "Insufficient Funds", "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": "futurebilling", "created_at": 1708669936, "expires": 1708673536, "secret": "epk_8c2eac5c44034e18827f3010def0cda0" }, "manual_retry_allowed": true, "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": null, "payment_link": null, "profile_id": "pro_9dOQiOX8uDPqZLfv43Nk", "surcharge_details": null, "attempt_count": 1, "merchant_decision": null, "merchant_connector_id": "mca_8Qy72oJr0qiR02QRfx5s", "incremental_authorization_allowed": false, "authorization_count": null, "incremental_authorizations": null, "expires_on": "2024-02-23T06:47:16.486Z", "fingerprint": null } ``` ### Actual Behavior Actual Response : ``` { "payment_id": "pay_3eyj9vgQYARPh25iJEXi", "merchant_id": "mannar_1707830889", "status": "failed", "amount": 100, "net_amount": 100, "amount_capturable": 0, "amount_received": null, "connector": "nuvei", "client_secret": "pay_3eyj9vgQYARPh25iJEXi_secret_Rml2NqJ8c2ObpTHY8NPf", "created": "2024-02-23T06:28:38.195Z", "currency": "USD", "customer_id": "futurebilling", "description": "testing", "refunds": null, "disputes": null, "mandate_id": "man_1hH78HlOeGSfhqXwHoBw", "mandate_data": { "update_mandate_id": null, "customer_acceptance": { "acceptance_type": "offline", "accepted_at": "1963-05-03T04:07:52.723Z", "online": { "ip_address": "127.0.0.1", "user_agent": "amet irure esse" } }, "mandate_type": { "multi_use": { "amount": 100, "currency": "USD", "start_date": null, "end_date": "2025-05-03T04:07:52.723Z", "metadata": { "frequency": "1" } } } }, "setup_future_usage": "off_session", "off_session": null, "capture_on": null, "capture_method": "automatic", "payment_method": "card", "payment_method_data": { "card": { "last4": "4872", "card_type": null, "card_network": null, "card_issuer": null, "card_issuing_country": null, "card_isin": "400017", "card_extended_bin": "40001739", "card_exp_month": "12", "card_exp_year": "2030", "card_holder_name": "joseph Doe" } }, "payment_token": "token_04lcgdDFWKc3j1FaI3Lu", "shipping": null, "billing": { "address": { "city": "San Fransico", "country": "JP", "line1": "1467", "line2": "jkjj Street", "line3": "no 1111 Street", "zip": "94122", "state": "California", "first_name": "joseph", "last_name": "Doe" }, "phone": { "number": "8056594427", "country_code": "+91" } }, "order_details": 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": 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": "futurebilling", "created_at": 1708669718, "expires": 1708673318, "secret": "epk_ae27cd98c8b64cc4845e6c1e0f3d84d9" }, "manual_retry_allowed": true, "connector_transaction_id": "711000000032512257", "frm_message": null, "metadata": { "udf1": "value1", "login_date": "2019-09-10T10:11:12Z", "new_customer": "true" }, "connector_metadata": null, "feature_metadata": null, "reference_id": "423006018", "payment_link": null, "profile_id": "pro_9dOQiOX8uDPqZLfv43Nk", "surcharge_details": null, "attempt_count": 1, "merchant_decision": null, "merchant_connector_id": "mca_8Qy72oJr0qiR02QRfx5s", "incremental_authorization_allowed": null, "authorization_count": null, "incremental_authorizations": null, "expires_on": "2024-02-23T06:43:38.195Z", "fingerprint": null } ``` ### 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/connector/nuvei/transformers.rs b/crates/router/src/connector/nuvei/transformers.rs index 13d522b86cc..bf622d7a077 100644 --- a/crates/router/src/connector/nuvei/transformers.rs +++ b/crates/router/src/connector/nuvei/transformers.rs @@ -1360,7 +1360,7 @@ fn build_error_response<T>( http_code, )); match response.transaction_status { - Some(NuveiTransactionStatus::Error) => err, + Some(NuveiTransactionStatus::Error) | Some(NuveiTransactionStatus::Declined) => err, _ => match response .gw_error_reason .as_ref() diff --git a/postman/collection-dir/nuvei/.auth.json b/postman/collection-dir/nuvei/.auth.json new file mode 100644 index 00000000000..915a2835790 --- /dev/null +++ b/postman/collection-dir/nuvei/.auth.json @@ -0,0 +1,22 @@ +{ + "auth": { + "type": "apikey", + "apikey": [ + { + "key": "value", + "value": "{{api_key}}", + "type": "string" + }, + { + "key": "key", + "value": "api-key", + "type": "string" + }, + { + "key": "in", + "value": "header", + "type": "string" + } + ] + } +} diff --git a/postman/collection-dir/nuvei/.event.meta.json b/postman/collection-dir/nuvei/.event.meta.json new file mode 100644 index 00000000000..2df9d47d936 --- /dev/null +++ b/postman/collection-dir/nuvei/.event.meta.json @@ -0,0 +1,6 @@ +{ + "eventOrder": [ + "event.prerequest.js", + "event.test.js" + ] +} diff --git a/postman/collection-dir/nuvei/.info.json b/postman/collection-dir/nuvei/.info.json new file mode 100644 index 00000000000..b1f71f3eee2 --- /dev/null +++ b/postman/collection-dir/nuvei/.info.json @@ -0,0 +1,9 @@ +{ + "info": { + "_postman_id": "d329ee53-0de4-4154-b0b1-78708ec6e708", + "name": "nuvei", + "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": "19204656" + } +} diff --git a/postman/collection-dir/nuvei/.meta.json b/postman/collection-dir/nuvei/.meta.json new file mode 100644 index 00000000000..91b6a65c5bc --- /dev/null +++ b/postman/collection-dir/nuvei/.meta.json @@ -0,0 +1,6 @@ +{ + "childrenOrder": [ + "Health check", + "Flow Testcases" + ] +} diff --git a/postman/collection-dir/nuvei/.variable.json b/postman/collection-dir/nuvei/.variable.json new file mode 100644 index 00000000000..84482b418fb --- /dev/null +++ b/postman/collection-dir/nuvei/.variable.json @@ -0,0 +1,86 @@ +{ + "variable": [ + { + "key": "baseUrl", + "value": "https://sandbox.hyperswitch.io", + "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" + } + ] +} diff --git a/postman/collection-dir/nuvei/Flow Testcases/.meta.json b/postman/collection-dir/nuvei/Flow Testcases/.meta.json new file mode 100644 index 00000000000..78d8ddcf5bb --- /dev/null +++ b/postman/collection-dir/nuvei/Flow Testcases/.meta.json @@ -0,0 +1,6 @@ +{ + "childrenOrder": [ + "QuickStart", + "Variation Cases" + ] +} diff --git a/postman/collection-dir/nuvei/Flow Testcases/QuickStart/.meta.json b/postman/collection-dir/nuvei/Flow Testcases/QuickStart/.meta.json new file mode 100644 index 00000000000..c4939d7ab91 --- /dev/null +++ b/postman/collection-dir/nuvei/Flow Testcases/QuickStart/.meta.json @@ -0,0 +1,11 @@ +{ + "childrenOrder": [ + "Merchant Account - Create", + "API Key - Create", + "Payment Connector - Create", + "Payments - Create", + "Payments - Retrieve", + "Refunds - Create", + "Refunds - Retrieve" + ] +} diff --git a/postman/collection-dir/nuvei/Flow Testcases/QuickStart/API Key - Create/.event.meta.json b/postman/collection-dir/nuvei/Flow Testcases/QuickStart/API Key - Create/.event.meta.json new file mode 100644 index 00000000000..688c85746ef --- /dev/null +++ b/postman/collection-dir/nuvei/Flow Testcases/QuickStart/API Key - Create/.event.meta.json @@ -0,0 +1,5 @@ +{ + "eventOrder": [ + "event.test.js" + ] +} diff --git a/postman/collection-dir/nuvei/Flow Testcases/QuickStart/API Key - Create/event.test.js b/postman/collection-dir/nuvei/Flow Testcases/QuickStart/API Key - Create/event.test.js new file mode 100644 index 00000000000..4e27c5a5025 --- /dev/null +++ b/postman/collection-dir/nuvei/Flow Testcases/QuickStart/API Key - Create/event.test.js @@ -0,0 +1,46 @@ +// Validate status 2xx +pm.test("[POST]::/api_keys/:merchant_id - Status code is 2xx", function () { + pm.response.to.be.success; +}); + +// Validate if response header has matching content-type +pm.test( + "[POST]::/api_keys/:merchant_id - Content-Type is application/json", + function () { + pm.expect(pm.response.headers.get("Content-Type")).to.include( + "application/json", + ); + }, +); + +// Set response object as internal variable +let jsonData = {}; +try { + jsonData = pm.response.json(); +} catch (e) {} + +// pm.collectionVariables - Set api_key_id as variable for jsonData.key_id +if (jsonData?.key_id) { + pm.collectionVariables.set("api_key_id", jsonData.key_id); + console.log( + "- use {{api_key_id}} as collection variable for value", + jsonData.key_id, + ); +} else { + console.log( + "INFO - Unable to assign variable {{api_key_id}}, as jsonData.key_id is undefined.", + ); +} + +// pm.collectionVariables - Set api_key as variable for jsonData.api_key +if (jsonData?.api_key) { + pm.collectionVariables.set("api_key", jsonData.api_key); + console.log( + "- use {{api_key}} as collection variable for value", + jsonData.api_key, + ); +} else { + console.log( + "INFO - Unable to assign variable {{api_key}}, as jsonData.api_key is undefined.", + ); +} diff --git a/postman/collection-dir/nuvei/Flow Testcases/QuickStart/API Key - Create/request.json b/postman/collection-dir/nuvei/Flow Testcases/QuickStart/API Key - Create/request.json new file mode 100644 index 00000000000..4e4c6628497 --- /dev/null +++ b/postman/collection-dir/nuvei/Flow Testcases/QuickStart/API Key - Create/request.json @@ -0,0 +1,52 @@ +{ + "auth": { + "type": "apikey", + "apikey": [ + { + "key": "value", + "value": "{{admin_api_key}}", + "type": "string" + }, + { + "key": "key", + "value": "api-key", + "type": "string" + } + ] + }, + "method": "POST", + "header": [ + { + "key": "Content-Type", + "value": "application/json" + }, + { + "key": "Accept", + "value": "application/json" + } + ], + "body": { + "mode": "raw", + "raw_json_formatted": { + "name": "API Key 1", + "description": null, + "expiration": "2069-09-23T01:02:03.000Z" + } + }, + "url": { + "raw": "{{baseUrl}}/api_keys/:merchant_id", + "host": [ + "{{baseUrl}}" + ], + "path": [ + "api_keys", + ":merchant_id" + ], + "variable": [ + { + "key": "merchant_id", + "value": "{{merchant_id}}" + } + ] + } +} diff --git a/postman/collection-dir/nuvei/Flow Testcases/QuickStart/API Key - Create/response.json b/postman/collection-dir/nuvei/Flow Testcases/QuickStart/API Key - Create/response.json new file mode 100644 index 00000000000..fe51488c706 --- /dev/null +++ b/postman/collection-dir/nuvei/Flow Testcases/QuickStart/API Key - Create/response.json @@ -0,0 +1 @@ +[] diff --git a/postman/collection-dir/nuvei/Flow Testcases/QuickStart/Merchant Account - Create/.event.meta.json b/postman/collection-dir/nuvei/Flow Testcases/QuickStart/Merchant Account - Create/.event.meta.json new file mode 100644 index 00000000000..4ac527d834a --- /dev/null +++ b/postman/collection-dir/nuvei/Flow Testcases/QuickStart/Merchant Account - Create/.event.meta.json @@ -0,0 +1,6 @@ +{ + "eventOrder": [ + "event.test.js", + "event.prerequest.js" + ] +} diff --git a/postman/collection-dir/nuvei/Flow Testcases/QuickStart/Merchant Account - Create/event.prerequest.js b/postman/collection-dir/nuvei/Flow Testcases/QuickStart/Merchant Account - Create/event.prerequest.js new file mode 100644 index 00000000000..e69de29bb2d diff --git a/postman/collection-dir/nuvei/Flow Testcases/QuickStart/Merchant Account - Create/event.test.js b/postman/collection-dir/nuvei/Flow Testcases/QuickStart/Merchant Account - Create/event.test.js new file mode 100644 index 00000000000..7de0d5beb31 --- /dev/null +++ b/postman/collection-dir/nuvei/Flow Testcases/QuickStart/Merchant Account - Create/event.test.js @@ -0,0 +1,56 @@ +// Validate status 2xx +pm.test("[POST]::/accounts - Status code is 2xx", function () { + pm.response.to.be.success; +}); + +// Validate if response header has matching content-type +pm.test("[POST]::/accounts - Content-Type is application/json", function () { + pm.expect(pm.response.headers.get("Content-Type")).to.include( + "application/json", + ); +}); + +// Set response object as internal variable +let jsonData = {}; +try { + jsonData = pm.response.json(); +} catch (e) {} + +// pm.collectionVariables - Set merchant_id as variable for jsonData.merchant_id +if (jsonData?.merchant_id) { + pm.collectionVariables.set("merchant_id", jsonData.merchant_id); + console.log( + "- use {{merchant_id}} as collection variable for value", + jsonData.merchant_id, + ); +} else { + console.log( + "INFO - Unable to assign variable {{merchant_id}}, as jsonData.merchant_id is undefined.", + ); +} + +// pm.collectionVariables - Set api_key as variable for jsonData.api_key +if (jsonData?.api_key) { + pm.collectionVariables.set("api_key", jsonData.api_key); + console.log( + "- use {{api_key}} as collection variable for value", + jsonData.api_key, + ); +} else { + console.log( + "INFO - Unable to assign variable {{api_key}}, as jsonData.api_key is undefined.", + ); +} + +// pm.collectionVariables - Set publishable_key as variable for jsonData.publishable_key +if (jsonData?.publishable_key) { + pm.collectionVariables.set("publishable_key", jsonData.publishable_key); + console.log( + "- use {{publishable_key}} as collection variable for value", + jsonData.publishable_key, + ); +} else { + console.log( + "INFO - Unable to assign variable {{publishable_key}}, as jsonData.publishable_key is undefined.", + ); +} diff --git a/postman/collection-dir/nuvei/Flow Testcases/QuickStart/Merchant Account - Create/request.json b/postman/collection-dir/nuvei/Flow Testcases/QuickStart/Merchant Account - Create/request.json new file mode 100644 index 00000000000..ffeea3410a4 --- /dev/null +++ b/postman/collection-dir/nuvei/Flow Testcases/QuickStart/Merchant Account - Create/request.json @@ -0,0 +1,95 @@ +{ + "auth": { + "type": "apikey", + "apikey": [ + { + "key": "value", + "value": "{{admin_api_key}}", + "type": "string" + }, + { + "key": "key", + "value": "api-key", + "type": "string" + }, + { + "key": "in", + "value": "header", + "type": "string" + } + ] + }, + "method": "POST", + "header": [ + { + "key": "Content-Type", + "value": "application/json" + }, + { + "key": "Accept", + "value": "application/json" + } + ], + "body": { + "mode": "raw", + "options": { + "raw": { + "language": "json" + } + }, + "raw_json_formatted": { + "merchant_id": "postman_merchant_GHAction_{{$guid}}", + "locker_id": "m0010", + "merchant_name": "NewAge Retailer", + "primary_business_details": [ + { + "country": "US", + "business": "default" + } + ], + "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://duck.com", + "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" + } + } + }, + "url": { + "raw": "{{baseUrl}}/accounts", + "host": [ + "{{baseUrl}}" + ], + "path": [ + "accounts" + ] + }, + "description": "Create a new account for a merchant. The merchant could be a seller or retailer or client who likes to receive and send payments." +} diff --git a/postman/collection-dir/nuvei/Flow Testcases/QuickStart/Merchant Account - Create/response.json b/postman/collection-dir/nuvei/Flow Testcases/QuickStart/Merchant Account - Create/response.json new file mode 100644 index 00000000000..fe51488c706 --- /dev/null +++ b/postman/collection-dir/nuvei/Flow Testcases/QuickStart/Merchant Account - Create/response.json @@ -0,0 +1 @@ +[] diff --git a/postman/collection-dir/nuvei/Flow Testcases/QuickStart/Payment Connector - Create/.event.meta.json b/postman/collection-dir/nuvei/Flow Testcases/QuickStart/Payment Connector - Create/.event.meta.json new file mode 100644 index 00000000000..4ac527d834a --- /dev/null +++ b/postman/collection-dir/nuvei/Flow Testcases/QuickStart/Payment Connector - Create/.event.meta.json @@ -0,0 +1,6 @@ +{ + "eventOrder": [ + "event.test.js", + "event.prerequest.js" + ] +} diff --git a/postman/collection-dir/nuvei/Flow Testcases/QuickStart/Payment Connector - Create/event.prerequest.js b/postman/collection-dir/nuvei/Flow Testcases/QuickStart/Payment Connector - Create/event.prerequest.js new file mode 100644 index 00000000000..e69de29bb2d diff --git a/postman/collection-dir/nuvei/Flow Testcases/QuickStart/Payment Connector - Create/event.test.js b/postman/collection-dir/nuvei/Flow Testcases/QuickStart/Payment Connector - Create/event.test.js new file mode 100644 index 00000000000..88e92d8d84a --- /dev/null +++ b/postman/collection-dir/nuvei/Flow Testcases/QuickStart/Payment Connector - Create/event.test.js @@ -0,0 +1,39 @@ +// Validate status 2xx +pm.test( + "[POST]::/account/:account_id/connectors - Status code is 2xx", + function () { + pm.response.to.be.success; + }, +); + +// Validate if response header has matching content-type +pm.test( + "[POST]::/account/:account_id/connectors - Content-Type is application/json", + function () { + pm.expect(pm.response.headers.get("Content-Type")).to.include( + "application/json", + ); + }, +); + +// Set response object as internal variable +let jsonData = {}; +try { + jsonData = pm.response.json(); +} catch (e) {} + +// pm.collectionVariables - Set merchant_connector_id as variable for jsonData.merchant_connector_id +if (jsonData?.merchant_connector_id) { + pm.collectionVariables.set( + "merchant_connector_id", + jsonData.merchant_connector_id, + ); + console.log( + "- use {{merchant_connector_id}} as collection variable for value", + jsonData.merchant_connector_id, + ); +} else { + console.log( + "INFO - Unable to assign variable {{merchant_connector_id}}, as jsonData.merchant_connector_id is undefined.", + ); +} diff --git a/postman/collection-dir/nuvei/Flow Testcases/QuickStart/Payment Connector - Create/request.json b/postman/collection-dir/nuvei/Flow Testcases/QuickStart/Payment Connector - Create/request.json new file mode 100644 index 00000000000..32e3afc6348 --- /dev/null +++ b/postman/collection-dir/nuvei/Flow Testcases/QuickStart/Payment Connector - Create/request.json @@ -0,0 +1,98 @@ +{ + "auth": { + "type": "apikey", + "apikey": [ + { + "key": "value", + "value": "{{admin_api_key}}", + "type": "string" + }, + { + "key": "key", + "value": "api-key", + "type": "string" + }, + { + "key": "in", + "value": "header", + "type": "string" + } + ] + }, + "method": "POST", + "header": [ + { + "key": "Content-Type", + "value": "application/json" + }, + { + "key": "Accept", + "value": "application/json" + } + ], + "body": { + "mode": "raw", + "options": { + "raw": { + "language": "json" + } + }, + "raw_json_formatted": { + "connector_type": "payment_processor", + "connector_name": "nuvei", + "connector_account_details": { + "auth_type": "SignatureKey", + "key1": "{{connector_key1}}", + "api_key": "{{connector_api_key}}", + "api_secret": "{{connector_api_secret}}" + }, + "test_mode": true, + "disabled": false, + "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": "card", + "payment_method_types": [ + { + "payment_method_type": "debit", + "minimum_amount": 1, + "maximum_amount": 68607706, + "recurring_enabled": true, + "installment_payment_enabled": true + } + ] + } + ] + } + }, + "url": { + "raw": "{{baseUrl}}/account/:account_id/connectors", + "host": [ + "{{baseUrl}}" + ], + "path": [ + "account", + ":account_id", + "connectors" + ], + "variable": [ + { + "key": "account_id", + "value": "{{merchant_id}}", + "description": "(Required) The unique identifier for the merchant account" + } + ] + }, + "description": "Create a new Payment Connector for the merchant account. The connector could be a payment processor / facilitator / acquirer or specialised services like Fraud / Accounting etc." +} diff --git a/postman/collection-dir/nuvei/Flow Testcases/QuickStart/Payment Connector - Create/response.json b/postman/collection-dir/nuvei/Flow Testcases/QuickStart/Payment Connector - Create/response.json new file mode 100644 index 00000000000..fe51488c706 --- /dev/null +++ b/postman/collection-dir/nuvei/Flow Testcases/QuickStart/Payment Connector - Create/response.json @@ -0,0 +1 @@ +[] diff --git a/postman/collection-dir/nuvei/Flow Testcases/QuickStart/Payments - Create/.event.meta.json b/postman/collection-dir/nuvei/Flow Testcases/QuickStart/Payments - Create/.event.meta.json new file mode 100644 index 00000000000..4ac527d834a --- /dev/null +++ b/postman/collection-dir/nuvei/Flow Testcases/QuickStart/Payments - Create/.event.meta.json @@ -0,0 +1,6 @@ +{ + "eventOrder": [ + "event.test.js", + "event.prerequest.js" + ] +} diff --git a/postman/collection-dir/nuvei/Flow Testcases/QuickStart/Payments - Create/event.prerequest.js b/postman/collection-dir/nuvei/Flow Testcases/QuickStart/Payments - Create/event.prerequest.js new file mode 100644 index 00000000000..27965bb9c01 --- /dev/null +++ b/postman/collection-dir/nuvei/Flow Testcases/QuickStart/Payments - Create/event.prerequest.js @@ -0,0 +1 @@ +pm.environment.set("random_number", _.random(1000, 100000)); diff --git a/postman/collection-dir/nuvei/Flow Testcases/QuickStart/Payments - Create/event.test.js b/postman/collection-dir/nuvei/Flow Testcases/QuickStart/Payments - Create/event.test.js new file mode 100644 index 00000000000..dc285fb1afe --- /dev/null +++ b/postman/collection-dir/nuvei/Flow Testcases/QuickStart/Payments - Create/event.test.js @@ -0,0 +1,66 @@ +pm.environment.set("random_number", _.random(1000, 100000)); + +// Set the environment variable 'amount' with the value from the response +pm.environment.set("amount", pm.response.json().amount); + +// Validate status 2xx +pm.test("[POST]::/payments - Status code is 2xx", function () { + pm.response.to.be.success; +}); + +// Validate if response header has matching content-type +pm.test("[POST]::/payments - 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]::/payments - Response has JSON Body", function () { + pm.response.to.have.jsonBody(); +}); + +// Set response object as internal variable +let jsonData = {}; +try { + jsonData = pm.response.json(); +} catch (e) {} + +// pm.collectionVariables - Set payment_id as variable for jsonData.payment_id +if (jsonData?.payment_id) { + pm.collectionVariables.set("payment_id", jsonData.payment_id); + console.log( + "- use {{payment_id}} as collection variable for value", + jsonData.payment_id, + ); +} else { + console.log( + "INFO - Unable to assign variable {{payment_id}}, as jsonData.payment_id is undefined.", + ); +} + +// pm.collectionVariables - Set mandate_id as variable for jsonData.mandate_id +if (jsonData?.mandate_id) { + pm.collectionVariables.set("mandate_id", jsonData.mandate_id); + console.log( + "- use {{mandate_id}} as collection variable for value", + jsonData.mandate_id, + ); +} else { + console.log( + "INFO - Unable to assign variable {{mandate_id}}, as jsonData.mandate_id is undefined.", + ); +} + +// pm.collectionVariables - Set client_secret as variable for jsonData.client_secret +if (jsonData?.client_secret) { + pm.collectionVariables.set("client_secret", jsonData.client_secret); + console.log( + "- use {{client_secret}} as collection variable for value", + jsonData.client_secret, + ); +} else { + console.log( + "INFO - Unable to assign variable {{client_secret}}, as jsonData.client_secret is undefined.", + ); +} diff --git a/postman/collection-dir/nuvei/Flow Testcases/QuickStart/Payments - Create/request.json b/postman/collection-dir/nuvei/Flow Testcases/QuickStart/Payments - Create/request.json new file mode 100644 index 00000000000..9ca781cb8f8 --- /dev/null +++ b/postman/collection-dir/nuvei/Flow Testcases/QuickStart/Payments - Create/request.json @@ -0,0 +1,111 @@ +{ + "method": "POST", + "header": [ + { + "key": "Content-Type", + "value": "application/json" + }, + { + "key": "Accept", + "value": "application/json" + } + ], + "body": { + "mode": "raw", + "options": { + "raw": { + "language": "json" + } + }, + "raw_json_formatted": { + "amount": 100, + "currency": "USD", + "confirm": true, + "capture_method": "automatic", + "connector": [ + "nuvei" + ], + "customer_id": "futurebilling", + "email": "guest@example.com", + "name": "John Doe", + "phone": "999999999", + "phone_country_code": "+65", + "description": "testing", + "authentication_type": "no_three_ds", + "return_url": "https://google.com", + "payment_method": "card", + "payment_method_type": "credit", + "setup_future_usage": "off_session", + "payment_method_data": { + "card": { + "card_number": "4111111111111111", + "card_exp_month": "12", + "card_exp_year": "2030", + "card_holder_name": "joseph Doe", + "card_cvc": "123" + } + }, + "mandate_data": { + "customer_acceptance": { + "acceptance_type": "offline", + "accepted_at": "1963-05-03T04:07:52.723Z", + "online": { + "ip_address": "127.0.0.1", + "user_agent": "amet irure esse" + } + }, + "mandate_type": { + "multi_use": { + "amount": 100, + "currency": "USD", + "metadata": { + "frequency": "1" + }, + "end_date": "2025-05-03T04:07:52.723Z" + } + } + }, + "billing": { + "address": { + "line1": "1467", + "line2": "jkjj Street", + "line3": "no 1111 Street", + "city": "San Fransico", + "state": "California", + "zip": "94122", + "country": "JP", + "first_name": "joseph", + "last_name": "Doe" + } + }, + "statement_descriptor_name": "joseph", + "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": "127.0.0.1" + } + } + }, + "url": { + "raw": "{{baseUrl}}/payments", + "host": [ + "{{baseUrl}}" + ], + "path": [ + "payments" + ] + }, + "description": "To process a payment you will have to create a payment, attach a payment method and confirm. Depending on the user journey you wish to achieve, you may opt to all the steps in a single request or in a sequence of API request using following APIs: (i) Payments - Update, (ii) Payments - Confirm, and (iii) Payments - Capture" +} diff --git a/postman/collection-dir/nuvei/Flow Testcases/QuickStart/Payments - Create/response.json b/postman/collection-dir/nuvei/Flow Testcases/QuickStart/Payments - Create/response.json new file mode 100644 index 00000000000..fe51488c706 --- /dev/null +++ b/postman/collection-dir/nuvei/Flow Testcases/QuickStart/Payments - Create/response.json @@ -0,0 +1 @@ +[] diff --git a/postman/collection-dir/nuvei/Flow Testcases/QuickStart/Payments - Retrieve/.event.meta.json b/postman/collection-dir/nuvei/Flow Testcases/QuickStart/Payments - Retrieve/.event.meta.json new file mode 100644 index 00000000000..688c85746ef --- /dev/null +++ b/postman/collection-dir/nuvei/Flow Testcases/QuickStart/Payments - Retrieve/.event.meta.json @@ -0,0 +1,5 @@ +{ + "eventOrder": [ + "event.test.js" + ] +} diff --git a/postman/collection-dir/nuvei/Flow Testcases/QuickStart/Payments - Retrieve/event.test.js b/postman/collection-dir/nuvei/Flow Testcases/QuickStart/Payments - Retrieve/event.test.js new file mode 100644 index 00000000000..bbd8e544e2c --- /dev/null +++ b/postman/collection-dir/nuvei/Flow Testcases/QuickStart/Payments - Retrieve/event.test.js @@ -0,0 +1,30 @@ +// Validate status 2xx +pm.test("[GET]::/refunds/:id - Status code is 2xx", function () { + pm.response.to.be.success; +}); + +// Validate if response header has matching content-type +pm.test("[GET]::/refunds/:id - Content-Type is application/json", function () { + pm.expect(pm.response.headers.get("Content-Type")).to.include( + "application/json", + ); +}); + +// Set response object as internal variable +let jsonData = {}; +try { + jsonData = pm.response.json(); +} catch (e) {} + +// pm.collectionVariables - Set refund_id as variable for jsonData.payment_id +if (jsonData?.refund_id) { + pm.collectionVariables.set("refund_id", jsonData.refund_id); + console.log( + "- use {{refund_id}} as collection variable for value", + jsonData.refund_id, + ); +} else { + console.log( + "INFO - Unable to assign variable {{refund_id}}, as jsonData.refund_id is undefined.", + ); +} diff --git a/postman/collection-dir/nuvei/Flow Testcases/QuickStart/Payments - Retrieve/request.json b/postman/collection-dir/nuvei/Flow Testcases/QuickStart/Payments - Retrieve/request.json new file mode 100644 index 00000000000..203cc8ad8d1 --- /dev/null +++ b/postman/collection-dir/nuvei/Flow Testcases/QuickStart/Payments - Retrieve/request.json @@ -0,0 +1,33 @@ +{ + "method": "GET", + "header": [ + { + "key": "Accept", + "value": "application/json" + } + ], + "url": { + "raw": "{{baseUrl}}/payments/:id?force_sync=true", + "host": [ + "{{baseUrl}}" + ], + "path": [ + "payments", + ":id" + ], + "query": [ + { + "key": "force_sync", + "value": "true" + } + ], + "variable": [ + { + "key": "id", + "value": "{{payment_id}}", + "description": "(Required) unique refund id" + } + ] + }, + "description": "To retrieve the properties of a Refund. This may be used to get the status of a previously initiated payment or next action for an ongoing payment" +} diff --git a/postman/collection-dir/nuvei/Flow Testcases/QuickStart/Payments - Retrieve/response.json b/postman/collection-dir/nuvei/Flow Testcases/QuickStart/Payments - Retrieve/response.json new file mode 100644 index 00000000000..fe51488c706 --- /dev/null +++ b/postman/collection-dir/nuvei/Flow Testcases/QuickStart/Payments - Retrieve/response.json @@ -0,0 +1 @@ +[] diff --git a/postman/collection-dir/nuvei/Flow Testcases/QuickStart/Refunds - Create/.event.meta.json b/postman/collection-dir/nuvei/Flow Testcases/QuickStart/Refunds - Create/.event.meta.json new file mode 100644 index 00000000000..688c85746ef --- /dev/null +++ b/postman/collection-dir/nuvei/Flow Testcases/QuickStart/Refunds - Create/.event.meta.json @@ -0,0 +1,5 @@ +{ + "eventOrder": [ + "event.test.js" + ] +} diff --git a/postman/collection-dir/nuvei/Flow Testcases/QuickStart/Refunds - Create/event.test.js b/postman/collection-dir/nuvei/Flow Testcases/QuickStart/Refunds - Create/event.test.js new file mode 100644 index 00000000000..61f29c86540 --- /dev/null +++ b/postman/collection-dir/nuvei/Flow Testcases/QuickStart/Refunds - Create/event.test.js @@ -0,0 +1,33 @@ +// Get the value of 'amount' from the environment +const amount = pm.environment.get("amount"); + +// Validate status 2xx +pm.test("[POST]::/refunds - Status code is 2xx", function () { + pm.response.to.be.success; +}); + +// Validate if response header has matching content-type +pm.test("[POST]::/refunds - Content-Type is application/json", function () { + pm.expect(pm.response.headers.get("Content-Type")).to.include( + "application/json", + ); +}); + +// Set response object as internal variable +let jsonData = {}; +try { + jsonData = pm.response.json(); +} catch (e) {} + +// pm.collectionVariables - Set refund_id as variable for jsonData.payment_id +if (jsonData?.refund_id) { + pm.collectionVariables.set("refund_id", jsonData.refund_id); + console.log( + "- use {{refund_id}} as collection variable for value", + jsonData.refund_id, + ); +} else { + console.log( + "INFO - Unable to assign variable {{refund_id}}, as jsonData.refund_id is undefined.", + ); +} diff --git a/postman/collection-dir/nuvei/Flow Testcases/QuickStart/Refunds - Create/request.json b/postman/collection-dir/nuvei/Flow Testcases/QuickStart/Refunds - Create/request.json new file mode 100644 index 00000000000..e9cb375957e --- /dev/null +++ b/postman/collection-dir/nuvei/Flow Testcases/QuickStart/Refunds - Create/request.json @@ -0,0 +1,32 @@ +{ + "method": "POST", + "header": [ + { + "key": "Content-Type", + "value": "application/json" + }, + { + "key": "Accept", + "value": "application/json" + } + ], + "body": { + "mode": "raw", + "raw": "{\n \"payment_id\": \"{{payment_id}}\",\n \"amount\": {{amount}},\n \"reason\": \"Customer returned product\",\n \"refund_type\": \"instant\",\n \"metadata\": {\n \"udf1\": \"value1\",\n \"new_customer\": \"true\",\n \"login_date\": \"2019-09-10T10:11:12Z\"\n }\n}", + "options": { + "raw": { + "language": "json" + } + } + }, + "url": { + "raw": "{{baseUrl}}/refunds", + "host": [ + "{{baseUrl}}" + ], + "path": [ + "refunds" + ] + }, + "description": "To create a refund against an already processed payment" +} diff --git a/postman/collection-dir/nuvei/Flow Testcases/QuickStart/Refunds - Create/response.json b/postman/collection-dir/nuvei/Flow Testcases/QuickStart/Refunds - Create/response.json new file mode 100644 index 00000000000..fe51488c706 --- /dev/null +++ b/postman/collection-dir/nuvei/Flow Testcases/QuickStart/Refunds - Create/response.json @@ -0,0 +1 @@ +[] diff --git a/postman/collection-dir/nuvei/Flow Testcases/QuickStart/Refunds - Retrieve/.event.meta.json b/postman/collection-dir/nuvei/Flow Testcases/QuickStart/Refunds - Retrieve/.event.meta.json new file mode 100644 index 00000000000..688c85746ef --- /dev/null +++ b/postman/collection-dir/nuvei/Flow Testcases/QuickStart/Refunds - Retrieve/.event.meta.json @@ -0,0 +1,5 @@ +{ + "eventOrder": [ + "event.test.js" + ] +} diff --git a/postman/collection-dir/nuvei/Flow Testcases/QuickStart/Refunds - Retrieve/event.test.js b/postman/collection-dir/nuvei/Flow Testcases/QuickStart/Refunds - Retrieve/event.test.js new file mode 100644 index 00000000000..bbd8e544e2c --- /dev/null +++ b/postman/collection-dir/nuvei/Flow Testcases/QuickStart/Refunds - Retrieve/event.test.js @@ -0,0 +1,30 @@ +// Validate status 2xx +pm.test("[GET]::/refunds/:id - Status code is 2xx", function () { + pm.response.to.be.success; +}); + +// Validate if response header has matching content-type +pm.test("[GET]::/refunds/:id - Content-Type is application/json", function () { + pm.expect(pm.response.headers.get("Content-Type")).to.include( + "application/json", + ); +}); + +// Set response object as internal variable +let jsonData = {}; +try { + jsonData = pm.response.json(); +} catch (e) {} + +// pm.collectionVariables - Set refund_id as variable for jsonData.payment_id +if (jsonData?.refund_id) { + pm.collectionVariables.set("refund_id", jsonData.refund_id); + console.log( + "- use {{refund_id}} as collection variable for value", + jsonData.refund_id, + ); +} else { + console.log( + "INFO - Unable to assign variable {{refund_id}}, as jsonData.refund_id is undefined.", + ); +} diff --git a/postman/collection-dir/nuvei/Flow Testcases/QuickStart/Refunds - Retrieve/request.json b/postman/collection-dir/nuvei/Flow Testcases/QuickStart/Refunds - Retrieve/request.json new file mode 100644 index 00000000000..06b44cf7fd3 --- /dev/null +++ b/postman/collection-dir/nuvei/Flow Testcases/QuickStart/Refunds - Retrieve/request.json @@ -0,0 +1,33 @@ +{ + "method": "GET", + "header": [ + { + "key": "Accept", + "value": "application/json" + } + ], + "url": { + "raw": "{{baseUrl}}/refunds/:id?force_sync=true", + "host": [ + "{{baseUrl}}" + ], + "path": [ + "refunds", + ":id" + ], + "query": [ + { + "key": "force_sync", + "value": "true" + } + ], + "variable": [ + { + "key": "id", + "value": "{{refund_id}}", + "description": "(Required) unique refund id" + } + ] + }, + "description": "To retrieve the properties of a Refund. This may be used to get the status of a previously initiated payment or next action for an ongoing payment" +} diff --git a/postman/collection-dir/nuvei/Flow Testcases/QuickStart/Refunds - Retrieve/response.json b/postman/collection-dir/nuvei/Flow Testcases/QuickStart/Refunds - Retrieve/response.json new file mode 100644 index 00000000000..fe51488c706 --- /dev/null +++ b/postman/collection-dir/nuvei/Flow Testcases/QuickStart/Refunds - Retrieve/response.json @@ -0,0 +1 @@ +[] diff --git a/postman/collection-dir/nuvei/Flow Testcases/Variation Cases/.meta.json b/postman/collection-dir/nuvei/Flow Testcases/Variation Cases/.meta.json new file mode 100644 index 00000000000..8ae4ccb0019 --- /dev/null +++ b/postman/collection-dir/nuvei/Flow Testcases/Variation Cases/.meta.json @@ -0,0 +1,6 @@ +{ + "childrenOrder": [ + "Scenario1- Create Payment with Invalid card", + "Scenario1- Payment Decline scenario" + ] +} diff --git a/postman/collection-dir/nuvei/Flow Testcases/Variation Cases/Scenario1- Create Payment with Invalid card/.meta.json b/postman/collection-dir/nuvei/Flow Testcases/Variation Cases/Scenario1- Create Payment with Invalid card/.meta.json new file mode 100644 index 00000000000..10f13eaa42a --- /dev/null +++ b/postman/collection-dir/nuvei/Flow Testcases/Variation Cases/Scenario1- Create Payment with Invalid card/.meta.json @@ -0,0 +1,7 @@ +{ + "childrenOrder": [ + "Payments - Create(Expired Card)", + "Payments - Create(Invalid CVV)", + "Payments - Create(Lost Card)" + ] +} diff --git a/postman/collection-dir/nuvei/Flow Testcases/Variation Cases/Scenario1- Create Payment with Invalid card/Payments - Create(Expired Card)/.event.meta.json b/postman/collection-dir/nuvei/Flow Testcases/Variation Cases/Scenario1- Create Payment with Invalid card/Payments - Create(Expired Card)/.event.meta.json new file mode 100644 index 00000000000..688c85746ef --- /dev/null +++ b/postman/collection-dir/nuvei/Flow Testcases/Variation Cases/Scenario1- Create Payment with Invalid card/Payments - Create(Expired Card)/.event.meta.json @@ -0,0 +1,5 @@ +{ + "eventOrder": [ + "event.test.js" + ] +} diff --git a/postman/collection-dir/nuvei/Flow Testcases/Variation Cases/Scenario1- Create Payment with Invalid card/Payments - Create(Expired Card)/event.test.js b/postman/collection-dir/nuvei/Flow Testcases/Variation Cases/Scenario1- Create Payment with Invalid card/Payments - Create(Expired Card)/event.test.js new file mode 100644 index 00000000000..f6232ceea45 --- /dev/null +++ b/postman/collection-dir/nuvei/Flow Testcases/Variation Cases/Scenario1- Create Payment with Invalid card/Payments - Create(Expired Card)/event.test.js @@ -0,0 +1,73 @@ +pm.environment.set("random_number", _.random(100, 100000)); + +// Validate status 2xx +pm.test("[POST]::/payments - Status code is 2xx", function () { + pm.response.to.be.success; +}); + + +// Validate if response header has matching content-type +pm.test("[POST]::/payments - 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]::/payments - Response has JSON Body", function () { + pm.response.to.have.jsonBody(); +}); + +// Set response object as internal variable +let jsonData = {}; +try { + jsonData = pm.response.json(); +} catch (e) {} + +// pm.collectionVariables - Set payment_id as variable for jsonData.payment_id +if (jsonData?.payment_id) { + pm.collectionVariables.set("payment_id", jsonData.payment_id); + console.log( + "- use {{payment_id}} as collection variable for value", + jsonData.payment_id, + ); +} else { + console.log( + "INFO - Unable to assign variable {{payment_id}}, as jsonData.payment_id is undefined.", + ); +} + +// pm.collectionVariables - Set mandate_id as variable for jsonData.mandate_id +if (jsonData?.mandate_id) { + pm.collectionVariables.set("mandate_id", jsonData.mandate_id); + console.log( + "- use {{mandate_id}} as collection variable for value", + jsonData.mandate_id, + ); +} else { + console.log( + "INFO - Unable to assign variable {{mandate_id}}, as jsonData.mandate_id is undefined.", + ); +} + +// pm.collectionVariables - Set client_secret as variable for jsonData.client_secret +if (jsonData?.client_secret) { + pm.collectionVariables.set("client_secret", jsonData.client_secret); + console.log( + "- use {{client_secret}} as collection variable for value", + jsonData.client_secret, + ); +} else { + console.log( + "INFO - Unable to assign variable {{client_secret}}, as jsonData.client_secret is undefined.", + ); +} + + +// Response body should have "error_message: Expired Card" +pm.test("[POST]::/payments - Content check if 'error_message : Expired Card' exists", function () { + pm.expect(jsonData.error_message).to.eql("Expired Card"); +}); + + + diff --git a/postman/collection-dir/nuvei/Flow Testcases/Variation Cases/Scenario1- Create Payment with Invalid card/Payments - Create(Expired Card)/request.json b/postman/collection-dir/nuvei/Flow Testcases/Variation Cases/Scenario1- Create Payment with Invalid card/Payments - Create(Expired Card)/request.json new file mode 100644 index 00000000000..6bfc1515950 --- /dev/null +++ b/postman/collection-dir/nuvei/Flow Testcases/Variation Cases/Scenario1- Create Payment with Invalid card/Payments - Create(Expired Card)/request.json @@ -0,0 +1,111 @@ +{ + "method": "POST", + "header": [ + { + "key": "Content-Type", + "value": "application/json" + }, + { + "key": "Accept", + "value": "application/json" + } + ], + "body": { + "mode": "raw", + "options": { + "raw": { + "language": "json" + } + }, + "raw_json_formatted": { + "amount": 100, + "currency": "USD", + "confirm": true, + "capture_method": "automatic", + "connector": [ + "nuvei" + ], + "customer_id": "futurebilling", + "email": "guest@example.com", + "name": "John Doe", + "phone": "999999999", + "phone_country_code": "+65", + "description": "testing", + "authentication_type": "no_three_ds", + "return_url": "https://google.com", + "payment_method": "card", + "payment_method_type": "credit", + "setup_future_usage": "off_session", + "payment_method_data": { + "card": { + "card_number": "4000247422310226", + "card_exp_month": "12", + "card_exp_year": "2030", + "card_holder_name": "joseph Doe", + "card_cvc": "123" + } + }, + "mandate_data": { + "customer_acceptance": { + "acceptance_type": "offline", + "accepted_at": "1963-05-03T04:07:52.723Z", + "online": { + "ip_address": "127.0.0.1", + "user_agent": "amet irure esse" + } + }, + "mandate_type": { + "multi_use": { + "amount": 100, + "currency": "USD", + "metadata": { + "frequency": "1" + }, + "end_date": "2025-05-03T04:07:52.723Z" + } + } + }, + "billing": { + "address": { + "line1": "1467", + "line2": "jkjj Street", + "line3": "no 1111 Street", + "city": "San Fransico", + "state": "California", + "zip": "94122", + "country": "JP", + "first_name": "joseph", + "last_name": "Doe" + } + }, + "statement_descriptor_name": "joseph", + "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": "127.0.0.1" + } + } + }, + "url": { + "raw": "{{baseUrl}}/payments", + "host": [ + "{{baseUrl}}" + ], + "path": [ + "payments" + ] + }, + "description": "To process a payment you will have to create a payment, attach a payment method and confirm. Depending on the user journey you wish to achieve, you may opt to all the steps in a single request or in a sequence of API request using following APIs: (i) Payments - Update, (ii) Payments - Confirm, and (iii) Payments - Capture" +} diff --git a/postman/collection-dir/nuvei/Flow Testcases/Variation Cases/Scenario1- Create Payment with Invalid card/Payments - Create(Expired Card)/response.json b/postman/collection-dir/nuvei/Flow Testcases/Variation Cases/Scenario1- Create Payment with Invalid card/Payments - Create(Expired Card)/response.json new file mode 100644 index 00000000000..fe51488c706 --- /dev/null +++ b/postman/collection-dir/nuvei/Flow Testcases/Variation Cases/Scenario1- Create Payment with Invalid card/Payments - Create(Expired Card)/response.json @@ -0,0 +1 @@ +[] diff --git a/postman/collection-dir/nuvei/Flow Testcases/Variation Cases/Scenario1- Create Payment with Invalid card/Payments - Create(Invalid CVV)/.event.meta.json b/postman/collection-dir/nuvei/Flow Testcases/Variation Cases/Scenario1- Create Payment with Invalid card/Payments - Create(Invalid CVV)/.event.meta.json new file mode 100644 index 00000000000..688c85746ef --- /dev/null +++ b/postman/collection-dir/nuvei/Flow Testcases/Variation Cases/Scenario1- Create Payment with Invalid card/Payments - Create(Invalid CVV)/.event.meta.json @@ -0,0 +1,5 @@ +{ + "eventOrder": [ + "event.test.js" + ] +} diff --git a/postman/collection-dir/nuvei/Flow Testcases/Variation Cases/Scenario1- Create Payment with Invalid card/Payments - Create(Invalid CVV)/event.test.js b/postman/collection-dir/nuvei/Flow Testcases/Variation Cases/Scenario1- Create Payment with Invalid card/Payments - Create(Invalid CVV)/event.test.js new file mode 100644 index 00000000000..4dee6c97027 --- /dev/null +++ b/postman/collection-dir/nuvei/Flow Testcases/Variation Cases/Scenario1- Create Payment with Invalid card/Payments - Create(Invalid CVV)/event.test.js @@ -0,0 +1,73 @@ +pm.environment.set("random_number", _.random(100, 100000)); + +// Validate status 2xx +pm.test("[POST]::/payments - Status code is 2xx", function () { + pm.response.to.be.success; +}); + + +// Validate if response header has matching content-type +pm.test("[POST]::/payments - 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]::/payments - Response has JSON Body", function () { + pm.response.to.have.jsonBody(); +}); + +// Set response object as internal variable +let jsonData = {}; +try { + jsonData = pm.response.json(); +} catch (e) {} + +// pm.collectionVariables - Set payment_id as variable for jsonData.payment_id +if (jsonData?.payment_id) { + pm.collectionVariables.set("payment_id", jsonData.payment_id); + console.log( + "- use {{payment_id}} as collection variable for value", + jsonData.payment_id, + ); +} else { + console.log( + "INFO - Unable to assign variable {{payment_id}}, as jsonData.payment_id is undefined.", + ); +} + +// pm.collectionVariables - Set mandate_id as variable for jsonData.mandate_id +if (jsonData?.mandate_id) { + pm.collectionVariables.set("mandate_id", jsonData.mandate_id); + console.log( + "- use {{mandate_id}} as collection variable for value", + jsonData.mandate_id, + ); +} else { + console.log( + "INFO - Unable to assign variable {{mandate_id}}, as jsonData.mandate_id is undefined.", + ); +} + +// pm.collectionVariables - Set client_secret as variable for jsonData.client_secret +if (jsonData?.client_secret) { + pm.collectionVariables.set("client_secret", jsonData.client_secret); + console.log( + "- use {{client_secret}} as collection variable for value", + jsonData.client_secret, + ); +} else { + console.log( + "INFO - Unable to assign variable {{client_secret}}, as jsonData.client_secret is undefined.", + ); +} + + +// Response body should have "error_message: Invalid CVV" +pm.test("[POST]::/payments - Content check if 'error_message : Invalid CVV' exists", function () { + pm.expect(jsonData.error_message).to.eql("Invalid CVV"); +}); + + + diff --git a/postman/collection-dir/nuvei/Flow Testcases/Variation Cases/Scenario1- Create Payment with Invalid card/Payments - Create(Invalid CVV)/request.json b/postman/collection-dir/nuvei/Flow Testcases/Variation Cases/Scenario1- Create Payment with Invalid card/Payments - Create(Invalid CVV)/request.json new file mode 100644 index 00000000000..f936588a9f5 --- /dev/null +++ b/postman/collection-dir/nuvei/Flow Testcases/Variation Cases/Scenario1- Create Payment with Invalid card/Payments - Create(Invalid CVV)/request.json @@ -0,0 +1,111 @@ +{ + "method": "POST", + "header": [ + { + "key": "Content-Type", + "value": "application/json" + }, + { + "key": "Accept", + "value": "application/json" + } + ], + "body": { + "mode": "raw", + "options": { + "raw": { + "language": "json" + } + }, + "raw_json_formatted": { + "amount": 100, + "currency": "USD", + "confirm": true, + "capture_method": "automatic", + "connector": [ + "nuvei" + ], + "customer_id": "futurebilling", + "email": "guest@example.com", + "name": "John Doe", + "phone": "999999999", + "phone_country_code": "+65", + "description": "testing", + "authentication_type": "no_three_ds", + "return_url": "https://google.com", + "payment_method": "card", + "payment_method_type": "credit", + "setup_future_usage": "off_session", + "payment_method_data": { + "card": { + "card_number": "5333583123003909", + "card_exp_month": "12", + "card_exp_year": "2030", + "card_holder_name": "joseph Doe", + "card_cvc": "123" + } + }, + "mandate_data": { + "customer_acceptance": { + "acceptance_type": "offline", + "accepted_at": "1963-05-03T04:07:52.723Z", + "online": { + "ip_address": "127.0.0.1", + "user_agent": "amet irure esse" + } + }, + "mandate_type": { + "multi_use": { + "amount": 100, + "currency": "USD", + "metadata": { + "frequency": "1" + }, + "end_date": "2025-05-03T04:07:52.723Z" + } + } + }, + "billing": { + "address": { + "line1": "1467", + "line2": "jkjj Street", + "line3": "no 1111 Street", + "city": "San Fransico", + "state": "California", + "zip": "94122", + "country": "JP", + "first_name": "joseph", + "last_name": "Doe" + } + }, + "statement_descriptor_name": "joseph", + "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": "127.0.0.1" + } + } + }, + "url": { + "raw": "{{baseUrl}}/payments", + "host": [ + "{{baseUrl}}" + ], + "path": [ + "payments" + ] + }, + "description": "To process a payment you will have to create a payment, attach a payment method and confirm. Depending on the user journey you wish to achieve, you may opt to all the steps in a single request or in a sequence of API request using following APIs: (i) Payments - Update, (ii) Payments - Confirm, and (iii) Payments - Capture" +} diff --git a/postman/collection-dir/nuvei/Flow Testcases/Variation Cases/Scenario1- Create Payment with Invalid card/Payments - Create(Invalid CVV)/response.json b/postman/collection-dir/nuvei/Flow Testcases/Variation Cases/Scenario1- Create Payment with Invalid card/Payments - Create(Invalid CVV)/response.json new file mode 100644 index 00000000000..fe51488c706 --- /dev/null +++ b/postman/collection-dir/nuvei/Flow Testcases/Variation Cases/Scenario1- Create Payment with Invalid card/Payments - Create(Invalid CVV)/response.json @@ -0,0 +1 @@ +[] diff --git a/postman/collection-dir/nuvei/Flow Testcases/Variation Cases/Scenario1- Create Payment with Invalid card/Payments - Create(Lost Card)/.event.meta.json b/postman/collection-dir/nuvei/Flow Testcases/Variation Cases/Scenario1- Create Payment with Invalid card/Payments - Create(Lost Card)/.event.meta.json new file mode 100644 index 00000000000..688c85746ef --- /dev/null +++ b/postman/collection-dir/nuvei/Flow Testcases/Variation Cases/Scenario1- Create Payment with Invalid card/Payments - Create(Lost Card)/.event.meta.json @@ -0,0 +1,5 @@ +{ + "eventOrder": [ + "event.test.js" + ] +} diff --git a/postman/collection-dir/nuvei/Flow Testcases/Variation Cases/Scenario1- Create Payment with Invalid card/Payments - Create(Lost Card)/event.test.js b/postman/collection-dir/nuvei/Flow Testcases/Variation Cases/Scenario1- Create Payment with Invalid card/Payments - Create(Lost Card)/event.test.js new file mode 100644 index 00000000000..c603c454610 --- /dev/null +++ b/postman/collection-dir/nuvei/Flow Testcases/Variation Cases/Scenario1- Create Payment with Invalid card/Payments - Create(Lost Card)/event.test.js @@ -0,0 +1,73 @@ +pm.environment.set("random_number", _.random(100, 100000)); + +// Validate status 2xx +pm.test("[POST]::/payments - Status code is 2xx", function () { + pm.response.to.be.success; +}); + + +// Validate if response header has matching content-type +pm.test("[POST]::/payments - 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]::/payments - Response has JSON Body", function () { + pm.response.to.have.jsonBody(); +}); + +// Set response object as internal variable +let jsonData = {}; +try { + jsonData = pm.response.json(); +} catch (e) {} + +// pm.collectionVariables - Set payment_id as variable for jsonData.payment_id +if (jsonData?.payment_id) { + pm.collectionVariables.set("payment_id", jsonData.payment_id); + console.log( + "- use {{payment_id}} as collection variable for value", + jsonData.payment_id, + ); +} else { + console.log( + "INFO - Unable to assign variable {{payment_id}}, as jsonData.payment_id is undefined.", + ); +} + +// pm.collectionVariables - Set mandate_id as variable for jsonData.mandate_id +if (jsonData?.mandate_id) { + pm.collectionVariables.set("mandate_id", jsonData.mandate_id); + console.log( + "- use {{mandate_id}} as collection variable for value", + jsonData.mandate_id, + ); +} else { + console.log( + "INFO - Unable to assign variable {{mandate_id}}, as jsonData.mandate_id is undefined.", + ); +} + +// pm.collectionVariables - Set client_secret as variable for jsonData.client_secret +if (jsonData?.client_secret) { + pm.collectionVariables.set("client_secret", jsonData.client_secret); + console.log( + "- use {{client_secret}} as collection variable for value", + jsonData.client_secret, + ); +} else { + console.log( + "INFO - Unable to assign variable {{client_secret}}, as jsonData.client_secret is undefined.", + ); +} + + +// Response body should have "error_message: Lost/Stolen" +pm.test("[POST]::/payments - Content check if 'error_message : Lost/Stolen' exists", function () { + pm.expect(jsonData.error_message).to.eql("Lost/Stolen"); +}); + + + diff --git a/postman/collection-dir/nuvei/Flow Testcases/Variation Cases/Scenario1- Create Payment with Invalid card/Payments - Create(Lost Card)/request.json b/postman/collection-dir/nuvei/Flow Testcases/Variation Cases/Scenario1- Create Payment with Invalid card/Payments - Create(Lost Card)/request.json new file mode 100644 index 00000000000..9d317ce5293 --- /dev/null +++ b/postman/collection-dir/nuvei/Flow Testcases/Variation Cases/Scenario1- Create Payment with Invalid card/Payments - Create(Lost Card)/request.json @@ -0,0 +1,111 @@ +{ + "method": "POST", + "header": [ + { + "key": "Content-Type", + "value": "application/json" + }, + { + "key": "Accept", + "value": "application/json" + } + ], + "body": { + "mode": "raw", + "options": { + "raw": { + "language": "json" + } + }, + "raw_json_formatted": { + "amount": 100, + "currency": "USD", + "confirm": true, + "capture_method": "automatic", + "connector": [ + "nuvei" + ], + "customer_id": "futurebilling", + "email": "guest@example.com", + "name": "John Doe", + "phone": "999999999", + "phone_country_code": "+65", + "description": "testing", + "authentication_type": "no_three_ds", + "return_url": "https://google.com", + "payment_method": "card", + "payment_method_type": "credit", + "setup_future_usage": "off_session", + "payment_method_data": { + "card": { + "card_number": "5333452804487502", + "card_exp_month": "12", + "card_exp_year": "2030", + "card_holder_name": "joseph Doe", + "card_cvc": "123" + } + }, + "mandate_data": { + "customer_acceptance": { + "acceptance_type": "offline", + "accepted_at": "1963-05-03T04:07:52.723Z", + "online": { + "ip_address": "127.0.0.1", + "user_agent": "amet irure esse" + } + }, + "mandate_type": { + "multi_use": { + "amount": 100, + "currency": "USD", + "metadata": { + "frequency": "1" + }, + "end_date": "2025-05-03T04:07:52.723Z" + } + } + }, + "billing": { + "address": { + "line1": "1467", + "line2": "jkjj Street", + "line3": "no 1111 Street", + "city": "San Fransico", + "state": "California", + "zip": "94122", + "country": "JP", + "first_name": "joseph", + "last_name": "Doe" + } + }, + "statement_descriptor_name": "joseph", + "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": "127.0.0.1" + } + } + }, + "url": { + "raw": "{{baseUrl}}/payments", + "host": [ + "{{baseUrl}}" + ], + "path": [ + "payments" + ] + }, + "description": "To process a payment you will have to create a payment, attach a payment method and confirm. Depending on the user journey you wish to achieve, you may opt to all the steps in a single request or in a sequence of API request using following APIs: (i) Payments - Update, (ii) Payments - Confirm, and (iii) Payments - Capture" +} diff --git a/postman/collection-dir/nuvei/Flow Testcases/Variation Cases/Scenario1- Create Payment with Invalid card/Payments - Create(Lost Card)/response.json b/postman/collection-dir/nuvei/Flow Testcases/Variation Cases/Scenario1- Create Payment with Invalid card/Payments - Create(Lost Card)/response.json new file mode 100644 index 00000000000..fe51488c706 --- /dev/null +++ b/postman/collection-dir/nuvei/Flow Testcases/Variation Cases/Scenario1- Create Payment with Invalid card/Payments - Create(Lost Card)/response.json @@ -0,0 +1 @@ +[] diff --git a/postman/collection-dir/nuvei/Flow Testcases/Variation Cases/Scenario1- Payment Decline scenario/.meta.json b/postman/collection-dir/nuvei/Flow Testcases/Variation Cases/Scenario1- Payment Decline scenario/.meta.json new file mode 100644 index 00000000000..c0cc1f23cc1 --- /dev/null +++ b/postman/collection-dir/nuvei/Flow Testcases/Variation Cases/Scenario1- Payment Decline scenario/.meta.json @@ -0,0 +1,7 @@ +{ + "childrenOrder": [ + "Payments - Create(Decline)", + "Payments - Create(Do Not Honor)", + "Payments - Create(Insufficient Funds)" + ] +} diff --git a/postman/collection-dir/nuvei/Flow Testcases/Variation Cases/Scenario1- Payment Decline scenario/Payments - Create(Decline)/.event.meta.json b/postman/collection-dir/nuvei/Flow Testcases/Variation Cases/Scenario1- Payment Decline scenario/Payments - Create(Decline)/.event.meta.json new file mode 100644 index 00000000000..688c85746ef --- /dev/null +++ b/postman/collection-dir/nuvei/Flow Testcases/Variation Cases/Scenario1- Payment Decline scenario/Payments - Create(Decline)/.event.meta.json @@ -0,0 +1,5 @@ +{ + "eventOrder": [ + "event.test.js" + ] +} diff --git a/postman/collection-dir/nuvei/Flow Testcases/Variation Cases/Scenario1- Payment Decline scenario/Payments - Create(Decline)/event.test.js b/postman/collection-dir/nuvei/Flow Testcases/Variation Cases/Scenario1- Payment Decline scenario/Payments - Create(Decline)/event.test.js new file mode 100644 index 00000000000..354776fa309 --- /dev/null +++ b/postman/collection-dir/nuvei/Flow Testcases/Variation Cases/Scenario1- Payment Decline scenario/Payments - Create(Decline)/event.test.js @@ -0,0 +1,73 @@ +pm.environment.set("random_number", _.random(100, 100000)); + +// Validate status 2xx +pm.test("[POST]::/payments - Status code is 2xx", function () { + pm.response.to.be.success; +}); + + +// Validate if response header has matching content-type +pm.test("[POST]::/payments - 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]::/payments - Response has JSON Body", function () { + pm.response.to.have.jsonBody(); +}); + +// Set response object as internal variable +let jsonData = {}; +try { + jsonData = pm.response.json(); +} catch (e) {} + +// pm.collectionVariables - Set payment_id as variable for jsonData.payment_id +if (jsonData?.payment_id) { + pm.collectionVariables.set("payment_id", jsonData.payment_id); + console.log( + "- use {{payment_id}} as collection variable for value", + jsonData.payment_id, + ); +} else { + console.log( + "INFO - Unable to assign variable {{payment_id}}, as jsonData.payment_id is undefined.", + ); +} + +// pm.collectionVariables - Set mandate_id as variable for jsonData.mandate_id +if (jsonData?.mandate_id) { + pm.collectionVariables.set("mandate_id", jsonData.mandate_id); + console.log( + "- use {{mandate_id}} as collection variable for value", + jsonData.mandate_id, + ); +} else { + console.log( + "INFO - Unable to assign variable {{mandate_id}}, as jsonData.mandate_id is undefined.", + ); +} + +// pm.collectionVariables - Set client_secret as variable for jsonData.client_secret +if (jsonData?.client_secret) { + pm.collectionVariables.set("client_secret", jsonData.client_secret); + console.log( + "- use {{client_secret}} as collection variable for value", + jsonData.client_secret, + ); +} else { + console.log( + "INFO - Unable to assign variable {{client_secret}}, as jsonData.client_secret is undefined.", + ); +} + + +// Response body should have "error_message: Decline" +pm.test("[POST]::/payments - Content check if 'error_message : Decline' exists", function () { + pm.expect(jsonData.error_message).to.eql("Decline"); +}); + + + diff --git a/postman/collection-dir/nuvei/Flow Testcases/Variation Cases/Scenario1- Payment Decline scenario/Payments - Create(Decline)/request.json b/postman/collection-dir/nuvei/Flow Testcases/Variation Cases/Scenario1- Payment Decline scenario/Payments - Create(Decline)/request.json new file mode 100644 index 00000000000..93f6d30da08 --- /dev/null +++ b/postman/collection-dir/nuvei/Flow Testcases/Variation Cases/Scenario1- Payment Decline scenario/Payments - Create(Decline)/request.json @@ -0,0 +1,111 @@ +{ + "method": "POST", + "header": [ + { + "key": "Content-Type", + "value": "application/json" + }, + { + "key": "Accept", + "value": "application/json" + } + ], + "body": { + "mode": "raw", + "options": { + "raw": { + "language": "json" + } + }, + "raw_json_formatted": { + "amount": 100, + "currency": "USD", + "confirm": true, + "capture_method": "automatic", + "connector": [ + "nuvei" + ], + "customer_id": "futurebilling", + "email": "guest@example.com", + "name": "John Doe", + "phone": "999999999", + "phone_country_code": "+65", + "description": "testing", + "authentication_type": "no_three_ds", + "return_url": "https://google.com", + "payment_method": "card", + "payment_method_type": "credit", + "setup_future_usage": "off_session", + "payment_method_data": { + "card": { + "card_number": "375521501910816", + "card_exp_month": "12", + "card_exp_year": "2030", + "card_holder_name": "joseph Doe", + "card_cvc": "123" + } + }, + "mandate_data": { + "customer_acceptance": { + "acceptance_type": "offline", + "accepted_at": "1963-05-03T04:07:52.723Z", + "online": { + "ip_address": "127.0.0.1", + "user_agent": "amet irure esse" + } + }, + "mandate_type": { + "multi_use": { + "amount": 100, + "currency": "USD", + "metadata": { + "frequency": "1" + }, + "end_date": "2025-05-03T04:07:52.723Z" + } + } + }, + "billing": { + "address": { + "line1": "1467", + "line2": "jkjj Street", + "line3": "no 1111 Street", + "city": "San Fransico", + "state": "California", + "zip": "94122", + "country": "JP", + "first_name": "joseph", + "last_name": "Doe" + } + }, + "statement_descriptor_name": "joseph", + "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": "127.0.0.1" + } + } + }, + "url": { + "raw": "{{baseUrl}}/payments", + "host": [ + "{{baseUrl}}" + ], + "path": [ + "payments" + ] + }, + "description": "To process a payment you will have to create a payment, attach a payment method and confirm. Depending on the user journey you wish to achieve, you may opt to all the steps in a single request or in a sequence of API request using following APIs: (i) Payments - Update, (ii) Payments - Confirm, and (iii) Payments - Capture" +} diff --git a/postman/collection-dir/nuvei/Flow Testcases/Variation Cases/Scenario1- Payment Decline scenario/Payments - Create(Decline)/response.json b/postman/collection-dir/nuvei/Flow Testcases/Variation Cases/Scenario1- Payment Decline scenario/Payments - Create(Decline)/response.json new file mode 100644 index 00000000000..fe51488c706 --- /dev/null +++ b/postman/collection-dir/nuvei/Flow Testcases/Variation Cases/Scenario1- Payment Decline scenario/Payments - Create(Decline)/response.json @@ -0,0 +1 @@ +[] diff --git a/postman/collection-dir/nuvei/Flow Testcases/Variation Cases/Scenario1- Payment Decline scenario/Payments - Create(Do Not Honor)/.event.meta.json b/postman/collection-dir/nuvei/Flow Testcases/Variation Cases/Scenario1- Payment Decline scenario/Payments - Create(Do Not Honor)/.event.meta.json new file mode 100644 index 00000000000..688c85746ef --- /dev/null +++ b/postman/collection-dir/nuvei/Flow Testcases/Variation Cases/Scenario1- Payment Decline scenario/Payments - Create(Do Not Honor)/.event.meta.json @@ -0,0 +1,5 @@ +{ + "eventOrder": [ + "event.test.js" + ] +} diff --git a/postman/collection-dir/nuvei/Flow Testcases/Variation Cases/Scenario1- Payment Decline scenario/Payments - Create(Do Not Honor)/event.test.js b/postman/collection-dir/nuvei/Flow Testcases/Variation Cases/Scenario1- Payment Decline scenario/Payments - Create(Do Not Honor)/event.test.js new file mode 100644 index 00000000000..c2070d7a153 --- /dev/null +++ b/postman/collection-dir/nuvei/Flow Testcases/Variation Cases/Scenario1- Payment Decline scenario/Payments - Create(Do Not Honor)/event.test.js @@ -0,0 +1,73 @@ +pm.environment.set("random_number", _.random(100, 100000)); + +// Validate status 2xx +pm.test("[POST]::/payments - Status code is 2xx", function () { + pm.response.to.be.success; +}); + + +// Validate if response header has matching content-type +pm.test("[POST]::/payments - 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]::/payments - Response has JSON Body", function () { + pm.response.to.have.jsonBody(); +}); + +// Set response object as internal variable +let jsonData = {}; +try { + jsonData = pm.response.json(); +} catch (e) {} + +// pm.collectionVariables - Set payment_id as variable for jsonData.payment_id +if (jsonData?.payment_id) { + pm.collectionVariables.set("payment_id", jsonData.payment_id); + console.log( + "- use {{payment_id}} as collection variable for value", + jsonData.payment_id, + ); +} else { + console.log( + "INFO - Unable to assign variable {{payment_id}}, as jsonData.payment_id is undefined.", + ); +} + +// pm.collectionVariables - Set mandate_id as variable for jsonData.mandate_id +if (jsonData?.mandate_id) { + pm.collectionVariables.set("mandate_id", jsonData.mandate_id); + console.log( + "- use {{mandate_id}} as collection variable for value", + jsonData.mandate_id, + ); +} else { + console.log( + "INFO - Unable to assign variable {{mandate_id}}, as jsonData.mandate_id is undefined.", + ); +} + +// pm.collectionVariables - Set client_secret as variable for jsonData.client_secret +if (jsonData?.client_secret) { + pm.collectionVariables.set("client_secret", jsonData.client_secret); + console.log( + "- use {{client_secret}} as collection variable for value", + jsonData.client_secret, + ); +} else { + console.log( + "INFO - Unable to assign variable {{client_secret}}, as jsonData.client_secret is undefined.", + ); +} + + +// Response body should have "error_message: Do Not Honor" +pm.test("[POST]::/payments - Content check if 'error_message : Do Not Honor' exists", function () { + pm.expect(jsonData.error_message).to.eql("Do Not Honor"); +}); + + + diff --git a/postman/collection-dir/nuvei/Flow Testcases/Variation Cases/Scenario1- Payment Decline scenario/Payments - Create(Do Not Honor)/request.json b/postman/collection-dir/nuvei/Flow Testcases/Variation Cases/Scenario1- Payment Decline scenario/Payments - Create(Do Not Honor)/request.json new file mode 100644 index 00000000000..b9cbf1fa7a5 --- /dev/null +++ b/postman/collection-dir/nuvei/Flow Testcases/Variation Cases/Scenario1- Payment Decline scenario/Payments - Create(Do Not Honor)/request.json @@ -0,0 +1,111 @@ +{ + "method": "POST", + "header": [ + { + "key": "Content-Type", + "value": "application/json" + }, + { + "key": "Accept", + "value": "application/json" + } + ], + "body": { + "mode": "raw", + "options": { + "raw": { + "language": "json" + } + }, + "raw_json_formatted": { + "amount": 100, + "currency": "USD", + "confirm": true, + "capture_method": "automatic", + "connector": [ + "nuvei" + ], + "customer_id": "futurebilling", + "email": "guest@example.com", + "name": "John Doe", + "phone": "999999999", + "phone_country_code": "+65", + "description": "testing", + "authentication_type": "no_three_ds", + "return_url": "https://google.com", + "payment_method": "card", + "payment_method_type": "credit", + "setup_future_usage": "off_session", + "payment_method_data": { + "card": { + "card_number": "5333463046218753", + "card_exp_month": "12", + "card_exp_year": "2030", + "card_holder_name": "joseph Doe", + "card_cvc": "123" + } + }, + "mandate_data": { + "customer_acceptance": { + "acceptance_type": "offline", + "accepted_at": "1963-05-03T04:07:52.723Z", + "online": { + "ip_address": "127.0.0.1", + "user_agent": "amet irure esse" + } + }, + "mandate_type": { + "multi_use": { + "amount": 100, + "currency": "USD", + "metadata": { + "frequency": "1" + }, + "end_date": "2025-05-03T04:07:52.723Z" + } + } + }, + "billing": { + "address": { + "line1": "1467", + "line2": "jkjj Street", + "line3": "no 1111 Street", + "city": "San Fransico", + "state": "California", + "zip": "94122", + "country": "JP", + "first_name": "joseph", + "last_name": "Doe" + } + }, + "statement_descriptor_name": "joseph", + "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": "127.0.0.1" + } + } + }, + "url": { + "raw": "{{baseUrl}}/payments", + "host": [ + "{{baseUrl}}" + ], + "path": [ + "payments" + ] + }, + "description": "To process a payment you will have to create a payment, attach a payment method and confirm. Depending on the user journey you wish to achieve, you may opt to all the steps in a single request or in a sequence of API request using following APIs: (i) Payments - Update, (ii) Payments - Confirm, and (iii) Payments - Capture" +} diff --git a/postman/collection-dir/nuvei/Flow Testcases/Variation Cases/Scenario1- Payment Decline scenario/Payments - Create(Do Not Honor)/response.json b/postman/collection-dir/nuvei/Flow Testcases/Variation Cases/Scenario1- Payment Decline scenario/Payments - Create(Do Not Honor)/response.json new file mode 100644 index 00000000000..fe51488c706 --- /dev/null +++ b/postman/collection-dir/nuvei/Flow Testcases/Variation Cases/Scenario1- Payment Decline scenario/Payments - Create(Do Not Honor)/response.json @@ -0,0 +1 @@ +[] diff --git a/postman/collection-dir/nuvei/Flow Testcases/Variation Cases/Scenario1- Payment Decline scenario/Payments - Create(Insufficient Funds)/.event.meta.json b/postman/collection-dir/nuvei/Flow Testcases/Variation Cases/Scenario1- Payment Decline scenario/Payments - Create(Insufficient Funds)/.event.meta.json new file mode 100644 index 00000000000..688c85746ef --- /dev/null +++ b/postman/collection-dir/nuvei/Flow Testcases/Variation Cases/Scenario1- Payment Decline scenario/Payments - Create(Insufficient Funds)/.event.meta.json @@ -0,0 +1,5 @@ +{ + "eventOrder": [ + "event.test.js" + ] +} diff --git a/postman/collection-dir/nuvei/Flow Testcases/Variation Cases/Scenario1- Payment Decline scenario/Payments - Create(Insufficient Funds)/event.test.js b/postman/collection-dir/nuvei/Flow Testcases/Variation Cases/Scenario1- Payment Decline scenario/Payments - Create(Insufficient Funds)/event.test.js new file mode 100644 index 00000000000..09d39c6965c --- /dev/null +++ b/postman/collection-dir/nuvei/Flow Testcases/Variation Cases/Scenario1- Payment Decline scenario/Payments - Create(Insufficient Funds)/event.test.js @@ -0,0 +1,73 @@ +pm.environment.set("random_number", _.random(100, 100000)); + +// Validate status 2xx +pm.test("[POST]::/payments - Status code is 2xx", function () { + pm.response.to.be.success; +}); + + +// Validate if response header has matching content-type +pm.test("[POST]::/payments - 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]::/payments - Response has JSON Body", function () { + pm.response.to.have.jsonBody(); +}); + +// Set response object as internal variable +let jsonData = {}; +try { + jsonData = pm.response.json(); +} catch (e) {} + +// pm.collectionVariables - Set payment_id as variable for jsonData.payment_id +if (jsonData?.payment_id) { + pm.collectionVariables.set("payment_id", jsonData.payment_id); + console.log( + "- use {{payment_id}} as collection variable for value", + jsonData.payment_id, + ); +} else { + console.log( + "INFO - Unable to assign variable {{payment_id}}, as jsonData.payment_id is undefined.", + ); +} + +// pm.collectionVariables - Set mandate_id as variable for jsonData.mandate_id +if (jsonData?.mandate_id) { + pm.collectionVariables.set("mandate_id", jsonData.mandate_id); + console.log( + "- use {{mandate_id}} as collection variable for value", + jsonData.mandate_id, + ); +} else { + console.log( + "INFO - Unable to assign variable {{mandate_id}}, as jsonData.mandate_id is undefined.", + ); +} + +// pm.collectionVariables - Set client_secret as variable for jsonData.client_secret +if (jsonData?.client_secret) { + pm.collectionVariables.set("client_secret", jsonData.client_secret); + console.log( + "- use {{client_secret}} as collection variable for value", + jsonData.client_secret, + ); +} else { + console.log( + "INFO - Unable to assign variable {{client_secret}}, as jsonData.client_secret is undefined.", + ); +} + + +// Response body should have "error_message: Insufficient Funds" +pm.test("[POST]::/payments - Content check if 'error_message : Insufficient Funds' exists", function () { + pm.expect(jsonData.error_message).to.eql("Insufficient Funds"); +}); + + + diff --git a/postman/collection-dir/nuvei/Flow Testcases/Variation Cases/Scenario1- Payment Decline scenario/Payments - Create(Insufficient Funds)/request.json b/postman/collection-dir/nuvei/Flow Testcases/Variation Cases/Scenario1- Payment Decline scenario/Payments - Create(Insufficient Funds)/request.json new file mode 100644 index 00000000000..41edc08e2f9 --- /dev/null +++ b/postman/collection-dir/nuvei/Flow Testcases/Variation Cases/Scenario1- Payment Decline scenario/Payments - Create(Insufficient Funds)/request.json @@ -0,0 +1,111 @@ +{ + "method": "POST", + "header": [ + { + "key": "Content-Type", + "value": "application/json" + }, + { + "key": "Accept", + "value": "application/json" + } + ], + "body": { + "mode": "raw", + "options": { + "raw": { + "language": "json" + } + }, + "raw_json_formatted": { + "amount": 100, + "currency": "USD", + "confirm": true, + "capture_method": "automatic", + "connector": [ + "nuvei" + ], + "customer_id": "futurebilling", + "email": "guest@example.com", + "name": "John Doe", + "phone": "999999999", + "phone_country_code": "+65", + "description": "testing", + "authentication_type": "no_three_ds", + "return_url": "https://google.com", + "payment_method": "card", + "payment_method_type": "credit", + "setup_future_usage": "off_session", + "payment_method_data": { + "card": { + "card_number": "5333475572200849", + "card_exp_month": "12", + "card_exp_year": "2030", + "card_holder_name": "joseph Doe", + "card_cvc": "123" + } + }, + "mandate_data": { + "customer_acceptance": { + "acceptance_type": "offline", + "accepted_at": "1963-05-03T04:07:52.723Z", + "online": { + "ip_address": "127.0.0.1", + "user_agent": "amet irure esse" + } + }, + "mandate_type": { + "multi_use": { + "amount": 100, + "currency": "USD", + "metadata": { + "frequency": "1" + }, + "end_date": "2025-05-03T04:07:52.723Z" + } + } + }, + "billing": { + "address": { + "line1": "1467", + "line2": "jkjj Street", + "line3": "no 1111 Street", + "city": "San Fransico", + "state": "California", + "zip": "94122", + "country": "JP", + "first_name": "joseph", + "last_name": "Doe" + } + }, + "statement_descriptor_name": "joseph", + "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": "127.0.0.1" + } + } + }, + "url": { + "raw": "{{baseUrl}}/payments", + "host": [ + "{{baseUrl}}" + ], + "path": [ + "payments" + ] + }, + "description": "To process a payment you will have to create a payment, attach a payment method and confirm. Depending on the user journey you wish to achieve, you may opt to all the steps in a single request or in a sequence of API request using following APIs: (i) Payments - Update, (ii) Payments - Confirm, and (iii) Payments - Capture" +} diff --git a/postman/collection-dir/nuvei/Flow Testcases/Variation Cases/Scenario1- Payment Decline scenario/Payments - Create(Insufficient Funds)/response.json b/postman/collection-dir/nuvei/Flow Testcases/Variation Cases/Scenario1- Payment Decline scenario/Payments - Create(Insufficient Funds)/response.json new file mode 100644 index 00000000000..fe51488c706 --- /dev/null +++ b/postman/collection-dir/nuvei/Flow Testcases/Variation Cases/Scenario1- Payment Decline scenario/Payments - Create(Insufficient Funds)/response.json @@ -0,0 +1 @@ +[] diff --git a/postman/collection-dir/nuvei/Health check/.meta.json b/postman/collection-dir/nuvei/Health check/.meta.json new file mode 100644 index 00000000000..66ee7e50cab --- /dev/null +++ b/postman/collection-dir/nuvei/Health check/.meta.json @@ -0,0 +1,5 @@ +{ + "childrenOrder": [ + "New Request" + ] +} diff --git a/postman/collection-dir/nuvei/Health check/New Request/.event.meta.json b/postman/collection-dir/nuvei/Health check/New Request/.event.meta.json new file mode 100644 index 00000000000..688c85746ef --- /dev/null +++ b/postman/collection-dir/nuvei/Health check/New Request/.event.meta.json @@ -0,0 +1,5 @@ +{ + "eventOrder": [ + "event.test.js" + ] +} diff --git a/postman/collection-dir/nuvei/Health check/New Request/event.test.js b/postman/collection-dir/nuvei/Health check/New Request/event.test.js new file mode 100644 index 00000000000..b490b8be090 --- /dev/null +++ b/postman/collection-dir/nuvei/Health check/New Request/event.test.js @@ -0,0 +1,4 @@ +// Validate status 2xx +pm.test("[POST]::/accounts - Status code is 2xx", function () { + pm.response.to.be.success; +}); diff --git a/postman/collection-dir/nuvei/Health check/New Request/request.json b/postman/collection-dir/nuvei/Health check/New Request/request.json new file mode 100644 index 00000000000..4cc8d4b1a96 --- /dev/null +++ b/postman/collection-dir/nuvei/Health check/New Request/request.json @@ -0,0 +1,20 @@ +{ + "method": "GET", + "header": [ + { + "key": "x-feature", + "value": "router-custom", + "type": "text", + "disabled": true + } + ], + "url": { + "raw": "{{baseUrl}}/health", + "host": [ + "{{baseUrl}}" + ], + "path": [ + "health" + ] + } +} diff --git a/postman/collection-dir/nuvei/Health check/New Request/response.json b/postman/collection-dir/nuvei/Health check/New Request/response.json new file mode 100644 index 00000000000..fe51488c706 --- /dev/null +++ b/postman/collection-dir/nuvei/Health check/New Request/response.json @@ -0,0 +1 @@ +[] diff --git a/postman/collection-dir/nuvei/event.prerequest.js b/postman/collection-dir/nuvei/event.prerequest.js new file mode 100644 index 00000000000..e69de29bb2d diff --git a/postman/collection-dir/nuvei/event.test.js b/postman/collection-dir/nuvei/event.test.js new file mode 100644 index 00000000000..fb52caec30f --- /dev/null +++ b/postman/collection-dir/nuvei/event.test.js @@ -0,0 +1,13 @@ +// Set response object as internal variable +let jsonData = {}; +try { + jsonData = pm.response.json(); +} catch (e) {} + +// pm.collectionVariables - Set payment_id as variable for jsonData.payment_id +if (jsonData?.payment_id) { + pm.collectionVariables.set("payment_id", jsonData.payment_id); + console.log("[LOG]::payment_id - " + jsonData.payment_id); +} + +console.log("[LOG]::x-request-id - " + pm.response.headers.get("x-request-id")); diff --git a/postman/collection-json/nuvei.postman_collection.json b/postman/collection-json/nuvei.postman_collection.json new file mode 100644 index 00000000000..4c6b80a3d5c --- /dev/null +++ b/postman/collection-json/nuvei.postman_collection.json @@ -0,0 +1,1662 @@ + +{ + "info": { + "_postman_id": "d329ee53-0de4-4154-b0b1-78708ec6e708", + "name": "nuvei", + "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": "19204656" + }, + "item": [ + { + "name": "Health check", + "item": [ + { + "name": "New Request", + "event": [ + { + "listen": "test", + "script": { + "exec": [ + "// Validate status 2xx", + "pm.test(\"[POST]::/accounts - Status code is 2xx\", function () {", + " pm.response.to.be.success;", + "});", + "" + ], + "type": "text/javascript" + } + } + ], + "request": { + "method": "GET", + "header": [ + { + "key": "x-feature", + "value": "router-custom", + "type": "text", + "disabled": true + } + ], + "url": { + "raw": "{{baseUrl}}/health", + "host": [ + "{{baseUrl}}" + ], + "path": [ + "health" + ] + } + }, + "response": [] + } + ] + }, + { + "name": "Flow Testcases", + "item": [ + { + "name": "QuickStart", + "item": [ + { + "name": "Merchant Account - Create", + "event": [ + { + "listen": "test", + "script": { + "exec": [ + "// Validate status 2xx", + "pm.test(\"[POST]::/accounts - Status code is 2xx\", function () {", + " pm.response.to.be.success;", + "});", + "", + "// Validate if response header has matching content-type", + "pm.test(\"[POST]::/accounts - Content-Type is application/json\", function () {", + " pm.expect(pm.response.headers.get(\"Content-Type\")).to.include(", + " \"application/json\",", + " );", + "});", + "", + "// Set response object as internal variable", + "let jsonData = {};", + "try {", + " jsonData = pm.response.json();", + "} catch (e) {}", + "", + "// pm.collectionVariables - Set merchant_id as variable for jsonData.merchant_id", + "if (jsonData?.merchant_id) {", + " pm.collectionVariables.set(\"merchant_id\", jsonData.merchant_id);", + " console.log(", + " \"- use {{merchant_id}} as collection variable for value\",", + " jsonData.merchant_id,", + " );", + "} else {", + " console.log(", + " \"INFO - Unable to assign variable {{merchant_id}}, as jsonData.merchant_id is undefined.\",", + " );", + "}", + "", + "// pm.collectionVariables - Set api_key as variable for jsonData.api_key", + "if (jsonData?.api_key) {", + " pm.collectionVariables.set(\"api_key\", jsonData.api_key);", + " console.log(", + " \"- use {{api_key}} as collection variable for value\",", + " jsonData.api_key,", + " );", + "} else {", + " console.log(", + " \"INFO - Unable to assign variable {{api_key}}, as jsonData.api_key is undefined.\",", + " );", + "}", + "", + "// pm.collectionVariables - Set publishable_key as variable for jsonData.publishable_key", + "if (jsonData?.publishable_key) {", + " pm.collectionVariables.set(\"publishable_key\", jsonData.publishable_key);", + " console.log(", + " \"- use {{publishable_key}} as collection variable for value\",", + " jsonData.publishable_key,", + " );", + "} else {", + " console.log(", + " \"INFO - Unable to assign variable {{publishable_key}}, as jsonData.publishable_key is undefined.\",", + " );", + "}", + "" + ], + "type": "text/javascript" + } + }, + { + "listen": "prerequest", + "script": { + "exec": [ + "" + ], + "type": "text/javascript" + } + } + ], + "request": { + "auth": { + "type": "apikey", + "apikey": [ + { + "key": "value", + "value": "{{admin_api_key}}", + "type": "string" + }, + { + "key": "key", + "value": "api-key", + "type": "string" + }, + { + "key": "in", + "value": "header", + "type": "string" + } + ] + }, + "method": "POST", + "header": [ + { + "key": "Content-Type", + "value": "application/json" + }, + { + "key": "Accept", + "value": "application/json" + } + ], + "body": { + "mode": "raw", + "raw": "{\"merchant_id\":\"postman_merchant_GHAction_{{$guid}}\",\"locker_id\":\"m0010\",\"merchant_name\":\"NewAge Retailer\",\"primary_business_details\":[{\"country\":\"US\",\"business\":\"default\"}],\"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://duck.com\",\"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\"}}", + "options": { + "raw": { + "language": "json" + } + } + }, + "url": { + "raw": "{{baseUrl}}/accounts", + "host": [ + "{{baseUrl}}" + ], + "path": [ + "accounts" + ] + }, + "description": "Create a new account for a merchant. The merchant could be a seller or retailer or client who likes to receive and send payments." + }, + "response": [] + }, + { + "name": "API Key - Create", + "event": [ + { + "listen": "test", + "script": { + "exec": [ + "// Validate status 2xx", + "pm.test(\"[POST]::/api_keys/:merchant_id - Status code is 2xx\", function () {", + " pm.response.to.be.success;", + "});", + "", + "// Validate if response header has matching content-type", + "pm.test(", + " \"[POST]::/api_keys/:merchant_id - Content-Type is application/json\",", + " function () {", + " pm.expect(pm.response.headers.get(\"Content-Type\")).to.include(", + " \"application/json\",", + " );", + " },", + ");", + "", + "// Set response object as internal variable", + "let jsonData = {};", + "try {", + " jsonData = pm.response.json();", + "} catch (e) {}", + "", + "// pm.collectionVariables - Set api_key_id as variable for jsonData.key_id", + "if (jsonData?.key_id) {", + " pm.collectionVariables.set(\"api_key_id\", jsonData.key_id);", + " console.log(", + " \"- use {{api_key_id}} as collection variable for value\",", + " jsonData.key_id,", + " );", + "} else {", + " console.log(", + " \"INFO - Unable to assign variable {{api_key_id}}, as jsonData.key_id is undefined.\",", + " );", + "}", + "", + "// pm.collectionVariables - Set api_key as variable for jsonData.api_key", + "if (jsonData?.api_key) {", + " pm.collectionVariables.set(\"api_key\", jsonData.api_key);", + " console.log(", + " \"- use {{api_key}} as collection variable for value\",", + " jsonData.api_key,", + " );", + "} else {", + " console.log(", + " \"INFO - Unable to assign variable {{api_key}}, as jsonData.api_key is undefined.\",", + " );", + "}", + "" + ], + "type": "text/javascript" + } + } + ], + "request": { + "auth": { + "type": "apikey", + "apikey": [ + { + "key": "value", + "value": "{{admin_api_key}}", + "type": "string" + }, + { + "key": "key", + "value": "api-key", + "type": "string" + } + ] + }, + "method": "POST", + "header": [ + { + "key": "Content-Type", + "value": "application/json" + }, + { + "key": "Accept", + "value": "application/json" + } + ], + "body": { + "mode": "raw", + "raw": "{\"name\":\"API Key 1\",\"description\":null,\"expiration\":\"2069-09-23T01:02:03.000Z\"}" + }, + "url": { + "raw": "{{baseUrl}}/api_keys/:merchant_id", + "host": [ + "{{baseUrl}}" + ], + "path": [ + "api_keys", + ":merchant_id" + ], + "variable": [ + { + "key": "merchant_id", + "value": "{{merchant_id}}" + } + ] + } + }, + "response": [] + }, + { + "name": "Payment Connector - Create", + "event": [ + { + "listen": "test", + "script": { + "exec": [ + "// Validate status 2xx", + "pm.test(", + " \"[POST]::/account/:account_id/connectors - Status code is 2xx\",", + " function () {", + " pm.response.to.be.success;", + " },", + ");", + "", + "// Validate if response header has matching content-type", + "pm.test(", + " \"[POST]::/account/:account_id/connectors - Content-Type is application/json\",", + " function () {", + " pm.expect(pm.response.headers.get(\"Content-Type\")).to.include(", + " \"application/json\",", + " );", + " },", + ");", + "", + "// Set response object as internal variable", + "let jsonData = {};", + "try {", + " jsonData = pm.response.json();", + "} catch (e) {}", + "", + "// pm.collectionVariables - Set merchant_connector_id as variable for jsonData.merchant_connector_id", + "if (jsonData?.merchant_connector_id) {", + " pm.collectionVariables.set(", + " \"merchant_connector_id\",", + " jsonData.merchant_connector_id,", + " );", + " console.log(", + " \"- use {{merchant_connector_id}} as collection variable for value\",", + " jsonData.merchant_connector_id,", + " );", + "} else {", + " console.log(", + " \"INFO - Unable to assign variable {{merchant_connector_id}}, as jsonData.merchant_connector_id is undefined.\",", + " );", + "}", + "" + ], + "type": "text/javascript" + } + }, + { + "listen": "prerequest", + "script": { + "exec": [ + "" + ], + "type": "text/javascript" + } + } + ], + "request": { + "auth": { + "type": "apikey", + "apikey": [ + { + "key": "value", + "value": "{{admin_api_key}}", + "type": "string" + }, + { + "key": "key", + "value": "api-key", + "type": "string" + }, + { + "key": "in", + "value": "header", + "type": "string" + } + ] + }, + "method": "POST", + "header": [ + { + "key": "Content-Type", + "value": "application/json" + }, + { + "key": "Accept", + "value": "application/json" + } + ], + "body": { + "mode": "raw", + "raw": "{\"connector_type\":\"payment_processor\",\"connector_name\":\"nuvei\",\"connector_account_details\":{\"auth_type\":\"SignatureKey\",\"key1\":\"{{connector_key1}}\",\"api_key\":\"{{connector_api_key}}\",\"api_secret\":\"{{connector_api_secret}}\"},\"test_mode\":true,\"disabled\":false,\"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\":\"card\",\"payment_method_types\":[{\"payment_method_type\":\"debit\",\"minimum_amount\":1,\"maximum_amount\":68607706,\"recurring_enabled\":true,\"installment_payment_enabled\":true}]}]}", + "options": { + "raw": { + "language": "json" + } + } + }, + "url": { + "raw": "{{baseUrl}}/account/:account_id/connectors", + "host": [ + "{{baseUrl}}" + ], + "path": [ + "account", + ":account_id", + "connectors" + ], + "variable": [ + { + "key": "account_id", + "value": "{{merchant_id}}", + "description": "(Required) The unique identifier for the merchant account" + } + ] + }, + "description": "Create a new Payment Connector for the merchant account. The connector could be a payment processor / facilitator / acquirer or specialised services like Fraud / Accounting etc." + }, + "response": [] + }, + { + "name": "Payments - Create", + "event": [ + { + "listen": "test", + "script": { + "exec": [ + "pm.environment.set(\"random_number\", _.random(1000, 100000));", + "", + "// Set the environment variable 'amount' with the value from the response", + "pm.environment.set(\"amount\", pm.response.json().amount);", + "", + "// Validate status 2xx", + "pm.test(\"[POST]::/payments - Status code is 2xx\", function () {", + " pm.response.to.be.success;", + "});", + "", + "// Validate if response header has matching content-type", + "pm.test(\"[POST]::/payments - 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]::/payments - Response has JSON Body\", function () {", + " pm.response.to.have.jsonBody();", + "});", + "", + "// Set response object as internal variable", + "let jsonData = {};", + "try {", + " jsonData = pm.response.json();", + "} catch (e) {}", + "", + "// pm.collectionVariables - Set payment_id as variable for jsonData.payment_id", + "if (jsonData?.payment_id) {", + " pm.collectionVariables.set(\"payment_id\", jsonData.payment_id);", + " console.log(", + " \"- use {{payment_id}} as collection variable for value\",", + " jsonData.payment_id,", + " );", + "} else {", + " console.log(", + " \"INFO - Unable to assign variable {{payment_id}}, as jsonData.payment_id is undefined.\",", + " );", + "}", + "", + "// pm.collectionVariables - Set mandate_id as variable for jsonData.mandate_id", + "if (jsonData?.mandate_id) {", + " pm.collectionVariables.set(\"mandate_id\", jsonData.mandate_id);", + " console.log(", + " \"- use {{mandate_id}} as collection variable for value\",", + " jsonData.mandate_id,", + " );", + "} else {", + " console.log(", + " \"INFO - Unable to assign variable {{mandate_id}}, as jsonData.mandate_id is undefined.\",", + " );", + "}", + "", + "// pm.collectionVariables - Set client_secret as variable for jsonData.client_secret", + "if (jsonData?.client_secret) {", + " pm.collectionVariables.set(\"client_secret\", jsonData.client_secret);", + " console.log(", + " \"- use {{client_secret}} as collection variable for value\",", + " jsonData.client_secret,", + " );", + "} else {", + " console.log(", + " \"INFO - Unable to assign variable {{client_secret}}, as jsonData.client_secret is undefined.\",", + " );", + "}", + "" + ], + "type": "text/javascript" + } + }, + { + "listen": "prerequest", + "script": { + "exec": [ + "pm.environment.set(\"random_number\", _.random(1000, 100000));", + "" + ], + "type": "text/javascript" + } + } + ], + "request": { + "method": "POST", + "header": [ + { + "key": "Content-Type", + "value": "application/json" + }, + { + "key": "Accept", + "value": "application/json" + } + ], + "body": { + "mode": "raw", + "raw": "{\"amount\":100,\"currency\":\"USD\",\"confirm\":true,\"capture_method\":\"automatic\",\"connector\":[\"nuvei\"],\"customer_id\":\"futurebilling\",\"email\":\"guest@example.com\",\"name\":\"John Doe\",\"phone\":\"999999999\",\"phone_country_code\":\"+65\",\"description\":\"testing\",\"authentication_type\":\"no_three_ds\",\"return_url\":\"https://google.com\",\"payment_method\":\"card\",\"payment_method_type\":\"credit\",\"setup_future_usage\":\"off_session\",\"payment_method_data\":{\"card\":{\"card_number\":\"4111111111111111\",\"card_exp_month\":\"12\",\"card_exp_year\":\"2030\",\"card_holder_name\":\"joseph Doe\",\"card_cvc\":\"123\"}},\"mandate_data\":{\"customer_acceptance\":{\"acceptance_type\":\"offline\",\"accepted_at\":\"1963-05-03T04:07:52.723Z\",\"online\":{\"ip_address\":\"127.0.0.1\",\"user_agent\":\"amet irure esse\"}},\"mandate_type\":{\"multi_use\":{\"amount\":100,\"currency\":\"USD\",\"metadata\":{\"frequency\":\"1\"},\"end_date\":\"2025-05-03T04:07:52.723Z\"}}},\"billing\":{\"address\":{\"line1\":\"1467\",\"line2\":\"jkjj Street\",\"line3\":\"no 1111 Street\",\"city\":\"San Fransico\",\"state\":\"California\",\"zip\":\"94122\",\"country\":\"JP\",\"first_name\":\"joseph\",\"last_name\":\"Doe\"}},\"statement_descriptor_name\":\"joseph\",\"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\":\"127.0.0.1\"}}", + "options": { + "raw": { + "language": "json" + } + } + }, + "url": { + "raw": "{{baseUrl}}/payments", + "host": [ + "{{baseUrl}}" + ], + "path": [ + "payments" + ] + }, + "description": "To process a payment you will have to create a payment, attach a payment method and confirm. Depending on the user journey you wish to achieve, you may opt to all the steps in a single request or in a sequence of API request using following APIs: (i) Payments - Update, (ii) Payments - Confirm, and (iii) Payments - Capture" + }, + "response": [] + }, + { + "name": "Payments - Retrieve", + "event": [ + { + "listen": "test", + "script": { + "exec": [ + "// Validate status 2xx", + "pm.test(\"[GET]::/refunds/:id - Status code is 2xx\", function () {", + " pm.response.to.be.success;", + "});", + "", + "// Validate if response header has matching content-type", + "pm.test(\"[GET]::/refunds/:id - Content-Type is application/json\", function () {", + " pm.expect(pm.response.headers.get(\"Content-Type\")).to.include(", + " \"application/json\",", + " );", + "});", + "", + "// Set response object as internal variable", + "let jsonData = {};", + "try {", + " jsonData = pm.response.json();", + "} catch (e) {}", + "", + "// pm.collectionVariables - Set refund_id as variable for jsonData.payment_id", + "if (jsonData?.refund_id) {", + " pm.collectionVariables.set(\"refund_id\", jsonData.refund_id);", + " console.log(", + " \"- use {{refund_id}} as collection variable for value\",", + " jsonData.refund_id,", + " );", + "} else {", + " console.log(", + " \"INFO - Unable to assign variable {{refund_id}}, as jsonData.refund_id is undefined.\",", + " );", + "}", + "" + ], + "type": "text/javascript" + } + } + ], + "request": { + "method": "GET", + "header": [ + { + "key": "Accept", + "value": "application/json" + } + ], + "url": { + "raw": "{{baseUrl}}/payments/:id?force_sync=true", + "host": [ + "{{baseUrl}}" + ], + "path": [ + "payments", + ":id" + ], + "query": [ + { + "key": "force_sync", + "value": "true" + } + ], + "variable": [ + { + "key": "id", + "value": "{{payment_id}}", + "description": "(Required) unique refund id" + } + ] + }, + "description": "To retrieve the properties of a Refund. This may be used to get the status of a previously initiated payment or next action for an ongoing payment" + }, + "response": [] + }, + { + "name": "Refunds - Create", + "event": [ + { + "listen": "test", + "script": { + "exec": [ + "// Get the value of 'amount' from the environment", + "const amount = pm.environment.get(\"amount\");", + "", + "// Validate status 2xx", + "pm.test(\"[POST]::/refunds - Status code is 2xx\", function () {", + " pm.response.to.be.success;", + "});", + "", + "// Validate if response header has matching content-type", + "pm.test(\"[POST]::/refunds - Content-Type is application/json\", function () {", + " pm.expect(pm.response.headers.get(\"Content-Type\")).to.include(", + " \"application/json\",", + " );", + "});", + "", + "// Set response object as internal variable", + "let jsonData = {};", + "try {", + " jsonData = pm.response.json();", + "} catch (e) {}", + "", + "// pm.collectionVariables - Set refund_id as variable for jsonData.payment_id", + "if (jsonData?.refund_id) {", + " pm.collectionVariables.set(\"refund_id\", jsonData.refund_id);", + " console.log(", + " \"- use {{refund_id}} as collection variable for value\",", + " jsonData.refund_id,", + " );", + "} else {", + " console.log(", + " \"INFO - Unable to assign variable {{refund_id}}, as jsonData.refund_id is undefined.\",", + " );", + "}", + "" + ], + "type": "text/javascript" + } + } + ], + "request": { + "method": "POST", + "header": [ + { + "key": "Content-Type", + "value": "application/json" + }, + { + "key": "Accept", + "value": "application/json" + } + ], + "body": { + "mode": "raw", + "raw": "{\n \"payment_id\": \"{{payment_id}}\",\n \"amount\": {{amount}},\n \"reason\": \"Customer returned product\",\n \"refund_type\": \"instant\",\n \"metadata\": {\n \"udf1\": \"value1\",\n \"new_customer\": \"true\",\n \"login_date\": \"2019-09-10T10:11:12Z\"\n }\n}", + "options": { + "raw": { + "language": "json" + } + } + }, + "url": { + "raw": "{{baseUrl}}/refunds", + "host": [ + "{{baseUrl}}" + ], + "path": [ + "refunds" + ] + }, + "description": "To create a refund against an already processed payment" + }, + "response": [] + }, + { + "name": "Refunds - Retrieve", + "event": [ + { + "listen": "test", + "script": { + "exec": [ + "// Validate status 2xx", + "pm.test(\"[GET]::/refunds/:id - Status code is 2xx\", function () {", + " pm.response.to.be.success;", + "});", + "", + "// Validate if response header has matching content-type", + "pm.test(\"[GET]::/refunds/:id - Content-Type is application/json\", function () {", + " pm.expect(pm.response.headers.get(\"Content-Type\")).to.include(", + " \"application/json\",", + " );", + "});", + "", + "// Set response object as internal variable", + "let jsonData = {};", + "try {", + " jsonData = pm.response.json();", + "} catch (e) {}", + "", + "// pm.collectionVariables - Set refund_id as variable for jsonData.payment_id", + "if (jsonData?.refund_id) {", + " pm.collectionVariables.set(\"refund_id\", jsonData.refund_id);", + " console.log(", + " \"- use {{refund_id}} as collection variable for value\",", + " jsonData.refund_id,", + " );", + "} else {", + " console.log(", + " \"INFO - Unable to assign variable {{refund_id}}, as jsonData.refund_id is undefined.\",", + " );", + "}", + "" + ], + "type": "text/javascript" + } + } + ], + "request": { + "method": "GET", + "header": [ + { + "key": "Accept", + "value": "application/json" + } + ], + "url": { + "raw": "{{baseUrl}}/refunds/:id?force_sync=true", + "host": [ + "{{baseUrl}}" + ], + "path": [ + "refunds", + ":id" + ], + "query": [ + { + "key": "force_sync", + "value": "true" + } + ], + "variable": [ + { + "key": "id", + "value": "{{refund_id}}", + "description": "(Required) unique refund id" + } + ] + }, + "description": "To retrieve the properties of a Refund. This may be used to get the status of a previously initiated payment or next action for an ongoing payment" + }, + "response": [] + } + ] + }, + { + "name": "Variation Cases", + "item": [ + { + "name": "Scenario1- Create Payment with Invalid card", + "item": [ + { + "name": "Payments - Create(Expired Card)", + "event": [ + { + "listen": "test", + "script": { + "exec": [ + "pm.environment.set(\"random_number\", _.random(100, 100000));", + "", + "// Validate status 2xx", + "pm.test(\"[POST]::/payments - Status code is 2xx\", function () {", + " pm.response.to.be.success;", + "});", + "", + "", + "// Validate if response header has matching content-type", + "pm.test(\"[POST]::/payments - 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]::/payments - Response has JSON Body\", function () {", + " pm.response.to.have.jsonBody();", + "});", + "", + "// Set response object as internal variable", + "let jsonData = {};", + "try {", + " jsonData = pm.response.json();", + "} catch (e) {}", + "", + "// pm.collectionVariables - Set payment_id as variable for jsonData.payment_id", + "if (jsonData?.payment_id) {", + " pm.collectionVariables.set(\"payment_id\", jsonData.payment_id);", + " console.log(", + " \"- use {{payment_id}} as collection variable for value\",", + " jsonData.payment_id,", + " );", + "} else {", + " console.log(", + " \"INFO - Unable to assign variable {{payment_id}}, as jsonData.payment_id is undefined.\",", + " );", + "}", + "", + "// pm.collectionVariables - Set mandate_id as variable for jsonData.mandate_id", + "if (jsonData?.mandate_id) {", + " pm.collectionVariables.set(\"mandate_id\", jsonData.mandate_id);", + " console.log(", + " \"- use {{mandate_id}} as collection variable for value\",", + " jsonData.mandate_id,", + " );", + "} else {", + " console.log(", + " \"INFO - Unable to assign variable {{mandate_id}}, as jsonData.mandate_id is undefined.\",", + " );", + "}", + "", + "// pm.collectionVariables - Set client_secret as variable for jsonData.client_secret", + "if (jsonData?.client_secret) {", + " pm.collectionVariables.set(\"client_secret\", jsonData.client_secret);", + " console.log(", + " \"- use {{client_secret}} as collection variable for value\",", + " jsonData.client_secret,", + " );", + "} else {", + " console.log(", + " \"INFO - Unable to assign variable {{client_secret}}, as jsonData.client_secret is undefined.\",", + " );", + "}", + "", + "", + "// Response body should have \"error_message: Expired Card\"", + "pm.test(\"[POST]::/payments - Content check if 'error_message : Expired Card' exists\", function () {", + " pm.expect(jsonData.error_message).to.eql(\"Expired Card\");", + "});", + "", + "", + "", + "" + ], + "type": "text/javascript" + } + } + ], + "request": { + "method": "POST", + "header": [ + { + "key": "Content-Type", + "value": "application/json" + }, + { + "key": "Accept", + "value": "application/json" + } + ], + "body": { + "mode": "raw", + "raw": "{\"amount\":100,\"currency\":\"USD\",\"confirm\":true,\"capture_method\":\"automatic\",\"connector\":[\"nuvei\"],\"customer_id\":\"futurebilling\",\"email\":\"guest@example.com\",\"name\":\"John Doe\",\"phone\":\"999999999\",\"phone_country_code\":\"+65\",\"description\":\"testing\",\"authentication_type\":\"no_three_ds\",\"return_url\":\"https://google.com\",\"payment_method\":\"card\",\"payment_method_type\":\"credit\",\"setup_future_usage\":\"off_session\",\"payment_method_data\":{\"card\":{\"card_number\":\"4000247422310226\",\"card_exp_month\":\"12\",\"card_exp_year\":\"2030\",\"card_holder_name\":\"joseph Doe\",\"card_cvc\":\"123\"}},\"mandate_data\":{\"customer_acceptance\":{\"acceptance_type\":\"offline\",\"accepted_at\":\"1963-05-03T04:07:52.723Z\",\"online\":{\"ip_address\":\"127.0.0.1\",\"user_agent\":\"amet irure esse\"}},\"mandate_type\":{\"multi_use\":{\"amount\":100,\"currency\":\"USD\",\"metadata\":{\"frequency\":\"1\"},\"end_date\":\"2025-05-03T04:07:52.723Z\"}}},\"billing\":{\"address\":{\"line1\":\"1467\",\"line2\":\"jkjj Street\",\"line3\":\"no 1111 Street\",\"city\":\"San Fransico\",\"state\":\"California\",\"zip\":\"94122\",\"country\":\"JP\",\"first_name\":\"joseph\",\"last_name\":\"Doe\"}},\"statement_descriptor_name\":\"joseph\",\"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\":\"127.0.0.1\"}}", + "options": { + "raw": { + "language": "json" + } + } + }, + "url": { + "raw": "{{baseUrl}}/payments", + "host": [ + "{{baseUrl}}" + ], + "path": [ + "payments" + ] + }, + "description": "To process a payment you will have to create a payment, attach a payment method and confirm. Depending on the user journey you wish to achieve, you may opt to all the steps in a single request or in a sequence of API request using following APIs: (i) Payments - Update, (ii) Payments - Confirm, and (iii) Payments - Capture" + }, + "response": [] + }, + { + "name": "Payments - Create(Invalid CVV)", + "event": [ + { + "listen": "test", + "script": { + "exec": [ + "pm.environment.set(\"random_number\", _.random(100, 100000));", + "", + "// Validate status 2xx", + "pm.test(\"[POST]::/payments - Status code is 2xx\", function () {", + " pm.response.to.be.success;", + "});", + "", + "", + "// Validate if response header has matching content-type", + "pm.test(\"[POST]::/payments - 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]::/payments - Response has JSON Body\", function () {", + " pm.response.to.have.jsonBody();", + "});", + "", + "// Set response object as internal variable", + "let jsonData = {};", + "try {", + " jsonData = pm.response.json();", + "} catch (e) {}", + "", + "// pm.collectionVariables - Set payment_id as variable for jsonData.payment_id", + "if (jsonData?.payment_id) {", + " pm.collectionVariables.set(\"payment_id\", jsonData.payment_id);", + " console.log(", + " \"- use {{payment_id}} as collection variable for value\",", + " jsonData.payment_id,", + " );", + "} else {", + " console.log(", + " \"INFO - Unable to assign variable {{payment_id}}, as jsonData.payment_id is undefined.\",", + " );", + "}", + "", + "// pm.collectionVariables - Set mandate_id as variable for jsonData.mandate_id", + "if (jsonData?.mandate_id) {", + " pm.collectionVariables.set(\"mandate_id\", jsonData.mandate_id);", + " console.log(", + " \"- use {{mandate_id}} as collection variable for value\",", + " jsonData.mandate_id,", + " );", + "} else {", + " console.log(", + " \"INFO - Unable to assign variable {{mandate_id}}, as jsonData.mandate_id is undefined.\",", + " );", + "}", + "", + "// pm.collectionVariables - Set client_secret as variable for jsonData.client_secret", + "if (jsonData?.client_secret) {", + " pm.collectionVariables.set(\"client_secret\", jsonData.client_secret);", + " console.log(", + " \"- use {{client_secret}} as collection variable for value\",", + " jsonData.client_secret,", + " );", + "} else {", + " console.log(", + " \"INFO - Unable to assign variable {{client_secret}}, as jsonData.client_secret is undefined.\",", + " );", + "}", + "", + "", + "// Response body should have \"error_message: Invalid CVV\"", + "pm.test(\"[POST]::/payments - Content check if 'error_message : Invalid CVV' exists\", function () {", + " pm.expect(jsonData.error_message).to.eql(\"Invalid CVV\");", + "});", + "", + "", + "", + "" + ], + "type": "text/javascript" + } + } + ], + "request": { + "method": "POST", + "header": [ + { + "key": "Content-Type", + "value": "application/json" + }, + { + "key": "Accept", + "value": "application/json" + } + ], + "body": { + "mode": "raw", + "raw": "{\"amount\":100,\"currency\":\"USD\",\"confirm\":true,\"capture_method\":\"automatic\",\"connector\":[\"nuvei\"],\"customer_id\":\"futurebilling\",\"email\":\"guest@example.com\",\"name\":\"John Doe\",\"phone\":\"999999999\",\"phone_country_code\":\"+65\",\"description\":\"testing\",\"authentication_type\":\"no_three_ds\",\"return_url\":\"https://google.com\",\"payment_method\":\"card\",\"payment_method_type\":\"credit\",\"setup_future_usage\":\"off_session\",\"payment_method_data\":{\"card\":{\"card_number\":\"5333583123003909\",\"card_exp_month\":\"12\",\"card_exp_year\":\"2030\",\"card_holder_name\":\"joseph Doe\",\"card_cvc\":\"123\"}},\"mandate_data\":{\"customer_acceptance\":{\"acceptance_type\":\"offline\",\"accepted_at\":\"1963-05-03T04:07:52.723Z\",\"online\":{\"ip_address\":\"127.0.0.1\",\"user_agent\":\"amet irure esse\"}},\"mandate_type\":{\"multi_use\":{\"amount\":100,\"currency\":\"USD\",\"metadata\":{\"frequency\":\"1\"},\"end_date\":\"2025-05-03T04:07:52.723Z\"}}},\"billing\":{\"address\":{\"line1\":\"1467\",\"line2\":\"jkjj Street\",\"line3\":\"no 1111 Street\",\"city\":\"San Fransico\",\"state\":\"California\",\"zip\":\"94122\",\"country\":\"JP\",\"first_name\":\"joseph\",\"last_name\":\"Doe\"}},\"statement_descriptor_name\":\"joseph\",\"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\":\"127.0.0.1\"}}", + "options": { + "raw": { + "language": "json" + } + } + }, + "url": { + "raw": "{{baseUrl}}/payments", + "host": [ + "{{baseUrl}}" + ], + "path": [ + "payments" + ] + }, + "description": "To process a payment you will have to create a payment, attach a payment method and confirm. Depending on the user journey you wish to achieve, you may opt to all the steps in a single request or in a sequence of API request using following APIs: (i) Payments - Update, (ii) Payments - Confirm, and (iii) Payments - Capture" + }, + "response": [] + }, + { + "name": "Payments - Create(Lost Card)", + "event": [ + { + "listen": "test", + "script": { + "exec": [ + "pm.environment.set(\"random_number\", _.random(100, 100000));", + "", + "// Validate status 2xx", + "pm.test(\"[POST]::/payments - Status code is 2xx\", function () {", + " pm.response.to.be.success;", + "});", + "", + "", + "// Validate if response header has matching content-type", + "pm.test(\"[POST]::/payments - 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]::/payments - Response has JSON Body\", function () {", + " pm.response.to.have.jsonBody();", + "});", + "", + "// Set response object as internal variable", + "let jsonData = {};", + "try {", + " jsonData = pm.response.json();", + "} catch (e) {}", + "", + "// pm.collectionVariables - Set payment_id as variable for jsonData.payment_id", + "if (jsonData?.payment_id) {", + " pm.collectionVariables.set(\"payment_id\", jsonData.payment_id);", + " console.log(", + " \"- use {{payment_id}} as collection variable for value\",", + " jsonData.payment_id,", + " );", + "} else {", + " console.log(", + " \"INFO - Unable to assign variable {{payment_id}}, as jsonData.payment_id is undefined.\",", + " );", + "}", + "", + "// pm.collectionVariables - Set mandate_id as variable for jsonData.mandate_id", + "if (jsonData?.mandate_id) {", + " pm.collectionVariables.set(\"mandate_id\", jsonData.mandate_id);", + " console.log(", + " \"- use {{mandate_id}} as collection variable for value\",", + " jsonData.mandate_id,", + " );", + "} else {", + " console.log(", + " \"INFO - Unable to assign variable {{mandate_id}}, as jsonData.mandate_id is undefined.\",", + " );", + "}", + "", + "// pm.collectionVariables - Set client_secret as variable for jsonData.client_secret", + "if (jsonData?.client_secret) {", + " pm.collectionVariables.set(\"client_secret\", jsonData.client_secret);", + " console.log(", + " \"- use {{client_secret}} as collection variable for value\",", + " jsonData.client_secret,", + " );", + "} else {", + " console.log(", + " \"INFO - Unable to assign variable {{client_secret}}, as jsonData.client_secret is undefined.\",", + " );", + "}", + "", + "", + "// Response body should have \"error_message: Lost/Stolen\"", + "pm.test(\"[POST]::/payments - Content check if 'error_message : Lost/Stolen' exists\", function () {", + " pm.expect(jsonData.error_message).to.eql(\"Lost/Stolen\");", + "});", + "", + "", + "", + "" + ], + "type": "text/javascript" + } + } + ], + "request": { + "method": "POST", + "header": [ + { + "key": "Content-Type", + "value": "application/json" + }, + { + "key": "Accept", + "value": "application/json" + } + ], + "body": { + "mode": "raw", + "raw": "{\"amount\":100,\"currency\":\"USD\",\"confirm\":true,\"capture_method\":\"automatic\",\"connector\":[\"nuvei\"],\"customer_id\":\"futurebilling\",\"email\":\"guest@example.com\",\"name\":\"John Doe\",\"phone\":\"999999999\",\"phone_country_code\":\"+65\",\"description\":\"testing\",\"authentication_type\":\"no_three_ds\",\"return_url\":\"https://google.com\",\"payment_method\":\"card\",\"payment_method_type\":\"credit\",\"setup_future_usage\":\"off_session\",\"payment_method_data\":{\"card\":{\"card_number\":\"5333452804487502\",\"card_exp_month\":\"12\",\"card_exp_year\":\"2030\",\"card_holder_name\":\"joseph Doe\",\"card_cvc\":\"123\"}},\"mandate_data\":{\"customer_acceptance\":{\"acceptance_type\":\"offline\",\"accepted_at\":\"1963-05-03T04:07:52.723Z\",\"online\":{\"ip_address\":\"127.0.0.1\",\"user_agent\":\"amet irure esse\"}},\"mandate_type\":{\"multi_use\":{\"amount\":100,\"currency\":\"USD\",\"metadata\":{\"frequency\":\"1\"},\"end_date\":\"2025-05-03T04:07:52.723Z\"}}},\"billing\":{\"address\":{\"line1\":\"1467\",\"line2\":\"jkjj Street\",\"line3\":\"no 1111 Street\",\"city\":\"San Fransico\",\"state\":\"California\",\"zip\":\"94122\",\"country\":\"JP\",\"first_name\":\"joseph\",\"last_name\":\"Doe\"}},\"statement_descriptor_name\":\"joseph\",\"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\":\"127.0.0.1\"}}", + "options": { + "raw": { + "language": "json" + } + } + }, + "url": { + "raw": "{{baseUrl}}/payments", + "host": [ + "{{baseUrl}}" + ], + "path": [ + "payments" + ] + }, + "description": "To process a payment you will have to create a payment, attach a payment method and confirm. Depending on the user journey you wish to achieve, you may opt to all the steps in a single request or in a sequence of API request using following APIs: (i) Payments - Update, (ii) Payments - Confirm, and (iii) Payments - Capture" + }, + "response": [] + } + ] + }, + { + "name": "Scenario1- Payment Decline scenario", + "item": [ + { + "name": "Payments - Create(Decline)", + "event": [ + { + "listen": "test", + "script": { + "exec": [ + "pm.environment.set(\"random_number\", _.random(100, 100000));", + "", + "// Validate status 2xx", + "pm.test(\"[POST]::/payments - Status code is 2xx\", function () {", + " pm.response.to.be.success;", + "});", + "", + "", + "// Validate if response header has matching content-type", + "pm.test(\"[POST]::/payments - 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]::/payments - Response has JSON Body\", function () {", + " pm.response.to.have.jsonBody();", + "});", + "", + "// Set response object as internal variable", + "let jsonData = {};", + "try {", + " jsonData = pm.response.json();", + "} catch (e) {}", + "", + "// pm.collectionVariables - Set payment_id as variable for jsonData.payment_id", + "if (jsonData?.payment_id) {", + " pm.collectionVariables.set(\"payment_id\", jsonData.payment_id);", + " console.log(", + " \"- use {{payment_id}} as collection variable for value\",", + " jsonData.payment_id,", + " );", + "} else {", + " console.log(", + " \"INFO - Unable to assign variable {{payment_id}}, as jsonData.payment_id is undefined.\",", + " );", + "}", + "", + "// pm.collectionVariables - Set mandate_id as variable for jsonData.mandate_id", + "if (jsonData?.mandate_id) {", + " pm.collectionVariables.set(\"mandate_id\", jsonData.mandate_id);", + " console.log(", + " \"- use {{mandate_id}} as collection variable for value\",", + " jsonData.mandate_id,", + " );", + "} else {", + " console.log(", + " \"INFO - Unable to assign variable {{mandate_id}}, as jsonData.mandate_id is undefined.\",", + " );", + "}", + "", + "// pm.collectionVariables - Set client_secret as variable for jsonData.client_secret", + "if (jsonData?.client_secret) {", + " pm.collectionVariables.set(\"client_secret\", jsonData.client_secret);", + " console.log(", + " \"- use {{client_secret}} as collection variable for value\",", + " jsonData.client_secret,", + " );", + "} else {", + " console.log(", + " \"INFO - Unable to assign variable {{client_secret}}, as jsonData.client_secret is undefined.\",", + " );", + "}", + "", + "", + "// Response body should have \"error_message: Decline\"", + "pm.test(\"[POST]::/payments - Content check if 'error_message : Decline' exists\", function () {", + " pm.expect(jsonData.error_message).to.eql(\"Decline\");", + "});", + "", + "", + "", + "" + ], + "type": "text/javascript" + } + } + ], + "request": { + "method": "POST", + "header": [ + { + "key": "Content-Type", + "value": "application/json" + }, + { + "key": "Accept", + "value": "application/json" + } + ], + "body": { + "mode": "raw", + "raw": "{\"amount\":100,\"currency\":\"USD\",\"confirm\":true,\"capture_method\":\"automatic\",\"connector\":[\"nuvei\"],\"customer_id\":\"futurebilling\",\"email\":\"guest@example.com\",\"name\":\"John Doe\",\"phone\":\"999999999\",\"phone_country_code\":\"+65\",\"description\":\"testing\",\"authentication_type\":\"no_three_ds\",\"return_url\":\"https://google.com\",\"payment_method\":\"card\",\"payment_method_type\":\"credit\",\"setup_future_usage\":\"off_session\",\"payment_method_data\":{\"card\":{\"card_number\":\"375521501910816\",\"card_exp_month\":\"12\",\"card_exp_year\":\"2030\",\"card_holder_name\":\"joseph Doe\",\"card_cvc\":\"123\"}},\"mandate_data\":{\"customer_acceptance\":{\"acceptance_type\":\"offline\",\"accepted_at\":\"1963-05-03T04:07:52.723Z\",\"online\":{\"ip_address\":\"127.0.0.1\",\"user_agent\":\"amet irure esse\"}},\"mandate_type\":{\"multi_use\":{\"amount\":100,\"currency\":\"USD\",\"metadata\":{\"frequency\":\"1\"},\"end_date\":\"2025-05-03T04:07:52.723Z\"}}},\"billing\":{\"address\":{\"line1\":\"1467\",\"line2\":\"jkjj Street\",\"line3\":\"no 1111 Street\",\"city\":\"San Fransico\",\"state\":\"California\",\"zip\":\"94122\",\"country\":\"JP\",\"first_name\":\"joseph\",\"last_name\":\"Doe\"}},\"statement_descriptor_name\":\"joseph\",\"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\":\"127.0.0.1\"}}", + "options": { + "raw": { + "language": "json" + } + } + }, + "url": { + "raw": "{{baseUrl}}/payments", + "host": [ + "{{baseUrl}}" + ], + "path": [ + "payments" + ] + }, + "description": "To process a payment you will have to create a payment, attach a payment method and confirm. Depending on the user journey you wish to achieve, you may opt to all the steps in a single request or in a sequence of API request using following APIs: (i) Payments - Update, (ii) Payments - Confirm, and (iii) Payments - Capture" + }, + "response": [] + }, + { + "name": "Payments - Create(Do Not Honor)", + "event": [ + { + "listen": "test", + "script": { + "exec": [ + "pm.environment.set(\"random_number\", _.random(100, 100000));", + "", + "// Validate status 2xx", + "pm.test(\"[POST]::/payments - Status code is 2xx\", function () {", + " pm.response.to.be.success;", + "});", + "", + "", + "// Validate if response header has matching content-type", + "pm.test(\"[POST]::/payments - 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]::/payments - Response has JSON Body\", function () {", + " pm.response.to.have.jsonBody();", + "});", + "", + "// Set response object as internal variable", + "let jsonData = {};", + "try {", + " jsonData = pm.response.json();", + "} catch (e) {}", + "", + "// pm.collectionVariables - Set payment_id as variable for jsonData.payment_id", + "if (jsonData?.payment_id) {", + " pm.collectionVariables.set(\"payment_id\", jsonData.payment_id);", + " console.log(", + " \"- use {{payment_id}} as collection variable for value\",", + " jsonData.payment_id,", + " );", + "} else {", + " console.log(", + " \"INFO - Unable to assign variable {{payment_id}}, as jsonData.payment_id is undefined.\",", + " );", + "}", + "", + "// pm.collectionVariables - Set mandate_id as variable for jsonData.mandate_id", + "if (jsonData?.mandate_id) {", + " pm.collectionVariables.set(\"mandate_id\", jsonData.mandate_id);", + " console.log(", + " \"- use {{mandate_id}} as collection variable for value\",", + " jsonData.mandate_id,", + " );", + "} else {", + " console.log(", + " \"INFO - Unable to assign variable {{mandate_id}}, as jsonData.mandate_id is undefined.\",", + " );", + "}", + "", + "// pm.collectionVariables - Set client_secret as variable for jsonData.client_secret", + "if (jsonData?.client_secret) {", + " pm.collectionVariables.set(\"client_secret\", jsonData.client_secret);", + " console.log(", + " \"- use {{client_secret}} as collection variable for value\",", + " jsonData.client_secret,", + " );", + "} else {", + " console.log(", + " \"INFO - Unable to assign variable {{client_secret}}, as jsonData.client_secret is undefined.\",", + " );", + "}", + "", + "", + "// Response body should have \"error_message: Do Not Honor\"", + "pm.test(\"[POST]::/payments - Content check if 'error_message : Do Not Honor' exists\", function () {", + " pm.expect(jsonData.error_message).to.eql(\"Do Not Honor\");", + "});", + "", + "", + "", + "" + ], + "type": "text/javascript" + } + } + ], + "request": { + "method": "POST", + "header": [ + { + "key": "Content-Type", + "value": "application/json" + }, + { + "key": "Accept", + "value": "application/json" + } + ], + "body": { + "mode": "raw", + "raw": "{\"amount\":100,\"currency\":\"USD\",\"confirm\":true,\"capture_method\":\"automatic\",\"connector\":[\"nuvei\"],\"customer_id\":\"futurebilling\",\"email\":\"guest@example.com\",\"name\":\"John Doe\",\"phone\":\"999999999\",\"phone_country_code\":\"+65\",\"description\":\"testing\",\"authentication_type\":\"no_three_ds\",\"return_url\":\"https://google.com\",\"payment_method\":\"card\",\"payment_method_type\":\"credit\",\"setup_future_usage\":\"off_session\",\"payment_method_data\":{\"card\":{\"card_number\":\"5333463046218753\",\"card_exp_month\":\"12\",\"card_exp_year\":\"2030\",\"card_holder_name\":\"joseph Doe\",\"card_cvc\":\"123\"}},\"mandate_data\":{\"customer_acceptance\":{\"acceptance_type\":\"offline\",\"accepted_at\":\"1963-05-03T04:07:52.723Z\",\"online\":{\"ip_address\":\"127.0.0.1\",\"user_agent\":\"amet irure esse\"}},\"mandate_type\":{\"multi_use\":{\"amount\":100,\"currency\":\"USD\",\"metadata\":{\"frequency\":\"1\"},\"end_date\":\"2025-05-03T04:07:52.723Z\"}}},\"billing\":{\"address\":{\"line1\":\"1467\",\"line2\":\"jkjj Street\",\"line3\":\"no 1111 Street\",\"city\":\"San Fransico\",\"state\":\"California\",\"zip\":\"94122\",\"country\":\"JP\",\"first_name\":\"joseph\",\"last_name\":\"Doe\"}},\"statement_descriptor_name\":\"joseph\",\"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\":\"127.0.0.1\"}}", + "options": { + "raw": { + "language": "json" + } + } + }, + "url": { + "raw": "{{baseUrl}}/payments", + "host": [ + "{{baseUrl}}" + ], + "path": [ + "payments" + ] + }, + "description": "To process a payment you will have to create a payment, attach a payment method and confirm. Depending on the user journey you wish to achieve, you may opt to all the steps in a single request or in a sequence of API request using following APIs: (i) Payments - Update, (ii) Payments - Confirm, and (iii) Payments - Capture" + }, + "response": [] + }, + { + "name": "Payments - Create(Insufficient Funds)", + "event": [ + { + "listen": "test", + "script": { + "exec": [ + "pm.environment.set(\"random_number\", _.random(100, 100000));", + "", + "// Validate status 2xx", + "pm.test(\"[POST]::/payments - Status code is 2xx\", function () {", + " pm.response.to.be.success;", + "});", + "", + "", + "// Validate if response header has matching content-type", + "pm.test(\"[POST]::/payments - 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]::/payments - Response has JSON Body\", function () {", + " pm.response.to.have.jsonBody();", + "});", + "", + "// Set response object as internal variable", + "let jsonData = {};", + "try {", + " jsonData = pm.response.json();", + "} catch (e) {}", + "", + "// pm.collectionVariables - Set payment_id as variable for jsonData.payment_id", + "if (jsonData?.payment_id) {", + " pm.collectionVariables.set(\"payment_id\", jsonData.payment_id);", + " console.log(", + " \"- use {{payment_id}} as collection variable for value\",", + " jsonData.payment_id,", + " );", + "} else {", + " console.log(", + " \"INFO - Unable to assign variable {{payment_id}}, as jsonData.payment_id is undefined.\",", + " );", + "}", + "", + "// pm.collectionVariables - Set mandate_id as variable for jsonData.mandate_id", + "if (jsonData?.mandate_id) {", + " pm.collectionVariables.set(\"mandate_id\", jsonData.mandate_id);", + " console.log(", + " \"- use {{mandate_id}} as collection variable for value\",", + " jsonData.mandate_id,", + " );", + "} else {", + " console.log(", + " \"INFO - Unable to assign variable {{mandate_id}}, as jsonData.mandate_id is undefined.\",", + " );", + "}", + "", + "// pm.collectionVariables - Set client_secret as variable for jsonData.client_secret", + "if (jsonData?.client_secret) {", + " pm.collectionVariables.set(\"client_secret\", jsonData.client_secret);", + " console.log(", + " \"- use {{client_secret}} as collection variable for value\",", + " jsonData.client_secret,", + " );", + "} else {", + " console.log(", + " \"INFO - Unable to assign variable {{client_secret}}, as jsonData.client_secret is undefined.\",", + " );", + "}", + "", + "", + "// Response body should have \"error_message: Insufficient Funds\"", + "pm.test(\"[POST]::/payments - Content check if 'error_message : Insufficient Funds' exists\", function () {", + " pm.expect(jsonData.error_message).to.eql(\"Insufficient Funds\");", + "});", + "", + "", + "", + "" + ], + "type": "text/javascript" + } + } + ], + "request": { + "method": "POST", + "header": [ + { + "key": "Content-Type", + "value": "application/json" + }, + { + "key": "Accept", + "value": "application/json" + } + ], + "body": { + "mode": "raw", + "raw": "{\"amount\":100,\"currency\":\"USD\",\"confirm\":true,\"capture_method\":\"automatic\",\"connector\":[\"nuvei\"],\"customer_id\":\"futurebilling\",\"email\":\"guest@example.com\",\"name\":\"John Doe\",\"phone\":\"999999999\",\"phone_country_code\":\"+65\",\"description\":\"testing\",\"authentication_type\":\"no_three_ds\",\"return_url\":\"https://google.com\",\"payment_method\":\"card\",\"payment_method_type\":\"credit\",\"setup_future_usage\":\"off_session\",\"payment_method_data\":{\"card\":{\"card_number\":\"5333475572200849\",\"card_exp_month\":\"12\",\"card_exp_year\":\"2030\",\"card_holder_name\":\"joseph Doe\",\"card_cvc\":\"123\"}},\"mandate_data\":{\"customer_acceptance\":{\"acceptance_type\":\"offline\",\"accepted_at\":\"1963-05-03T04:07:52.723Z\",\"online\":{\"ip_address\":\"127.0.0.1\",\"user_agent\":\"amet irure esse\"}},\"mandate_type\":{\"multi_use\":{\"amount\":100,\"currency\":\"USD\",\"metadata\":{\"frequency\":\"1\"},\"end_date\":\"2025-05-03T04:07:52.723Z\"}}},\"billing\":{\"address\":{\"line1\":\"1467\",\"line2\":\"jkjj Street\",\"line3\":\"no 1111 Street\",\"city\":\"San Fransico\",\"state\":\"California\",\"zip\":\"94122\",\"country\":\"JP\",\"first_name\":\"joseph\",\"last_name\":\"Doe\"}},\"statement_descriptor_name\":\"joseph\",\"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\":\"127.0.0.1\"}}", + "options": { + "raw": { + "language": "json" + } + } + }, + "url": { + "raw": "{{baseUrl}}/payments", + "host": [ + "{{baseUrl}}" + ], + "path": [ + "payments" + ] + }, + "description": "To process a payment you will have to create a payment, attach a payment method and confirm. Depending on the user journey you wish to achieve, you may opt to all the steps in a single request or in a sequence of API request using following APIs: (i) Payments - Update, (ii) Payments - Confirm, and (iii) Payments - Capture" + }, + "response": [] + } + ] + } + ] + } + ] + } + ], + "auth": { + "type": "apikey", + "apikey": [ + { + "key": "value", + "value": "{{api_key}}", + "type": "string" + }, + { + "key": "key", + "value": "api-key", + "type": "string" + }, + { + "key": "in", + "value": "header", + "type": "string" + } + ] + }, + "event": [ + { + "listen": "prerequest", + "script": { + "exec": [ + "" + ], + "type": "text/javascript" + } + }, + { + "listen": "test", + "script": { + "exec": [ + "// Set response object as internal variable", + "let jsonData = {};", + "try {", + " jsonData = pm.response.json();", + "} catch (e) {}", + "", + "// pm.collectionVariables - Set payment_id as variable for jsonData.payment_id", + "if (jsonData?.payment_id) {", + " pm.collectionVariables.set(\"payment_id\", jsonData.payment_id);", + " console.log(\"[LOG]::payment_id - \" + jsonData.payment_id);", + "}", + "", + "console.log(\"[LOG]::x-request-id - \" + pm.response.headers.get(\"x-request-id\"));", + "" + ], + "type": "text/javascript" + } + } + ], + "variable": [ + { + "key": "baseUrl", + "value": "https://sandbox.hyperswitch.io", + "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" + } + ] +} \ No newline at end of file
2024-02-27T04:51:25Z
## Type of Change <!-- Put an `x` in the boxes that apply --> - [X] Bugfix - [ ] New feature - [X] Enhancement - [ ] Refactoring - [ ] Dependency updates - [ ] Documentation - [ ] CI/CD ## Description Nuvei error handling for payment declined status ### 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/issues/3792 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)? --> Tested via postman test and included scripts ## 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 - [X] I added unit tests for my changes where possible - [ ] I added a [CHANGELOG](/CHANGELOG.md) entry if applicable
901d61bc0ddb4b2ad742de927126f468629a79af
Tested via postman test and included scripts
juspay/hyperswitch
juspay__hyperswitch-3761
Bug: [BUG] Internal Server Error thrown when updating or deleting non-existent API key ### Bug Description When a user tries to update or delete a non-existent API key, an internal server error is thrown. The expected behavior is that the server returns a 404 status code, informing that the API key does not exist. ### Expected Behavior Server should return 404 status code. ### Actual Behavior Server returns internal server error (500 status code) with the following response: ```json { "error": { "type": "api", "message": "Something went wrong", "code": "HE_00" } } ``` ### Steps To Reproduce The following steps assume that the admin API key for the deployed server is known to the user. 1. Create a merchant account using the create merchant account API and admin API key. 2. Try to use the update API key endpoint or the delete API key endpoint with a non-existent API key ID. For example, the delete API key request could look like so: ```shell curl --location --request DELETE 'http://localhost:8080/api_keys/<merchant_id>/a-non-existent-key-id' \ --header 'Content-Type: application/json' \ --header 'Accept: application/json' \ --header 'api-key: <ADMIN_API_KEY>' ``` Server returns the aforementioned response. ### 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/storage_impl/src/errors.rs b/crates/storage_impl/src/errors.rs index 14d1eb2db63..9e3ef903f5c 100644 --- a/crates/storage_impl/src/errors.rs +++ b/crates/storage_impl/src/errors.rs @@ -139,6 +139,7 @@ impl StorageError { pub fn is_db_not_found(&self) -> bool { match self { Self::DatabaseError(err) => matches!(err.current_context(), DatabaseError::NotFound), + Self::ValueNotFound(_) => true, _ => false, } }
2024-02-21T20:35: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 --> This PR fixes a bug with the update API key and delete API key endpoints throwing an internal server error when a non-existent API key was provided. ## 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). --> Fixes #3761. ## 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)? --> Locally. Trying to either update a non-existent API key returns a 404 status code, with an error message stating that the API key does not exist. 1. Update API key (request body may contain data or could just be an empty object): ```shell curl --location 'http://localhost:8080/api_keys/<merchant_id>/invalid-api-key-id' \ --header 'Content-Type: application/json' \ --header 'Accept: application/json' \ --header 'api-key: <ADMIN_API_KEY>' \ --data '{}' ``` 2. Delete API key: ```shell curl --location --request DELETE 'http://localhost:8080/<merchant_id>/merchant_1708546282/invalid-api-key-id' \ --header 'Content-Type: application/json' \ --header 'Accept: application/json' \ --header 'api-key:<ADMIN_API_KEY>' ``` In both cases, the response returned should be the same, with a 404 status code: ```json { "error": { "type": "invalid_request", "message": "API Key does not exist in our records", "code": "HE_02" } } ``` ## 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 - [ ] I added a [CHANGELOG](/CHANGELOG.md) entry if applicable
ef5e886ab1abdf50254343be8c6c48100ec2ec2d
Locally. Trying to either update a non-existent API key returns a 404 status code, with an error message stating that the API key does not exist. 1. Update API key (request body may contain data or could just be an empty object): ```shell curl --location 'http://localhost:8080/api_keys/<merchant_id>/invalid-api-key-id' \ --header 'Content-Type: application/json' \ --header 'Accept: application/json' \ --header 'api-key: <ADMIN_API_KEY>' \ --data '{}' ``` 2. Delete API key: ```shell curl --location --request DELETE 'http://localhost:8080/<merchant_id>/merchant_1708546282/invalid-api-key-id' \ --header 'Content-Type: application/json' \ --header 'Accept: application/json' \ --header 'api-key:<ADMIN_API_KEY>' ``` In both cases, the response returned should be the same, with a 404 status code: ```json { "error": { "type": "invalid_request", "message": "API Key does not exist in our records", "code": "HE_02" } } ```
juspay/hyperswitch
juspay__hyperswitch-3756
Bug: fix(invite): set user status to invitation sent if a registered user is invited
diff --git a/crates/router/src/core/user.rs b/crates/router/src/core/user.rs index 54fbecc64f3..96753236c1c 100644 --- a/crates/router/src/core/user.rs +++ b/crates/router/src/core/user.rs @@ -666,7 +666,13 @@ async fn handle_existing_user_invitation( merchant_id: user_from_token.merchant_id.clone(), role_id: request.role_id.clone(), org_id: user_from_token.org_id.clone(), - status: UserStatus::Active, + 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,
2024-02-21T13:40:29Z
## 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 will set the status of the user who has been invited but already registered with Hyperswitch as InvitationSent ### 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 #3756 ## 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)? --> Local SES. ``` curl --location 'http://localhost:8080/user/user/invite_multiple \ --header 'Content-Type: application/json' \ --header 'Authorization: Bearer JWT' \ --data-raw '{ "email": "email of the registered user“, "name": "name", "role_id": "some valid role" } ``` ``` curl --location 'http://localhost:8080/user/user/list' \ --header 'Authorization: Bearer JWT' ``` In this api response, the invited user status will be InvitationSent ``` [ { "email": "invited user email", "name": "invited user name", "role_id": "merchant_admin", "role_name": "Admin", "status": "InvitationSent", "last_modified_at": "2024-02-21T13:37:26.847Z" } ] ``` ## 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 - [ ] I added a [CHANGELOG](/CHANGELOG.md) entry if applicable
7c63c76011cec5fb398cff90b6237578c132b87d
Local SES. ``` curl --location 'http://localhost:8080/user/user/invite_multiple \ --header 'Content-Type: application/json' \ --header 'Authorization: Bearer JWT' \ --data-raw '{ "email": "email of the registered user“, "name": "name", "role_id": "some valid role" } ``` ``` curl --location 'http://localhost:8080/user/user/list' \ --header 'Authorization: Bearer JWT' ``` In this api response, the invited user status will be InvitationSent ``` [ { "email": "invited user email", "name": "invited user name", "role_id": "merchant_admin", "role_name": "Admin", "status": "InvitationSent", "last_modified_at": "2024-02-21T13:37:26.847Z" } ] ```
juspay/hyperswitch
juspay__hyperswitch-3754
Bug: DB Updates for Payment Methods Table
diff --git a/crates/common_enums/src/enums.rs b/crates/common_enums/src/enums.rs index c3976321f0a..29c416e9a85 100644 --- a/crates/common_enums/src/enums.rs +++ b/crates/common_enums/src/enums.rs @@ -1177,6 +1177,32 @@ pub enum PaymentMethodIssuerCode { JpBacs, } +#[derive( + Clone, + Copy, + Debug, + PartialEq, + Eq, + Hash, + serde::Serialize, + serde::Deserialize, + strum::Display, + strum::EnumString, + ToSchema, +)] +#[router_derive::diesel_enum(storage_type = "text")] +#[strum(serialize_all = "snake_case")] +#[serde(rename_all = "snake_case")] +pub enum PaymentMethodStatus { + /// Indicates that the payment method is active and can be used for payments. + Active, + /// Indicates that the payment method is not active and hence cannot be used for payments. + Inactive, + /// Indicates that the payment method is awaiting some data or action before it can be marked + /// as 'active'. + Processing, +} + /// To indicate the type of payment experience that the customer would go through #[derive( Eq, diff --git a/crates/diesel_models/src/payment_method.rs b/crates/diesel_models/src/payment_method.rs index f9767e2939b..09be739581e 100644 --- a/crates/diesel_models/src/payment_method.rs +++ b/crates/diesel_models/src/payment_method.rs @@ -34,6 +34,9 @@ pub struct PaymentMethod { pub metadata: Option<pii::SecretSerdeValue>, pub payment_method_data: Option<Encryption>, pub locker_id: Option<String>, + pub connector_mandate_details: Option<serde_json::Value>, + pub customer_acceptance: Option<pii::SecretSerdeValue>, + pub status: storage_enums::PaymentMethodStatus, } #[derive(Clone, Debug, Eq, PartialEq, Insertable, Queryable, router_derive::DebugAsDisplay)] @@ -61,6 +64,9 @@ pub struct PaymentMethodNew { pub metadata: Option<pii::SecretSerdeValue>, pub payment_method_data: Option<Encryption>, pub locker_id: Option<String>, + pub connector_mandate_details: Option<serde_json::Value>, + pub customer_acceptance: Option<pii::SecretSerdeValue>, + pub status: storage_enums::PaymentMethodStatus, } impl Default for PaymentMethodNew { @@ -90,6 +96,9 @@ impl Default for PaymentMethodNew { last_modified: now, metadata: Option::default(), payment_method_data: Option::default(), + connector_mandate_details: Option::default(), + customer_acceptance: Option::default(), + status: storage_enums::PaymentMethodStatus::Active, } } } diff --git a/crates/diesel_models/src/query/payment_method.rs b/crates/diesel_models/src/query/payment_method.rs index 298db2a234b..aa227962760 100644 --- a/crates/diesel_models/src/query/payment_method.rs +++ b/crates/diesel_models/src/query/payment_method.rs @@ -3,7 +3,7 @@ use router_env::{instrument, tracing}; use super::generics; use crate::{ - errors, + enums as storage_enums, errors, payment_method::{self, PaymentMethod, PaymentMethodNew}, schema::payment_methods::dsl, PgPooledConn, StorageResult, @@ -108,6 +108,31 @@ impl PaymentMethod { .await } + #[instrument(skip(conn))] + pub async fn find_by_customer_id_merchant_id_status( + conn: &PgPooledConn, + customer_id: &str, + merchant_id: &str, + status: storage_enums::PaymentMethodStatus, + ) -> StorageResult<Vec<Self>> { + generics::generic_filter::< + <Self as HasTable>::Table, + _, + <<Self as HasTable>::Table as Table>::PrimaryKey, + _, + >( + conn, + dsl::customer_id + .eq(customer_id.to_owned()) + .and(dsl::merchant_id.eq(merchant_id.to_owned())) + .and(dsl::status.eq(status)), + None, + None, + None, + ) + .await + } + pub async fn update_with_payment_method_id( self, conn: &PgPooledConn, diff --git a/crates/diesel_models/src/schema.rs b/crates/diesel_models/src/schema.rs index 4ac75f5e7de..f3c6f23e086 100644 --- a/crates/diesel_models/src/schema.rs +++ b/crates/diesel_models/src/schema.rs @@ -831,6 +831,10 @@ diesel::table! { payment_method_data -> Nullable<Bytea>, #[max_length = 64] locker_id -> Nullable<Varchar>, + connector_mandate_details -> Nullable<Jsonb>, + customer_acceptance -> Nullable<Jsonb>, + #[max_length = 64] + status -> Varchar, } } diff --git a/crates/router/src/core/payment_methods/cards.rs b/crates/router/src/core/payment_methods/cards.rs index 0a1cc023ece..a92215936a0 100644 --- a/crates/router/src/core/payment_methods/cards.rs +++ b/crates/router/src/core/payment_methods/cards.rs @@ -2667,9 +2667,10 @@ pub async fn list_customer_payment_method( let requires_cvv = is_requires_cvv.config != "false"; let resp = db - .find_payment_method_by_customer_id_merchant_id_list( + .find_payment_method_by_customer_id_merchant_id_status( customer_id, &merchant_account.merchant_id, + common_enums::PaymentMethodStatus::Active, ) .await .to_not_found_response(errors::ApiErrorResponse::PaymentMethodNotFound)?; diff --git a/crates/router/src/db/kafka_store.rs b/crates/router/src/db/kafka_store.rs index acc703d5c1b..1c1ec00ce79 100644 --- a/crates/router/src/db/kafka_store.rs +++ b/crates/router/src/db/kafka_store.rs @@ -1273,6 +1273,17 @@ impl PaymentMethodInterface for KafkaStore { .await } + async fn find_payment_method_by_customer_id_merchant_id_status( + &self, + customer_id: &str, + merchant_id: &str, + status: common_enums::PaymentMethodStatus, + ) -> CustomResult<Vec<storage::PaymentMethod>, errors::StorageError> { + self.diesel_store + .find_payment_method_by_customer_id_merchant_id_status(customer_id, merchant_id, status) + .await + } + async fn find_payment_method_by_locker_id( &self, locker_id: &str, diff --git a/crates/router/src/db/payment_method.rs b/crates/router/src/db/payment_method.rs index 4f4087f552e..f15ceecd1c4 100644 --- a/crates/router/src/db/payment_method.rs +++ b/crates/router/src/db/payment_method.rs @@ -26,6 +26,13 @@ pub trait PaymentMethodInterface { merchant_id: &str, ) -> CustomResult<Vec<storage::PaymentMethod>, errors::StorageError>; + async fn find_payment_method_by_customer_id_merchant_id_status( + &self, + customer_id: &str, + merchant_id: &str, + status: common_enums::PaymentMethodStatus, + ) -> CustomResult<Vec<storage::PaymentMethod>, errors::StorageError>; + async fn insert_payment_method( &self, payment_method_new: storage::PaymentMethodNew, @@ -105,6 +112,24 @@ impl PaymentMethodInterface for Store { .into_report() } + async fn find_payment_method_by_customer_id_merchant_id_status( + &self, + customer_id: &str, + merchant_id: &str, + status: common_enums::PaymentMethodStatus, + ) -> CustomResult<Vec<storage::PaymentMethod>, errors::StorageError> { + let conn = connection::pg_connection_read(self).await?; + storage::PaymentMethod::find_by_customer_id_merchant_id_status( + &conn, + customer_id, + merchant_id, + status, + ) + .await + .map_err(Into::into) + .into_report() + } + async fn delete_payment_method_by_merchant_id_payment_method_id( &self, merchant_id: &str, @@ -196,6 +221,9 @@ impl PaymentMethodInterface for MockDb { 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, + connector_mandate_details: payment_method_new.connector_mandate_details, + customer_acceptance: payment_method_new.customer_acceptance, + status: payment_method_new.status, }; payment_methods.push(payment_method.clone()); Ok(payment_method) @@ -223,6 +251,33 @@ impl PaymentMethodInterface for MockDb { } } + async fn find_payment_method_by_customer_id_merchant_id_status( + &self, + customer_id: &str, + merchant_id: &str, + status: common_enums::PaymentMethodStatus, + ) -> CustomResult<Vec<storage::PaymentMethod>, errors::StorageError> { + let payment_methods = self.payment_methods.lock().await; + let payment_methods_found: Vec<storage::PaymentMethod> = payment_methods + .iter() + .filter(|pm| { + pm.customer_id == customer_id + && pm.merchant_id == merchant_id + && pm.status == status + }) + .cloned() + .collect(); + + if payment_methods_found.is_empty() { + Err(errors::StorageError::ValueNotFound( + "cannot find payment methods".to_string(), + )) + .into_report() + } else { + Ok(payment_methods_found) + } + } + async fn delete_payment_method_by_merchant_id_payment_method_id( &self, merchant_id: &str, diff --git a/migrations/2024-02-22-060352_add_mit_columns_to_payment_methods/down.sql b/migrations/2024-02-22-060352_add_mit_columns_to_payment_methods/down.sql new file mode 100644 index 00000000000..65367b5cd54 --- /dev/null +++ b/migrations/2024-02-22-060352_add_mit_columns_to_payment_methods/down.sql @@ -0,0 +1,10 @@ +-- This file should undo anything in `up.sql` + +ALTER TABLE payment_methods +DROP COLUMN status; + +ALTER TABLE payment_methods +DROP COLUMN customer_acceptance; + +ALTER TABLE payment_methods +DROP COLUMN connector_mandate_details; diff --git a/migrations/2024-02-22-060352_add_mit_columns_to_payment_methods/up.sql b/migrations/2024-02-22-060352_add_mit_columns_to_payment_methods/up.sql new file mode 100644 index 00000000000..c43c347da38 --- /dev/null +++ b/migrations/2024-02-22-060352_add_mit_columns_to_payment_methods/up.sql @@ -0,0 +1,13 @@ +-- Your SQL goes here + +ALTER TABLE payment_methods +ADD COLUMN connector_mandate_details JSONB +DEFAULT NULL; + +ALTER TABLE payment_methods +ADD COLUMN customer_acceptance JSONB +DEFAULT NULL; + +ALTER TABLE payment_methods +ADD COLUMN status VARCHAR(64) +NOT NULL DEFAULT 'active';
2024-02-22T07:25: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 3 columns to the `payment_methods` table, with the purpose of enabling MIT Transaction Orchestration in the near future. - `connector_mandate_details`: Intended to store Connector MIT details such as the mandate ID - `customer_acceptance`: Intended to store customer consent and acceptance details - `status`: The status of the payment method (Can be `processing` initially for connector MITs that rely on asynchronous flows and/or time-based factors for setup) #### Flows Affected - **List Payment Methods for Customer**: This was updated such that only payment methods with status `active` are listed for the customer. To make this backwards compatible, the default status for new saved cards is set to `active`. ### 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). --> This change is important for setting up MIT orchestration in the future. ## 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)? --> Local testing, postman tests. The saved card payments flow needs to work as usual which is covered by Postman tests. When saving a card, the values of the added columns are set to default for now. This is NULL for `connector_mandate_details` and `customer_acceptance`, and `active` for `status`. <img width="420" alt="image" src="https://github.com/juspay/hyperswitch/assets/47862918/0bf2473c-90bb-4d9c-b3d2-b83905b5101c"> Since the default for the status column is set to `active`, the `List Payment Methods for Customer` flow works as intended for saved payment methods. <img width="502" alt="image" src="https://github.com/juspay/hyperswitch/assets/47862918/6c7cbbea-4c99-4391-97db-81012d11e448"> ## 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 - [ ] I added a [CHANGELOG](/CHANGELOG.md) entry if applicable
385622678f764b2bdb67423be0e5c8f055dd0b7c
Local testing, postman tests. The saved card payments flow needs to work as usual which is covered by Postman tests. When saving a card, the values of the added columns are set to default for now. This is NULL for `connector_mandate_details` and `customer_acceptance`, and `active` for `status`. <img width="420" alt="image" src="https://github.com/juspay/hyperswitch/assets/47862918/0bf2473c-90bb-4d9c-b3d2-b83905b5101c"> Since the default for the status column is set to `active`, the `List Payment Methods for Customer` flow works as intended for saved payment methods. <img width="502" alt="image" src="https://github.com/juspay/hyperswitch/assets/47862918/6c7cbbea-4c99-4391-97db-81012d11e448">
juspay/hyperswitch
juspay__hyperswitch-3753
Bug: Remove validation for `mandate_data` object in payments create request - Mandate data to be an optional field and not a required param for setup_future_usage:off-session payments
diff --git a/crates/router/src/core/payments/operations/payment_create.rs b/crates/router/src/core/payments/operations/payment_create.rs index 2eaa11f44ee..f4db64dcfb5 100644 --- a/crates/router/src/core/payments/operations/payment_create.rs +++ b/crates/router/src/core/payments/operations/payment_create.rs @@ -8,7 +8,7 @@ use data_models::{ payments::payment_attempt::PaymentAttempt, }; use diesel_models::ephemeral_key; -use error_stack::{self, report, ResultExt}; +use error_stack::{self, ResultExt}; use masking::PeekInterface; use router_derive::PaymentOperation; use router_env::{instrument, tracing}; @@ -628,17 +628,6 @@ impl<F: Send + Clone, Ctx: PaymentMethodRetrieve> ValidateRequest<F, api::Paymen helpers::validate_payment_method_fields_present(request)?; - if request.mandate_data.is_none() - && request - .setup_future_usage - .map(|fut_usage| fut_usage == enums::FutureUsage::OffSession) - .unwrap_or(false) - { - Err(report!(errors::ApiErrorResponse::PreconditionFailed { - message: "`setup_future_usage` cannot be `off_session` for normal payments".into() - }))? - } - let mandate_type = helpers::validate_mandate(request, payments::is_operation_confirm(self))?; diff --git a/crates/router/src/core/payments/operations/payment_update.rs b/crates/router/src/core/payments/operations/payment_update.rs index 071d919eb19..494db2b8529 100644 --- a/crates/router/src/core/payments/operations/payment_update.rs +++ b/crates/router/src/core/payments/operations/payment_update.rs @@ -683,17 +683,6 @@ impl<F: Send + Clone, Ctx: PaymentMethodRetrieve> ValidateRequest<F, api::Paymen helpers::validate_payment_method_fields_present(request)?; - if request.mandate_data.is_none() - && request - .setup_future_usage - .map(|fut_usage| fut_usage == storage_enums::FutureUsage::OffSession) - .unwrap_or(false) - { - Err(report!(errors::ApiErrorResponse::PreconditionFailed { - message: "`setup_future_usage` cannot be `off_session` for normal payments".into() - }))? - } - let mandate_type = helpers::validate_mandate(request, false)?; Ok((
2024-02-28T08:00:08Z
## 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 removes the validation such that mandate data to be an optional field and not a required param for setup_future_usage: off-session payments ### 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)? --> Before removing validation - ``` curl --location 'http://localhost:8080/payments' \ --header 'Content-Type: application/json' \ --header 'Accept: application/json' \ --header 'api-key: dev_nDlEYaebMeZFC4W7OzfK7g3ohwAqztjYxNVk58rg755miOXOFdmB3CBGJzRqvMEs' \ --data-raw '{ "amount": 0, "currency": "USD", "confirm": true, "capture_method": "automatic", "capture_on": "2022-09-10T10:11:12Z", "customer_id": "cus_eTs98Of0QUAoWNfv7Fyt", "business_country": "US", "business_label": "default", "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://google.com", "setup_future_usage": "off_session", "payment_method": "card", "payment_method_type": "credit", "payment_type": "setup_mandate", "payment_method_data": { "card": { "card_number": "4242424242424242", "card_exp_month": "10", "card_exp_year": "25", "card_cvc": "123" } }, "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": "8056594430", "country_code": "+91" } }, "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" } }, "statement_descriptor_name": "joseph", "statement_descriptor_suffix": "JS", "metadata": { "udf1": "value1", "new_customer": "true", "login_date": "2019-09-10T10:11:12Z" } }' ``` ![image](https://github.com/juspay/hyperswitch/assets/70657455/4df97e1a-5174-4a2e-b842-301c6494eb9c) After removing validation (same curl req)- ``` curl --location 'http://localhost:8080/payments' \ --header 'Content-Type: application/json' \ --header 'Accept: application/json' \ --header 'api-key: dev_nDlEYaebMeZFC4W7OzfK7g3ohwAqztjYxNVk58rg755miOXOFdmB3CBGJzRqvMEs' \ --data-raw '{ "amount": 0, "currency": "USD", "confirm": true, "capture_method": "automatic", "capture_on": "2022-09-10T10:11:12Z", "customer_id": "cus_eTs98Of0QUAoWNfv7Fyt", "business_country": "US", "business_label": "default", "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://google.com", "setup_future_usage": "off_session", "payment_method": "card", "payment_method_type": "credit", "payment_type": "setup_mandate", "payment_method_data": { "card": { "card_number": "4242424242424242", "card_exp_month": "10", "card_exp_year": "25", "card_cvc": "123" } }, "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": "8056594430", "country_code": "+91" } }, "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" } }, "statement_descriptor_name": "joseph", "statement_descriptor_suffix": "JS", "metadata": { "udf1": "value1", "new_customer": "true", "login_date": "2019-09-10T10:11:12Z" } }' ``` Payment succeeded - ![image](https://github.com/juspay/hyperswitch/assets/70657455/7827566e-2a15-4ded-be76-c3e8e7b34079) ## 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 - [ ] I added a [CHANGELOG](/CHANGELOG.md) entry if applicable
0fa43612c2e6c11d555efecd49e6982403a45000
Before removing validation - ``` curl --location 'http://localhost:8080/payments' \ --header 'Content-Type: application/json' \ --header 'Accept: application/json' \ --header 'api-key: dev_nDlEYaebMeZFC4W7OzfK7g3ohwAqztjYxNVk58rg755miOXOFdmB3CBGJzRqvMEs' \ --data-raw '{ "amount": 0, "currency": "USD", "confirm": true, "capture_method": "automatic", "capture_on": "2022-09-10T10:11:12Z", "customer_id": "cus_eTs98Of0QUAoWNfv7Fyt", "business_country": "US", "business_label": "default", "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://google.com", "setup_future_usage": "off_session", "payment_method": "card", "payment_method_type": "credit", "payment_type": "setup_mandate", "payment_method_data": { "card": { "card_number": "4242424242424242", "card_exp_month": "10", "card_exp_year": "25", "card_cvc": "123" } }, "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": "8056594430", "country_code": "+91" } }, "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" } }, "statement_descriptor_name": "joseph", "statement_descriptor_suffix": "JS", "metadata": { "udf1": "value1", "new_customer": "true", "login_date": "2019-09-10T10:11:12Z" } }' ``` ![image](https://github.com/juspay/hyperswitch/assets/70657455/4df97e1a-5174-4a2e-b842-301c6494eb9c) After removing validation (same curl req)- ``` curl --location 'http://localhost:8080/payments' \ --header 'Content-Type: application/json' \ --header 'Accept: application/json' \ --header 'api-key: dev_nDlEYaebMeZFC4W7OzfK7g3ohwAqztjYxNVk58rg755miOXOFdmB3CBGJzRqvMEs' \ --data-raw '{ "amount": 0, "currency": "USD", "confirm": true, "capture_method": "automatic", "capture_on": "2022-09-10T10:11:12Z", "customer_id": "cus_eTs98Of0QUAoWNfv7Fyt", "business_country": "US", "business_label": "default", "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://google.com", "setup_future_usage": "off_session", "payment_method": "card", "payment_method_type": "credit", "payment_type": "setup_mandate", "payment_method_data": { "card": { "card_number": "4242424242424242", "card_exp_month": "10", "card_exp_year": "25", "card_cvc": "123" } }, "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": "8056594430", "country_code": "+91" } }, "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" } }, "statement_descriptor_name": "joseph", "statement_descriptor_suffix": "JS", "metadata": { "udf1": "value1", "new_customer": "true", "login_date": "2019-09-10T10:11:12Z" } }' ``` Payment succeeded - ![image](https://github.com/juspay/hyperswitch/assets/70657455/7827566e-2a15-4ded-be76-c3e8e7b34079)
juspay/hyperswitch
juspay__hyperswitch-3765
Bug: [FEATURE] : mask pii information in connector request and response for stripe, aci, adyen, airwallex and authorizedotnet ### Feature Description Mask pii information passed and received in the connector request and response ### Possible Implementation Refactor all sensitive response and request fields secret ### 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/aci/transformers.rs b/crates/router/src/connector/aci/transformers.rs index ed56fc5f524..fe621bccd05 100644 --- a/crates/router/src/connector/aci/transformers.rs +++ b/crates/router/src/connector/aci/transformers.rs @@ -3,7 +3,7 @@ use std::str::FromStr; use api_models::enums::BankNames; use common_utils::pii::Email; use error_stack::report; -use masking::Secret; +use masking::{ExposeInterface, Secret}; use reqwest::Url; use serde::{Deserialize, Serialize}; @@ -382,7 +382,7 @@ pub struct Instruction { #[derive(Debug, Clone, Eq, PartialEq, Serialize)] pub struct BankDetails { #[serde(rename = "bankAccount.holder")] - pub account_holder: String, + pub account_holder: Secret<String>, } #[allow(dead_code)] @@ -657,10 +657,11 @@ impl FromStr for AciPaymentStatus { #[serde(rename_all = "camelCase")] pub struct AciPaymentsResponse { id: String, - registration_id: Option<String>, + registration_id: Option<Secret<String>>, // ndc is an internal unique identifier for the request. ndc: String, timestamp: String, + // Number useful for support purposes. build_number: String, pub(super) result: ResultCode, pub(super) redirect: Option<AciRedirectionData>, @@ -734,7 +735,7 @@ impl<F, T> .response .registration_id .map(|id| types::MandateReference { - connector_mandate_id: Some(id), + connector_mandate_id: Some(id.expose()), payment_method_id: None, }); diff --git a/crates/router/src/connector/adyen.rs b/crates/router/src/connector/adyen.rs index c634d38c614..0c22b0413a3 100644 --- a/crates/router/src/connector/adyen.rs +++ b/crates/router/src/connector/adyen.rs @@ -7,6 +7,7 @@ use base64::Engine; use common_utils::request::RequestContent; use diesel_models::{enums as storage_enums, enums}; use error_stack::{IntoReport, ResultExt}; +use masking::ExposeInterface; use ring::hmac; use router_env::{instrument, tracing}; @@ -467,8 +468,10 @@ impl .response .parse_struct("AdyenCaptureResponse") .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(), @@ -610,8 +613,10 @@ impl .response .parse_struct("AdyenPaymentResponse") .change_context(errors::ConnectorError::ResponseDeserializationFailed)?; + event_builder.map(|i| i.set_response_body(&response)); router_env::logger::info!(connector_response=?response); + let is_multiple_capture_sync = match data.request.sync_type { types::SyncRequestType::MultipleCaptureSync(_) => true, types::SyncRequestType::SinglePaymentSync => false, @@ -1513,7 +1518,7 @@ impl api::IncomingWebhook for Adyen { let notif_item = get_webhook_object_from_body(request.body) .change_context(errors::ConnectorError::WebhookSourceVerificationFailed)?; - let base64_signature = notif_item.additional_data.hmac_signature; + let base64_signature = notif_item.additional_data.hmac_signature.expose(); Ok(base64_signature.as_bytes().to_vec()) } diff --git a/crates/router/src/connector/adyen/transformers.rs b/crates/router/src/connector/adyen/transformers.rs index 05c1a0ede97..8070a9ec325 100644 --- a/crates/router/src/connector/adyen/transformers.rs +++ b/crates/router/src/connector/adyen/transformers.rs @@ -4,7 +4,7 @@ use api_models::{enums, payments, webhooks}; use cards::CardNumber; use common_utils::ext_traits::Encode; use error_stack::ResultExt; -use masking::PeekInterface; +use masking::{ExposeInterface, PeekInterface}; use reqwest::Url; use serde::{Deserialize, Serialize}; use time::{Duration, OffsetDateTime, PrimitiveDateTime}; @@ -95,10 +95,10 @@ pub struct AdditionalData { pub recurring_processing_model: Option<AdyenRecurringModel>, /// Enable recurring details in dashboard to receive this ID, https://docs.adyen.com/online-payments/tokenization/create-and-use-tokens#test-and-go-live #[serde(rename = "recurring.recurringDetailReference")] - recurring_detail_reference: Option<String>, + recurring_detail_reference: Option<Secret<String>>, #[serde(rename = "recurring.shopperReference")] recurring_shopper_reference: Option<String>, - network_tx_reference: Option<String>, + network_tx_reference: Option<Secret<String>>, #[cfg(feature = "payouts")] payout_eligible: Option<PayoutEligibility>, funds_availability: Option<String>, @@ -553,7 +553,7 @@ pub struct JCSVoucherData { first_name: Secret<String>, last_name: Option<Secret<String>>, shopper_email: Email, - telephone_number: String, + telephone_number: Secret<String>, } #[derive(Debug, Clone, Serialize)] @@ -604,14 +604,6 @@ pub struct BacsDirectDebitData { holder_name: Secret<String>, } -#[derive(Debug, Clone, Serialize)] -#[serde(rename_all = "camelCase")] -pub struct MandateData { - #[serde(rename = "type")] - payment_type: PaymentType, - stored_payment_method_id: String, -} - #[derive(Debug, Clone, Serialize)] #[serde(rename_all = "camelCase")] pub struct BancontactCardData { @@ -674,7 +666,7 @@ impl TryFrom<&Box<payments::JCSVoucherData>> for JCSVoucherData { first_name: jcs_data.first_name.clone(), last_name: jcs_data.last_name.clone(), shopper_email: jcs_data.email.clone(), - telephone_number: jcs_data.phone_number.clone(), + telephone_number: Secret::new(jcs_data.phone_number.clone()), }) } } @@ -1031,7 +1023,7 @@ impl TryFrom<&api_enums::BankNames> for OpenBankingUKIssuer { pub struct BlikRedirectionData { #[serde(rename = "type")] payment_type: PaymentType, - blik_code: String, + blik_code: Secret<String>, } #[derive(Debug, Clone, Serialize)] @@ -1047,7 +1039,7 @@ pub struct BankRedirectionWithIssuer<'a> { pub struct AdyenMandate { #[serde(rename = "type")] payment_type: PaymentType, - stored_payment_method_id: String, + stored_payment_method_id: Secret<String>, } #[derive(Debug, Clone, Serialize, Deserialize)] @@ -1060,7 +1052,7 @@ pub struct AdyenCard { expiry_year: Secret<String>, cvc: Option<Secret<String>>, brand: Option<CardBrand>, //Mandatory for mandate using network_txns_id - network_payment_reference: Option<String>, + network_payment_reference: Option<Secret<String>>, } #[derive(Debug, Clone, Serialize, Deserialize)] @@ -1143,7 +1135,7 @@ pub struct AdyenRefundRequest { #[derive(Default, Debug, Clone, Serialize, Deserialize)] #[serde(rename_all = "camelCase")] pub struct AdyenRefundResponse { - merchant_account: String, + merchant_account: Secret<String>, psp_reference: String, payment_psp_reference: String, reference: String, @@ -2131,11 +2123,11 @@ impl<'a> TryFrom<&api_models::payments::BankRedirectData> for AdyenPaymentMethod api_models::payments::BankRedirectData::Blik { blik_code } => { Ok(AdyenPaymentMethod::Blik(Box::new(BlikRedirectionData { payment_type: PaymentType::Blik, - blik_code: blik_code.clone().ok_or( + blik_code: Secret::new(blik_code.clone().ok_or( errors::ConnectorError::MissingRequiredField { field_name: "blik_code", }, - )?, + )?), }))) } api_models::payments::BankRedirectData::Eps { bank_name, .. } => Ok( @@ -2357,7 +2349,9 @@ impl<'a> payments::MandateReferenceId::ConnectorMandateId(connector_mandate_ids) => { let adyen_mandate = AdyenMandate { payment_type: PaymentType::try_from(payment_method_type)?, - stored_payment_method_id: connector_mandate_ids.get_connector_mandate_id()?, + stored_payment_method_id: Secret::new( + connector_mandate_ids.get_connector_mandate_id()?, + ), }; Ok::<AdyenPaymentMethod<'_>, Self::Error>(AdyenPaymentMethod::Mandate(Box::new( adyen_mandate, @@ -2375,7 +2369,7 @@ impl<'a> expiry_year: card.card_exp_year.clone(), cvc: None, brand: Some(brand), - network_payment_reference: Some(network_mandate_id), + network_payment_reference: Some(Secret::new(network_mandate_id)), }; Ok(AdyenPaymentMethod::AdyenCard(Box::new(adyen_card))) } @@ -3047,12 +3041,14 @@ pub fn get_adyen_response( .as_ref() .and_then(|data| data.recurring_detail_reference.to_owned()) .map(|mandate_id| types::MandateReference { - connector_mandate_id: Some(mandate_id), + connector_mandate_id: Some(mandate_id.expose()), payment_method_id: None, }); - let network_txn_id = response - .additional_data - .and_then(|additional_data| additional_data.network_tx_reference); + let network_txn_id = response.additional_data.and_then(|additional_data| { + additional_data + .network_tx_reference + .map(|network_tx_id| network_tx_id.expose()) + }); let payments_response_data = types::PaymentsResponseData::TransactionResponse { resource_id: types::ResponseId::ConnectorTransactionId(response.psp_reference), @@ -3314,7 +3310,7 @@ pub fn get_redirection_error_response( pub fn get_qr_metadata( response: &QrCodeResponseResponse, ) -> errors::CustomResult<Option<serde_json::Value>, errors::ConnectorError> { - let image_data = crate_utils::QrImage::new_from_data(response.action.qr_code_data.to_owned()) + let image_data = crate_utils::QrImage::new_from_data(response.action.qr_code_data.clone()) .change_context(errors::ConnectorError::ResponseHandlingFailed)?; let image_data_url = Url::parse(image_data.data.clone().as_str()).ok(); @@ -3636,7 +3632,7 @@ impl TryFrom<&AdyenRouterData<&types::PaymentsCaptureRouterData>> for AdyenCaptu #[derive(Default, Debug, Serialize, Deserialize)] #[serde(rename_all = "camelCase")] pub struct AdyenCaptureResponse { - merchant_account: String, + merchant_account: Secret<String>, payment_psp_reference: String, psp_reference: String, reference: String, @@ -3789,7 +3785,7 @@ pub enum DisputeStatus { #[derive(Debug, Deserialize)] #[serde(rename_all = "camelCase")] pub struct AdyenAdditionalDataWH { - pub hmac_signature: String, + pub hmac_signature: Secret<String>, pub dispute_status: Option<DisputeStatus>, pub chargeback_reason_code: Option<String>, #[serde(default, with = "common_utils::custom_serde::iso8601::option")] diff --git a/crates/router/src/connector/airwallex.rs b/crates/router/src/connector/airwallex.rs index a788a4a2ab0..defc6a339fb 100644 --- a/crates/router/src/connector/airwallex.rs +++ b/crates/router/src/connector/airwallex.rs @@ -522,8 +522,10 @@ impl ConnectorIntegration<api::PSync, types::PaymentsSyncData, types::PaymentsRe .response .parse_struct("airwallex AirwallexPaymentsSyncResponse") .change_context(errors::ConnectorError::ResponseDeserializationFailed)?; + event_builder.map(|i| i.set_response_body(&response)); router_env::logger::info!(connector_response=?response); + types::PaymentsSyncRouterData::try_from(types::ResponseRouterData { response, data: data.clone(), diff --git a/crates/router/src/connector/airwallex/transformers.rs b/crates/router/src/connector/airwallex/transformers.rs index 692458715f7..767d1c8a6e0 100644 --- a/crates/router/src/connector/airwallex/transformers.rs +++ b/crates/router/src/connector/airwallex/transformers.rs @@ -1,5 +1,5 @@ use error_stack::{IntoReport, ResultExt}; -use masking::PeekInterface; +use masking::{ExposeInterface, PeekInterface}; use serde::{Deserialize, Serialize}; use time::PrimitiveDateTime; use url::Url; @@ -416,10 +416,10 @@ pub enum AirwallexNextActionStage { #[derive(Debug, Clone, Deserialize, PartialEq, Serialize)] pub struct AirwallexRedirectFormData { #[serde(rename = "JWT")] - jwt: Option<String>, + jwt: Option<Secret<String>>, #[serde(rename = "threeDSMethodData")] - three_ds_method_data: Option<String>, - token: Option<String>, + three_ds_method_data: Option<Secret<String>>, + token: Option<Secret<String>>, provider: Option<String>, version: Option<String>, } @@ -439,7 +439,7 @@ pub struct AirwallexPaymentsResponse { id: String, amount: Option<f32>, //ID of the PaymentConsent related to this PaymentIntent - payment_consent_id: Option<String>, + payment_consent_id: Option<Secret<String>>, next_action: Option<AirwallexPaymentsNextAction>, } @@ -450,7 +450,7 @@ pub struct AirwallexPaymentsSyncResponse { id: String, amount: Option<f32>, //ID of the PaymentConsent related to this PaymentIntent - payment_consent_id: Option<String>, + payment_consent_id: Option<Secret<String>>, next_action: Option<AirwallexPaymentsNextAction>, } @@ -464,18 +464,27 @@ fn get_redirection_form( //Some form fields might be empty based on the authentication type by the connector ( "JWT".to_string(), - response_url_data.data.jwt.unwrap_or_default(), + response_url_data + .data + .jwt + .map(|jwt| jwt.expose()) + .unwrap_or_default(), ), ( "threeDSMethodData".to_string(), response_url_data .data .three_ds_method_data + .map(|three_ds_method_data| three_ds_method_data.expose()) .unwrap_or_default(), ), ( "token".to_string(), - response_url_data.data.token.unwrap_or_default(), + response_url_data + .data + .token + .map(|token: Secret<String>| token.expose()) + .unwrap_or_default(), ), ( "provider".to_string(), diff --git a/crates/router/src/connector/authorizedotnet.rs b/crates/router/src/connector/authorizedotnet.rs index 04704a90919..ba232c01bbf 100644 --- a/crates/router/src/connector/authorizedotnet.rs +++ b/crates/router/src/connector/authorizedotnet.rs @@ -212,8 +212,10 @@ impl ConnectorIntegration<api::Capture, types::PaymentsCaptureData, types::Payme let response: authorizedotnet::AuthorizedotnetPaymentsResponse = intermediate_response .parse_struct("AuthorizedotnetPaymentsResponse") .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(), @@ -353,7 +355,6 @@ impl ConnectorIntegration<api::Authorize, types::PaymentsAuthorizeData, types::P ))?; let connector_req = authorizedotnet::CreateTransactionRequest::try_from(&connector_router_data)?; - Ok(RequestContent::Json(Box::new(connector_req))) } @@ -400,8 +401,10 @@ impl ConnectorIntegration<api::Authorize, types::PaymentsAuthorizeData, types::P let response: authorizedotnet::AuthorizedotnetPaymentsResponse = intermediate_response .parse_struct("AuthorizedotnetPaymentsResponse") .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(), diff --git a/crates/router/src/connector/authorizedotnet/transformers.rs b/crates/router/src/connector/authorizedotnet/transformers.rs index bc5bfe86ca1..eb5f13881fb 100644 --- a/crates/router/src/connector/authorizedotnet/transformers.rs +++ b/crates/router/src/connector/authorizedotnet/transformers.rs @@ -3,7 +3,7 @@ use common_utils::{ ext_traits::{Encode, ValueExt}, }; use error_stack::{IntoReport, ResultExt}; -use masking::{PeekInterface, Secret, StrongSecret}; +use masking::{ExposeInterface, PeekInterface, Secret, StrongSecret}; use serde::{Deserialize, Serialize}; use crate::{ @@ -119,7 +119,7 @@ pub struct PayPalDetails { #[serde(rename_all = "camelCase")] pub struct WalletDetails { pub data_descriptor: WalletMethod, - pub data_value: String, + pub data_value: Secret<String>, } #[derive(Serialize, Debug, Deserialize)] @@ -147,14 +147,12 @@ fn get_pm_and_subsequent_auth_detail( .to_owned() .and_then(|mandate_ids| mandate_ids.mandate_reference_id) { - Some(api_models::payments::MandateReferenceId::NetworkMandateId( - original_network_trans_id, - )) => { + Some(api_models::payments::MandateReferenceId::NetworkMandateId(network_trans_id)) => { let processing_options = Some(ProcessingOptions { is_subsequent_auth: true, }); let subseuent_auth_info = Some(SubsequentAuthInformation { - original_network_trans_id, + original_network_trans_id: Secret::new(network_trans_id), reason: Reason::Resubmission, }); match item.router_data.request.payment_method_data { @@ -225,7 +223,7 @@ pub struct ProcessingOptions { #[derive(Debug, Serialize)] #[serde(rename_all = "camelCase")] pub struct SubsequentAuthInformation { - original_network_trans_id: String, + original_network_trans_id: Secret<String>, // original_auth_amount: String, Required for Discover, Diners Club, JCB, and China Union Pay transactions. reason: Reason, } @@ -474,8 +472,8 @@ pub struct AuthorizedotnetTransactionResponse { response_code: AuthorizedotnetPaymentStatus, #[serde(rename = "transId")] transaction_id: String, - network_trans_id: Option<String>, - pub(super) account_number: Option<String>, + network_trans_id: Option<Secret<String>>, + pub(super) account_number: Option<Secret<String>>, pub(super) errors: Option<Vec<ErrorMessage>>, secure_acceptance: Option<SecureAcceptance>, } @@ -487,8 +485,8 @@ pub struct RefundResponse { #[serde(rename = "transId")] transaction_id: String, #[allow(dead_code)] - network_trans_id: Option<String>, - pub account_number: Option<String>, + network_trans_id: Option<Secret<String>>, + pub account_number: Option<Secret<String>>, pub errors: Option<Vec<ErrorMessage>>, } @@ -518,8 +516,8 @@ pub struct VoidResponse { response_code: AuthorizedotnetVoidStatus, #[serde(rename = "transId")] transaction_id: String, - network_trans_id: Option<String>, - pub account_number: Option<String>, + network_trans_id: Option<Secret<String>>, + pub account_number: Option<Secret<String>>, pub errors: Option<Vec<ErrorMessage>>, } @@ -581,7 +579,7 @@ impl<F, T> .account_number .as_ref() .map(|acc_no| { - construct_refund_payment_details(acc_no.clone()).encode_to_value() + construct_refund_payment_details(acc_no.clone().expose()).encode_to_value() }) .transpose() .change_context(errors::ConnectorError::MissingRequiredField { @@ -604,7 +602,10 @@ impl<F, T> redirection_data, mandate_reference: None, connector_metadata: metadata, - network_txn_id: transaction_response.network_trans_id.clone(), + network_txn_id: transaction_response + .network_trans_id + .clone() + .map(|network_trans_id| network_trans_id.expose()), connector_response_reference_id: Some( transaction_response.transaction_id.clone(), ), @@ -656,7 +657,7 @@ impl<F, T> .account_number .as_ref() .map(|acc_no| { - construct_refund_payment_details(acc_no.clone()).encode_to_value() + construct_refund_payment_details(acc_no.clone().expose()).encode_to_value() }) .transpose() .change_context(errors::ConnectorError::MissingRequiredField { @@ -673,7 +674,10 @@ impl<F, T> redirection_data: None, mandate_reference: None, connector_metadata: metadata, - network_txn_id: transaction_response.network_trans_id.clone(), + network_txn_id: transaction_response + .network_trans_id + .clone() + .map(|network_trans_id| network_trans_id.expose()), connector_response_reference_id: Some( transaction_response.transaction_id.clone(), ), @@ -1152,13 +1156,13 @@ fn get_wallet_data( api_models::payments::WalletData::GooglePay(_) => { Ok(PaymentDetails::OpaqueData(WalletDetails { data_descriptor: WalletMethod::Googlepay, - data_value: wallet_data.get_encoded_wallet_token()?, + data_value: Secret::new(wallet_data.get_encoded_wallet_token()?), })) } api_models::payments::WalletData::ApplePay(applepay_token) => { Ok(PaymentDetails::OpaqueData(WalletDetails { data_descriptor: WalletMethod::Applepay, - data_value: applepay_token.payment_data.clone(), + data_value: Secret::new(applepay_token.payment_data.clone()), })) } api_models::payments::WalletData::PaypalRedirect(_) => { @@ -1215,7 +1219,7 @@ pub struct Paypal { #[derive(Debug, Serialize, Deserialize)] pub struct PaypalQueryParams { #[serde(rename = "PayerID")] - payer_id: String, + payer_id: Secret<String>, } impl TryFrom<&AuthorizedotnetRouterData<&types::PaymentsCompleteAuthorizeRouterData>> @@ -1232,12 +1236,11 @@ impl TryFrom<&AuthorizedotnetRouterData<&types::PaymentsCompleteAuthorizeRouterD .as_ref() .and_then(|redirect_response| redirect_response.params.as_ref()) .ok_or(errors::ConnectorError::ResponseDeserializationFailed)?; - let payer_id: Secret<String> = Secret::new( + let payer_id: Secret<String> = serde_urlencoded::from_str::<PaypalQueryParams>(params.peek()) .into_report() .change_context(errors::ConnectorError::ResponseDeserializationFailed)? - .payer_id, - ); + .payer_id; let transaction_type = match item.router_data.request.capture_method { Some(enums::CaptureMethod::Manual) => TransactionType::ContinueAuthorization, _ => TransactionType::ContinueCapture, diff --git a/crates/router/src/connector/stripe.rs b/crates/router/src/connector/stripe.rs index b85725c249d..389e773da5e 100644 --- a/crates/router/src/connector/stripe.rs +++ b/crates/router/src/connector/stripe.rs @@ -1708,7 +1708,7 @@ impl fn handle_response( &self, data: &types::RetrieveFileRouterData, - _event_builder: Option<&mut ConnectorEvent>, + event_builder: Option<&mut ConnectorEvent>, res: types::Response, ) -> CustomResult< types::RouterData< @@ -1719,7 +1719,10 @@ impl errors::ConnectorError, > { let response = res.response; - router_env::logger::info!(connector_response=?response); + + event_builder.map(|event| event.set_response_body(&serde_json::json!({"connector_response_type": "file", "status_code": res.status_code}))); + router_env::logger::info!(connector_response_type=?"file"); + Ok(types::RetrieveFileRouterData { response: Ok(types::RetrieveFileResponse { file_data: response.to_vec(), @@ -1737,6 +1740,7 @@ impl .response .parse_struct("ErrorResponse") .change_context(errors::ConnectorError::ResponseDeserializationFailed)?; + event_builder.map(|i| i.set_error_response_body(&response)); router_env::logger::info!(connector_response=?response); diff --git a/crates/router/src/connector/stripe/transformers.rs b/crates/router/src/connector/stripe/transformers.rs index 8c370317c62..a40abced13a 100644 --- a/crates/router/src/connector/stripe/transformers.rs +++ b/crates/router/src/connector/stripe/transformers.rs @@ -188,7 +188,7 @@ pub struct TokenRequest { #[derive(Debug, Eq, PartialEq, Deserialize, Serialize)] pub struct StripeTokenResponse { - pub id: String, + pub id: Secret<String>, pub object: String, } @@ -198,7 +198,7 @@ pub struct CustomerRequest { pub email: Option<Email>, pub phone: Option<Secret<String>>, pub name: Option<Secret<String>>, - pub source: Option<String>, + pub source: Option<Secret<String>>, } #[derive(Debug, Eq, PartialEq, Deserialize, Serialize)] @@ -324,7 +324,7 @@ pub struct StripeBlik { #[serde(rename = "payment_method_data[type]")] pub payment_method_data_type: StripePaymentMethodType, #[serde(rename = "payment_method_options[blik][code]")] - pub code: String, + pub code: Secret<String>, } #[derive(Debug, Eq, PartialEq, Serialize)] @@ -499,7 +499,7 @@ pub struct StripeApplePay { pub pk_token: Secret<String>, pub pk_token_instrument_name: String, pub pk_token_payment_network: String, - pub pk_token_transaction_id: String, + pub pk_token_transaction_id: Secret<String>, } #[derive(Debug, Eq, PartialEq, Serialize)] @@ -547,7 +547,7 @@ pub enum WechatClient { #[derive(Debug, Eq, PartialEq, Serialize)] pub struct GooglepayPayment { #[serde(rename = "payment_method_data[card][token]")] - pub token: String, + pub token: Secret<String>, #[serde(rename = "payment_method_data[type]")] pub payment_method_types: StripePaymentMethodType, } @@ -1536,9 +1536,9 @@ impl TryFrom<(&payments::WalletData, Option<types::PaymentMethodToken>)> .payment_method .network .to_owned(), - pk_token_transaction_id: applepay_data - .transaction_identifier - .to_owned(), + pk_token_transaction_id: Secret::new( + applepay_data.transaction_identifier.to_owned(), + ), }))); }; let pmd = apple_pay_decrypt_data @@ -1611,11 +1611,11 @@ impl TryFrom<&payments::BankRedirectData> for StripePaymentMethodData { payments::BankRedirectData::Blik { blik_code } => Ok(Self::BankRedirect( StripeBankRedirectData::StripeBlik(Box::new(StripeBlik { payment_method_data_type, - code: blik_code.clone().ok_or( + code: Secret::new(blik_code.clone().ok_or( errors::ConnectorError::MissingRequiredField { field_name: "blik_code", }, - )?, + )?), })), )), payments::BankRedirectData::Eps { bank_name, .. } => Ok(Self::BankRedirect( @@ -2042,7 +2042,7 @@ impl TryFrom<&types::ConnectorCustomerRouterData> for CustomerRequest { email: item.request.email.to_owned(), phone: item.request.phone.to_owned(), name: item.request.name.to_owned(), - source: item.request.preprocessing_id.to_owned(), + source: item.request.preprocessing_id.to_owned().map(Secret::new), }) } } @@ -2096,8 +2096,8 @@ pub struct PaymentIntentResponse { pub status: StripePaymentStatus, pub client_secret: Option<Secret<String>>, pub created: i32, - pub customer: Option<String>, - pub payment_method: Option<String>, + pub customer: Option<Secret<String>>, + pub payment_method: Option<Secret<String>>, pub description: Option<String>, pub statement_descriptor: Option<String>, pub statement_descriptor_suffix: Option<String>, @@ -2206,7 +2206,7 @@ pub struct StripeCharge { #[derive(Deserialize, Clone, Debug, Serialize)] pub struct StripeBankRedirectDetails { #[serde(rename = "generated_sepa_debit")] - attached_payment_method: Option<String>, + attached_payment_method: Option<Secret<String>>, } impl Deref for PaymentIntentSyncResponse { @@ -2308,7 +2308,7 @@ pub struct SetupIntentResponse { pub object: String, pub status: StripePaymentStatus, // Change to SetupStatus pub client_secret: Secret<String>, - pub customer: Option<String>, + pub customer: Option<Secret<String>>, pub payment_method: Option<String>, pub statement_descriptor: Option<String>, pub statement_descriptor_suffix: Option<String>, @@ -2327,7 +2327,7 @@ impl ForeignFrom<(Option<StripePaymentMethodOptions>, String)> for types::Mandat connector_mandate_id: payment_method_options.and_then(|options| match options { StripePaymentMethodOptions::Card { mandate_options, .. - } => mandate_options.map(|mandate_options| mandate_options.reference), + } => mandate_options.map(|mandate_options| mandate_options.reference.expose()), StripePaymentMethodOptions::Klarna {} | StripePaymentMethodOptions::Affirm {} | StripePaymentMethodOptions::AfterpayClearpay {} @@ -2369,7 +2369,10 @@ impl<F, T> }); let mandate_reference = item.response.payment_method.map(|pm| { - types::MandateReference::foreign_from((item.response.payment_method_options, pm)) + types::MandateReference::foreign_from(( + item.response.payment_method_options, + pm.expose(), + )) }); //Note: we might have to call retrieve_setup_intent to get the network_transaction_id in case its not sent in PaymentIntentResponse @@ -2488,14 +2491,19 @@ impl<F, T> Some(StripeChargeEnum::ChargeObject(charge)) => { match charge.payment_method_details { Some(StripePaymentMethodDetailsResponse::Bancontact { bancontact }) => { - bancontact.attached_payment_method.unwrap_or(pm) - } - Some(StripePaymentMethodDetailsResponse::Ideal { ideal }) => { - ideal.attached_payment_method.unwrap_or(pm) - } - Some(StripePaymentMethodDetailsResponse::Sofort { sofort }) => { - sofort.attached_payment_method.unwrap_or(pm) + bancontact + .attached_payment_method + .map(|attached_payment_method| attached_payment_method.expose()) + .unwrap_or(pm.expose()) } + Some(StripePaymentMethodDetailsResponse::Ideal { ideal }) => ideal + .attached_payment_method + .map(|attached_payment_method| attached_payment_method.expose()) + .unwrap_or(pm.expose()), + Some(StripePaymentMethodDetailsResponse::Sofort { sofort }) => sofort + .attached_payment_method + .map(|attached_payment_method| attached_payment_method.expose()) + .unwrap_or(pm.expose()), Some(StripePaymentMethodDetailsResponse::Blik) | Some(StripePaymentMethodDetailsResponse::Eps) | Some(StripePaymentMethodDetailsResponse::Fpx) @@ -2513,10 +2521,10 @@ impl<F, T> | Some(StripePaymentMethodDetailsResponse::Wechatpay) | Some(StripePaymentMethodDetailsResponse::Alipay) | Some(StripePaymentMethodDetailsResponse::CustomerBalance) - | None => pm, + | None => pm.expose(), } } - Some(StripeChargeEnum::ChargeId(_)) | None => pm, + Some(StripeChargeEnum::ChargeId(_)) | None => pm.expose(), }, )) }); @@ -2751,17 +2759,17 @@ pub struct StripeFinanicalInformation { #[derive(Clone, Debug, Eq, PartialEq, Deserialize, Serialize)] pub struct SepaFinancialDetails { - pub account_holder_name: String, - pub bic: String, - pub country: String, - pub iban: String, + pub account_holder_name: Secret<String>, + pub bic: Secret<String>, + pub country: Secret<String>, + pub iban: Secret<String>, } #[derive(Clone, Debug, Eq, PartialEq, Deserialize, Serialize)] pub struct BacsFinancialDetails { - pub account_holder_name: String, - pub account_number: String, - pub sort_code: String, + pub account_holder_name: Secret<String>, + pub account_number: Secret<String>, + pub sort_code: Secret<String>, } // REFUND : @@ -2962,7 +2970,7 @@ pub struct StripeBillingAddress { #[derive(Debug, Clone, serde::Deserialize, Eq, PartialEq)] pub struct StripeRedirectResponse { pub payment_intent: Option<String>, - pub payment_intent_client_secret: Option<String>, + pub payment_intent_client_secret: Option<Secret<String>>, pub source_redirect_slug: Option<String>, pub redirect_status: Option<StripePaymentStatus>, pub source_type: Option<Secret<String>>, @@ -3036,7 +3044,7 @@ pub struct LatestPaymentAttempt { // pub struct Card #[derive(serde::Serialize, serde::Deserialize, Clone, Debug, Default, Eq, PartialEq)] pub struct StripeMandateOptions { - reference: String, // Extendable, But only important field to be captured + reference: Secret<String>, // Extendable, But only important field to be captured } /// Represents the capture request body for stripe connector. #[derive(Debug, Serialize, Clone, Copy)] @@ -3238,7 +3246,7 @@ impl<F, T> ) -> Result<Self, Self::Error> { Ok(Self { response: Ok(types::PaymentsResponseData::TokenizationResponse { - token: item.response.id, + token: item.response.id.expose(), }), ..item.data }) @@ -3619,7 +3627,7 @@ pub struct Evidence { #[serde(rename = "evidence[access_activity_log]")] pub access_activity_log: Option<String>, #[serde(rename = "evidence[billing_address]")] - pub billing_address: Option<String>, + pub billing_address: Option<Secret<String>>, #[serde(rename = "evidence[cancellation_policy]")] pub cancellation_policy: Option<String>, #[serde(rename = "evidence[cancellation_policy_disclosure]")] @@ -3629,17 +3637,17 @@ pub struct Evidence { #[serde(rename = "evidence[customer_communication]")] pub customer_communication: Option<String>, #[serde(rename = "evidence[customer_email_address]")] - pub customer_email_address: Option<String>, + pub customer_email_address: Option<Secret<String, pii::EmailStrategy>>, #[serde(rename = "evidence[customer_name]")] - pub customer_name: Option<String>, + pub customer_name: Option<Secret<String>>, #[serde(rename = "evidence[customer_purchase_ip]")] - pub customer_purchase_ip: Option<String>, + pub customer_purchase_ip: Option<Secret<String, pii::IpAddress>>, #[serde(rename = "evidence[customer_signature]")] - pub customer_signature: Option<String>, + pub customer_signature: Option<Secret<String>>, #[serde(rename = "evidence[product_description]")] pub product_description: Option<String>, #[serde(rename = "evidence[receipt]")] - pub receipt: Option<String>, + pub receipt: Option<Secret<String>>, #[serde(rename = "evidence[refund_policy]")] pub refund_policy: Option<String>, #[serde(rename = "evidence[refund_policy_disclosure]")] @@ -3651,15 +3659,15 @@ pub struct Evidence { #[serde(rename = "evidence[service_documentation]")] pub service_documentation: Option<String>, #[serde(rename = "evidence[shipping_address]")] - pub shipping_address: Option<String>, + pub shipping_address: Option<Secret<String>>, #[serde(rename = "evidence[shipping_carrier]")] pub shipping_carrier: Option<String>, #[serde(rename = "evidence[shipping_date]")] pub shipping_date: Option<String>, #[serde(rename = "evidence[shipping_documentation]")] - pub shipping_documentation: Option<String>, + pub shipping_documentation: Option<Secret<String>>, #[serde(rename = "evidence[shipping_tracking_number]")] - pub shipping_tracking_number: Option<String>, + pub shipping_tracking_number: Option<Secret<String>>, #[serde(rename = "evidence[uncategorized_file]")] pub uncategorized_file: Option<String>, #[serde(rename = "evidence[uncategorized_text]")] @@ -3708,31 +3716,46 @@ impl TryFrom<&types::SubmitEvidenceRouterData> for Evidence { let submit_evidence_request_data = item.request.clone(); Ok(Self { access_activity_log: submit_evidence_request_data.access_activity_log, - billing_address: submit_evidence_request_data.billing_address, + billing_address: submit_evidence_request_data + .billing_address + .map(Secret::new), cancellation_policy: submit_evidence_request_data.cancellation_policy_provider_file_id, cancellation_policy_disclosure: submit_evidence_request_data .cancellation_policy_disclosure, cancellation_rebuttal: submit_evidence_request_data.cancellation_rebuttal, customer_communication: submit_evidence_request_data .customer_communication_provider_file_id, - customer_email_address: submit_evidence_request_data.customer_email_address, - customer_name: submit_evidence_request_data.customer_name, - customer_purchase_ip: submit_evidence_request_data.customer_purchase_ip, - customer_signature: submit_evidence_request_data.customer_signature_provider_file_id, + customer_email_address: submit_evidence_request_data + .customer_email_address + .map(Secret::new), + customer_name: submit_evidence_request_data.customer_name.map(Secret::new), + customer_purchase_ip: submit_evidence_request_data + .customer_purchase_ip + .map(Secret::new), + customer_signature: submit_evidence_request_data + .customer_signature_provider_file_id + .map(Secret::new), product_description: submit_evidence_request_data.product_description, - receipt: submit_evidence_request_data.receipt_provider_file_id, + receipt: submit_evidence_request_data + .receipt_provider_file_id + .map(Secret::new), refund_policy: submit_evidence_request_data.refund_policy_provider_file_id, refund_policy_disclosure: submit_evidence_request_data.refund_policy_disclosure, refund_refusal_explanation: submit_evidence_request_data.refund_refusal_explanation, service_date: submit_evidence_request_data.service_date, service_documentation: submit_evidence_request_data .service_documentation_provider_file_id, - shipping_address: submit_evidence_request_data.shipping_address, + shipping_address: submit_evidence_request_data + .shipping_address + .map(Secret::new), shipping_carrier: submit_evidence_request_data.shipping_carrier, shipping_date: submit_evidence_request_data.shipping_date, shipping_documentation: submit_evidence_request_data - .shipping_documentation_provider_file_id, - shipping_tracking_number: submit_evidence_request_data.shipping_tracking_number, + .shipping_documentation_provider_file_id + .map(Secret::new), + shipping_tracking_number: submit_evidence_request_data + .shipping_tracking_number + .map(Secret::new), uncategorized_file: submit_evidence_request_data.uncategorized_file_provider_file_id, uncategorized_text: submit_evidence_request_data.uncategorized_text, submit: true,
2024-02-16T09:28:14Z
## Type of Change <!-- Put an `x` in the boxes that apply --> - [ ] Bugfix - [ ] New feature - [x] Enhancement - [x] Refactoring - [ ] Dependency updates - [ ] Documentation - [ ] CI/CD ## Description <!-- Describe your changes in detail --> Mask pii information passed and received in the connector request and response for stripe, aci, adyen, airwallex and authorizedotnet ## Test Case Check if sensitive fields within connector request and response is masked in the click house for all these connectors 1. Aci and Adyen payment create ``` curl --location 'http://localhost: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": "StripeCustomer", "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://hs-payments-test.netlify.app/payments", "billing": { "address": { "line1": "1467", "line2": "Harrison Street", "line3": "Harrison Street", "city": "San Fransico", "state": "California", "zip": "94122", "country": "US" } }, "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_method": "card", "payment_method_data": { "card": { "card_number": "4917 6100 0000 0000", "card_exp_month": "03", "card_exp_year": "2030", "card_holder_name": "Joseph Doe", "card_cvc": "737" } }, "setup_future_usage": "off_session", "mandate_data": { "customer_acceptance": { "acceptance_type": "offline", "accepted_at": "1963-05-03T04:07:52.723Z", "online": { "ip_address": "13.232.74.226", "user_agent": "amet irure esse" } } , "mandate_type": { "multi_use": { "amount": 799, "currency": "USD" } } } }' ``` 2.ACI mandate payment ``` curl --location 'http://localhost:8080/payments' \ --header 'Content-Type: application/json' \ --header 'Accept: application/json' \ --header 'api-key:{}' \ --data '{ "amount": 700, "currency": "USD", "off_session": true, "confirm": true, "capture_method": "automatic", "description": "Initiated by merchant", "mandate_id": "man_Y214d8eLCfEpkyEmrN9s", "customer_id": "StripeCustomer", "billing": { "address": { "line1": "1467", "line2": "Harrison Street", "line3": "Harrison Street", "city": "San Fransico", "state": "California", "zip": "94122", "country": "US", "first_name": "John", "last_name": "Doe" } } }' ``` 3. Airwallex 3Ds ``` curl --location 'http://localhost:8080/payments' \ --header 'Content-Type: application/json' \ --header 'Accept: application/json' \ --header 'api-key:{{}}' \ --data-raw '{ "amount": 2000, "currency": "GBP", "confirm": true, "capture_method": "automatic", "capture_on": "2022-09-10T10:11:12Z", "customer_id": "StripeCustomer", "email": "abcdef123@gmail.com", "name": "John Doe", "phone": "999999999", "phone_country_code": "+65", "description": "Its my first payment request", "authentication_type": "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": "US" } }, "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_method": "card", "payment_method_data": { "card": { "card_number": "4012000300000088", "card_exp_month": "10", "card_exp_year": "2025", "card_holder_name": "Joseph Doe", "card_cvc": "123" } } }' ``` 4. Stripe Apple pay 5. Authorize.dot Mandate Payment and refund _Note: can't be tested, there is a known bug_ Check if all the sensitive data in the `masked_response` is masked ``` curl --location '{{base_url}}/analytics/v1/connector_event_logs?type=Payment&payment_id={{payment_id}}' \ --header 'sec-ch-ua: "Not A(Brand";v="99", "Google Chrome";v="121", "Chromium";v="121"' \ --header 'sec-ch-ua-mobile: ?0' \ --header 'authorization: Bearer JWT_token' \ --header 'User-Agent: Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/121.0.0.0 Safari/537.36' \ --header 'Content-Type: application/json' \ --header 'Referer: https://integ.hyperswitch.io/' \ --header 'api-key: {{api-key}}' \ --header 'sec-ch-ua-platform: "macOS"' ``` 1. Response for ACI - payment create ``` "masked_response\":\"{\\\"id\\\":\\\"8ac7a4a08de5447e018de582bb107592\\\",\\\"registrationId\\\":\\\"*** alloc::string::String ***\\\",\\\"ndc\\\":\\\"8ac7a4c97d044305017d053142b009ed_6c787329b2284b9689b010b7ee2ef803\\\",\\\"timestamp\\\":\\\"2024-02-26 13:02:46+0000\\\",\\\"buildNumber\\\":\\\"65a0c4e5cfd8d1606f555dfc25cfe3ab19688806@2024-02-23 04:43:28 +0000\\\",\\\"result\\\":{\\\"code\\\":\\\"000.100.110\\\",\\\"description\\\":\\\"Request successfully processed in 'Merchant in Integrator Test Mode'\\\",\\\"parameterErrors\\\":null} ``` 3. Response for ACI - mandate payment ``` \"masked_response\":\"{\\\"id\\\":\\\"8ac7a49f8de5402f018de58580910358\\\",\\\"registrationId\\\":null,\\\"ndc\\\":\\\"8ac7a4c97d044305017d053142b009ed_0ba46b44820f4f81b7876e9e8efeccf0\\\",\\\"timestamp\\\":\\\"2024-02-26 13:05:48+0000\\\",\\\"buildNumber\\\":\\\"65a0c4e5cfd8d1606f555dfc25cfe3ab19688806@2024-02-23 04:43:28 +0000\\\",\\\"result\\\":{\\\"code\\\":\\\"000.100.110\\\",\\\"description\\\":\\\"Request successfully processed in 'Merchant in Integrator Test Mode'\\\",\\\"parameterErrors\\\":null},\\\"redirect\\\":null} ``` 6. Response for Adyen - mandate payment ``` masked_response\":\"{\\\"pspReference\\\":\\\"N5SF6G38NXTQ7RT5\\\",\\\"resultCode\\\":\\\"Authorised\\\",\\\"amount\\\":{\\\"currency\\\":\\\"USD\\\",\\\"value\\\":10000},\\\"merchantReference\\\":\\\"pay_mf45Xy9Of4vVcMEIPqGj_1\\\",\\\"refusalReason\\\":null,\\\"refusalReasonCode\\\":null,\\\"additionalData\\\":{\\\"authorisationType\\\":null,\\\"manualCapture\\\":null,\\\"recurringProcessingModel\\\":\\\"UnscheduledCardOnFile\\\",\\\"recurring.recurringDetailReference\\\":\\\"*** alloc::string::String ***\\\",\\\"recurring.shopperReference\\\":\\\"merchant_1709011022_StripeCustomer\\\",\\\"networkTxReference\\\":\\\"*** alloc::string::String ***\\\",\\\"payoutEligible\\\":null,\\\"fundsAvailability\\\":null} ``` _Note: There is a known bug in adyen recurring mandate payment_ 7.Response for Airwallex 3DS ``` {\\\"status\\\":\\\"REQUIRES_CUSTOMER_ACTION\\\",\\\"id\\\":\\\"int_hkdm5rvp6gtsl5v8q2w\\\",\\\"amount\\\":20.0,\\\"payment_consent_id\\\":null,\\\"next_action\\\":{\\\"url\\\":\\\"https://pci-api-demo.airwallex.com/pa/card3ds/hk/three-ds-method/redirect/start?key=1999b53e-ff3b-4b6e-aeaf-28ba23f4767b\\\",\\\"method\\\":\\\"POST\\\",\\\"data\\\":{\\\"JWT\\\":null,\\\"threeDSMethodData\\\":\\\"*** alloc::string::String ***\\\",\\\"token\\\":\\\"*** alloc::string::String ***\\\",\\\"provider\\\":null,\\\"version\\\":null},\\\"stage\\\":\\\"WAITING_DEVICE_DATA_COLLECTION\\\"}} ``` ## 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 - [ ] I added a [CHANGELOG](/CHANGELOG.md) entry if applicable
df739a302b062277647afe5c3888015272fdc2cf
juspay/hyperswitch
juspay__hyperswitch-3748
Bug: [FEATURE]: add `offset` field to mandates list ### Feature Description The [mandates list](https://github.com/juspay/hyperswitch/blob/54c0b218d9f20c6388dde0f30ea525011cdad573/crates/router/src/routes/mandates.rs#L114) endpoint currently has no field to specify `offset`, which would skip certain number of entries from the start. This is necessary in order to provide pagination support. ### Possible Implementation accept a field called `offset` which specifies the number of items to skip from the start. This would be similar to the `payments_list` pagination. Refer [here](https://github.com/juspay/hyperswitch/blob/54c0b218d9f20c6388dde0f30ea525011cdad573/crates/router/src/routes/payments.rs#L868) ### 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 7c20a902d28..bd5c5b5a1a0 100644 --- a/crates/api_models/src/mandates.rs +++ b/crates/api_models/src/mandates.rs @@ -87,6 +87,8 @@ pub struct MandateCardDetails { pub struct MandateListConstraints { /// limit on the number of objects to return pub limit: Option<i64>, + /// offset on the number of objects to return + pub offset: Option<i64>, /// status of the mandate pub mandate_status: Option<api_enums::MandateStatus>, /// connector linked to mandate diff --git a/crates/router/src/db/mandate.rs b/crates/router/src/db/mandate.rs index eb2859e57e1..936344f5af5 100644 --- a/crates/router/src/db/mandate.rs +++ b/crates/router/src/db/mandate.rs @@ -262,14 +262,22 @@ impl MandateInterface for MockDb { checker }); + #[allow(clippy::as_conversions)] + let offset = (if mandate_constraints.offset.unwrap_or(0) < 0 { + 0 + } else { + mandate_constraints.offset.unwrap_or(0) + }) as usize; + let mandates: Vec<storage::Mandate> = if let Some(limit) = mandate_constraints.limit { #[allow(clippy::as_conversions)] mandates_iter + .skip(offset) .take((if limit < 0 { 0 } else { limit }) as usize) .cloned() .collect() } else { - mandates_iter.cloned().collect() + mandates_iter.skip(offset).cloned().collect() }; Ok(mandates) } diff --git a/crates/router/src/routes/mandates.rs b/crates/router/src/routes/mandates.rs index 1203b766cbb..3e47d78da8a 100644 --- a/crates/router/src/routes/mandates.rs +++ b/crates/router/src/routes/mandates.rs @@ -101,6 +101,7 @@ pub async fn revoke_mandate( ("created_time.gt" = Option<PrimitiveDateTime>, Query, description = "Time greater than the mandate created time"), ("created_time.lte" = Option<PrimitiveDateTime>, Query, description = "Time less than or equals to the mandate created time"), ("created_time.gte" = Option<PrimitiveDateTime>, Query, description = "Time greater than or equals to the mandate created time"), + ("offset" = Option<i64>, Query, description = "The number of Mandate Objects to skip when retrieving the list Mandates."), ), responses( (status = 200, description = "The mandate list was retrieved successfully", body = Vec<MandateResponse>), diff --git a/crates/router/src/types/storage/mandate.rs b/crates/router/src/types/storage/mandate.rs index 32c0798e95c..05a5733053f 100644 --- a/crates/router/src/types/storage/mandate.rs +++ b/crates/router/src/types/storage/mandate.rs @@ -54,6 +54,9 @@ impl MandateDbExt for Mandate { if let Some(limit) = mandate_list_constraints.limit { filter = filter.limit(limit); } + if let Some(offset) = mandate_list_constraints.offset { + filter = filter.offset(offset); + } logger::debug!(query = %diesel::debug_query::<diesel::pg::Pg, _>(&filter).to_string());
2024-03-03T10:30:15Z
## 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 offset to mandate list endpoint. Closes #3748 ### 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). --> ## 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 10 mandates. - Use the below curl to list the first 5 mandates. ```bash curl --location 'http://localhost:8080/mandates/list?limit=5' \ --header 'api-key: dev_dg0YfZam6V6VM2KBPFLr0olm6kGM3QojUE9Ba6f8Gzzi7IIAnkN4fyfKsyc55pB4' ``` - Use the below curl to list next 5 mandates. ```bash curl --location 'http://localhost:8080/mandates/list?limit=5&offset=5' \ --header 'api-key: dev_dg0YfZam6V6VM2KBPFLr0olm6kGM3QojUE9Ba6f8Gzzi7IIAnkN4fyfKsyc55pB4' ``` ## 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 - [ ] I added a [CHANGELOG](/CHANGELOG.md) entry if applicable
a2f179350a7e5819db1b6088b75ff3a7b1ad9bad
- Create 10 mandates. - Use the below curl to list the first 5 mandates. ```bash curl --location 'http://localhost:8080/mandates/list?limit=5' \ --header 'api-key: dev_dg0YfZam6V6VM2KBPFLr0olm6kGM3QojUE9Ba6f8Gzzi7IIAnkN4fyfKsyc55pB4' ``` - Use the below curl to list next 5 mandates. ```bash curl --location 'http://localhost:8080/mandates/list?limit=5&offset=5' \ --header 'api-key: dev_dg0YfZam6V6VM2KBPFLr0olm6kGM3QojUE9Ba6f8Gzzi7IIAnkN4fyfKsyc55pB4' ```
juspay/hyperswitch
juspay__hyperswitch-3747
Bug: Storing MIT details in PM table instead of Mandate table Move the connector recurring payment information (`connector_mandate_id`) to the PM table. - Create a column for storing recurring_payment_details in PM table - The connector_mandate_id to be stored against he merchant_connector_id - This columns will hold a simple JSON in the following format `{ <MCA_ID> : <connector_mandate_id>, <MCA_ID> : <connector_mandate_id> . . }`
diff --git a/crates/router/src/core/payment_methods/cards.rs b/crates/router/src/core/payment_methods/cards.rs index 4fdf957c842..5b059f255f9 100644 --- a/crates/router/src/core/payment_methods/cards.rs +++ b/crates/router/src/core/payment_methods/cards.rs @@ -84,6 +84,7 @@ pub async fn create_payment_method( customer_acceptance: Option<serde_json::Value>, payment_method_data: Option<Encryption>, key_store: &domain::MerchantKeyStore, + connector_mandate_details: Option<serde_json::Value>, ) -> errors::CustomResult<storage::PaymentMethod, errors::ApiErrorResponse> { db.find_customer_by_customer_id_merchant_id(customer_id, merchant_id, key_store) .await @@ -101,6 +102,7 @@ pub async fn create_payment_method( scheme: req.card_network.clone(), metadata: pm_metadata.map(masking::Secret::new), payment_method_data, + connector_mandate_details, customer_acceptance: customer_acceptance.map(masking::Secret::new), ..storage::PaymentMethodNew::default() }) @@ -187,6 +189,7 @@ pub async fn get_or_insert_payment_method( resp.metadata.clone().map(|val| val.expose()), None, locker_id, + None, ) .await } else { @@ -372,6 +375,7 @@ pub async fn add_payment_method( pm_metadata.cloned(), None, locker_id, + None, ) .await?; } @@ -391,6 +395,7 @@ pub async fn insert_payment_method( pm_metadata: Option<serde_json::Value>, customer_acceptance: Option<serde_json::Value>, locker_id: Option<String>, + connector_mandate_details: Option<serde_json::Value>, ) -> errors::RouterResult<diesel_models::PaymentMethod> { let pm_card_details = resp .card @@ -408,6 +413,7 @@ pub async fn insert_payment_method( customer_acceptance, pm_data_encrypted, key_store, + connector_mandate_details, ) .await } @@ -1249,12 +1255,16 @@ pub async fn list_payment_methods( }) .await .transpose()?; - + let setup_future_usage = payment_intent.as_ref().and_then(|pi| pi.setup_future_usage); let payment_type = payment_attempt.as_ref().map(|pa| { let amount = api::Amount::from(pa.amount); let mandate_type = if pa.mandate_id.is_some() { Some(api::MandateTransactionType::RecurringMandateTransaction) - } else if pa.mandate_details.is_some() { + } else if pa.mandate_details.is_some() + || setup_future_usage + .map(|future_usage| future_usage == api_enums::FutureUsage::OffSession) + .unwrap_or(false) + { Some(api::MandateTransactionType::NewMandateTransaction) } else { None diff --git a/crates/router/src/core/payments/tokenization.rs b/crates/router/src/core/payments/tokenization.rs index 943550ef434..c449b76c608 100644 --- a/crates/router/src/core/payments/tokenization.rs +++ b/crates/router/src/core/payments/tokenization.rs @@ -1,3 +1,5 @@ +use std::collections::HashMap; + use api_models::payment_methods::PaymentMethodsData; use common_enums::PaymentMethod; use common_utils::{ @@ -42,7 +44,7 @@ where FData: mandate::MandateBehaviour, { match resp.response { - Ok(_) => { + Ok(responses) => { let db = &*state.store; let token_store = state .conf @@ -84,6 +86,22 @@ where .change_context(errors::ApiErrorResponse::InternalServerError) .attach_printable("Unable to serialize customer acceptance to value")?; + let connector_mandate_details = if resp.request.get_setup_mandate_details().is_none() + && resp + .request + .get_setup_future_usage() + .map(|future_usage| future_usage == storage_enums::FutureUsage::OffSession) + .unwrap_or(false) + { + add_connector_mandate_details_in_payment_method(responses, connector) + } else { + None + } + .map(|connector_mandate_data| connector_mandate_data.encode_to_value()) + .transpose() + .change_context(errors::ApiErrorResponse::InternalServerError) + .attach_printable("Unable to serialize customer acceptance to value")?; + let pm_id = if resp.request.get_setup_future_usage().is_some() && customer_acceptance.is_some() { @@ -194,6 +212,7 @@ where customer_acceptance, pm_data_encrypted, key_store, + connector_mandate_details, ) .await } else { @@ -256,6 +275,7 @@ where resp.metadata.clone().map(|val| val.expose()), customer_acceptance, locker_id, + connector_mandate_details, ) .await } else { @@ -372,6 +392,7 @@ where customer_acceptance, pm_data_encrypted, key_store, + connector_mandate_details, ) .await?; } @@ -623,3 +644,30 @@ pub async fn add_payment_method_token<F: Clone, T: types::Tokenizable + Clone>( _ => Ok(None), } } + +fn add_connector_mandate_details_in_payment_method( + resp: types::PaymentsResponseData, + connector: &api::ConnectorData, +) -> Option<storage::PaymentsMandateReference> { + let mut mandate_details = HashMap::new(); + + let connector_mandate_id = match resp { + types::PaymentsResponseData::TransactionResponse { + mandate_reference, .. + } => { + if let Some(mandate_ref) = mandate_reference { + mandate_ref.connector_mandate_id.clone() + } else { + None + } + } + _ => None, + }; + + if let Some(mca_id) = connector.merchant_connector_id.clone() { + mandate_details.insert(mca_id, connector_mandate_id); + Some(storage::PaymentsMandateReference(mandate_details)) + } else { + None + } +} diff --git a/crates/router/src/core/payouts/helpers.rs b/crates/router/src/core/payouts/helpers.rs index 7005e955dff..9fd7458155a 100644 --- a/crates/router/src/core/payouts/helpers.rs +++ b/crates/router/src/core/payouts/helpers.rs @@ -385,6 +385,7 @@ pub async fn save_payout_data_to_locker( None, card_details_encrypted, key_store, + None, ) .await?; diff --git a/crates/router/src/types/storage/payment_method.rs b/crates/router/src/types/storage/payment_method.rs index a787a4d932c..dee7a8d452f 100644 --- a/crates/router/src/types/storage/payment_method.rs +++ b/crates/router/src/types/storage/payment_method.rs @@ -1,9 +1,10 @@ +use std::collections::HashMap; + use api_models::payment_methods; pub use diesel_models::payment_method::{ PaymentMethod, PaymentMethodNew, PaymentMethodUpdate, PaymentMethodUpdateInternal, TokenizeCoreWorkflow, }; - #[derive(Debug, Clone, serde::Serialize, serde::Deserialize)] #[serde(rename_all = "snake_case")] pub enum PaymentTokenKind { @@ -52,3 +53,6 @@ impl PaymentTokenData { Self::TemporaryGeneric(GenericTokenData { token }) } } + +#[derive(Debug, Clone, serde::Serialize, serde::Deserialize)] +pub struct PaymentsMandateReference(pub HashMap<String, Option<String>>);
2024-03-01T07:56:04Z
## Type of Change <!-- Put an `x` in the boxes that apply --> - [ ] Bugfix - [x] New feature - [ ] Enhancement - [ ] Refactoring - [ ] Dependency updates - [ ] Documentation - [ ] CI/CD ## Description store connector_mandate_details in PaymentMethods table, if its a MIT payment, i.e, if its off_session and mandate_type is not present. Also If we do the `LIstPaymentMethodforMerchnats` we get the payment_type as setup_mandate ### 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 an MA and an MCA with cybersource(cause currently creating a mandate with 0 dollars and just off_session,i.e,MIT is just supported by cybersource) -Make a zero dollar payment, with off_session and no mandate_type ``` curl --location 'http://localhost:8080/payments' \ --header 'Content-Type: application/json' \ --header 'Accept: application/json' \ --header 'api-key: dev_O7Znp5PhvGpSeE22Hxn4K8snHW6ObRfbA8R1isvLhUXpJRGHOINvlGufM4mGDAqj' \ --data-raw ' {"amount": 0, "currency": "USD", "confirm": false, "capture_method": "automatic", "authentication_type": "no_three_ds", "customer_id": "q7cc", "email": "something@gmail.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" } }, "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" } }, "metadata": { "order_details": { "product_name": "Apple iphone 15", "quantity": 1 } }, "business_country": "US", "business_label": "default", "setup_future_usage": "off_session" }' ``` ![Screenshot 2024-03-05 at 1 20 20 PM](https://github.com/juspay/hyperswitch/assets/55580080/a2975f96-f1f1-4aeb-8b56-ece43ed23e41) - Do a LIstPaymentMethodforMerchnats , the payment_type = 'setup_mandate' ![Screenshot 2024-03-05 at 1 20 00 PM](https://github.com/juspay/hyperswitch/assets/55580080/6e1538b8-5dc9-4a59-bd51-a85b9b0e3687) - Confirm the payment_with customer_acceptance the card will be save and a mandate would be saved in the database against that payment_method ``` curl --location 'http://localhost:8080/payments/pay_847yeh8NWPsQJRr29528/confirm' \ --header 'Content-Type: application/json' \ --header 'Accept: application/json' \ --header 'api-key: dev_O7Znp5PhvGpSeE22Hxn4K8snHW6ObRfbA8R1isvLhUXpJRGHOINvlGufM4mGDAqj' \ --data '{ "confirm": true, "payment_type": "setup_mandate", "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_type": "debit", "payment_method_data": { "card": { "card_number":"4242424242424242", "card_exp_month": "11", "card_exp_year": "2040", "card_holder_name": "AKA", "card_cvc": "123", "nick_name": "HELO" } } }' ``` <img width="974" alt="Screenshot 2024-03-05 at 1 22 58 PM" src="https://github.com/juspay/hyperswitch/assets/55580080/8ebddf69-344b-4d17-ab68-6131bc79662a"> -It'll be stored as a HashMap<merchant_connector_id, connector_mandate_id> <img width="1728" alt="Screenshot 2024-03-05 at 1 45 50 AM" src="https://github.com/juspay/hyperswitch/assets/55580080/34305f6b-ff3b-4910-b3eb-9cca2836efe7"> ## 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 - [ ] I added a [CHANGELOG](/CHANGELOG.md) entry if applicable
a1fd36a1abea4d400386a00ccf182dfe9da5bcda
- Create an MA and an MCA with cybersource(cause currently creating a mandate with 0 dollars and just off_session,i.e,MIT is just supported by cybersource) -Make a zero dollar payment, with off_session and no mandate_type ``` curl --location 'http://localhost:8080/payments' \ --header 'Content-Type: application/json' \ --header 'Accept: application/json' \ --header 'api-key: dev_O7Znp5PhvGpSeE22Hxn4K8snHW6ObRfbA8R1isvLhUXpJRGHOINvlGufM4mGDAqj' \ --data-raw ' {"amount": 0, "currency": "USD", "confirm": false, "capture_method": "automatic", "authentication_type": "no_three_ds", "customer_id": "q7cc", "email": "something@gmail.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" } }, "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" } }, "metadata": { "order_details": { "product_name": "Apple iphone 15", "quantity": 1 } }, "business_country": "US", "business_label": "default", "setup_future_usage": "off_session" }' ``` ![Screenshot 2024-03-05 at 1 20 20 PM](https://github.com/juspay/hyperswitch/assets/55580080/a2975f96-f1f1-4aeb-8b56-ece43ed23e41) - Do a LIstPaymentMethodforMerchnats , the payment_type = 'setup_mandate' ![Screenshot 2024-03-05 at 1 20 00 PM](https://github.com/juspay/hyperswitch/assets/55580080/6e1538b8-5dc9-4a59-bd51-a85b9b0e3687) - Confirm the payment_with customer_acceptance the card will be save and a mandate would be saved in the database against that payment_method ``` curl --location 'http://localhost:8080/payments/pay_847yeh8NWPsQJRr29528/confirm' \ --header 'Content-Type: application/json' \ --header 'Accept: application/json' \ --header 'api-key: dev_O7Znp5PhvGpSeE22Hxn4K8snHW6ObRfbA8R1isvLhUXpJRGHOINvlGufM4mGDAqj' \ --data '{ "confirm": true, "payment_type": "setup_mandate", "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_type": "debit", "payment_method_data": { "card": { "card_number":"4242424242424242", "card_exp_month": "11", "card_exp_year": "2040", "card_holder_name": "AKA", "card_cvc": "123", "nick_name": "HELO" } } }' ``` <img width="974" alt="Screenshot 2024-03-05 at 1 22 58 PM" src="https://github.com/juspay/hyperswitch/assets/55580080/8ebddf69-344b-4d17-ab68-6131bc79662a"> -It'll be stored as a HashMap<merchant_connector_id, connector_mandate_id> <img width="1728" alt="Screenshot 2024-03-05 at 1 45 50 AM" src="https://github.com/juspay/hyperswitch/assets/55580080/34305f6b-ff3b-4910-b3eb-9cca2836efe7">
juspay/hyperswitch
juspay__hyperswitch-3744
Bug: Setup future usage validations for recurring payments (CIT and MIT) Setup Future Usage parameter to be used for saving PM for both CIT and MIT recurring payments. - If on-session, save card in locker and add PM for future payments based on (payment success + customer acceptance) - If off-session, save card in locker set up for MITs with the connector and add MIT details to the PM table based on (customer acceptance) - If customer acceptance is null in both cases, do not save the PM NOTE: setup_future_usage : on-session will now come from the payments/create request and conveys the merchant's intention of saving it for future CIT payments. In payments/confirm call the customer acceptance of the on-session request will be provided.
diff --git a/crates/api_models/src/payments.rs b/crates/api_models/src/payments.rs index 9a3afd2f0ff..d48be04b763 100644 --- a/crates/api_models/src/payments.rs +++ b/crates/api_models/src/payments.rs @@ -348,9 +348,12 @@ pub struct PaymentsRequest { #[remove_in(PaymentsUpdateRequest, PaymentsCreateRequest)] pub client_secret: Option<String>, - /// Passing this object during payments creates a mandate. The mandate_type sub object is passed by the server usually and the customer_acceptance sub object is usually passed by the SDK or client + /// Passing this object during payments creates a mandate. The mandate_type sub object is passed by the server. pub mandate_data: Option<MandateData>, + /// Passing this object during payments confirm . The customer_acceptance sub object is usually passed by the SDK or client + pub customer_acceptance: Option<CustomerAcceptance>, + /// A unique identifier to link the payment to a mandate. To do Recurring payments after a mandate has been created, pass the mandate_id instead of payment_method_data #[schema(max_length = 255, example = "mandate_iwer89rnjef349dni3")] #[remove_in(PaymentsUpdateRequest)] diff --git a/crates/common_enums/src/enums.rs b/crates/common_enums/src/enums.rs index 6b25b692c12..dfa98634e27 100644 --- a/crates/common_enums/src/enums.rs +++ b/crates/common_enums/src/enums.rs @@ -1143,8 +1143,8 @@ pub enum IntentStatus { #[serde(rename_all = "snake_case")] #[strum(serialize_all = "snake_case")] pub enum FutureUsage { - #[default] OffSession, + #[default] OnSession, } diff --git a/crates/data_models/src/mandates.rs b/crates/data_models/src/mandates.rs index b4478f84ee9..fa22a4e57d5 100644 --- a/crates/data_models/src/mandates.rs +++ b/crates/data_models/src/mandates.rs @@ -113,6 +113,16 @@ impl From<ApiCustomerAcceptance> for CustomerAcceptance { } } +impl From<CustomerAcceptance> for ApiCustomerAcceptance { + fn from(value: CustomerAcceptance) -> Self { + Self { + acceptance_type: value.acceptance_type.into(), + accepted_at: value.accepted_at, + online: value.online.map(|d| d.into()), + } + } +} + impl From<ApiAcceptanceType> for AcceptanceType { fn from(value: ApiAcceptanceType) -> Self { match value { @@ -121,6 +131,14 @@ impl From<ApiAcceptanceType> for AcceptanceType { } } } +impl From<AcceptanceType> for ApiAcceptanceType { + fn from(value: AcceptanceType) -> Self { + match value { + AcceptanceType::Online => Self::Online, + AcceptanceType::Offline => Self::Offline, + } + } +} impl From<ApiOnlineMandate> for OnlineMandate { fn from(value: ApiOnlineMandate) -> Self { @@ -130,6 +148,14 @@ impl From<ApiOnlineMandate> for OnlineMandate { } } } +impl From<OnlineMandate> for ApiOnlineMandate { + fn from(value: OnlineMandate) -> Self { + Self { + ip_address: value.ip_address, + user_agent: value.user_agent, + } + } +} impl CustomerAcceptance { pub fn get_ip_address(&self) -> Option<String> { diff --git a/crates/router/src/core/mandate.rs b/crates/router/src/core/mandate.rs index ec3bb7e4299..d07a8814c88 100644 --- a/crates/router/src/core/mandate.rs +++ b/crates/router/src/core/mandate.rs @@ -495,4 +495,5 @@ pub trait MandateBehaviour { fn set_mandate_id(&mut self, new_mandate_id: Option<api_models::payments::MandateIds>); fn get_payment_method_data(&self) -> api_models::payments::PaymentMethodData; fn get_setup_mandate_details(&self) -> Option<&data_models::mandates::MandateData>; + fn get_customer_acceptance(&self) -> Option<api_models::payments::CustomerAcceptance>; } diff --git a/crates/router/src/core/payment_methods/cards.rs b/crates/router/src/core/payment_methods/cards.rs index ce7f48405e2..4fdf957c842 100644 --- a/crates/router/src/core/payment_methods/cards.rs +++ b/crates/router/src/core/payment_methods/cards.rs @@ -81,6 +81,7 @@ pub async fn create_payment_method( locker_id: Option<String>, merchant_id: &str, pm_metadata: Option<serde_json::Value>, + customer_acceptance: Option<serde_json::Value>, payment_method_data: Option<Encryption>, key_store: &domain::MerchantKeyStore, ) -> errors::CustomResult<storage::PaymentMethod, errors::ApiErrorResponse> { @@ -100,6 +101,7 @@ pub async fn create_payment_method( scheme: req.card_network.clone(), metadata: pm_metadata.map(masking::Secret::new), payment_method_data, + customer_acceptance: customer_acceptance.map(masking::Secret::new), ..storage::PaymentMethodNew::default() }) .await @@ -183,6 +185,7 @@ pub async fn get_or_insert_payment_method( &merchant_account.merchant_id, customer_id, resp.metadata.clone().map(|val| val.expose()), + None, locker_id, ) .await @@ -367,6 +370,7 @@ pub async fn add_payment_method( merchant_id, &customer_id, pm_metadata.cloned(), + None, locker_id, ) .await?; @@ -385,6 +389,7 @@ pub async fn insert_payment_method( merchant_id: &str, customer_id: &str, pm_metadata: Option<serde_json::Value>, + customer_acceptance: Option<serde_json::Value>, locker_id: Option<String>, ) -> errors::RouterResult<diesel_models::PaymentMethod> { let pm_card_details = resp @@ -400,6 +405,7 @@ pub async fn insert_payment_method( locker_id, merchant_id, pm_metadata, + customer_acceptance, pm_data_encrypted, key_store, ) diff --git a/crates/router/src/core/payments.rs b/crates/router/src/core/payments.rs index 7e8fa2ae44d..88a437a087e 100644 --- a/crates/router/src/core/payments.rs +++ b/crates/router/src/core/payments.rs @@ -15,7 +15,7 @@ use std::{fmt::Debug, marker::PhantomData, ops::Deref, time::Instant, vec::IntoI use api_models::{self, enums, payments::HeaderPayload}; use common_utils::{ext_traits::AsyncExt, pii, types::Surcharge}; -use data_models::mandates::MandateData; +use data_models::mandates::{CustomerAcceptance, MandateData}; use diesel_models::{ephemeral_key, fraud_check::FraudCheck}; use error_stack::{IntoReport, ResultExt}; use futures::future::join_all; @@ -2049,6 +2049,7 @@ where pub mandate_connector: Option<MandateConnectorDetails>, pub currency: storage_enums::Currency, pub setup_mandate: Option<MandateData>, + pub customer_acceptance: Option<CustomerAcceptance>, pub address: PaymentAddress, pub token: Option<String>, pub confirm: Option<bool>, diff --git a/crates/router/src/core/payments/flows/authorize_flow.rs b/crates/router/src/core/payments/flows/authorize_flow.rs index d7d122c3252..cc2540aa221 100644 --- a/crates/router/src/core/payments/flows/authorize_flow.rs +++ b/crates/router/src/core/payments/flows/authorize_flow.rs @@ -99,7 +99,6 @@ impl Feature<api::Authorize, types::PaymentsAuthorizeData> for types::PaymentsAu merchant_account, self.request.payment_method_type, key_store, - is_mandate, )) .await?; Ok(mandate::mandate_procedure( @@ -131,7 +130,6 @@ impl Feature<api::Authorize, types::PaymentsAuthorizeData> for types::PaymentsAu &merchant_account, self.request.payment_method_type, &key_store, - is_mandate, )) .await; @@ -294,6 +292,9 @@ impl mandate::MandateBehaviour for types::PaymentsAuthorizeData { fn set_mandate_id(&mut self, new_mandate_id: Option<api_models::payments::MandateIds>) { self.mandate_id = new_mandate_id; } + fn get_customer_acceptance(&self) -> Option<api_models::payments::CustomerAcceptance> { + self.customer_acceptance.clone().map(From::from) + } } pub async fn authorize_preprocessing_steps<F: Clone>( diff --git a/crates/router/src/core/payments/flows/setup_mandate_flow.rs b/crates/router/src/core/payments/flows/setup_mandate_flow.rs index 3f43204b986..71d43989336 100644 --- a/crates/router/src/core/payments/flows/setup_mandate_flow.rs +++ b/crates/router/src/core/payments/flows/setup_mandate_flow.rs @@ -98,7 +98,7 @@ impl Feature<api::SetupMandate, types::SetupMandateRequestData> for types::Setup ) .await .to_setup_mandate_failed_response()?; - let is_mandate = resp.request.setup_mandate_details.is_some(); + let pm_id = Box::pin(tokenization::save_payment_method( state, connector, @@ -107,7 +107,6 @@ impl Feature<api::SetupMandate, types::SetupMandateRequestData> for types::Setup merchant_account, self.request.payment_method_type, key_store, - is_mandate, )) .await?; mandate::mandate_procedure( @@ -234,8 +233,6 @@ impl types::SetupMandateRouterData { let payment_method_type = self.request.payment_method_type; - let is_mandate = resp.request.setup_mandate_details.is_some(); - let pm_id = Box::pin(tokenization::save_payment_method( state, connector, @@ -244,7 +241,6 @@ impl types::SetupMandateRouterData { merchant_account, payment_method_type, key_store, - is_mandate, )) .await?; @@ -320,7 +316,6 @@ impl types::SetupMandateRouterData { ) .await .to_setup_mandate_failed_response()?; - let is_mandate = resp.request.setup_mandate_details.is_some(); let pm_id = Box::pin(tokenization::save_payment_method( state, connector, @@ -329,7 +324,6 @@ impl types::SetupMandateRouterData { merchant_account, self.request.payment_method_type, key_store, - is_mandate, )) .await?; let mandate = state @@ -430,6 +424,9 @@ impl mandate::MandateBehaviour for types::SetupMandateRequestData { fn get_setup_mandate_details(&self) -> Option<&data_models::mandates::MandateData> { self.setup_mandate_details.as_ref() } + fn get_customer_acceptance(&self) -> Option<api_models::payments::CustomerAcceptance> { + self.customer_acceptance.clone().map(From::from) + } } impl TryFrom<types::SetupMandateRequestData> for types::PaymentMethodTokenizationData { diff --git a/crates/router/src/core/payments/helpers.rs b/crates/router/src/core/payments/helpers.rs index d711bca7ab4..f0a5e38cca4 100644 --- a/crates/router/src/core/payments/helpers.rs +++ b/crates/router/src/core/payments/helpers.rs @@ -825,16 +825,6 @@ fn validate_new_mandate_request( .clone() .get_required_value("mandate_data")?; - if api_enums::FutureUsage::OnSession - == req - .setup_future_usage - .get_required_value("setup_future_usage")? - { - Err(report!(errors::ApiErrorResponse::PreconditionFailed { - message: "`setup_future_usage` must be `off_session` for mandates".into() - }))? - }; - // Only use this validation if the customer_acceptance is present if mandate_data .customer_acceptance @@ -3855,3 +3845,17 @@ pub fn validate_session_expiry(session_expiry: u32) -> Result<(), errors::ApiErr Ok(()) } } + +// This function validates the mandate_data with its setup_future_usage +pub fn validate_mandate_data_and_future_usage( + setup_future_usages: Option<api_enums::FutureUsage>, + mandate_details_present: bool, +) -> Result<(), errors::ApiErrorResponse> { + if Some(api_enums::FutureUsage::OnSession) == setup_future_usages && mandate_details_present { + Err(errors::ApiErrorResponse::PreconditionFailed { + message: "`setup_future_usage` must be `off_session` for mandates".into(), + }) + } else { + Ok(()) + } +} diff --git a/crates/router/src/core/payments/operations/payment_approve.rs b/crates/router/src/core/payments/operations/payment_approve.rs index caca29d8e2a..a38c7bbdd3c 100644 --- a/crates/router/src/core/payments/operations/payment_approve.rs +++ b/crates/router/src/core/payments/operations/payment_approve.rs @@ -147,6 +147,7 @@ impl<F: Send + Clone, Ctx: PaymentMethodRetrieve> mandate_id: None, mandate_connector: None, setup_mandate: None, + customer_acceptance: None, token: None, address: PaymentAddress { shipping: shipping_address.as_ref().map(|a| a.into()), diff --git a/crates/router/src/core/payments/operations/payment_cancel.rs b/crates/router/src/core/payments/operations/payment_cancel.rs index 097b7ab40e1..1b09e9abce5 100644 --- a/crates/router/src/core/payments/operations/payment_cancel.rs +++ b/crates/router/src/core/payments/operations/payment_cancel.rs @@ -155,6 +155,7 @@ impl<F: Send + Clone, Ctx: PaymentMethodRetrieve> mandate_id: None, mandate_connector: None, setup_mandate: None, + customer_acceptance: None, token: None, address: PaymentAddress { shipping: shipping_address.as_ref().map(|a| a.into()), diff --git a/crates/router/src/core/payments/operations/payment_capture.rs b/crates/router/src/core/payments/operations/payment_capture.rs index e9d520e4abc..4a488a07eb3 100644 --- a/crates/router/src/core/payments/operations/payment_capture.rs +++ b/crates/router/src/core/payments/operations/payment_capture.rs @@ -200,6 +200,7 @@ impl<F: Send + Clone, Ctx: PaymentMethodRetrieve> mandate_id: None, mandate_connector: None, setup_mandate: None, + customer_acceptance: None, token: None, address: payments::PaymentAddress { shipping: shipping_address.as_ref().map(|a| a.into()), diff --git a/crates/router/src/core/payments/operations/payment_complete_authorize.rs b/crates/router/src/core/payments/operations/payment_complete_authorize.rs index f7e7598cf73..395f8e59dbc 100644 --- a/crates/router/src/core/payments/operations/payment_complete_authorize.rs +++ b/crates/router/src/core/payments/operations/payment_complete_authorize.rs @@ -215,6 +215,12 @@ impl<F: Send + Clone, Ctx: PaymentMethodRetrieve> // The operation merges mandate data from both request and payment_attempt let setup_mandate = setup_mandate.map(Into::into); + let mandate_details_present = + payment_attempt.mandate_details.is_some() || request.mandate_data.is_some(); + helpers::validate_mandate_data_and_future_usage( + payment_intent.setup_future_usage, + mandate_details_present, + )?; let profile_id = payment_intent .profile_id .as_ref() @@ -239,6 +245,7 @@ impl<F: Send + Clone, Ctx: PaymentMethodRetrieve> mandate_id: None, mandate_connector, setup_mandate, + customer_acceptance: None, token, address: PaymentAddress { shipping: shipping_address.as_ref().map(|a| a.into()), diff --git a/crates/router/src/core/payments/operations/payment_confirm.rs b/crates/router/src/core/payments/operations/payment_confirm.rs index 5c47c3f323e..9117f406040 100644 --- a/crates/router/src/core/payments/operations/payment_confirm.rs +++ b/crates/router/src/core/payments/operations/payment_confirm.rs @@ -361,6 +361,7 @@ impl<F: Send + Clone, Ctx: PaymentMethodRetrieve> .change_context(errors::ApiErrorResponse::InvalidDataValue { field_name: "browser_info", })?; + let customer_acceptance = request.customer_acceptance.clone().map(From::from); helpers::validate_card_data( request @@ -461,6 +462,12 @@ impl<F: Send + Clone, Ctx: PaymentMethodRetrieve> sm }); + let mandate_details_present = + payment_attempt.mandate_details.is_some() || request.mandate_data.is_some(); + helpers::validate_mandate_data_and_future_usage( + payment_intent.setup_future_usage, + mandate_details_present, + )?; let n_request_payment_method_data = request .payment_method_data .as_ref() @@ -539,6 +546,7 @@ impl<F: Send + Clone, Ctx: PaymentMethodRetrieve> mandate_id: None, mandate_connector, setup_mandate, + customer_acceptance, token, address: PaymentAddress { shipping: shipping_address.as_ref().map(|a| a.into()), diff --git a/crates/router/src/core/payments/operations/payment_create.rs b/crates/router/src/core/payments/operations/payment_create.rs index 11ab21b891d..2c07f4249e8 100644 --- a/crates/router/src/core/payments/operations/payment_create.rs +++ b/crates/router/src/core/payments/operations/payment_create.rs @@ -281,6 +281,12 @@ impl<F: Send + Clone, Ctx: PaymentMethodRetrieve> .to_duplicate_response(errors::ApiErrorResponse::DuplicatePayment { payment_id: payment_id.clone(), })?; + let mandate_details_present = payment_attempt.mandate_details.is_some(); + + helpers::validate_mandate_data_and_future_usage( + request.setup_future_usage, + mandate_details_present, + )?; // connector mandate reference update history let mandate_id = request .mandate_id @@ -355,6 +361,8 @@ impl<F: Send + Clone, Ctx: PaymentMethodRetrieve> // The operation merges mandate data from both request and payment_attempt let setup_mandate = setup_mandate.map(MandateData::from); + let customer_acceptance = request.customer_acceptance.clone().map(From::from); + let surcharge_details = request.surcharge_details.map(|request_surcharge_details| { payments::types::SurchargeDetails::from((&request_surcharge_details, &payment_attempt)) }); @@ -368,6 +376,7 @@ impl<F: Send + Clone, Ctx: PaymentMethodRetrieve> .payment_method_data .apply_additional_payment_data(additional_payment_data) }); + let amount = payment_attempt.get_total_amount().into(); let payment_data = PaymentData { flow: PhantomData, @@ -379,6 +388,7 @@ impl<F: Send + Clone, Ctx: PaymentMethodRetrieve> mandate_id, mandate_connector, setup_mandate, + customer_acceptance, token, address: PaymentAddress { shipping: shipping_address.as_ref().map(|a| a.into()), diff --git a/crates/router/src/core/payments/operations/payment_reject.rs b/crates/router/src/core/payments/operations/payment_reject.rs index 281ffdd06f7..a1416ea1908 100644 --- a/crates/router/src/core/payments/operations/payment_reject.rs +++ b/crates/router/src/core/payments/operations/payment_reject.rs @@ -143,6 +143,7 @@ impl<F: Send + Clone, Ctx: PaymentMethodRetrieve> mandate_id: None, mandate_connector: None, setup_mandate: None, + customer_acceptance: None, token: None, address: PaymentAddress { shipping: shipping_address.as_ref().map(|a| a.into()), diff --git a/crates/router/src/core/payments/operations/payment_session.rs b/crates/router/src/core/payments/operations/payment_session.rs index 966600a5498..ed3eda8832b 100644 --- a/crates/router/src/core/payments/operations/payment_session.rs +++ b/crates/router/src/core/payments/operations/payment_session.rs @@ -167,6 +167,7 @@ impl<F: Send + Clone, Ctx: PaymentMethodRetrieve> email: None, mandate_id: None, mandate_connector: None, + customer_acceptance: None, token: None, setup_mandate: None, address: payments::PaymentAddress { diff --git a/crates/router/src/core/payments/operations/payment_start.rs b/crates/router/src/core/payments/operations/payment_start.rs index 2ca413b73aa..650fef7e1bf 100644 --- a/crates/router/src/core/payments/operations/payment_start.rs +++ b/crates/router/src/core/payments/operations/payment_start.rs @@ -145,6 +145,7 @@ impl<F: Send + Clone, Ctx: PaymentMethodRetrieve> mandate_id: None, mandate_connector: None, setup_mandate: None, + customer_acceptance: None, token: payment_attempt.payment_token.clone(), address: PaymentAddress { shipping: shipping_address.as_ref().map(|a| a.into()), diff --git a/crates/router/src/core/payments/operations/payment_status.rs b/crates/router/src/core/payments/operations/payment_status.rs index aa622b3558b..70f04ed364d 100644 --- a/crates/router/src/core/payments/operations/payment_status.rs +++ b/crates/router/src/core/payments/operations/payment_status.rs @@ -414,6 +414,7 @@ async fn get_tracker_for_sync< }), mandate_connector: None, setup_mandate: None, + customer_acceptance: None, token: None, address: PaymentAddress { shipping: shipping_address.as_ref().map(|a| a.into()), diff --git a/crates/router/src/core/payments/operations/payment_update.rs b/crates/router/src/core/payments/operations/payment_update.rs index cd73df26ff3..7661ee515d9 100644 --- a/crates/router/src/core/payments/operations/payment_update.rs +++ b/crates/router/src/core/payments/operations/payment_update.rs @@ -349,7 +349,12 @@ impl<F: Send + Clone, Ctx: PaymentMethodRetrieve> // The operation merges mandate data from both request and payment_attempt let setup_mandate = setup_mandate.map(Into::into); - + let mandate_details_present = + payment_attempt.mandate_details.is_some() || request.mandate_data.is_some(); + helpers::validate_mandate_data_and_future_usage( + payment_intent.setup_future_usage, + mandate_details_present, + )?; let profile_id = payment_intent .profile_id .as_ref() @@ -363,7 +368,7 @@ impl<F: Send + Clone, Ctx: PaymentMethodRetrieve> .to_not_found_response(errors::ApiErrorResponse::BusinessProfileNotFound { id: profile_id.to_string(), })?; - + let customer_acceptance = request.customer_acceptance.clone().map(From::from); let surcharge_details = request.surcharge_details.map(|request_surcharge_details| { payments::types::SurchargeDetails::from((&request_surcharge_details, &payment_attempt)) }); @@ -379,6 +384,7 @@ impl<F: Send + Clone, Ctx: PaymentMethodRetrieve> mandate_connector, token, setup_mandate, + customer_acceptance, address: PaymentAddress { shipping: shipping_address.as_ref().map(|a| a.into()), billing: billing_address.as_ref().map(|a| a.into()), diff --git a/crates/router/src/core/payments/operations/payments_incremental_authorization.rs b/crates/router/src/core/payments/operations/payments_incremental_authorization.rs index 24292507c0e..96cbf9fb9db 100644 --- a/crates/router/src/core/payments/operations/payments_incremental_authorization.rs +++ b/crates/router/src/core/payments/operations/payments_incremental_authorization.rs @@ -120,6 +120,7 @@ impl<F: Send + Clone, Ctx: PaymentMethodRetrieve> mandate_id: None, mandate_connector: None, setup_mandate: None, + customer_acceptance: None, token: None, address: PaymentAddress { billing: None, diff --git a/crates/router/src/core/payments/tokenization.rs b/crates/router/src/core/payments/tokenization.rs index 1f793e2e185..943550ef434 100644 --- a/crates/router/src/core/payments/tokenization.rs +++ b/crates/router/src/core/payments/tokenization.rs @@ -1,6 +1,9 @@ use api_models::payment_methods::PaymentMethodsData; use common_enums::PaymentMethod; -use common_utils::{ext_traits::ValueExt, pii}; +use common_utils::{ + ext_traits::{Encode, ValueExt}, + pii, +}; use error_stack::{report, ResultExt}; use masking::ExposeInterface; use router_env::{instrument, tracing}; @@ -34,7 +37,6 @@ pub async fn save_payment_method<F: Clone, FData>( merchant_account: &domain::MerchantAccount, payment_method_type: Option<storage_enums::PaymentMethodType>, key_store: &domain::MerchantKeyStore, - is_mandate: bool, ) -> RouterResult<Option<String>> where FData: mandate::MandateBehaviour, @@ -67,16 +69,24 @@ where } else { None }; - let future_usage_validation = resp + + let mandate_data_customer_acceptance = resp .request - .get_setup_future_usage() - .map(|future_usage| { - (future_usage == storage_enums::FutureUsage::OffSession && is_mandate) - || (future_usage == storage_enums::FutureUsage::OnSession && !is_mandate) - }) - .unwrap_or(false); + .get_setup_mandate_details() + .and_then(|mandate_data| mandate_data.customer_acceptance.clone()); + + let customer_acceptance = resp + .request + .get_customer_acceptance() + .or(mandate_data_customer_acceptance.clone().map(From::from)) + .map(|ca| ca.encode_to_value()) + .transpose() + .change_context(errors::ApiErrorResponse::InternalServerError) + .attach_printable("Unable to serialize customer acceptance to value")?; - let pm_id = if future_usage_validation { + let pm_id = if resp.request.get_setup_future_usage().is_some() + && customer_acceptance.is_some() + { let customer = maybe_customer.to_owned().get_required_value("customer")?; let payment_method_create_request = helpers::get_payment_method_create_request( Some(&resp.request.get_payment_method_data()), @@ -181,6 +191,7 @@ where locker_id, merchant_id, pm_metadata, + customer_acceptance, pm_data_encrypted, key_store, ) @@ -243,6 +254,7 @@ where &merchant_account.merchant_id, &customer.customer_id, resp.metadata.clone().map(|val| val.expose()), + customer_acceptance, locker_id, ) .await @@ -357,6 +369,7 @@ where locker_id, merchant_id, pm_metadata, + customer_acceptance, pm_data_encrypted, key_store, ) diff --git a/crates/router/src/core/payments/transformers.rs b/crates/router/src/core/payments/transformers.rs index 7c7bac80cf0..8ccab155c69 100644 --- a/crates/router/src/core/payments/transformers.rs +++ b/crates/router/src/core/payments/transformers.rs @@ -1141,6 +1141,7 @@ impl<F: Clone> TryFrom<PaymentAdditionalData<'_, F>> for types::PaymentsAuthoriz | Some(RequestIncrementalAuthorization::Default) ), metadata: additional_data.payment_data.payment_intent.metadata, + customer_acceptance: payment_data.customer_acceptance, }) } } @@ -1436,6 +1437,7 @@ impl<F: Clone> TryFrom<PaymentAdditionalData<'_, F>> for types::SetupMandateRequ off_session: payment_data.mandate_id.as_ref().map(|_| true), mandate_id: payment_data.mandate_id.clone(), setup_mandate_details: payment_data.setup_mandate, + customer_acceptance: payment_data.customer_acceptance, router_return_url, email: payment_data.email, customer_name, diff --git a/crates/router/src/core/payouts/helpers.rs b/crates/router/src/core/payouts/helpers.rs index fcd2569ea99..7005e955dff 100644 --- a/crates/router/src/core/payouts/helpers.rs +++ b/crates/router/src/core/payouts/helpers.rs @@ -382,6 +382,7 @@ pub async fn save_payout_data_to_locker( Some(stored_resp.card_reference), &merchant_account.merchant_id, None, + None, card_details_encrypted, key_store, ) diff --git a/crates/router/src/types.rs b/crates/router/src/types.rs index 07691879d4a..106872fb43f 100644 --- a/crates/router/src/types.rs +++ b/crates/router/src/types.rs @@ -24,7 +24,7 @@ pub use api_models::{ use common_enums::MandateStatus; pub use common_utils::request::{RequestBody, RequestContent}; use common_utils::{pii, pii::Email}; -use data_models::mandates::MandateData; +use data_models::mandates::{CustomerAcceptance, MandateData}; use error_stack::{IntoReport, ResultExt}; use masking::Secret; use serde::Serialize; @@ -408,6 +408,7 @@ pub struct PaymentsAuthorizeData { pub setup_future_usage: Option<storage_enums::FutureUsage>, pub mandate_id: Option<api_models::payments::MandateIds>, pub off_session: Option<bool>, + pub customer_acceptance: Option<CustomerAcceptance>, pub setup_mandate_details: Option<MandateData>, pub browser_info: Option<BrowserInformation>, pub order_details: Option<Vec<api_models::payments::OrderDetailsWithAmount>>, @@ -584,6 +585,7 @@ pub struct SetupMandateRequestData { pub amount: Option<i64>, pub confirm: bool, pub statement_descriptor_suffix: Option<String>, + pub customer_acceptance: Option<CustomerAcceptance>, pub mandate_id: Option<api_models::payments::MandateIds>, pub setup_future_usage: Option<storage_enums::FutureUsage>, pub off_session: Option<bool>, @@ -1423,6 +1425,7 @@ impl From<&SetupMandateRouterData> for PaymentsAuthorizeData { surcharge_details: None, request_incremental_authorization: data.request.request_incremental_authorization, metadata: None, + customer_acceptance: data.request.customer_acceptance.clone(), } } } diff --git a/crates/router/src/types/api/verify_connector.rs b/crates/router/src/types/api/verify_connector.rs index 221d16a8b46..4f3d6f7e296 100644 --- a/crates/router/src/types/api/verify_connector.rs +++ b/crates/router/src/types/api/verify_connector.rs @@ -50,6 +50,7 @@ impl VerifyConnectorData { related_transaction_id: None, statement_descriptor_suffix: None, request_incremental_authorization: false, + customer_acceptance: None, } } diff --git a/crates/router/tests/connectors/aci.rs b/crates/router/tests/connectors/aci.rs index d3f8147fb26..5c4660805fb 100644 --- a/crates/router/tests/connectors/aci.rs +++ b/crates/router/tests/connectors/aci.rs @@ -72,6 +72,7 @@ fn construct_payment_router_data() -> types::PaymentsAuthorizeRouterData { surcharge_details: None, request_incremental_authorization: false, metadata: None, + customer_acceptance: None, }, response: Err(types::ErrorResponse::default()), payment_method_id: None, diff --git a/crates/router/tests/connectors/adyen.rs b/crates/router/tests/connectors/adyen.rs index 12812a70857..55f9f6b4b6b 100644 --- a/crates/router/tests/connectors/adyen.rs +++ b/crates/router/tests/connectors/adyen.rs @@ -170,6 +170,7 @@ impl AdyenTest { surcharge_details: None, request_incremental_authorization: false, metadata: None, + customer_acceptance: None, }) } } diff --git a/crates/router/tests/connectors/bitpay.rs b/crates/router/tests/connectors/bitpay.rs index d24e20cd660..93043f37c9b 100644 --- a/crates/router/tests/connectors/bitpay.rs +++ b/crates/router/tests/connectors/bitpay.rs @@ -96,6 +96,7 @@ fn payment_method_details() -> Option<types::PaymentsAuthorizeData> { surcharge_details: None, request_incremental_authorization: false, metadata: None, + customer_acceptance: None, }) } diff --git a/crates/router/tests/connectors/cashtocode.rs b/crates/router/tests/connectors/cashtocode.rs index a9d81d2bb62..7dd70d86695 100644 --- a/crates/router/tests/connectors/cashtocode.rs +++ b/crates/router/tests/connectors/cashtocode.rs @@ -70,6 +70,7 @@ impl CashtocodeTest { surcharge_details: None, request_incremental_authorization: false, metadata: None, + customer_acceptance: None, }) } diff --git a/crates/router/tests/connectors/coinbase.rs b/crates/router/tests/connectors/coinbase.rs index 7a872ecb585..b1fffb302cb 100644 --- a/crates/router/tests/connectors/coinbase.rs +++ b/crates/router/tests/connectors/coinbase.rs @@ -98,6 +98,7 @@ fn payment_method_details() -> Option<types::PaymentsAuthorizeData> { surcharge_details: None, request_incremental_authorization: false, metadata: None, + customer_acceptance: None, }) } diff --git a/crates/router/tests/connectors/cryptopay.rs b/crates/router/tests/connectors/cryptopay.rs index d61a93c8b82..6eaf514db21 100644 --- a/crates/router/tests/connectors/cryptopay.rs +++ b/crates/router/tests/connectors/cryptopay.rs @@ -96,6 +96,7 @@ fn payment_method_details() -> Option<types::PaymentsAuthorizeData> { surcharge_details: None, request_incremental_authorization: false, metadata: None, + customer_acceptance: None, }) } diff --git a/crates/router/tests/connectors/opennode.rs b/crates/router/tests/connectors/opennode.rs index 8415be949a0..4702012597e 100644 --- a/crates/router/tests/connectors/opennode.rs +++ b/crates/router/tests/connectors/opennode.rs @@ -97,6 +97,7 @@ fn payment_method_details() -> Option<types::PaymentsAuthorizeData> { surcharge_details: None, request_incremental_authorization: false, metadata: None, + customer_acceptance: None, }) } diff --git a/crates/router/tests/connectors/utils.rs b/crates/router/tests/connectors/utils.rs index 8f749a0b2ff..83380f76073 100644 --- a/crates/router/tests/connectors/utils.rs +++ b/crates/router/tests/connectors/utils.rs @@ -915,6 +915,7 @@ impl Default for PaymentAuthorizeType { surcharge_details: None, request_incremental_authorization: false, metadata: None, + customer_acceptance: None, }; Self(data) } diff --git a/crates/router/tests/connectors/worldline.rs b/crates/router/tests/connectors/worldline.rs index c5b12a0b0b2..ba946b296bf 100644 --- a/crates/router/tests/connectors/worldline.rs +++ b/crates/router/tests/connectors/worldline.rs @@ -106,6 +106,7 @@ impl WorldlineTest { surcharge_details: None, request_incremental_authorization: false, metadata: None, + customer_acceptance: None, }) } } diff --git a/openapi/openapi_spec.json b/openapi/openapi_spec.json index 293bfc85a7c..1a3e71f38c0 100644 --- a/openapi/openapi_spec.json +++ b/openapi/openapi_spec.json @@ -12529,6 +12529,14 @@ ], "nullable": true }, + "customer_acceptance": { + "allOf": [ + { + "$ref": "#/components/schemas/CustomerAcceptance" + } + ], + "nullable": true + }, "mandate_id": { "type": "string", "description": "A unique identifier to link the payment to a mandate. To do Recurring payments after a mandate has been created, pass the mandate_id instead of payment_method_data", @@ -12880,6 +12888,14 @@ ], "nullable": true }, + "customer_acceptance": { + "allOf": [ + { + "$ref": "#/components/schemas/CustomerAcceptance" + } + ], + "nullable": true + }, "mandate_id": { "type": "string", "description": "A unique identifier to link the payment to a mandate. To do Recurring payments after a mandate has been created, pass the mandate_id instead of payment_method_data", @@ -13286,6 +13302,14 @@ ], "nullable": true }, + "customer_acceptance": { + "allOf": [ + { + "$ref": "#/components/schemas/CustomerAcceptance" + } + ], + "nullable": true + }, "mandate_id": { "type": "string", "description": "A unique identifier to link the payment to a mandate. To do Recurring payments after a mandate has been created, pass the mandate_id instead of payment_method_data", @@ -14277,6 +14301,14 @@ ], "nullable": true }, + "customer_acceptance": { + "allOf": [ + { + "$ref": "#/components/schemas/CustomerAcceptance" + } + ], + "nullable": true + }, "browser_info": { "allOf": [ { diff --git a/postman/collection-dir/aci/Flow Testcases/Happy Cases/Scenario11-Create a mandate and recurring payment/Payments - Create/request.json b/postman/collection-dir/aci/Flow Testcases/Happy Cases/Scenario11-Create a mandate and recurring payment/Payments - Create/request.json index f7573b64a60..9988d0e2cb1 100644 --- a/postman/collection-dir/aci/Flow Testcases/Happy Cases/Scenario11-Create a mandate and recurring payment/Payments - Create/request.json +++ b/postman/collection-dir/aci/Flow Testcases/Happy Cases/Scenario11-Create a mandate and recurring payment/Payments - Create/request.json @@ -59,6 +59,14 @@ } } }, + "customer_acceptance": { + "acceptance_type": "offline", + "accepted_at": "1963-05-03T04:07:52.723Z", + "online": { + "ip_address": "127.0.0.1", + "user_agent": "amet irure esse" + } + }, "billing": { "address": { "line1": "1467", diff --git a/postman/collection-dir/aci/Flow Testcases/Happy Cases/Scenario11-Refund recurring payment/Payments - Create/request.json b/postman/collection-dir/aci/Flow Testcases/Happy Cases/Scenario11-Refund recurring payment/Payments - Create/request.json index b66df150887..9570f0f0b8d 100644 --- a/postman/collection-dir/aci/Flow Testcases/Happy Cases/Scenario11-Refund recurring payment/Payments - Create/request.json +++ b/postman/collection-dir/aci/Flow Testcases/Happy Cases/Scenario11-Refund recurring payment/Payments - Create/request.json @@ -59,6 +59,14 @@ } } }, + "customer_acceptance": { + "acceptance_type": "offline", + "accepted_at": "1963-05-03T04:07:52.723Z", + "online": { + "ip_address": "127.0.0.1", + "user_agent": "amet irure esse" + } + }, "shipping": { "address": { "line1": "1467", diff --git a/postman/collection-dir/aci/Flow Testcases/Variation Cases/Scenario9-Create a recurring payment with greater mandate amount/Payments - Create/request.json b/postman/collection-dir/aci/Flow Testcases/Variation Cases/Scenario9-Create a recurring payment with greater mandate amount/Payments - Create/request.json index f7573b64a60..9988d0e2cb1 100644 --- a/postman/collection-dir/aci/Flow Testcases/Variation Cases/Scenario9-Create a recurring payment with greater mandate amount/Payments - Create/request.json +++ b/postman/collection-dir/aci/Flow Testcases/Variation Cases/Scenario9-Create a recurring payment with greater mandate amount/Payments - Create/request.json @@ -59,6 +59,14 @@ } } }, + "customer_acceptance": { + "acceptance_type": "offline", + "accepted_at": "1963-05-03T04:07:52.723Z", + "online": { + "ip_address": "127.0.0.1", + "user_agent": "amet irure esse" + } + }, "billing": { "address": { "line1": "1467", diff --git a/postman/collection-dir/adyen_uk/Flow Testcases/Happy Cases/Scenario10-Create a mandate and recurring payment/Payments - Create/request.json b/postman/collection-dir/adyen_uk/Flow Testcases/Happy Cases/Scenario10-Create a mandate and recurring payment/Payments - Create/request.json index 80dad74bb60..0bf892efdf5 100644 --- a/postman/collection-dir/adyen_uk/Flow Testcases/Happy Cases/Scenario10-Create a mandate and recurring payment/Payments - Create/request.json +++ b/postman/collection-dir/adyen_uk/Flow Testcases/Happy Cases/Scenario10-Create a mandate and recurring payment/Payments - Create/request.json @@ -60,6 +60,14 @@ } } }, + "customer_acceptance": { + "acceptance_type": "offline", + "accepted_at": "1963-05-03T04:07:52.723Z", + "online": { + "ip_address": "127.0.0.1", + "user_agent": "amet irure esse" + } + }, "billing": { "address": { "line1": "1467", diff --git a/postman/collection-dir/adyen_uk/Flow Testcases/Happy Cases/Scenario14-Refund recurring payment/Payments - Create/request.json b/postman/collection-dir/adyen_uk/Flow Testcases/Happy Cases/Scenario14-Refund recurring payment/Payments - Create/request.json index 08e62dca6e9..a515beb2661 100644 --- a/postman/collection-dir/adyen_uk/Flow Testcases/Happy Cases/Scenario14-Refund recurring payment/Payments - Create/request.json +++ b/postman/collection-dir/adyen_uk/Flow Testcases/Happy Cases/Scenario14-Refund recurring payment/Payments - Create/request.json @@ -60,6 +60,14 @@ } } }, + "customer_acceptance": { + "acceptance_type": "offline", + "accepted_at": "1963-05-03T04:07:52.723Z", + "online": { + "ip_address": "127.0.0.1", + "user_agent": "amet irure esse" + } + }, "shipping": { "address": { "line1": "1467", diff --git a/postman/collection-dir/adyen_uk/Flow Testcases/Happy Cases/Scenario16-Bank debit-ach/Payments - Create/request.json b/postman/collection-dir/adyen_uk/Flow Testcases/Happy Cases/Scenario16-Bank debit-ach/Payments - Create/request.json index 21c079e0ad0..eecdf810746 100644 --- a/postman/collection-dir/adyen_uk/Flow Testcases/Happy Cases/Scenario16-Bank debit-ach/Payments - Create/request.json +++ b/postman/collection-dir/adyen_uk/Flow Testcases/Happy Cases/Scenario16-Bank debit-ach/Payments - Create/request.json @@ -32,6 +32,14 @@ "authentication_type": "three_ds", "return_url": "https://duck.com", "setup_future_usage": "on_session", + "customer_acceptance": { + "acceptance_type": "offline", + "accepted_at": "1963-05-03T04:07:52.723Z", + "online": { + "ip_address": "127.0.0.1", + "user_agent": "amet irure esse" + } + }, "billing": { "address": { "line1": "1467", diff --git a/postman/collection-dir/adyen_uk/Flow Testcases/Happy Cases/Scenario17-Bank debit-Bacs/Payments - Create/request.json b/postman/collection-dir/adyen_uk/Flow Testcases/Happy Cases/Scenario17-Bank debit-Bacs/Payments - Create/request.json index 1ec9a829a48..660ef06c518 100644 --- a/postman/collection-dir/adyen_uk/Flow Testcases/Happy Cases/Scenario17-Bank debit-Bacs/Payments - Create/request.json +++ b/postman/collection-dir/adyen_uk/Flow Testcases/Happy Cases/Scenario17-Bank debit-Bacs/Payments - Create/request.json @@ -32,6 +32,14 @@ "authentication_type": "no_three_ds", "return_url": "https://duck.com", "setup_future_usage": "on_session", + "customer_acceptance": { + "acceptance_type": "offline", + "accepted_at": "1963-05-03T04:07:52.723Z", + "online": { + "ip_address": "127.0.0.1", + "user_agent": "amet irure esse" + } + }, "billing": { "address": { "line1": "1467", diff --git a/postman/collection-dir/adyen_uk/Flow Testcases/Happy Cases/Scenario19-Add card flow/Payments - Create/request.json b/postman/collection-dir/adyen_uk/Flow Testcases/Happy Cases/Scenario19-Add card flow/Payments - Create/request.json index 9260edb1a99..397f164511f 100644 --- a/postman/collection-dir/adyen_uk/Flow Testcases/Happy Cases/Scenario19-Add card flow/Payments - Create/request.json +++ b/postman/collection-dir/adyen_uk/Flow Testcases/Happy Cases/Scenario19-Add card flow/Payments - Create/request.json @@ -33,6 +33,14 @@ "authentication_type": "no_three_ds", "return_url": "https://google.com", "setup_future_usage": "on_session", + "customer_acceptance": { + "acceptance_type": "offline", + "accepted_at": "1963-05-03T04:07:52.723Z", + "online": { + "ip_address": "127.0.0.1", + "user_agent": "amet irure esse" + } + }, "payment_method": "card", "payment_method_type": "credit", "payment_method_data": { @@ -89,12 +97,8 @@ }, "url": { "raw": "{{baseUrl}}/payments", - "host": [ - "{{baseUrl}}" - ], - "path": [ - "payments" - ] + "host": ["{{baseUrl}}"], + "path": ["payments"] }, "description": "To process a payment you will have to create a payment, attach a payment method and confirm. Depending on the user journey you wish to achieve, you may opt to all the steps in a single request or in a sequence of API request using following APIs: (i) Payments - Update, (ii) Payments - Confirm, and (iii) Payments - Capture" } diff --git a/postman/collection-dir/adyen_uk/Flow Testcases/Happy Cases/Scenario20-Pass Invalid CVV for save card flow and verify failed payment/Payments - Create/request.json b/postman/collection-dir/adyen_uk/Flow Testcases/Happy Cases/Scenario20-Pass Invalid CVV for save card flow and verify failed payment/Payments - Create/request.json index 9260edb1a99..397f164511f 100644 --- a/postman/collection-dir/adyen_uk/Flow Testcases/Happy Cases/Scenario20-Pass Invalid CVV for save card flow and verify failed payment/Payments - Create/request.json +++ b/postman/collection-dir/adyen_uk/Flow Testcases/Happy Cases/Scenario20-Pass Invalid CVV for save card flow and verify failed payment/Payments - Create/request.json @@ -33,6 +33,14 @@ "authentication_type": "no_three_ds", "return_url": "https://google.com", "setup_future_usage": "on_session", + "customer_acceptance": { + "acceptance_type": "offline", + "accepted_at": "1963-05-03T04:07:52.723Z", + "online": { + "ip_address": "127.0.0.1", + "user_agent": "amet irure esse" + } + }, "payment_method": "card", "payment_method_type": "credit", "payment_method_data": { @@ -89,12 +97,8 @@ }, "url": { "raw": "{{baseUrl}}/payments", - "host": [ - "{{baseUrl}}" - ], - "path": [ - "payments" - ] + "host": ["{{baseUrl}}"], + "path": ["payments"] }, "description": "To process a payment you will have to create a payment, attach a payment method and confirm. Depending on the user journey you wish to achieve, you may opt to all the steps in a single request or in a sequence of API request using following APIs: (i) Payments - Update, (ii) Payments - Confirm, and (iii) Payments - Capture" } diff --git a/postman/collection-dir/adyen_uk/Flow Testcases/Happy Cases/Scenario21-Don't Pass CVV for save card flow and verify failed payment Copy/Payments - Create/request.json b/postman/collection-dir/adyen_uk/Flow Testcases/Happy Cases/Scenario21-Don't Pass CVV for save card flow and verify failed payment Copy/Payments - Create/request.json index 9260edb1a99..397f164511f 100644 --- a/postman/collection-dir/adyen_uk/Flow Testcases/Happy Cases/Scenario21-Don't Pass CVV for save card flow and verify failed payment Copy/Payments - Create/request.json +++ b/postman/collection-dir/adyen_uk/Flow Testcases/Happy Cases/Scenario21-Don't Pass CVV for save card flow and verify failed payment Copy/Payments - Create/request.json @@ -33,6 +33,14 @@ "authentication_type": "no_three_ds", "return_url": "https://google.com", "setup_future_usage": "on_session", + "customer_acceptance": { + "acceptance_type": "offline", + "accepted_at": "1963-05-03T04:07:52.723Z", + "online": { + "ip_address": "127.0.0.1", + "user_agent": "amet irure esse" + } + }, "payment_method": "card", "payment_method_type": "credit", "payment_method_data": { @@ -89,12 +97,8 @@ }, "url": { "raw": "{{baseUrl}}/payments", - "host": [ - "{{baseUrl}}" - ], - "path": [ - "payments" - ] + "host": ["{{baseUrl}}"], + "path": ["payments"] }, "description": "To process a payment you will have to create a payment, attach a payment method and confirm. Depending on the user journey you wish to achieve, you may opt to all the steps in a single request or in a sequence of API request using following APIs: (i) Payments - Update, (ii) Payments - Confirm, and (iii) Payments - Capture" } diff --git a/postman/collection-dir/adyen_uk/Flow Testcases/Variation Cases/Scenario9-Create a recurring payment with greater mandate amount/Payments - Create/request.json b/postman/collection-dir/adyen_uk/Flow Testcases/Variation Cases/Scenario9-Create a recurring payment with greater mandate amount/Payments - Create/request.json index 93e802128f2..40a78911a9a 100644 --- a/postman/collection-dir/adyen_uk/Flow Testcases/Variation Cases/Scenario9-Create a recurring payment with greater mandate amount/Payments - Create/request.json +++ b/postman/collection-dir/adyen_uk/Flow Testcases/Variation Cases/Scenario9-Create a recurring payment with greater mandate amount/Payments - Create/request.json @@ -59,6 +59,14 @@ } } }, + "customer_acceptance": { + "acceptance_type": "offline", + "accepted_at": "1963-05-03T04:07:52.723Z", + "online": { + "ip_address": "127.0.0.1", + "user_agent": "amet irure esse" + } + }, "billing": { "address": { "line1": "1467", diff --git a/postman/collection-dir/authorizedotnet/Flow Testcases/Variation Cases/Scenario11-Create a recurring payment with greater mandate amount/Payments - Create/request.json b/postman/collection-dir/authorizedotnet/Flow Testcases/Variation Cases/Scenario11-Create a recurring payment with greater mandate amount/Payments - Create/request.json index e3d19912b79..d152474c374 100644 --- a/postman/collection-dir/authorizedotnet/Flow Testcases/Variation Cases/Scenario11-Create a recurring payment with greater mandate amount/Payments - Create/request.json +++ b/postman/collection-dir/authorizedotnet/Flow Testcases/Variation Cases/Scenario11-Create a recurring payment with greater mandate amount/Payments - Create/request.json @@ -59,6 +59,14 @@ } } }, + "customer_acceptance": { + "acceptance_type": "online", + "accepted_at": "2022-09-10T10:11:12Z", + "online": { + "ip_address": "123.32.25.123", + "user_agent": "Mozilla/5.0 (Linux; Android 12; SM-S906N Build/QP1A.190711.020; wv) AppleWebKit/537.36 (KHTML, like Gecko) Version/4.0 Chrome/80.0.3987.119 Mobile Safari/537.36" + } + }, "billing": { "address": { "line1": "1467", diff --git a/postman/collection-dir/bankofamerica/Flow Testcases/Happy Cases/Scenario1-Create payment with confirm true/Payments - Create/request.json b/postman/collection-dir/bankofamerica/Flow Testcases/Happy Cases/Scenario1-Create payment with confirm true/Payments - Create/request.json index e37391b78b5..43eb0c9cc12 100644 --- a/postman/collection-dir/bankofamerica/Flow Testcases/Happy Cases/Scenario1-Create payment with confirm true/Payments - Create/request.json +++ b/postman/collection-dir/bankofamerica/Flow Testcases/Happy Cases/Scenario1-Create payment with confirm true/Payments - Create/request.json @@ -35,6 +35,14 @@ "authentication_type": "no_three_ds", "return_url": "https://duck.com", "setup_future_usage": "on_session", + "customer_acceptance": { + "acceptance_type": "online", + "accepted_at": "2022-09-10T10:11:12Z", + "online": { + "ip_address": "123.32.25.123", + "user_agent": "Mozilla/5.0 (Linux; Android 12; SM-S906N Build/QP1A.190711.020; wv) AppleWebKit/537.36 (KHTML, like Gecko) Version/4.0 Chrome/80.0.3987.119 Mobile Safari/537.36" + } + }, "payment_method": "card", "payment_method_type": "debit", "payment_method_data": { @@ -87,12 +95,8 @@ }, "url": { "raw": "{{baseUrl}}/payments", - "host": [ - "{{baseUrl}}" - ], - "path": [ - "payments" - ] + "host": ["{{baseUrl}}"], + "path": ["payments"] }, "description": "To process a payment you will have to create a payment, attach a payment method and confirm. Depending on the user journey you wish to achieve, you may opt to all the steps in a single request or in a sequence of API request using following APIs: (i) Payments - Update, (ii) Payments - Confirm, and (iii) Payments - Capture" } diff --git a/postman/collection-dir/nmi/Flow Testcases/Happy Cases/Scenario12-Add card flow/Payments - Create/request.json b/postman/collection-dir/nmi/Flow Testcases/Happy Cases/Scenario12-Add card flow/Payments - Create/request.json index 056b9269a29..d0320b09975 100644 --- a/postman/collection-dir/nmi/Flow Testcases/Happy Cases/Scenario12-Add card flow/Payments - Create/request.json +++ b/postman/collection-dir/nmi/Flow Testcases/Happy Cases/Scenario12-Add card flow/Payments - Create/request.json @@ -33,6 +33,14 @@ "authentication_type": "no_three_ds", "return_url": "https://duck.com", "setup_future_usage": "on_session", + "customer_acceptance": { + "acceptance_type": "online", + "accepted_at": "2022-09-10T10:11:12Z", + "online": { + "ip_address": "123.32.25.123", + "user_agent": "Mozilla/5.0 (Linux; Android 12; SM-S906N Build/QP1A.190711.020; wv) AppleWebKit/537.36 (KHTML, like Gecko) Version/4.0 Chrome/80.0.3987.119 Mobile Safari/537.36" + } + }, "payment_method": "card", "payment_method_type": "credit", "payment_method_data": { diff --git a/postman/collection-dir/nmi/Flow Testcases/Happy Cases/Scenario13-Don't Pass CVV for save card flow and verify success payment/Payments - Create/request.json b/postman/collection-dir/nmi/Flow Testcases/Happy Cases/Scenario13-Don't Pass CVV for save card flow and verify success payment/Payments - Create/request.json index 1d85fee7356..fe4adccda47 100644 --- a/postman/collection-dir/nmi/Flow Testcases/Happy Cases/Scenario13-Don't Pass CVV for save card flow and verify success payment/Payments - Create/request.json +++ b/postman/collection-dir/nmi/Flow Testcases/Happy Cases/Scenario13-Don't Pass CVV for save card flow and verify success payment/Payments - Create/request.json @@ -33,6 +33,14 @@ "authentication_type": "no_three_ds", "return_url": "https://duck.com", "setup_future_usage": "on_session", + "customer_acceptance": { + "acceptance_type": "online", + "accepted_at": "2022-09-10T10:11:12Z", + "online": { + "ip_address": "123.32.25.123", + "user_agent": "Mozilla/5.0 (Linux; Android 12; SM-S906N Build/QP1A.190711.020; wv) AppleWebKit/537.36 (KHTML, like Gecko) Version/4.0 Chrome/80.0.3987.119 Mobile Safari/537.36" + } + }, "payment_method": "card", "payment_method_type": "credit", "payment_method_data": { diff --git a/postman/collection-dir/nmi/Flow Testcases/Happy Cases/Scenario14-Save card payment with manual capture/Payments - Create/request.json b/postman/collection-dir/nmi/Flow Testcases/Happy Cases/Scenario14-Save card payment with manual capture/Payments - Create/request.json index 73457bf3197..aaa993e4eef 100644 --- a/postman/collection-dir/nmi/Flow Testcases/Happy Cases/Scenario14-Save card payment with manual capture/Payments - Create/request.json +++ b/postman/collection-dir/nmi/Flow Testcases/Happy Cases/Scenario14-Save card payment with manual capture/Payments - Create/request.json @@ -33,6 +33,14 @@ "authentication_type": "no_three_ds", "return_url": "https://duck.com", "setup_future_usage": "on_session", + "customer_acceptance": { + "acceptance_type": "online", + "accepted_at": "2022-09-10T10:11:12Z", + "online": { + "ip_address": "123.32.25.123", + "user_agent": "Mozilla/5.0 (Linux; Android 12; SM-S906N Build/QP1A.190711.020; wv) AppleWebKit/537.36 (KHTML, like Gecko) Version/4.0 Chrome/80.0.3987.119 Mobile Safari/537.36" + } + }, "payment_method": "card", "payment_method_type": "credit", "payment_method_data": { diff --git a/postman/collection-dir/nmi/Flow Testcases/Happy Cases/Scenario15-Create payment without customer_id and with billing address and shipping address/Payments - Create/request.json b/postman/collection-dir/nmi/Flow Testcases/Happy Cases/Scenario15-Create payment without customer_id and with billing address and shipping address/Payments - Create/request.json index ffda1aef2d7..050f353af53 100644 --- a/postman/collection-dir/nmi/Flow Testcases/Happy Cases/Scenario15-Create payment without customer_id and with billing address and shipping address/Payments - Create/request.json +++ b/postman/collection-dir/nmi/Flow Testcases/Happy Cases/Scenario15-Create payment without customer_id and with billing address and shipping address/Payments - Create/request.json @@ -35,6 +35,14 @@ "authentication_type": "no_three_ds", "return_url": "https://duck.com", "setup_future_usage": "on_session", + "customer_acceptance": { + "acceptance_type": "online", + "accepted_at": "2022-09-10T10:11:12Z", + "online": { + "ip_address": "123.32.25.123", + "user_agent": "Mozilla/5.0 (Linux; Android 12; SM-S906N Build/QP1A.190711.020; wv) AppleWebKit/537.36 (KHTML, like Gecko) Version/4.0 Chrome/80.0.3987.119 Mobile Safari/537.36" + } + }, "payment_method": "card", "payment_method_type": "debit", "payment_method_data": { diff --git a/postman/collection-dir/nmi/Flow Testcases/Happy Cases/Scenario8-Create a failure card payment with confirm true/Payments - Create/request.json b/postman/collection-dir/nmi/Flow Testcases/Happy Cases/Scenario8-Create a failure card payment with confirm true/Payments - Create/request.json index 97cce7936c4..63d1eeba233 100644 --- a/postman/collection-dir/nmi/Flow Testcases/Happy Cases/Scenario8-Create a failure card payment with confirm true/Payments - Create/request.json +++ b/postman/collection-dir/nmi/Flow Testcases/Happy Cases/Scenario8-Create a failure card payment with confirm true/Payments - Create/request.json @@ -35,6 +35,14 @@ "authentication_type": "no_three_ds", "return_url": "https://duck.com", "setup_future_usage": "on_session", + "customer_acceptance": { + "acceptance_type": "online", + "accepted_at": "2022-09-10T10:11:12Z", + "online": { + "ip_address": "123.32.25.123", + "user_agent": "Mozilla/5.0 (Linux; Android 12; SM-S906N Build/QP1A.190711.020; wv) AppleWebKit/537.36 (KHTML, like Gecko) Version/4.0 Chrome/80.0.3987.119 Mobile Safari/537.36" + } + }, "payment_method": "card", "payment_method_type": "debit", "payment_method_data": { diff --git a/postman/collection-dir/nmi/Flow Testcases/Happy Cases/Scenario9-Update amount with automatic capture/Payments - Confirm/request.json b/postman/collection-dir/nmi/Flow Testcases/Happy Cases/Scenario9-Update amount with automatic capture/Payments - Confirm/request.json index 7b72495e5c4..962144d6bc6 100644 --- a/postman/collection-dir/nmi/Flow Testcases/Happy Cases/Scenario9-Update amount with automatic capture/Payments - Confirm/request.json +++ b/postman/collection-dir/nmi/Flow Testcases/Happy Cases/Scenario9-Update amount with automatic capture/Payments - Confirm/request.json @@ -29,7 +29,6 @@ "key": "Accept", "value": "application/json" }, - , { "key": "publishable_key", "value": "", @@ -58,6 +57,14 @@ } }, "setup_future_usage": "on_session", + "customer_acceptance": { + "acceptance_type": "online", + "accepted_at": "2022-09-10T10:11:12Z", + "online": { + "ip_address": "123.32.25.123", + "user_agent": "Mozilla/5.0 (Linux; Android 12; SM-S906N Build/QP1A.190711.020; wv) AppleWebKit/537.36 (KHTML, like Gecko) Version/4.0 Chrome/80.0.3987.119 Mobile Safari/537.36" + } + }, "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", diff --git a/postman/collection-dir/nmi/Flow Testcases/Happy Cases/Scenario9a-Update amount with manual capture/Payments - Confirm/request.json b/postman/collection-dir/nmi/Flow Testcases/Happy Cases/Scenario9a-Update amount with manual capture/Payments - Confirm/request.json index 7b72495e5c4..962144d6bc6 100644 --- a/postman/collection-dir/nmi/Flow Testcases/Happy Cases/Scenario9a-Update amount with manual capture/Payments - Confirm/request.json +++ b/postman/collection-dir/nmi/Flow Testcases/Happy Cases/Scenario9a-Update amount with manual capture/Payments - Confirm/request.json @@ -29,7 +29,6 @@ "key": "Accept", "value": "application/json" }, - , { "key": "publishable_key", "value": "", @@ -58,6 +57,14 @@ } }, "setup_future_usage": "on_session", + "customer_acceptance": { + "acceptance_type": "online", + "accepted_at": "2022-09-10T10:11:12Z", + "online": { + "ip_address": "123.32.25.123", + "user_agent": "Mozilla/5.0 (Linux; Android 12; SM-S906N Build/QP1A.190711.020; wv) AppleWebKit/537.36 (KHTML, like Gecko) Version/4.0 Chrome/80.0.3987.119 Mobile Safari/537.36" + } + }, "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", diff --git a/postman/collection-dir/nmi/Flow Testcases/Variation Cases/Scenario9-Create a recurring payment with greater mandate amount Copy/Payments - Create/request.json b/postman/collection-dir/nmi/Flow Testcases/Variation Cases/Scenario9-Create a recurring payment with greater mandate amount Copy/Payments - Create/request.json index 7aeaf601cc6..2cbfe4a20f1 100644 --- a/postman/collection-dir/nmi/Flow Testcases/Variation Cases/Scenario9-Create a recurring payment with greater mandate amount Copy/Payments - Create/request.json +++ b/postman/collection-dir/nmi/Flow Testcases/Variation Cases/Scenario9-Create a recurring payment with greater mandate amount Copy/Payments - Create/request.json @@ -59,6 +59,14 @@ } } }, + "customer_acceptance": { + "acceptance_type": "online", + "accepted_at": "2022-09-10T10:11:12Z", + "online": { + "ip_address": "123.32.25.123", + "user_agent": "Mozilla/5.0 (Linux; Android 12; SM-S906N Build/QP1A.190711.020; wv) AppleWebKit/537.36 (KHTML, like Gecko) Version/4.0 Chrome/80.0.3987.119 Mobile Safari/537.36" + } + }, "billing": { "address": { "line1": "1467", diff --git a/postman/collection-dir/paypal/Flow Testcases/Happy Cases/Scenario6-Create Wallet - Paypal/Payments - Create/request.json b/postman/collection-dir/paypal/Flow Testcases/Happy Cases/Scenario6-Create Wallet - Paypal/Payments - Create/request.json index 824bfb49230..7201fa121be 100644 --- a/postman/collection-dir/paypal/Flow Testcases/Happy Cases/Scenario6-Create Wallet - Paypal/Payments - Create/request.json +++ b/postman/collection-dir/paypal/Flow Testcases/Happy Cases/Scenario6-Create Wallet - Paypal/Payments - Create/request.json @@ -33,6 +33,14 @@ "authentication_type": "three_ds", "return_url": "https://duck.com", "setup_future_usage": "on_session", + "customer_acceptance": { + "acceptance_type": "online", + "accepted_at": "2022-09-10T10:11:12Z", + "online": { + "ip_address": "123.32.25.123", + "user_agent": "Mozilla/5.0 (Linux; Android 12; SM-S906N Build/QP1A.190711.020; wv) AppleWebKit/537.36 (KHTML, like Gecko) Version/4.0 Chrome/80.0.3987.119 Mobile Safari/537.36" + } + }, "billing": { "address": { "line1": "1467", diff --git a/postman/collection-dir/paypal/Flow Testcases/Happy Cases/Scenario7-Create Wallet - Paypal with confrm false/Payments - Confirm/request.json b/postman/collection-dir/paypal/Flow Testcases/Happy Cases/Scenario7-Create Wallet - Paypal with confrm false/Payments - Confirm/request.json index efa17534b1d..f5da408b2f3 100644 --- a/postman/collection-dir/paypal/Flow Testcases/Happy Cases/Scenario7-Create Wallet - Paypal with confrm false/Payments - Confirm/request.json +++ b/postman/collection-dir/paypal/Flow Testcases/Happy Cases/Scenario7-Create Wallet - Paypal with confrm false/Payments - Confirm/request.json @@ -45,6 +45,14 @@ "wallet": { "paypal_redirect": {} } + }, + "customer_acceptance": { + "acceptance_type": "online", + "accepted_at": "2022-09-10T10:11:12Z", + "online": { + "ip_address": "123.32.25.123", + "user_agent": "Mozilla/5.0 (Linux; Android 12; SM-S906N Build/QP1A.190711.020; wv) AppleWebKit/537.36 (KHTML, like Gecko) Version/4.0 Chrome/80.0.3987.119 Mobile Safari/537.36" + } } } }, diff --git a/postman/collection-dir/shift4/Flow Testcases/Variation Cases/Scenario9-Create a recurring payment with greater mandate amount/Payments - Create/request.json b/postman/collection-dir/shift4/Flow Testcases/Variation Cases/Scenario9-Create a recurring payment with greater mandate amount/Payments - Create/request.json index 57d625e7c39..fbbd60339e9 100644 --- a/postman/collection-dir/shift4/Flow Testcases/Variation Cases/Scenario9-Create a recurring payment with greater mandate amount/Payments - Create/request.json +++ b/postman/collection-dir/shift4/Flow Testcases/Variation Cases/Scenario9-Create a recurring payment with greater mandate amount/Payments - Create/request.json @@ -59,6 +59,14 @@ } } }, + "customer_acceptance": { + "acceptance_type": "online", + "accepted_at": "2022-09-10T10:11:12Z", + "online": { + "ip_address": "123.32.25.123", + "user_agent": "Mozilla/5.0 (Linux; Android 12; SM-S906N Build/QP1A.190711.020; wv) AppleWebKit/537.36 (KHTML, like Gecko) Version/4.0 Chrome/80.0.3987.119 Mobile Safari/537.36" + } + }, "billing": { "address": { "line1": "1467", diff --git a/postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario1-Create payment with confirm true/Payments - Create/request.json b/postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario1-Create payment with confirm true/Payments - Create/request.json index 93bcc23194f..9d0fac32c1f 100644 --- a/postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario1-Create payment with confirm true/Payments - Create/request.json +++ b/postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario1-Create payment with confirm true/Payments - Create/request.json @@ -35,6 +35,14 @@ "authentication_type": "no_three_ds", "return_url": "https://duck.com", "setup_future_usage": "on_session", + "customer_acceptance": { + "acceptance_type": "online", + "accepted_at": "2022-09-10T10:11:12Z", + "online": { + "ip_address": "123.32.25.123", + "user_agent": "Mozilla/5.0 (Linux; Android 12; SM-S906N Build/QP1A.190711.020; wv) AppleWebKit/537.36 (KHTML, like Gecko) Version/4.0 Chrome/80.0.3987.119 Mobile Safari/537.36" + } + }, "payment_method": "card", "payment_method_type": "debit", "payment_method_data": { diff --git a/postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario10-Create a mandate and recurring payment/Payments - Create/request.json b/postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario10-Create a mandate and recurring payment/Payments - Create/request.json index 3ffbe03a605..b5ef6b1afe2 100644 --- a/postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario10-Create a mandate and recurring payment/Payments - Create/request.json +++ b/postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario10-Create a mandate and recurring payment/Payments - Create/request.json @@ -59,6 +59,14 @@ } } }, + "customer_acceptance": { + "acceptance_type": "offline", + "accepted_at": "1963-05-03T04:07:52.723Z", + "online": { + "ip_address": "127.0.0.1", + "user_agent": "amet irure esse" + } + }, "billing": { "address": { "line1": "1467", @@ -98,12 +106,8 @@ }, "url": { "raw": "{{baseUrl}}/payments", - "host": [ - "{{baseUrl}}" - ], - "path": [ - "payments" - ] + "host": ["{{baseUrl}}"], + "path": ["payments"] }, "description": "To process a payment you will have to create a payment, attach a payment method and confirm. Depending on the user journey you wish to achieve, you may opt to all the steps in a single request or in a sequence of API request using following APIs: (i) Payments - Update, (ii) Payments - Confirm, and (iii) Payments - Capture" } diff --git a/postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario11-Refund recurring payment/Payments - Create/request.json b/postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario11-Refund recurring payment/Payments - Create/request.json index 9df18b5e886..61f007ede68 100644 --- a/postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario11-Refund recurring payment/Payments - Create/request.json +++ b/postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario11-Refund recurring payment/Payments - Create/request.json @@ -59,6 +59,14 @@ } } }, + "customer_acceptance": { + "acceptance_type": "online", + "accepted_at": "2022-09-10T10:11:12Z", + "online": { + "ip_address": "123.32.25.123", + "user_agent": "Mozilla/5.0 (Linux; Android 12; SM-S906N Build/QP1A.190711.020; wv) AppleWebKit/537.36 (KHTML, like Gecko) Version/4.0 Chrome/80.0.3987.119 Mobile Safari/537.36" + } + }, "shipping": { "address": { "line1": "1467", @@ -86,12 +94,8 @@ }, "url": { "raw": "{{baseUrl}}/payments", - "host": [ - "{{baseUrl}}" - ], - "path": [ - "payments" - ] + "host": ["{{baseUrl}}"], + "path": ["payments"] }, "description": "To process a payment you will have to create a payment, attach a payment method and confirm. Depending on the user journey you wish to achieve, you may opt to all the steps in a single request or in a sequence of API request using following APIs: (i) Payments - Update, (ii) Payments - Confirm, and (iii) Payments - Capture" } diff --git a/postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario20-Bank Debit-ach/Payments - Create/request.json b/postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario20-Bank Debit-ach/Payments - Create/request.json index eda0801c9cc..78d949505f4 100644 --- a/postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario20-Bank Debit-ach/Payments - Create/request.json +++ b/postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario20-Bank Debit-ach/Payments - Create/request.json @@ -23,9 +23,7 @@ "confirm": true, "business_label": "default", "capture_method": "automatic", - "connector": [ - "stripe" - ], + "connector": ["stripe"], "customer_id": "klarna", "capture_on": "2022-09-10T10:11:12Z", "authentication_type": "three_ds", @@ -55,6 +53,14 @@ } } }, + "customer_acceptance": { + "acceptance_type": "online", + "accepted_at": "2022-09-10T10:11:12Z", + "online": { + "ip_address": "123.32.25.123", + "user_agent": "Mozilla/5.0 (Linux; Android 12; SM-S906N Build/QP1A.190711.020; wv) AppleWebKit/537.36 (KHTML, like Gecko) Version/4.0 Chrome/80.0.3987.119 Mobile Safari/537.36" + } + }, "payment_method": "bank_debit", "payment_method_type": "ach", "payment_method_data": { @@ -85,12 +91,8 @@ }, "url": { "raw": "{{baseUrl}}/payments", - "host": [ - "{{baseUrl}}" - ], - "path": [ - "payments" - ] + "host": ["{{baseUrl}}"], + "path": ["payments"] }, "description": "To process a payment you will have to create a payment, attach a payment method and confirm. Depending on the user journey you wish to achieve, you may opt to all the steps in a single request or in a sequence of API request using following APIs: (i) Payments - Update, (ii) Payments - Confirm, and (iii) Payments - Capture" } diff --git a/postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario22- Update address and List Payment method/Payments - Confirm/request.json b/postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario22- Update address and List Payment method/Payments - Confirm/request.json index 20b99223ac4..43515f184b5 100644 --- a/postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario22- Update address and List Payment method/Payments - Confirm/request.json +++ b/postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario22- Update address and List Payment method/Payments - Confirm/request.json @@ -52,6 +52,7 @@ } } }, + "setup_future_usage": "off_session", "mandate_data": { "customer_acceptance": { "acceptance_type": "offline", @@ -73,7 +74,14 @@ } } }, - "setup_future_usage": "off_session", + "customer_acceptance": { + "acceptance_type": "offline", + "accepted_at": "1963-05-03T04:07:52.723Z", + "online": { + "ip_address": "127.0.0.1", + "user_agent": "amet irure esse" + } + }, "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", @@ -90,14 +98,8 @@ }, "url": { "raw": "{{baseUrl}}/payments/:id/confirm", - "host": [ - "{{baseUrl}}" - ], - "path": [ - "payments", - ":id", - "confirm" - ], + "host": ["{{baseUrl}}"], + "path": ["payments", ":id", "confirm"], "variable": [ { "key": "id", diff --git a/postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario22- Update address and List Payment method/Payments - Create/request.json b/postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario22- Update address and List Payment method/Payments - Create/request.json index 785122a83c5..beeb5b3983f 100644 --- a/postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario22- Update address and List Payment method/Payments - Create/request.json +++ b/postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario22- Update address and List Payment method/Payments - Create/request.json @@ -71,12 +71,8 @@ }, "url": { "raw": "{{baseUrl}}/payments", - "host": [ - "{{baseUrl}}" - ], - "path": [ - "payments" - ] + "host": ["{{baseUrl}}"], + "path": ["payments"] }, "description": "To process a payment you will have to create a payment, attach a payment method and confirm. Depending on the user journey you wish to achieve, you may opt to all the steps in a single request or in a sequence of API request using following APIs: (i) Payments - Update, (ii) Payments - Confirm, and (iii) Payments - Capture" } diff --git a/postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario23- Update Amount/Payments - Confirm/request.json b/postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario23- Update Amount/Payments - Confirm/request.json index 5a51941cf64..1b1757b9a49 100644 --- a/postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario23- Update Amount/Payments - Confirm/request.json +++ b/postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario23- Update Amount/Payments - Confirm/request.json @@ -29,7 +29,6 @@ "key": "Accept", "value": "application/json" }, - , { "key": "publishable_key", "value": "", @@ -58,6 +57,14 @@ } }, "setup_future_usage": "on_session", + "customer_acceptance": { + "acceptance_type": "offline", + "accepted_at": "1963-05-03T04:07:52.723Z", + "online": { + "ip_address": "127.0.0.1", + "user_agent": "amet irure esse" + } + }, "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", diff --git a/postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario24-Add card flow/Payments - Create/request.json b/postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario24-Add card flow/Payments - Create/request.json index 2019bae8790..2ac0cacfb99 100644 --- a/postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario24-Add card flow/Payments - Create/request.json +++ b/postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario24-Add card flow/Payments - Create/request.json @@ -33,6 +33,14 @@ "authentication_type": "no_three_ds", "return_url": "https://google.com", "setup_future_usage": "on_session", + "customer_acceptance": { + "acceptance_type": "offline", + "accepted_at": "1963-05-03T04:07:52.723Z", + "online": { + "ip_address": "127.0.0.1", + "user_agent": "amet irure esse" + } + }, "payment_method": "card", "payment_method_type": "credit", "payment_method_data": { @@ -93,12 +101,8 @@ }, "url": { "raw": "{{baseUrl}}/payments", - "host": [ - "{{baseUrl}}" - ], - "path": [ - "payments" - ] + "host": ["{{baseUrl}}"], + "path": ["payments"] }, "description": "To process a payment you will have to create a payment, attach a payment method and confirm. Depending on the user journey you wish to achieve, you may opt to all the steps in a single request or in a sequence of API request using following APIs: (i) Payments - Update, (ii) Payments - Confirm, and (iii) Payments - Capture" } diff --git a/postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario25-Don't Pass CVV for save card flow and verifysuccess payment/Payments - Create/request.json b/postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario25-Don't Pass CVV for save card flow and verifysuccess payment/Payments - Create/request.json index 4f02f7b6809..150106cfded 100644 --- a/postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario25-Don't Pass CVV for save card flow and verifysuccess payment/Payments - Create/request.json +++ b/postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario25-Don't Pass CVV for save card flow and verifysuccess payment/Payments - Create/request.json @@ -33,6 +33,14 @@ "authentication_type": "no_three_ds", "return_url": "https://google.com", "setup_future_usage": "on_session", + "customer_acceptance": { + "acceptance_type": "offline", + "accepted_at": "1963-05-03T04:07:52.723Z", + "online": { + "ip_address": "127.0.0.1", + "user_agent": "amet irure esse" + } + }, "payment_method": "card", "payment_method_type": "credit", "payment_method_data": { @@ -93,12 +101,8 @@ }, "url": { "raw": "{{baseUrl}}/payments", - "host": [ - "{{baseUrl}}" - ], - "path": [ - "payments" - ] + "host": ["{{baseUrl}}"], + "path": ["payments"] }, "description": "To process a payment you will have to create a payment, attach a payment method and confirm. Depending on the user journey you wish to achieve, you may opt to all the steps in a single request or in a sequence of API request using following APIs: (i) Payments - Update, (ii) Payments - Confirm, and (iii) Payments - Capture" } diff --git a/postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario26-Save card payment with manual capture/Payments - Create/request.json b/postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario26-Save card payment with manual capture/Payments - Create/request.json index 988bc4b800b..d73166871cd 100644 --- a/postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario26-Save card payment with manual capture/Payments - Create/request.json +++ b/postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario26-Save card payment with manual capture/Payments - Create/request.json @@ -33,6 +33,14 @@ "authentication_type": "no_three_ds", "return_url": "https://google.com", "setup_future_usage": "on_session", + "customer_acceptance": { + "acceptance_type": "offline", + "accepted_at": "1963-05-03T04:07:52.723Z", + "online": { + "ip_address": "127.0.0.1", + "user_agent": "amet irure esse" + } + }, "payment_method": "card", "payment_method_type": "credit", "payment_method_data": { @@ -93,12 +101,8 @@ }, "url": { "raw": "{{baseUrl}}/payments", - "host": [ - "{{baseUrl}}" - ], - "path": [ - "payments" - ] + "host": ["{{baseUrl}}"], + "path": ["payments"] }, "description": "To process a payment you will have to create a payment, attach a payment method and confirm. Depending on the user journey you wish to achieve, you may opt to all the steps in a single request or in a sequence of API request using following APIs: (i) Payments - Update, (ii) Payments - Confirm, and (iii) Payments - Capture" } diff --git a/postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario27-Create payment without customer_id and with billing address and shipping address/Payments - Create/request.json b/postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario27-Create payment without customer_id and with billing address and shipping address/Payments - Create/request.json index 60e56bb581c..6a9836d232c 100644 --- a/postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario27-Create payment without customer_id and with billing address and shipping address/Payments - Create/request.json +++ b/postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario27-Create payment without customer_id and with billing address and shipping address/Payments - Create/request.json @@ -35,6 +35,14 @@ "authentication_type": "no_three_ds", "return_url": "https://duck.com", "setup_future_usage": "on_session", + "customer_acceptance": { + "acceptance_type": "offline", + "accepted_at": "1963-05-03T04:07:52.723Z", + "online": { + "ip_address": "127.0.0.1", + "user_agent": "amet irure esse" + } + }, "payment_method": "card", "payment_method_type": "debit", "payment_method_data": { @@ -87,12 +95,8 @@ }, "url": { "raw": "{{baseUrl}}/payments", - "host": [ - "{{baseUrl}}" - ], - "path": [ - "payments" - ] + "host": ["{{baseUrl}}"], + "path": ["payments"] }, "description": "To process a payment you will have to create a payment, attach a payment method and confirm. Depending on the user journey you wish to achieve, you may opt to all the steps in a single request or in a sequence of API request using following APIs: (i) Payments - Update, (ii) Payments - Confirm, and (iii) Payments - Capture" } diff --git a/postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario28-Confirm a payment with requires_customer_action status/Payments - Create with confirm true/request.json b/postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario28-Confirm a payment with requires_customer_action status/Payments - Create with confirm true/request.json index d14ae6582c8..7e28058ccf6 100644 --- a/postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario28-Confirm a payment with requires_customer_action status/Payments - Create with confirm true/request.json +++ b/postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario28-Confirm a payment with requires_customer_action status/Payments - Create with confirm true/request.json @@ -35,6 +35,14 @@ "authentication_type": "three_ds", "return_url": "https://duck.com", "setup_future_usage": "on_session", + "customer_acceptance": { + "acceptance_type": "offline", + "accepted_at": "1963-05-03T04:07:52.723Z", + "online": { + "ip_address": "127.0.0.1", + "user_agent": "amet irure esse" + } + }, "payment_method": "card", "payment_method_data": { "card": { diff --git a/postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario6-Create 3DS payment/Payments - Create/request.json b/postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario6-Create 3DS payment/Payments - Create/request.json index d14ae6582c8..7e28058ccf6 100644 --- a/postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario6-Create 3DS payment/Payments - Create/request.json +++ b/postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario6-Create 3DS payment/Payments - Create/request.json @@ -35,6 +35,14 @@ "authentication_type": "three_ds", "return_url": "https://duck.com", "setup_future_usage": "on_session", + "customer_acceptance": { + "acceptance_type": "offline", + "accepted_at": "1963-05-03T04:07:52.723Z", + "online": { + "ip_address": "127.0.0.1", + "user_agent": "amet irure esse" + } + }, "payment_method": "card", "payment_method_data": { "card": { diff --git a/postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario8-Create a failure card payment with confirm true/Payments - Create/request.json b/postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario8-Create a failure card payment with confirm true/Payments - Create/request.json index 6d1bc5e0a0d..a3e0f52b8d7 100644 --- a/postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario8-Create a failure card payment with confirm true/Payments - Create/request.json +++ b/postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario8-Create a failure card payment with confirm true/Payments - Create/request.json @@ -35,6 +35,14 @@ "authentication_type": "no_three_ds", "return_url": "https://duck.com", "setup_future_usage": "on_session", + "customer_acceptance": { + "acceptance_type": "offline", + "accepted_at": "1963-05-03T04:07:52.723Z", + "online": { + "ip_address": "127.0.0.1", + "user_agent": "amet irure esse" + } + }, "payment_method": "card", "payment_method_type": "debit", "payment_method_data": { @@ -87,12 +95,8 @@ }, "url": { "raw": "{{baseUrl}}/payments", - "host": [ - "{{baseUrl}}" - ], - "path": [ - "payments" - ] + "host": ["{{baseUrl}}"], + "path": ["payments"] }, "description": "To process a payment you will have to create a payment, attach a payment method and confirm. Depending on the user journey you wish to achieve, you may opt to all the steps in a single request or in a sequence of API request using following APIs: (i) Payments - Update, (ii) Payments - Confirm, and (iii) Payments - Capture" } diff --git a/postman/collection-dir/stripe/Flow Testcases/Variation Cases/Scenario9-Create a recurring payment with greater mandate amount/Payments - Create/request.json b/postman/collection-dir/stripe/Flow Testcases/Variation Cases/Scenario9-Create a recurring payment with greater mandate amount/Payments - Create/request.json index a5c9391cf74..b5ef6b1afe2 100644 --- a/postman/collection-dir/stripe/Flow Testcases/Variation Cases/Scenario9-Create a recurring payment with greater mandate amount/Payments - Create/request.json +++ b/postman/collection-dir/stripe/Flow Testcases/Variation Cases/Scenario9-Create a recurring payment with greater mandate amount/Payments - Create/request.json @@ -59,6 +59,14 @@ } } }, + "customer_acceptance": { + "acceptance_type": "offline", + "accepted_at": "1963-05-03T04:07:52.723Z", + "online": { + "ip_address": "127.0.0.1", + "user_agent": "amet irure esse" + } + }, "billing": { "address": { "line1": "1467", diff --git a/postman/collection-dir/stripe/PaymentMethods/Payments - Create/request.json b/postman/collection-dir/stripe/PaymentMethods/Payments - Create/request.json index ac22dac750c..cc330f3c8f7 100644 --- a/postman/collection-dir/stripe/PaymentMethods/Payments - Create/request.json +++ b/postman/collection-dir/stripe/PaymentMethods/Payments - Create/request.json @@ -33,6 +33,14 @@ "authentication_type": "no_three_ds", "return_url": "https://duck.com", "setup_future_usage": "on_session", + "customer_acceptance": { + "acceptance_type": "offline", + "accepted_at": "1963-05-03T04:07:52.723Z", + "online": { + "ip_address": "127.0.0.1", + "user_agent": "amet irure esse" + } + }, "payment_method": "card", "payment_method_type": "debit", "payment_method_data": { diff --git a/postman/collection-dir/zen/Flow Testcases/Happy Cases/Scenario1-Create payment with confirm true/Payments - Create/request.json b/postman/collection-dir/zen/Flow Testcases/Happy Cases/Scenario1-Create payment with confirm true/Payments - Create/request.json index 7afc6d61c49..fd84bcaadb5 100644 --- a/postman/collection-dir/zen/Flow Testcases/Happy Cases/Scenario1-Create payment with confirm true/Payments - Create/request.json +++ b/postman/collection-dir/zen/Flow Testcases/Happy Cases/Scenario1-Create payment with confirm true/Payments - Create/request.json @@ -32,6 +32,14 @@ "authentication_type": "no_three_ds", "return_url": "https://duck.com", "setup_future_usage": "on_session", + "customer_acceptance": { + "acceptance_type": "offline", + "accepted_at": "1963-05-03T04:07:52.723Z", + "online": { + "ip_address": "127.0.0.1", + "user_agent": "amet irure esse" + } + }, "billing": { "address": { "line1": "1467", diff --git a/postman/collection-dir/zen/Flow Testcases/Happy Cases/Scenario2-Create payment with confirm false/Payments - Confirm/request.json b/postman/collection-dir/zen/Flow Testcases/Happy Cases/Scenario2-Create payment with confirm false/Payments - Confirm/request.json index 778f8872687..2f295eba3a8 100644 --- a/postman/collection-dir/zen/Flow Testcases/Happy Cases/Scenario2-Create payment with confirm false/Payments - Confirm/request.json +++ b/postman/collection-dir/zen/Flow Testcases/Happy Cases/Scenario2-Create payment with confirm false/Payments - Confirm/request.json @@ -51,6 +51,14 @@ "java_script_enabled": true, "ip_address": "127.0.0.1" }, + "customer_acceptance": { + "acceptance_type": "offline", + "accepted_at": "1963-05-03T04:07:52.723Z", + "online": { + "ip_address": "127.0.0.1", + "user_agent": "amet irure esse" + } + }, "order_details": [ { "amount": 6540, @@ -60,6 +68,7 @@ ] } }, + "url": { "raw": "{{baseUrl}}/payments/:id/confirm", "host": ["{{baseUrl}}"], diff --git a/postman/collection-dir/zen/Flow Testcases/Happy Cases/Scenario3-Create payment without PMD/Payments - Create/request.json b/postman/collection-dir/zen/Flow Testcases/Happy Cases/Scenario3-Create payment without PMD/Payments - Create/request.json index a6aef6ecb71..042a4bc1f73 100644 --- a/postman/collection-dir/zen/Flow Testcases/Happy Cases/Scenario3-Create payment without PMD/Payments - Create/request.json +++ b/postman/collection-dir/zen/Flow Testcases/Happy Cases/Scenario3-Create payment without PMD/Payments - Create/request.json @@ -32,6 +32,14 @@ "authentication_type": "no_three_ds", "return_url": "https://duck.com", "setup_future_usage": "on_session", + "customer_acceptance": { + "acceptance_type": "offline", + "accepted_at": "1963-05-03T04:07:52.723Z", + "online": { + "ip_address": "127.0.0.1", + "user_agent": "amet irure esse" + } + }, "billing": { "address": { "line1": "1467", diff --git a/postman/collection-dir/zen/Flow Testcases/Happy Cases/Scenario4-Create 3DS payment/Payments - Create/request.json b/postman/collection-dir/zen/Flow Testcases/Happy Cases/Scenario4-Create 3DS payment/Payments - Create/request.json index ee354325323..bed15211eea 100644 --- a/postman/collection-dir/zen/Flow Testcases/Happy Cases/Scenario4-Create 3DS payment/Payments - Create/request.json +++ b/postman/collection-dir/zen/Flow Testcases/Happy Cases/Scenario4-Create 3DS payment/Payments - Create/request.json @@ -32,6 +32,14 @@ "authentication_type": "no_three_ds", "return_url": "https://duck.com", "setup_future_usage": "off_session", + "customer_acceptance": { + "acceptance_type": "offline", + "accepted_at": "1963-05-03T04:07:52.723Z", + "online": { + "ip_address": "127.0.0.1", + "user_agent": "amet irure esse" + } + }, "order_details": [ { "amount": 6540, diff --git a/postman/collection-dir/zen/Flow Testcases/Happy Cases/Scenario5-Create 3DS payment with confrm false/Payments - Create/request.json b/postman/collection-dir/zen/Flow Testcases/Happy Cases/Scenario5-Create 3DS payment with confrm false/Payments - Create/request.json index 01fa4013653..91a932b12d9 100644 --- a/postman/collection-dir/zen/Flow Testcases/Happy Cases/Scenario5-Create 3DS payment with confrm false/Payments - Create/request.json +++ b/postman/collection-dir/zen/Flow Testcases/Happy Cases/Scenario5-Create 3DS payment with confrm false/Payments - Create/request.json @@ -32,6 +32,14 @@ "authentication_type": "no_three_ds", "return_url": "https://duck.com", "setup_future_usage": "on_session", + "customer_acceptance": { + "acceptance_type": "offline", + "accepted_at": "1963-05-03T04:07:52.723Z", + "online": { + "ip_address": "127.0.0.1", + "user_agent": "amet irure esse" + } + }, "billing": { "address": { "line1": "1467", diff --git a/postman/collection-dir/zen/Flow Testcases/QuickStart/Payments - Create/request.json b/postman/collection-dir/zen/Flow Testcases/QuickStart/Payments - Create/request.json index ee354325323..aa51751ae1e 100644 --- a/postman/collection-dir/zen/Flow Testcases/QuickStart/Payments - Create/request.json +++ b/postman/collection-dir/zen/Flow Testcases/QuickStart/Payments - Create/request.json @@ -31,7 +31,15 @@ "description": "Its my first payment request", "authentication_type": "no_three_ds", "return_url": "https://duck.com", - "setup_future_usage": "off_session", + "setup_future_usage": "on_session", + "customer_acceptance": { + "acceptance_type": "offline", + "accepted_at": "1963-05-03T04:07:52.723Z", + "online": { + "ip_address": "127.0.0.1", + "user_agent": "amet irure esse" + } + }, "order_details": [ { "amount": 6540, diff --git a/postman/collection-dir/zen/Flow Testcases/Variation Cases/Scenario2-Confirming the payment without PMD/Payments - Create/request.json b/postman/collection-dir/zen/Flow Testcases/Variation Cases/Scenario2-Confirming the payment without PMD/Payments - Create/request.json index a6aef6ecb71..042a4bc1f73 100644 --- a/postman/collection-dir/zen/Flow Testcases/Variation Cases/Scenario2-Confirming the payment without PMD/Payments - Create/request.json +++ b/postman/collection-dir/zen/Flow Testcases/Variation Cases/Scenario2-Confirming the payment without PMD/Payments - Create/request.json @@ -32,6 +32,14 @@ "authentication_type": "no_three_ds", "return_url": "https://duck.com", "setup_future_usage": "on_session", + "customer_acceptance": { + "acceptance_type": "offline", + "accepted_at": "1963-05-03T04:07:52.723Z", + "online": { + "ip_address": "127.0.0.1", + "user_agent": "amet irure esse" + } + }, "billing": { "address": { "line1": "1467",
2024-02-29T07:39:24Z
## Type of Change <!-- Put an `x` in the boxes that apply --> - [ ] Bugfix - [x] New feature - [ ] Enhancement - [ ] Refactoring - [ ] Dependency updates - [ ] Documentation - [ ] CI/CD ## Description store customer_acceptance in the payment_methods table and some changes to setup_future_usage - setup_future_usage should be inferred from the create and if passed in confirm should override the one in create - If customer_acceptance is passed then only the card will be saved on hyper switch's end ### 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? -make a on_session payment without customer_acceptance, card will not be saved -> Create ``` curl --location 'http://localhost:8080/payments' \ --header 'Content-Type: application/json' \ --header 'Accept: application/json' \ --header 'api-key: dev_O7Znp5PhvGpSeE22Hxn4K8snHW6ObRfbA8R1isvLhUXpJRGHOINvlGufM4mGDAqj' \ --data-raw ' {"amount": 6677, "currency": "USD", "confirm": false, "capture_method": "automatic", "authentication_type": "no_three_ds", "customer_id": "97cc", "email": "something@gmail.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" } }, "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" } }, "metadata": { "order_details": { "product_name": "Apple iphone 15", "quantity": 1 } }, "business_country": "US", "business_label": "default", "setup_future_usage": "on_session" }' ``` -> Confirm ``` curl --location 'http://localhost:8080/payments/pay_IHI92Rlo3i6kwihECXVr/confirm' \ --header 'Content-Type: application/json' \ --header 'Accept: application/json' \ --header 'api-key: dev_O7Znp5PhvGpSeE22Hxn4K8snHW6ObRfbA8R1isvLhUXpJRGHOINvlGufM4mGDAqj' \ --data '{ "confirm": true, "payment_type": "normal", "payment_method": "card", "payment_method_type": "debit", "payment_method_data": { "card": { "card_number":"4242424242424242", "card_exp_month": "11", "card_exp_year": "2040", "card_holder_name": "AKA", "card_cvc": "123", "nick_name": "HELO" } } }' ``` ![Screenshot 2024-03-05 at 1 47 56 PM](https://github.com/juspay/hyperswitch/assets/55580080/334f668c-fcd2-4b89-b31b-a5992865f1f4) -make a off_session payment without mandate_type ,i.e., MIT with customer_acceptance, the card will be saved on our end -> Create ``` curl --location 'http://localhost:8080/payments' \ --header 'Content-Type: application/json' \ --header 'Accept: application/json' \ --header 'api-key: dev_O7Znp5PhvGpSeE22Hxn4K8snHW6ObRfbA8R1isvLhUXpJRGHOINvlGufM4mGDAqj' \ --data-raw ' {"amount":0, "currency": "USD", "confirm": false, "capture_method": "automatic", "authentication_type": "no_three_ds", "customer_id": "q7cc", "email": "something@gmail.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" } }, "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" } }, "metadata": { "order_details": { "product_name": "Apple iphone 15", "quantity": 1 } }, "business_country": "US", "business_label": "default", "setup_future_usage": "off_session" }' ``` -> Confirm ``` curl --location 'http://localhost:8080/payments/pay_IHI92Rlo3i6kwihECXVr/confirm' \ --header 'Content-Type: application/json' \ --header 'Accept: application/json' \ --header 'api-key: dev_O7Znp5PhvGpSeE22Hxn4K8snHW6ObRfbA8R1isvLhUXpJRGHOINvlGufM4mGDAqj' \ --data '{ "confirm": true, "payment_type": "setup_mandate", "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_type": "debit", "payment_method_data": { "card": { "card_number":"4242424242424242", "card_exp_month": "11", "card_exp_year": "2040", "card_holder_name": "AKA", "card_cvc": "123", "nick_name": "HELO" } } }' ``` ![Screenshot 2024-03-05 at 1 45 30 PM](https://github.com/juspay/hyperswitch/assets/55580080/b7826fc2-08c7-4d82-84c8-f5bee65c7fef) <img width="1720" alt="Screenshot 2024-03-05 at 1 46 40 PM" src="https://github.com/juspay/hyperswitch/assets/55580080/ab269405-fa54-45d9-a1a3-f9135d94f839"> -to save the card both, customer_acceptance and setup_future_usage must be passed - if its a mandate_payment , we can have off_session in create with mandate type and customer_acceptance in confirm and also we can have customer_acceptance inside the mandate_data field which is for backwards compatibility currently there in mandate_data ## 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 - [ ] I added a [CHANGELOG](/CHANGELOG.md) entry if applicable
5eff9d47d3e53d380ef792a8fbdf06ecf78d3d16
-make a on_session payment without customer_acceptance, card will not be saved -> Create ``` curl --location 'http://localhost:8080/payments' \ --header 'Content-Type: application/json' \ --header 'Accept: application/json' \ --header 'api-key: dev_O7Znp5PhvGpSeE22Hxn4K8snHW6ObRfbA8R1isvLhUXpJRGHOINvlGufM4mGDAqj' \ --data-raw ' {"amount": 6677, "currency": "USD", "confirm": false, "capture_method": "automatic", "authentication_type": "no_three_ds", "customer_id": "97cc", "email": "something@gmail.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" } }, "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" } }, "metadata": { "order_details": { "product_name": "Apple iphone 15", "quantity": 1 } }, "business_country": "US", "business_label": "default", "setup_future_usage": "on_session" }' ``` -> Confirm ``` curl --location 'http://localhost:8080/payments/pay_IHI92Rlo3i6kwihECXVr/confirm' \ --header 'Content-Type: application/json' \ --header 'Accept: application/json' \ --header 'api-key: dev_O7Znp5PhvGpSeE22Hxn4K8snHW6ObRfbA8R1isvLhUXpJRGHOINvlGufM4mGDAqj' \ --data '{ "confirm": true, "payment_type": "normal", "payment_method": "card", "payment_method_type": "debit", "payment_method_data": { "card": { "card_number":"4242424242424242", "card_exp_month": "11", "card_exp_year": "2040", "card_holder_name": "AKA", "card_cvc": "123", "nick_name": "HELO" } } }' ``` ![Screenshot 2024-03-05 at 1 47 56 PM](https://github.com/juspay/hyperswitch/assets/55580080/334f668c-fcd2-4b89-b31b-a5992865f1f4) -make a off_session payment without mandate_type ,i.e., MIT with customer_acceptance, the card will be saved on our end -> Create ``` curl --location 'http://localhost:8080/payments' \ --header 'Content-Type: application/json' \ --header 'Accept: application/json' \ --header 'api-key: dev_O7Znp5PhvGpSeE22Hxn4K8snHW6ObRfbA8R1isvLhUXpJRGHOINvlGufM4mGDAqj' \ --data-raw ' {"amount":0, "currency": "USD", "confirm": false, "capture_method": "automatic", "authentication_type": "no_three_ds", "customer_id": "q7cc", "email": "something@gmail.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" } }, "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" } }, "metadata": { "order_details": { "product_name": "Apple iphone 15", "quantity": 1 } }, "business_country": "US", "business_label": "default", "setup_future_usage": "off_session" }' ``` -> Confirm ``` curl --location 'http://localhost:8080/payments/pay_IHI92Rlo3i6kwihECXVr/confirm' \ --header 'Content-Type: application/json' \ --header 'Accept: application/json' \ --header 'api-key: dev_O7Znp5PhvGpSeE22Hxn4K8snHW6ObRfbA8R1isvLhUXpJRGHOINvlGufM4mGDAqj' \ --data '{ "confirm": true, "payment_type": "setup_mandate", "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_type": "debit", "payment_method_data": { "card": { "card_number":"4242424242424242", "card_exp_month": "11", "card_exp_year": "2040", "card_holder_name": "AKA", "card_cvc": "123", "nick_name": "HELO" } } }' ``` ![Screenshot 2024-03-05 at 1 45 30 PM](https://github.com/juspay/hyperswitch/assets/55580080/b7826fc2-08c7-4d82-84c8-f5bee65c7fef) <img width="1720" alt="Screenshot 2024-03-05 at 1 46 40 PM" src="https://github.com/juspay/hyperswitch/assets/55580080/ab269405-fa54-45d9-a1a3-f9135d94f839"> -to save the card both, customer_acceptance and setup_future_usage must be passed - if its a mandate_payment , we can have off_session in create with mandate type and customer_acceptance in confirm and also we can have customer_acceptance inside the mandate_data field which is for backwards compatibility currently there in mandate_data
juspay/hyperswitch
juspay__hyperswitch-3741
Bug: Merchant Payment Method List changes for wallet restrictions Since we are currently not getting any differentiators for multiple mandates set via a single wallet, we will be restricting setting up recurring payment for wallet only once. - In Merchant Payment Method list, wallet types which are already saved and in active state for a customer should not be listed
diff --git a/crates/router/src/core/payment_methods/cards.rs b/crates/router/src/core/payment_methods/cards.rs index ce7f48405e2..8d54a6be408 100644 --- a/crates/router/src/core/payment_methods/cards.rs +++ b/crates/router/src/core/payment_methods/cards.rs @@ -1316,6 +1316,47 @@ pub async fn list_payment_methods( .await?; } + // Filter out applepay payment method from mca if customer has already saved it + response + .iter() + .position(|pm| { + pm.payment_method == enums::PaymentMethod::Wallet + && pm.payment_method_type == enums::PaymentMethodType::ApplePay + }) + .as_ref() + .zip(customer.as_ref()) + .async_map(|(index, customer)| async { + match db + .find_payment_method_by_customer_id_merchant_id_list( + &customer.customer_id, + &merchant_account.merchant_id, + None, + ) + .await + { + Ok(customer_payment_methods) => { + if customer_payment_methods.iter().any(|pm| { + pm.payment_method == enums::PaymentMethod::Wallet + && pm.payment_method_type == Some(enums::PaymentMethodType::ApplePay) + }) { + response.remove(*index); + } + Ok(()) + } + Err(error) => { + if error.current_context().is_db_not_found() { + Ok(()) + } else { + Err(error) + .change_context(errors::ApiErrorResponse::InternalServerError) + .attach_printable("failed to find payment methods for a customer") + } + } + } + }) + .await + .transpose()?; + let mut pmt_to_auth_connector = HashMap::new(); if let Some((payment_attempt, payment_intent)) =
2024-03-04T14:39:43Z
## 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 --> Since we are currently not getting any differentiators for multiple mandates set via a single wallet, we will be restricting setting up recurring payment for wallet only once. - In Merchant Payment Method list, wallet types which are already saved and in active state for a customer should not be listed ### 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. Create mca ``` curl --location 'http://localhost:8080/account/merchant_1709561576/connectors' \ --header 'Content-Type: application/json' \ --header 'Accept: application/json' \ --header 'api-key: test_admin' \ --data '{ "connector_type": "fiz_operations", "connector_name": "stripe", "connector_account_details": { "auth_type": "HeaderKey", "api_key": "abc" }, "test_mode": false, "disabled": false, "payment_methods_enabled": [ { "payment_method": "card", "payment_method_types": [ { "payment_method_type": "credit", "card_networks": [ "Visa", "Mastercard" ], "minimum_amount": 1, "maximum_amount": 68607706, "recurring_enabled": true, "installment_payment_enabled": true }, { "payment_method_type": "debit", "card_networks": [ "Visa", "Mastercard" ], "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": "apple_pay", "payment_experience": "invoke_sdk_client", "minimum_amount": 1, "maximum_amount": 68607706, "recurring_enabled": true, "installment_payment_enabled": true }, { "payment_method_type": "google_pay", "payment_experience": "invoke_sdk_client", "minimum_amount": 1, "maximum_amount": 68607706, "recurring_enabled": true, "installment_payment_enabled": true } ] } ], "metadata": { "apple_pay_combined": { "manual": { "session_token_data": { "initiative": "web", "certificate": "certificate", "display_name": "applepay", "certificate_keys": "keys", "initiative_context": "sdk-test-app.netlify.app", "merchant_identifier": "xyz" }, "payment_request_data": { "label": "applepay", "supported_networks": [ "visa", "masterCard", "amex", "discover" ], "merchant_capabilities": [ "supports3DS" ] } } }, "google_pay": { "merchant_info": { "merchant_name": "Stripe" }, "allowed_payment_methods": [ { "type": "CARD", "parameters": { "allowed_auth_methods": [ "PAN_ONLY", "CRYPTOGRAM_3DS" ], "allowed_card_networks": [ "AMEX", "DISCOVER", "INTERAC", "JCB", "MASTERCARD", "VISA" ] }, "tokenization_specification": { "type": "PAYMENT_GATEWAY", "parameters": { "gateway": "stripe", "stripe:version": "2018-10-31", "stripe:publishableKey": "abc" } } } ] } }, "connector_webhook_details": { "merchant_secret": "MyWebhookSecret" }, "business_country": "US", "business_label": "default" }' ``` 2. Create a applepay wallet payment so that wallet entry gets saved in `payment_methods` table ``` curl --location 'http://localhost:8080/payments' \ --header 'Content-Type: application/json' \ --header 'Accept: application/json' \ --header 'api-key: dev_UyebBGu4SpiswmyxyM5ISeJO5BoAVQO8yWX20QFoKFBwB7q50t23zvH3xRqQ6auv' \ --data-raw '{ "amount": 650, "currency": "USD", "confirm": true, "business_country": "US", "business_label": "default", "amount_to_capture": 650, "customer_id": "{{customer_id}}", "capture_method": "automatic", "capture_on": "2022-09-10T10:11:12Z", "authentication_type": "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", "statement_descriptor_name": "Juspay", "statement_descriptor_suffix": "Router", "payment_method": "wallet", "payment_method_type": "apple_pay", "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" } }, "payment_method_data": { "wallet": { "apple_pay": { "payment_data": "xyz", "payment_method": { "display_name": "Visa 0326", "network": "Mastercard", "type": "debit" }, "transaction_identifier": "abc" } } }, "customer_acceptance": { "acceptance_type": "offline", "accepted_at": "1963-05-03T04:07:52.723Z", "online": { "ip_address": "in sit", "user_agent": "amet irure esse" } } }' ``` 3. Do `list_customer_payment_method`. Find the wallet entry and get the `payment_method_id` from response 4. Now do a payment with any payment method with `confirm = false` 5. Do list MCA with `client_secret` ``` curl --location 'http://localhost:8080/account/payment_methods?client_secret=abc' \ --header 'Accept: application/json' \ --header 'api-key: abc' \ --data '' ``` 6. Applepay shoudn't be listed in the result (Applepay is configured in merchant MCA and applepay payment method exists for customer, hence it has to be filtered) ## 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 - [ ] I added a [CHANGELOG](/CHANGELOG.md) entry if applicable
087932f06044454570c971def0e82dc3d838598c
1. Create mca ``` curl --location 'http://localhost:8080/account/merchant_1709561576/connectors' \ --header 'Content-Type: application/json' \ --header 'Accept: application/json' \ --header 'api-key: test_admin' \ --data '{ "connector_type": "fiz_operations", "connector_name": "stripe", "connector_account_details": { "auth_type": "HeaderKey", "api_key": "abc" }, "test_mode": false, "disabled": false, "payment_methods_enabled": [ { "payment_method": "card", "payment_method_types": [ { "payment_method_type": "credit", "card_networks": [ "Visa", "Mastercard" ], "minimum_amount": 1, "maximum_amount": 68607706, "recurring_enabled": true, "installment_payment_enabled": true }, { "payment_method_type": "debit", "card_networks": [ "Visa", "Mastercard" ], "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": "apple_pay", "payment_experience": "invoke_sdk_client", "minimum_amount": 1, "maximum_amount": 68607706, "recurring_enabled": true, "installment_payment_enabled": true }, { "payment_method_type": "google_pay", "payment_experience": "invoke_sdk_client", "minimum_amount": 1, "maximum_amount": 68607706, "recurring_enabled": true, "installment_payment_enabled": true } ] } ], "metadata": { "apple_pay_combined": { "manual": { "session_token_data": { "initiative": "web", "certificate": "certificate", "display_name": "applepay", "certificate_keys": "keys", "initiative_context": "sdk-test-app.netlify.app", "merchant_identifier": "xyz" }, "payment_request_data": { "label": "applepay", "supported_networks": [ "visa", "masterCard", "amex", "discover" ], "merchant_capabilities": [ "supports3DS" ] } } }, "google_pay": { "merchant_info": { "merchant_name": "Stripe" }, "allowed_payment_methods": [ { "type": "CARD", "parameters": { "allowed_auth_methods": [ "PAN_ONLY", "CRYPTOGRAM_3DS" ], "allowed_card_networks": [ "AMEX", "DISCOVER", "INTERAC", "JCB", "MASTERCARD", "VISA" ] }, "tokenization_specification": { "type": "PAYMENT_GATEWAY", "parameters": { "gateway": "stripe", "stripe:version": "2018-10-31", "stripe:publishableKey": "abc" } } } ] } }, "connector_webhook_details": { "merchant_secret": "MyWebhookSecret" }, "business_country": "US", "business_label": "default" }' ``` 2. Create a applepay wallet payment so that wallet entry gets saved in `payment_methods` table ``` curl --location 'http://localhost:8080/payments' \ --header 'Content-Type: application/json' \ --header 'Accept: application/json' \ --header 'api-key: dev_UyebBGu4SpiswmyxyM5ISeJO5BoAVQO8yWX20QFoKFBwB7q50t23zvH3xRqQ6auv' \ --data-raw '{ "amount": 650, "currency": "USD", "confirm": true, "business_country": "US", "business_label": "default", "amount_to_capture": 650, "customer_id": "{{customer_id}}", "capture_method": "automatic", "capture_on": "2022-09-10T10:11:12Z", "authentication_type": "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", "statement_descriptor_name": "Juspay", "statement_descriptor_suffix": "Router", "payment_method": "wallet", "payment_method_type": "apple_pay", "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" } }, "payment_method_data": { "wallet": { "apple_pay": { "payment_data": "xyz", "payment_method": { "display_name": "Visa 0326", "network": "Mastercard", "type": "debit" }, "transaction_identifier": "abc" } } }, "customer_acceptance": { "acceptance_type": "offline", "accepted_at": "1963-05-03T04:07:52.723Z", "online": { "ip_address": "in sit", "user_agent": "amet irure esse" } } }' ``` 3. Do `list_customer_payment_method`. Find the wallet entry and get the `payment_method_id` from response 4. Now do a payment with any payment method with `confirm = false` 5. Do list MCA with `client_secret` ``` curl --location 'http://localhost:8080/account/payment_methods?client_secret=abc' \ --header 'Accept: application/json' \ --header 'api-key: abc' \ --data '' ``` 6. Applepay shoudn't be listed in the result (Applepay is configured in merchant MCA and applepay payment method exists for customer, hence it has to be filtered)
juspay/hyperswitch
juspay__hyperswitch-3734
Bug: [CI] Update NMI postman collection Existing NMI postman collection is outdated and needs to be updated to the latest one look after regressions
2024-02-24T17:21:42Z
## Type of Change <!-- Put an `x` in the boxes that apply --> - [ ] Bugfix - [ ] New feature - [ ] Enhancement - [x] Refactoring - [ ] Dependency updates - [ ] Documentation - [x] CI/CD ## Description <!-- Describe your changes in detail --> This PR aims at refactoring NMI collection by bringing it back to life. Added more flows to look after regressions. Closes #3734 ### 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). --> We need to check for regressions. ## 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)? --> Ran the collection: <img width="980" alt="image" src="https://github.com/juspay/hyperswitch/assets/69745008/9aaad0eb-a4d7-4735-9d8c-303d323fc915"> There is a bug in NMI connector which needs to be addressed. Created a separate collection to reproduce it. ## 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 - [ ] I added a [CHANGELOG](/CHANGELOG.md) entry if applicable
734327a957c216511b182151a2f0b27819e7e3bb
Ran the collection: <img width="980" alt="image" src="https://github.com/juspay/hyperswitch/assets/69745008/9aaad0eb-a4d7-4735-9d8c-303d323fc915"> There is a bug in NMI connector which needs to be addressed. Created a separate collection to reproduce it.
juspay/hyperswitch
juspay__hyperswitch-3733
Bug: [FIX] Add update mandate config in docker-compose file ### Feature Description Add update mandate config in docker-compose file ### Possible Implementation Add update mandate config in docker-compose 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!
diff --git a/config/docker_compose.toml b/config/docker_compose.toml index 3f7c64624fa..8170132bb85 100644 --- a/config/docker_compose.toml +++ b/config/docker_compose.toml @@ -359,6 +359,9 @@ bank_redirect.ideal = {connector_list = "stripe,adyen,globalpay"} bank_redirect.sofort = {connector_list = "stripe,adyen,globalpay"} bank_redirect.giropay = {connector_list = "adyen,globalpay"} +[mandates.update_mandate_supported] +card.credit ={connector_list ="cybersource"} +card.debit = {connector_list ="cybersource"} [connector_customer] connector_list = "gocardless,stax,stripe"
2024-02-20T17:07:37Z
## Type of Change <!-- Put an `x` in the boxes that apply --> - [x] Bugfix - [ ] New feature - [ ] Enhancement - [ ] Refactoring - [ ] Dependency updates - [ ] Documentation - [ ] CI/CD ## Description add update mandate config in docker_compose.toml file ### 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? Cannot test this PR as this is just a config addition ## 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 - [ ] I added a [CHANGELOG](/CHANGELOG.md) entry if applicable
6aeb44091b34f202b60868028979b3720e3507ce
Cannot test this PR as this is just a config addition
juspay/hyperswitch
juspay__hyperswitch-3742
Bug: Locker ID as a soft link for Payment Methods Decoupling the Payment Method ID and Locker ID to allow more flexibility in PM ID usage for other features/components - Add Card operation to save the Locker ID in the `locker_id` column of the PM table and generate and add a separate PM ID - During retrieve, locker fetch to happen based on Locker ID with Payment Method ID as fallback (for ensuring continuity)
diff --git a/crates/diesel_models/src/payment_method.rs b/crates/diesel_models/src/payment_method.rs index d8b46c1932e..f9767e2939b 100644 --- a/crates/diesel_models/src/payment_method.rs +++ b/crates/diesel_models/src/payment_method.rs @@ -33,6 +33,7 @@ pub struct PaymentMethod { pub payment_method_issuer_code: Option<storage_enums::PaymentMethodIssuerCode>, pub metadata: Option<pii::SecretSerdeValue>, pub payment_method_data: Option<Encryption>, + pub locker_id: Option<String>, } #[derive(Clone, Debug, Eq, PartialEq, Insertable, Queryable, router_derive::DebugAsDisplay)] @@ -59,6 +60,7 @@ pub struct PaymentMethodNew { pub last_modified: PrimitiveDateTime, pub metadata: Option<pii::SecretSerdeValue>, pub payment_method_data: Option<Encryption>, + pub locker_id: Option<String>, } impl Default for PaymentMethodNew { @@ -69,6 +71,7 @@ impl Default for PaymentMethodNew { customer_id: String::default(), merchant_id: String::default(), payment_method_id: String::default(), + locker_id: Option::default(), payment_method: storage_enums::PaymentMethod::default(), payment_method_type: Option::default(), payment_method_issuer: Option::default(), diff --git a/crates/diesel_models/src/query/payment_method.rs b/crates/diesel_models/src/query/payment_method.rs index b1ea3ee388a..298db2a234b 100644 --- a/crates/diesel_models/src/query/payment_method.rs +++ b/crates/diesel_models/src/query/payment_method.rs @@ -44,6 +44,15 @@ impl PaymentMethod { .await } + #[instrument(skip(conn))] + pub async fn find_by_locker_id(conn: &PgPooledConn, locker_id: &str) -> StorageResult<Self> { + generics::generic_find_one::<<Self as HasTable>::Table, _, _>( + conn, + dsl::locker_id.eq(locker_id.to_owned()), + ) + .await + } + #[instrument(skip(conn))] pub async fn find_by_payment_method_id( conn: &PgPooledConn, diff --git a/crates/diesel_models/src/schema.rs b/crates/diesel_models/src/schema.rs index 5093f0df7d0..3364e560277 100644 --- a/crates/diesel_models/src/schema.rs +++ b/crates/diesel_models/src/schema.rs @@ -828,6 +828,8 @@ diesel::table! { payment_method_issuer_code -> Nullable<PaymentMethodIssuerCode>, metadata -> Nullable<Json>, payment_method_data -> Nullable<Bytea>, + #[max_length = 64] + locker_id -> Nullable<Varchar>, } } diff --git a/crates/router/src/core/customers.rs b/crates/router/src/core/customers.rs index 9442bf2ff34..be306112873 100644 --- a/crates/router/src/core/customers.rs +++ b/crates/router/src/core/customers.rs @@ -218,7 +218,7 @@ pub async fn delete_customer( &state, &req.customer_id, &merchant_account.merchant_id, - &pm.payment_method_id, + pm.locker_id.as_ref().unwrap_or(&pm.payment_method_id), ) .await .switch()?; diff --git a/crates/router/src/core/locker_migration.rs b/crates/router/src/core/locker_migration.rs index 2ebec569b38..1347bb8ffd0 100644 --- a/crates/router/src/core/locker_migration.rs +++ b/crates/router/src/core/locker_migration.rs @@ -83,9 +83,13 @@ pub async fn call_to_locker( .into_iter() .filter(|pm| matches!(pm.payment_method, storage_enums::PaymentMethod::Card)) { - let card = - cards::get_card_from_locker(state, customer_id, merchant_id, &pm.payment_method_id) - .await; + let card = cards::get_card_from_locker( + state, + customer_id, + merchant_id, + pm.locker_id.as_ref().unwrap_or(&pm.payment_method_id), + ) + .await; let card = match card { Ok(card) => card, @@ -127,7 +131,7 @@ pub async fn call_to_locker( customer_id.to_string(), merchant_account, api_enums::LockerChoice::HyperswitchCardVault, - Some(&pm.payment_method_id), + Some(pm.locker_id.as_ref().unwrap_or(&pm.payment_method_id)), ) .await .change_context(errors::ApiErrorResponse::InternalServerError) diff --git a/crates/router/src/core/payment_methods.rs b/crates/router/src/core/payment_methods.rs index c1617fa77c9..bdbd9b02d9e 100644 --- a/crates/router/src/core/payment_methods.rs +++ b/crates/router/src/core/payment_methods.rs @@ -155,7 +155,7 @@ impl PaymentMethodRetrieve for Oss { storage::PaymentTokenData::Permanent(card_token) => { helpers::retrieve_card_with_permanent_token( state, - &card_token.token, + card_token.locker_id.as_ref().unwrap_or(&card_token.token), payment_intent, card_token_data, ) @@ -166,7 +166,7 @@ impl PaymentMethodRetrieve for Oss { storage::PaymentTokenData::PermanentCard(card_token) => { helpers::retrieve_card_with_permanent_token( state, - &card_token.token, + card_token.locker_id.as_ref().unwrap_or(&card_token.token), payment_intent, card_token_data, ) diff --git a/crates/router/src/core/payment_methods/cards.rs b/crates/router/src/core/payment_methods/cards.rs index dbd8efcd1cf..7bf956be9ff 100644 --- a/crates/router/src/core/payment_methods/cards.rs +++ b/crates/router/src/core/payment_methods/cards.rs @@ -76,6 +76,7 @@ pub async fn create_payment_method( req: &api::PaymentMethodCreate, customer_id: &str, payment_method_id: &str, + locker_id: Option<String>, merchant_id: &str, pm_metadata: Option<serde_json::Value>, payment_method_data: Option<Encryption>, @@ -90,6 +91,7 @@ pub async fn create_payment_method( customer_id: customer_id.to_string(), merchant_id: merchant_id.to_string(), payment_method_id: payment_method_id.to_string(), + locker_id, payment_method: req.payment_method, payment_method_type: req.payment_method_type, payment_method_issuer: req.payment_method_issuer.clone(), @@ -131,6 +133,65 @@ pub fn store_default_payment_method( (payment_method_response, None) } +#[instrument(skip_all)] +pub async fn get_or_insert_payment_method( + db: &dyn db::StorageInterface, + req: api::PaymentMethodCreate, + resp: &mut api::PaymentMethodResponse, + merchant_account: &domain::MerchantAccount, + customer_id: &str, + key_store: &domain::MerchantKeyStore, +) -> errors::RouterResult<diesel_models::PaymentMethod> { + let mut payment_method_id = resp.payment_method_id.clone(); + let mut locker_id = None; + let payment_method = { + let existing_pm_by_pmid = db.find_payment_method(&payment_method_id).await; + + if let Err(err) = existing_pm_by_pmid { + if err.current_context().is_db_not_found() { + locker_id = Some(payment_method_id.clone()); + let existing_pm_by_locker_id = db + .find_payment_method_by_locker_id(&payment_method_id) + .await; + + match &existing_pm_by_locker_id { + Ok(pm) => payment_method_id = pm.payment_method_id.clone(), + Err(_) => payment_method_id = generate_id(consts::ID_LENGTH, "pm"), + }; + existing_pm_by_locker_id + } else { + Err(err) + } + } else { + existing_pm_by_pmid + } + }; + resp.payment_method_id = payment_method_id.to_owned(); + + match payment_method { + Ok(pm) => Ok(pm), + Err(err) => { + if err.current_context().is_db_not_found() { + insert_payment_method( + db, + resp, + req, + key_store, + &merchant_account.merchant_id, + customer_id, + resp.metadata.clone().map(|val| val.expose()), + locker_id, + ) + .await + } else { + Err(err) + .change_context(errors::ApiErrorResponse::InternalServerError) + .attach_printable("Error while finding payment method") + } + } + } +} + #[instrument(skip_all)] pub async fn add_payment_method( state: routes::AppState, @@ -182,40 +243,41 @@ pub async fn add_payment_method( )), }; - let (resp, duplication_check) = response?; + let (mut resp, duplication_check) = response?; match duplication_check { Some(duplication_check) => match duplication_check { payment_methods::DataDuplicationCheck::Duplicated => { - let existing_pm = db.find_payment_method(&resp.payment_method_id).await; - - if let Err(err) = existing_pm { - if err.current_context().is_db_not_found() { - insert_payment_method( - db, - &resp, - req, - key_store, - merchant_id, - &customer_id, - None, - ) - .await - } else { - Err(err) - .change_context(errors::ApiErrorResponse::InternalServerError) - .attach_printable("Error while finding payment method") - }? - }; + get_or_insert_payment_method( + db, + req.clone(), + &mut resp, + merchant_account, + &customer_id, + key_store, + ) + .await?; } - payment_methods::DataDuplicationCheck::MetaDataChanged => { if let Some(card) = req.card.clone() { + let existing_pm = get_or_insert_payment_method( + db, + req.clone(), + &mut resp, + merchant_account, + &customer_id, + key_store, + ) + .await?; + delete_card_from_locker( &state, &customer_id, merchant_id, - &resp.payment_method_id, + existing_pm + .locker_id + .as_ref() + .unwrap_or(&existing_pm.payment_method_id), ) .await?; @@ -226,7 +288,12 @@ pub async fn add_payment_method( customer_id.clone(), merchant_account, api::enums::LockerChoice::HyperswitchCardVault, - Some(&resp.payment_method_id), + Some( + existing_pm + .locker_id + .as_ref() + .unwrap_or(&existing_pm.payment_method_id), + ), ) .await; @@ -243,69 +310,46 @@ pub async fn add_payment_method( .attach_printable("Failed while updating card metadata changes"))? }; - let existing_pm = db.find_payment_method(&resp.payment_method_id).await; - match existing_pm { - Ok(pm) => { - let updated_card = Some(api::CardDetailFromLocker { - scheme: None, - last4_digits: Some(card.card_number.clone().get_last4()), - issuer_country: None, - card_number: Some(card.card_number), - expiry_month: Some(card.card_exp_month), - expiry_year: Some(card.card_exp_year), - card_token: None, - card_fingerprint: None, - card_holder_name: card.card_holder_name, - nick_name: card.nick_name, - card_network: None, - card_isin: None, - card_issuer: None, - card_type: None, - saved_to_locker: true, - }); - - let updated_pmd = updated_card.as_ref().map(|card| { - PaymentMethodsData::Card(CardDetailsPaymentMethod::from( - card.clone(), - )) - }); - let pm_data_encrypted = - create_encrypted_payment_method_data(key_store, updated_pmd).await; - - let pm_update = storage::PaymentMethodUpdate::PaymentMethodDataUpdate { - payment_method_data: pm_data_encrypted, - }; - - db.update_payment_method(pm, pm_update) - .await - .change_context(errors::ApiErrorResponse::InternalServerError) - .attach_printable("Failed to add payment method in db")?; - } - Err(err) => { - if err.current_context().is_db_not_found() { - insert_payment_method( - db, - &resp, - req, - key_store, - merchant_id, - &customer_id, - None, - ) - .await - } else { - Err(err) - .change_context(errors::ApiErrorResponse::InternalServerError) - .attach_printable("Error while finding payment method") - }?; - } - } + let updated_card = Some(api::CardDetailFromLocker { + scheme: None, + last4_digits: Some(card.card_number.clone().get_last4()), + issuer_country: None, + card_number: Some(card.card_number), + expiry_month: Some(card.card_exp_month), + expiry_year: Some(card.card_exp_year), + card_token: None, + card_fingerprint: None, + card_holder_name: card.card_holder_name, + nick_name: card.nick_name, + card_network: None, + card_isin: None, + card_issuer: None, + card_type: None, + saved_to_locker: true, + }); + + let updated_pmd = updated_card.as_ref().map(|card| { + PaymentMethodsData::Card(CardDetailsPaymentMethod::from(card.clone())) + }); + let pm_data_encrypted = + create_encrypted_payment_method_data(key_store, updated_pmd).await; + + let pm_update = storage::PaymentMethodUpdate::PaymentMethodDataUpdate { + payment_method_data: pm_data_encrypted, + }; + + db.update_payment_method(existing_pm, pm_update) + .await + .change_context(errors::ApiErrorResponse::InternalServerError) + .attach_printable("Failed to add payment method in db")?; } } }, None => { let pm_metadata = resp.metadata.as_ref().map(|data| data.peek()); + let locker_id = Some(resp.payment_method_id); + resp.payment_method_id = generate_id(consts::ID_LENGTH, "pm"); insert_payment_method( db, &resp, @@ -314,14 +358,16 @@ pub async fn add_payment_method( merchant_id, &customer_id, pm_metadata.cloned(), + locker_id, ) .await?; } - }; + } Ok(services::ApplicationResponse::Json(resp)) } +#[allow(clippy::too_many_arguments)] pub async fn insert_payment_method( db: &dyn db::StorageInterface, resp: &api::PaymentMethodResponse, @@ -330,7 +376,8 @@ pub async fn insert_payment_method( merchant_id: &str, customer_id: &str, pm_metadata: Option<serde_json::Value>, -) -> errors::RouterResult<()> { + locker_id: Option<String>, +) -> errors::RouterResult<diesel_models::PaymentMethod> { let pm_card_details = resp .card .as_ref() @@ -341,14 +388,13 @@ pub async fn insert_payment_method( &req, customer_id, &resp.payment_method_id, + locker_id, merchant_id, pm_metadata, pm_data_encrypted, key_store, ) - .await?; - - Ok(()) + .await } #[instrument(skip_all)] @@ -372,7 +418,7 @@ pub async fn update_customer_payment_method( &state, &pm.customer_id, &pm.merchant_id, - &pm.payment_method_id, + pm.locker_id.as_ref().unwrap_or(&pm.payment_method_id), ) .await?; }; @@ -927,7 +973,7 @@ pub async fn mock_call_to_locker_hs<'a>( duplication_check: None, }; Ok(payment_methods::StoreCardResp { - status: "SUCCESS".to_string(), + status: "Ok".to_string(), error_code: None, error_message: None, payload: Some(payload), @@ -1013,7 +1059,7 @@ pub async fn mock_delete_card_hs<'a>( .await .change_context(errors::VaultError::FetchCardFailed)?; Ok(payment_methods::DeleteCardResp { - status: "SUCCESS".to_string(), + status: "Ok".to_string(), error_code: None, error_message: None, }) @@ -1032,7 +1078,7 @@ pub async fn mock_delete_card<'a>( card_id: Some(locker_mock_up.card_id), external_id: Some(locker_mock_up.external_id), card_isin: None, - status: "SUCCESS".to_string(), + status: "Ok".to_string(), }) } //------------------------------------------------------------------------------ @@ -2642,7 +2688,11 @@ pub async fn list_customer_payment_method( ( card_details, None, - PaymentTokenData::permanent_card(pm.payment_method_id.clone()), + 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()), + ), ) } else { continue; @@ -2662,7 +2712,7 @@ pub async fn list_customer_payment_method( &token, &pm.customer_id, &pm.merchant_id, - &pm.payment_method_id, + pm.locker_id.as_ref().unwrap_or(&pm.payment_method_id), ) .await?, ), @@ -2902,7 +2952,7 @@ pub async fn get_card_details_from_locker( state, &pm.customer_id, &pm.merchant_id, - &pm.payment_method_id, + pm.locker_id.as_ref().unwrap_or(&pm.payment_method_id), ) .await .change_context(errors::ApiErrorResponse::InternalServerError) @@ -3167,7 +3217,7 @@ pub async fn retrieve_payment_method( &state, &pm.customer_id, &pm.merchant_id, - &pm.payment_method_id, + pm.locker_id.as_ref().unwrap_or(&pm.payment_method_id), ) .await .change_context(errors::ApiErrorResponse::InternalServerError) @@ -3217,11 +3267,11 @@ pub async fn delete_payment_method( &state, &key.customer_id, &key.merchant_id, - pm_id.payment_method_id.as_str(), + key.locker_id.as_ref().unwrap_or(&key.payment_method_id), ) .await?; - if response.status == "SUCCESS" { + if response.status == "Ok" { logger::info!("Card From locker deleted Successfully!"); } else { logger::error!("Error: Deleting Card From Locker!\n{:#?}", response); diff --git a/crates/router/src/core/payment_methods/transformers.rs b/crates/router/src/core/payment_methods/transformers.rs index 57e46bc9769..6bad41630b5 100644 --- a/crates/router/src/core/payment_methods/transformers.rs +++ b/crates/router/src/core/payment_methods/transformers.rs @@ -397,46 +397,6 @@ pub fn mk_add_card_response_hs( } } -pub fn mk_add_card_response( - card: api::CardDetail, - response: AddCardResponse, - req: api::PaymentMethodCreate, - merchant_id: &str, -) -> api::PaymentMethodResponse { - let mut card_number = card.card_number.peek().to_owned(); - let card = api::CardDetailFromLocker { - scheme: None, - last4_digits: Some(card_number.split_off(card_number.len() - 4)), - issuer_country: None, // [#256] bin mapping - card_number: Some(card.card_number), - expiry_month: Some(card.card_exp_month), - expiry_year: Some(card.card_exp_year), - card_token: Some(response.external_id.into()), // [#256] - card_fingerprint: Some(response.card_fingerprint), - card_holder_name: card.card_holder_name, - nick_name: card.nick_name, - card_isin: None, - card_issuer: None, - card_network: None, - card_type: None, - saved_to_locker: true, - }; - api::PaymentMethodResponse { - merchant_id: merchant_id.to_owned(), - customer_id: req.customer_id, - payment_method_id: response.card_id, - payment_method: req.payment_method, - payment_method_type: req.payment_method_type, - bank_transfer: None, - card: Some(card), - metadata: req.metadata, - created: Some(common_utils::date_time::now()), - recurring_enabled: false, // [#256] - installment_payment_enabled: false, // [#256] Pending on discussion, and not stored in the card locker - payment_experience: None, // [#256] - } -} - pub fn mk_add_card_request( locker: &settings::Locker, card: &api::CardDetail, diff --git a/crates/router/src/core/payments/tokenization.rs b/crates/router/src/core/payments/tokenization.rs index 2d7a09bdae1..d08f0208500 100644 --- a/crates/router/src/core/payments/tokenization.rs +++ b/crates/router/src/core/payments/tokenization.rs @@ -6,6 +6,7 @@ use router_env::{instrument, tracing}; use super::helpers; use crate::{ + consts, core::{ errors::{self, ConnectorErrorExt, RouterResult, StorageErrorExt}, mandate, payment_methods, payments, @@ -19,7 +20,7 @@ use crate::{ domain, storage::{self, enums as storage_enums}, }, - utils::OptionExt, + utils::{generate_id, OptionExt}, }; #[instrument(skip_all)] @@ -85,7 +86,7 @@ where .await?; let merchant_id = &merchant_account.merchant_id; - let locker_response = if !state.conf.locker.locker_enabled { + let (mut resp, duplication_check) = if !state.conf.locker.locker_enabled { skip_saving_card_in_locker( merchant_account, payment_method_create_request.to_owned(), @@ -100,9 +101,7 @@ where .await? }; - let duplication_check = locker_response.1; - - let pm_card_details = locker_response.0.card.as_ref().map(|card| { + let pm_card_details = resp.card.as_ref().map(|card| { api::payment_methods::PaymentMethodsData::Card(CardDetailsPaymentMethod::from( card.clone(), )) @@ -115,13 +114,44 @@ where ) .await; + let mut payment_method_id = resp.payment_method_id.clone(); + let mut locker_id = None; + match duplication_check { Some(duplication_check) => match duplication_check { payment_methods::transformers::DataDuplicationCheck::Duplicated => { - let existing_pm = db - .find_payment_method(&locker_response.0.payment_method_id) - .await; - match existing_pm { + let payment_method = { + let existing_pm_by_pmid = + db.find_payment_method(&payment_method_id).await; + + if let Err(err) = existing_pm_by_pmid { + if err.current_context().is_db_not_found() { + locker_id = Some(payment_method_id.clone()); + let existing_pm_by_locker_id = db + .find_payment_method_by_locker_id(&payment_method_id) + .await; + + match &existing_pm_by_locker_id { + Ok(pm) => { + payment_method_id = pm.payment_method_id.clone() + } + Err(_) => { + payment_method_id = + generate_id(consts::ID_LENGTH, "pm") + } + }; + existing_pm_by_locker_id + } else { + Err(err) + } + } else { + existing_pm_by_pmid + } + }; + + resp.payment_method_id = payment_method_id; + + match payment_method { Ok(pm) => { let pm_metadata = create_payment_method_metadata( pm.metadata.as_ref(), @@ -146,7 +176,8 @@ where db, &payment_method_create_request, &customer.customer_id, - &locker_response.0.payment_method_id, + &resp.payment_method_id, + locker_id, merchant_id, pm_metadata, pm_data_encrypted, @@ -165,22 +196,87 @@ where } payment_methods::transformers::DataDuplicationCheck::MetaDataChanged => { if let Some(card) = payment_method_create_request.card.clone() { + let payment_method = { + let existing_pm_by_pmid = + db.find_payment_method(&payment_method_id).await; + + if let Err(err) = existing_pm_by_pmid { + if err.current_context().is_db_not_found() { + locker_id = Some(payment_method_id.clone()); + let existing_pm_by_locker_id = db + .find_payment_method_by_locker_id( + &payment_method_id, + ) + .await; + + match &existing_pm_by_locker_id { + Ok(pm) => { + payment_method_id = pm.payment_method_id.clone() + } + Err(_) => { + payment_method_id = + generate_id(consts::ID_LENGTH, "pm") + } + }; + existing_pm_by_locker_id + } else { + Err(err) + } + } else { + existing_pm_by_pmid + } + }; + + resp.payment_method_id = payment_method_id; + + let existing_pm = + match payment_method { + Ok(pm) => Ok(pm), + Err(err) => { + if err.current_context().is_db_not_found() { + payment_methods::cards::insert_payment_method( + db, + &resp, + payment_method_create_request.clone(), + key_store, + &merchant_account.merchant_id, + &customer.customer_id, + resp.metadata.clone().map(|val| val.expose()), + locker_id, + ) + .await + } else { + Err(err) + .change_context(errors::ApiErrorResponse::InternalServerError) + .attach_printable("Error while finding payment method") + } + } + }?; + payment_methods::cards::delete_card_from_locker( state, &customer.customer_id, merchant_id, - &locker_response.0.payment_method_id, + existing_pm + .locker_id + .as_ref() + .unwrap_or(&existing_pm.payment_method_id), ) .await?; let add_card_resp = payment_methods::cards::add_card_hs( state, - payment_method_create_request.clone(), + payment_method_create_request, &card, customer.customer_id.clone(), merchant_account, api::enums::LockerChoice::HyperswitchCardVault, - Some(&locker_response.0.payment_method_id), + Some( + existing_pm + .locker_id + .as_ref() + .unwrap_or(&existing_pm.payment_method_id), + ), ) .await; @@ -188,7 +284,7 @@ where logger::error!(vault_err=?err); db.delete_payment_method_by_merchant_id_payment_method_id( merchant_id, - &locker_response.0.payment_method_id, + &resp.payment_method_id, ) .await .to_not_found_response( @@ -201,90 +297,59 @@ where ))? }; - let existing_pm = db - .find_payment_method(&locker_response.0.payment_method_id) + let updated_card = Some(CardDetailFromLocker { + scheme: None, + last4_digits: Some(card.card_number.clone().get_last4()), + issuer_country: None, + card_number: Some(card.card_number), + expiry_month: Some(card.card_exp_month), + expiry_year: Some(card.card_exp_year), + card_token: None, + card_fingerprint: None, + card_holder_name: card.card_holder_name, + nick_name: card.nick_name, + card_network: None, + card_isin: None, + card_issuer: None, + card_type: None, + saved_to_locker: true, + }); + + let updated_pmd = updated_card.as_ref().map(|card| { + PaymentMethodsData::Card(CardDetailsPaymentMethod::from( + card.clone(), + )) + }); + let pm_data_encrypted = + payment_methods::cards::create_encrypted_payment_method_data( + key_store, + updated_pmd, + ) .await; - match existing_pm { - Ok(pm) => { - let updated_card = Some(CardDetailFromLocker { - scheme: None, - last4_digits: Some( - card.card_number.clone().get_last4(), - ), - issuer_country: None, - card_number: Some(card.card_number), - expiry_month: Some(card.card_exp_month), - expiry_year: Some(card.card_exp_year), - card_token: None, - card_fingerprint: None, - card_holder_name: card.card_holder_name, - nick_name: card.nick_name, - card_network: None, - card_isin: None, - card_issuer: None, - card_type: None, - saved_to_locker: true, - }); - - let updated_pmd = updated_card.as_ref().map(|card| { - PaymentMethodsData::Card( - CardDetailsPaymentMethod::from(card.clone()), - ) - }); - let pm_data_encrypted = - payment_methods::cards::create_encrypted_payment_method_data( - key_store, - updated_pmd, - ) - .await; - let pm_update = - storage::PaymentMethodUpdate::PaymentMethodDataUpdate { - payment_method_data: pm_data_encrypted, - }; + let pm_update = + storage::PaymentMethodUpdate::PaymentMethodDataUpdate { + payment_method_data: pm_data_encrypted, + }; - db.update_payment_method(pm, pm_update) - .await - .change_context( - errors::ApiErrorResponse::InternalServerError, - ) - .attach_printable( - "Failed to add payment method in db", - )?; - } - Err(err) => { - if err.current_context().is_db_not_found() { - payment_methods::cards::insert_payment_method( - db, - &locker_response.0, - payment_method_create_request, - key_store, - merchant_id, - &customer.customer_id, - None, - ) - .await - } else { - Err(err) - .change_context( - errors::ApiErrorResponse::InternalServerError, - ) - .attach_printable( - "Error while finding payment method", - ) - }?; - } - } + db.update_payment_method(existing_pm, pm_update) + .await + .change_context(errors::ApiErrorResponse::InternalServerError) + .attach_printable("Failed to add payment method in db")?; } } }, None => { let pm_metadata = create_payment_method_metadata(None, connector_token)?; + + locker_id = Some(resp.payment_method_id); + resp.payment_method_id = generate_id(consts::ID_LENGTH, "pm"); payment_methods::cards::create_payment_method( db, &payment_method_create_request, &customer.customer_id, - &locker_response.0.payment_method_id, + &resp.payment_method_id, + locker_id, merchant_id, pm_metadata, pm_data_encrypted, @@ -294,7 +359,7 @@ where } } - Some(locker_response.0.payment_method_id) + Some(resp.payment_method_id) } else { None }; diff --git a/crates/router/src/core/payouts/helpers.rs b/crates/router/src/core/payouts/helpers.rs index 7fb6fa3bde6..de57f8549db 100644 --- a/crates/router/src/core/payouts/helpers.rs +++ b/crates/router/src/core/payouts/helpers.rs @@ -78,9 +78,11 @@ pub async fn make_payout_method_data<'a>( .attach_printable("failed to deserialize hyperswitch token data")?; let payment_token = match payment_token_data { - storage::PaymentTokenData::PermanentCard(storage::CardTokenData { token }) => { - Some(token) - } + storage::PaymentTokenData::PermanentCard(storage::CardTokenData { + locker_id, + token, + .. + }) => locker_id.or(Some(token)), storage::PaymentTokenData::TemporaryGeneric(storage::GenericTokenData { token, }) => Some(token), @@ -364,11 +366,13 @@ pub async fn save_payout_data_to_locker( card_network: None, }; + let payment_method_id = common_utils::generate_id(crate::consts::ID_LENGTH, "pm"); cards::create_payment_method( db, &payment_method, &payout_attempt.customer_id, - &stored_resp.card_reference, + &payment_method_id, + Some(stored_resp.card_reference), &merchant_account.merchant_id, None, card_details_encrypted, diff --git a/crates/router/src/db/kafka_store.rs b/crates/router/src/db/kafka_store.rs index 78b95544ca1..9dbecd82485 100644 --- a/crates/router/src/db/kafka_store.rs +++ b/crates/router/src/db/kafka_store.rs @@ -1270,6 +1270,15 @@ impl PaymentMethodInterface for KafkaStore { .await } + async fn find_payment_method_by_locker_id( + &self, + locker_id: &str, + ) -> CustomResult<storage::PaymentMethod, errors::StorageError> { + self.diesel_store + .find_payment_method_by_locker_id(locker_id) + .await + } + async fn insert_payment_method( &self, m: storage::PaymentMethodNew, diff --git a/crates/router/src/db/payment_method.rs b/crates/router/src/db/payment_method.rs index b109d1fe5bd..4f4087f552e 100644 --- a/crates/router/src/db/payment_method.rs +++ b/crates/router/src/db/payment_method.rs @@ -15,6 +15,11 @@ pub trait PaymentMethodInterface { payment_method_id: &str, ) -> CustomResult<storage::PaymentMethod, errors::StorageError>; + async fn find_payment_method_by_locker_id( + &self, + locker_id: &str, + ) -> CustomResult<storage::PaymentMethod, errors::StorageError>; + async fn find_payment_method_by_customer_id_merchant_id_list( &self, customer_id: &str, @@ -52,6 +57,17 @@ impl PaymentMethodInterface for Store { .into_report() } + async fn find_payment_method_by_locker_id( + &self, + locker_id: &str, + ) -> CustomResult<storage::PaymentMethod, errors::StorageError> { + let conn = connection::pg_connection_read(self).await?; + storage::PaymentMethod::find_by_locker_id(&conn, locker_id) + .await + .map_err(Into::into) + .into_report() + } + async fn insert_payment_method( &self, payment_method_new: storage::PaymentMethodNew, @@ -127,6 +143,25 @@ impl PaymentMethodInterface for MockDb { } } + async fn find_payment_method_by_locker_id( + &self, + locker_id: &str, + ) -> CustomResult<storage::PaymentMethod, errors::StorageError> { + let payment_methods = self.payment_methods.lock().await; + let payment_method = payment_methods + .iter() + .find(|pm| pm.locker_id == Some(locker_id.to_string())) + .cloned(); + + match payment_method { + Some(pm) => Ok(pm), + None => Err(errors::StorageError::ValueNotFound( + "cannot find payment method".to_string(), + ) + .into()), + } + } + async fn insert_payment_method( &self, payment_method_new: storage::PaymentMethodNew, @@ -142,6 +177,7 @@ impl PaymentMethodInterface for MockDb { 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, diff --git a/crates/router/src/types/api/mandates.rs b/crates/router/src/types/api/mandates.rs index 051547dfa92..10c56973dd3 100644 --- a/crates/router/src/types/api/mandates.rs +++ b/crates/router/src/types/api/mandates.rs @@ -51,7 +51,10 @@ impl MandateResponseExt for MandateResponse { state, &payment_method.customer_id, &payment_method.merchant_id, - &payment_method.payment_method_id, + payment_method + .locker_id + .as_ref() + .unwrap_or(&payment_method.payment_method_id), ) .await?; diff --git a/crates/router/src/types/storage/payment_method.rs b/crates/router/src/types/storage/payment_method.rs index 096303446dc..a787a4d932c 100644 --- a/crates/router/src/types/storage/payment_method.rs +++ b/crates/router/src/types/storage/payment_method.rs @@ -13,6 +13,8 @@ pub enum PaymentTokenKind { #[derive(Debug, Clone, serde::Serialize, serde::Deserialize)] pub struct CardTokenData { + pub payment_method_id: Option<String>, + pub locker_id: Option<String>, pub token: String, } @@ -34,8 +36,16 @@ pub enum PaymentTokenData { } impl PaymentTokenData { - pub fn permanent_card(token: String) -> Self { - Self::PermanentCard(CardTokenData { token }) + pub fn permanent_card( + payment_method_id: Option<String>, + locker_id: Option<String>, + token: String, + ) -> Self { + Self::PermanentCard(CardTokenData { + payment_method_id, + locker_id, + token, + }) } pub fn temporary_generic(token: String) -> Self { diff --git a/migrations/2024-02-20-142032_add_locker_id_to_payment_methods/down.sql b/migrations/2024-02-20-142032_add_locker_id_to_payment_methods/down.sql new file mode 100644 index 00000000000..90eaebaf4da --- /dev/null +++ b/migrations/2024-02-20-142032_add_locker_id_to_payment_methods/down.sql @@ -0,0 +1,3 @@ +-- This file should undo anything in `up.sql` + +ALTER TABLE payment_methods DROP COLUMN IF EXISTS locker_id; diff --git a/migrations/2024-02-20-142032_add_locker_id_to_payment_methods/up.sql b/migrations/2024-02-20-142032_add_locker_id_to_payment_methods/up.sql new file mode 100644 index 00000000000..516dc8a8818 --- /dev/null +++ b/migrations/2024-02-20-142032_add_locker_id_to_payment_methods/up.sql @@ -0,0 +1,3 @@ +-- Your SQL goes here + +ALTER TABLE payment_methods ADD COLUMN IF NOT EXISTS locker_id VARCHAR(64) DEFAULT NULL; \ No newline at end of file
2024-02-21T17:18:08Z
## 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 we are mapping `locker_id` from locker to `payment_method_id` in Hyperswitch. This refactor involves changes to store the locker id in the `locker_id` column as opposed to the `payment_method_id` column, and store a unique ID in place of the `payment_method_id`. While reading the locker id, read from the `locker_id` column with `payment_method_id` as fallback. ### 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)? --> Sandbox testing - * Should be tested similar to https://github.com/juspay/hyperswitch/pull/3146 * Test it for both old card already saved before this PR went in along with new card * Both `/payment_methods` and `/payment` card flow has to be tested with metadata changes too. Everything should work fine Test cases (`payment_methods` table) - (Card 1): Db entry before this code changes :- `locker_id` should be null ![image](https://github.com/juspay/hyperswitch/assets/70657455/f6677536-a3ea-4db3-af1d-2493e30cbbae) (Card 1): MetaData updation :- Both `payment_method_id` and `locker_id` will remain same but with updated `payment_method_data` ![image](https://github.com/juspay/hyperswitch/assets/70657455/45cebebf-f96c-4101-94bf-d8604d57c5eb) (Card 2): Db entry when new card is added :- `locker_id` will now be the id from locker, `payment_method_id` will be nano_id ![image](https://github.com/juspay/hyperswitch/assets/70657455/210a0adb-2050-4fc2-9752-ca314284e4ec) (Card 2): MetaData updation :- Both `payment_method_id` and `locker_id` will remain same but with updated `payment_method_data` ![image](https://github.com/juspay/hyperswitch/assets/70657455/0aba88f8-72b1-4269-9d2c-35d20f075929) Redis entry (Local testing) - Old card (both locker_id and payment_method_id will be same): ![image](https://github.com/juspay/hyperswitch/assets/70657455/6ad1e019-69e6-444d-8b56-dde2543dc6b7) New card (payment_method_id will be nano_id and locker_id will be the id returned from locker): ![image](https://github.com/juspay/hyperswitch/assets/70657455/400f09b9-da64-4497-bfe5-25429feab4d9) ## 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 - [ ] I added a [CHANGELOG](/CHANGELOG.md) entry if applicable
75c633fc7c37341177597041ccbcdfc3cf9e236f
Sandbox testing - * Should be tested similar to https://github.com/juspay/hyperswitch/pull/3146 * Test it for both old card already saved before this PR went in along with new card * Both `/payment_methods` and `/payment` card flow has to be tested with metadata changes too. Everything should work fine Test cases (`payment_methods` table) - (Card 1): Db entry before this code changes :- `locker_id` should be null ![image](https://github.com/juspay/hyperswitch/assets/70657455/f6677536-a3ea-4db3-af1d-2493e30cbbae) (Card 1): MetaData updation :- Both `payment_method_id` and `locker_id` will remain same but with updated `payment_method_data` ![image](https://github.com/juspay/hyperswitch/assets/70657455/45cebebf-f96c-4101-94bf-d8604d57c5eb) (Card 2): Db entry when new card is added :- `locker_id` will now be the id from locker, `payment_method_id` will be nano_id ![image](https://github.com/juspay/hyperswitch/assets/70657455/210a0adb-2050-4fc2-9752-ca314284e4ec) (Card 2): MetaData updation :- Both `payment_method_id` and `locker_id` will remain same but with updated `payment_method_data` ![image](https://github.com/juspay/hyperswitch/assets/70657455/0aba88f8-72b1-4269-9d2c-35d20f075929) Redis entry (Local testing) - Old card (both locker_id and payment_method_id will be same): ![image](https://github.com/juspay/hyperswitch/assets/70657455/6ad1e019-69e6-444d-8b56-dde2543dc6b7) New card (payment_method_id will be nano_id and locker_id will be the id returned from locker): ![image](https://github.com/juspay/hyperswitch/assets/70657455/400f09b9-da64-4497-bfe5-25429feab4d9)
juspay/hyperswitch
juspay__hyperswitch-3745
Bug: Customer Acceptance to be moved out of Mandate object Customer acceptance needs to be a property of the Payment Method instead of Mandate. - Move the Customer Acceptance object outside of the Mandate object in the payments request - Store the Customer Acceptance data in the PM table
diff --git a/crates/api_models/src/payments.rs b/crates/api_models/src/payments.rs index 9a3afd2f0ff..d48be04b763 100644 --- a/crates/api_models/src/payments.rs +++ b/crates/api_models/src/payments.rs @@ -348,9 +348,12 @@ pub struct PaymentsRequest { #[remove_in(PaymentsUpdateRequest, PaymentsCreateRequest)] pub client_secret: Option<String>, - /// Passing this object during payments creates a mandate. The mandate_type sub object is passed by the server usually and the customer_acceptance sub object is usually passed by the SDK or client + /// Passing this object during payments creates a mandate. The mandate_type sub object is passed by the server. pub mandate_data: Option<MandateData>, + /// Passing this object during payments confirm . The customer_acceptance sub object is usually passed by the SDK or client + pub customer_acceptance: Option<CustomerAcceptance>, + /// A unique identifier to link the payment to a mandate. To do Recurring payments after a mandate has been created, pass the mandate_id instead of payment_method_data #[schema(max_length = 255, example = "mandate_iwer89rnjef349dni3")] #[remove_in(PaymentsUpdateRequest)] diff --git a/crates/common_enums/src/enums.rs b/crates/common_enums/src/enums.rs index 6b25b692c12..dfa98634e27 100644 --- a/crates/common_enums/src/enums.rs +++ b/crates/common_enums/src/enums.rs @@ -1143,8 +1143,8 @@ pub enum IntentStatus { #[serde(rename_all = "snake_case")] #[strum(serialize_all = "snake_case")] pub enum FutureUsage { - #[default] OffSession, + #[default] OnSession, } diff --git a/crates/data_models/src/mandates.rs b/crates/data_models/src/mandates.rs index b4478f84ee9..fa22a4e57d5 100644 --- a/crates/data_models/src/mandates.rs +++ b/crates/data_models/src/mandates.rs @@ -113,6 +113,16 @@ impl From<ApiCustomerAcceptance> for CustomerAcceptance { } } +impl From<CustomerAcceptance> for ApiCustomerAcceptance { + fn from(value: CustomerAcceptance) -> Self { + Self { + acceptance_type: value.acceptance_type.into(), + accepted_at: value.accepted_at, + online: value.online.map(|d| d.into()), + } + } +} + impl From<ApiAcceptanceType> for AcceptanceType { fn from(value: ApiAcceptanceType) -> Self { match value { @@ -121,6 +131,14 @@ impl From<ApiAcceptanceType> for AcceptanceType { } } } +impl From<AcceptanceType> for ApiAcceptanceType { + fn from(value: AcceptanceType) -> Self { + match value { + AcceptanceType::Online => Self::Online, + AcceptanceType::Offline => Self::Offline, + } + } +} impl From<ApiOnlineMandate> for OnlineMandate { fn from(value: ApiOnlineMandate) -> Self { @@ -130,6 +148,14 @@ impl From<ApiOnlineMandate> for OnlineMandate { } } } +impl From<OnlineMandate> for ApiOnlineMandate { + fn from(value: OnlineMandate) -> Self { + Self { + ip_address: value.ip_address, + user_agent: value.user_agent, + } + } +} impl CustomerAcceptance { pub fn get_ip_address(&self) -> Option<String> { diff --git a/crates/router/src/core/mandate.rs b/crates/router/src/core/mandate.rs index ec3bb7e4299..d07a8814c88 100644 --- a/crates/router/src/core/mandate.rs +++ b/crates/router/src/core/mandate.rs @@ -495,4 +495,5 @@ pub trait MandateBehaviour { fn set_mandate_id(&mut self, new_mandate_id: Option<api_models::payments::MandateIds>); fn get_payment_method_data(&self) -> api_models::payments::PaymentMethodData; fn get_setup_mandate_details(&self) -> Option<&data_models::mandates::MandateData>; + fn get_customer_acceptance(&self) -> Option<api_models::payments::CustomerAcceptance>; } diff --git a/crates/router/src/core/payment_methods/cards.rs b/crates/router/src/core/payment_methods/cards.rs index ce7f48405e2..4fdf957c842 100644 --- a/crates/router/src/core/payment_methods/cards.rs +++ b/crates/router/src/core/payment_methods/cards.rs @@ -81,6 +81,7 @@ pub async fn create_payment_method( locker_id: Option<String>, merchant_id: &str, pm_metadata: Option<serde_json::Value>, + customer_acceptance: Option<serde_json::Value>, payment_method_data: Option<Encryption>, key_store: &domain::MerchantKeyStore, ) -> errors::CustomResult<storage::PaymentMethod, errors::ApiErrorResponse> { @@ -100,6 +101,7 @@ pub async fn create_payment_method( scheme: req.card_network.clone(), metadata: pm_metadata.map(masking::Secret::new), payment_method_data, + customer_acceptance: customer_acceptance.map(masking::Secret::new), ..storage::PaymentMethodNew::default() }) .await @@ -183,6 +185,7 @@ pub async fn get_or_insert_payment_method( &merchant_account.merchant_id, customer_id, resp.metadata.clone().map(|val| val.expose()), + None, locker_id, ) .await @@ -367,6 +370,7 @@ pub async fn add_payment_method( merchant_id, &customer_id, pm_metadata.cloned(), + None, locker_id, ) .await?; @@ -385,6 +389,7 @@ pub async fn insert_payment_method( merchant_id: &str, customer_id: &str, pm_metadata: Option<serde_json::Value>, + customer_acceptance: Option<serde_json::Value>, locker_id: Option<String>, ) -> errors::RouterResult<diesel_models::PaymentMethod> { let pm_card_details = resp @@ -400,6 +405,7 @@ pub async fn insert_payment_method( locker_id, merchant_id, pm_metadata, + customer_acceptance, pm_data_encrypted, key_store, ) diff --git a/crates/router/src/core/payments.rs b/crates/router/src/core/payments.rs index 7e8fa2ae44d..88a437a087e 100644 --- a/crates/router/src/core/payments.rs +++ b/crates/router/src/core/payments.rs @@ -15,7 +15,7 @@ use std::{fmt::Debug, marker::PhantomData, ops::Deref, time::Instant, vec::IntoI use api_models::{self, enums, payments::HeaderPayload}; use common_utils::{ext_traits::AsyncExt, pii, types::Surcharge}; -use data_models::mandates::MandateData; +use data_models::mandates::{CustomerAcceptance, MandateData}; use diesel_models::{ephemeral_key, fraud_check::FraudCheck}; use error_stack::{IntoReport, ResultExt}; use futures::future::join_all; @@ -2049,6 +2049,7 @@ where pub mandate_connector: Option<MandateConnectorDetails>, pub currency: storage_enums::Currency, pub setup_mandate: Option<MandateData>, + pub customer_acceptance: Option<CustomerAcceptance>, pub address: PaymentAddress, pub token: Option<String>, pub confirm: Option<bool>, diff --git a/crates/router/src/core/payments/flows/authorize_flow.rs b/crates/router/src/core/payments/flows/authorize_flow.rs index d7d122c3252..cc2540aa221 100644 --- a/crates/router/src/core/payments/flows/authorize_flow.rs +++ b/crates/router/src/core/payments/flows/authorize_flow.rs @@ -99,7 +99,6 @@ impl Feature<api::Authorize, types::PaymentsAuthorizeData> for types::PaymentsAu merchant_account, self.request.payment_method_type, key_store, - is_mandate, )) .await?; Ok(mandate::mandate_procedure( @@ -131,7 +130,6 @@ impl Feature<api::Authorize, types::PaymentsAuthorizeData> for types::PaymentsAu &merchant_account, self.request.payment_method_type, &key_store, - is_mandate, )) .await; @@ -294,6 +292,9 @@ impl mandate::MandateBehaviour for types::PaymentsAuthorizeData { fn set_mandate_id(&mut self, new_mandate_id: Option<api_models::payments::MandateIds>) { self.mandate_id = new_mandate_id; } + fn get_customer_acceptance(&self) -> Option<api_models::payments::CustomerAcceptance> { + self.customer_acceptance.clone().map(From::from) + } } pub async fn authorize_preprocessing_steps<F: Clone>( diff --git a/crates/router/src/core/payments/flows/setup_mandate_flow.rs b/crates/router/src/core/payments/flows/setup_mandate_flow.rs index 3f43204b986..71d43989336 100644 --- a/crates/router/src/core/payments/flows/setup_mandate_flow.rs +++ b/crates/router/src/core/payments/flows/setup_mandate_flow.rs @@ -98,7 +98,7 @@ impl Feature<api::SetupMandate, types::SetupMandateRequestData> for types::Setup ) .await .to_setup_mandate_failed_response()?; - let is_mandate = resp.request.setup_mandate_details.is_some(); + let pm_id = Box::pin(tokenization::save_payment_method( state, connector, @@ -107,7 +107,6 @@ impl Feature<api::SetupMandate, types::SetupMandateRequestData> for types::Setup merchant_account, self.request.payment_method_type, key_store, - is_mandate, )) .await?; mandate::mandate_procedure( @@ -234,8 +233,6 @@ impl types::SetupMandateRouterData { let payment_method_type = self.request.payment_method_type; - let is_mandate = resp.request.setup_mandate_details.is_some(); - let pm_id = Box::pin(tokenization::save_payment_method( state, connector, @@ -244,7 +241,6 @@ impl types::SetupMandateRouterData { merchant_account, payment_method_type, key_store, - is_mandate, )) .await?; @@ -320,7 +316,6 @@ impl types::SetupMandateRouterData { ) .await .to_setup_mandate_failed_response()?; - let is_mandate = resp.request.setup_mandate_details.is_some(); let pm_id = Box::pin(tokenization::save_payment_method( state, connector, @@ -329,7 +324,6 @@ impl types::SetupMandateRouterData { merchant_account, self.request.payment_method_type, key_store, - is_mandate, )) .await?; let mandate = state @@ -430,6 +424,9 @@ impl mandate::MandateBehaviour for types::SetupMandateRequestData { fn get_setup_mandate_details(&self) -> Option<&data_models::mandates::MandateData> { self.setup_mandate_details.as_ref() } + fn get_customer_acceptance(&self) -> Option<api_models::payments::CustomerAcceptance> { + self.customer_acceptance.clone().map(From::from) + } } impl TryFrom<types::SetupMandateRequestData> for types::PaymentMethodTokenizationData { diff --git a/crates/router/src/core/payments/helpers.rs b/crates/router/src/core/payments/helpers.rs index d711bca7ab4..f0a5e38cca4 100644 --- a/crates/router/src/core/payments/helpers.rs +++ b/crates/router/src/core/payments/helpers.rs @@ -825,16 +825,6 @@ fn validate_new_mandate_request( .clone() .get_required_value("mandate_data")?; - if api_enums::FutureUsage::OnSession - == req - .setup_future_usage - .get_required_value("setup_future_usage")? - { - Err(report!(errors::ApiErrorResponse::PreconditionFailed { - message: "`setup_future_usage` must be `off_session` for mandates".into() - }))? - }; - // Only use this validation if the customer_acceptance is present if mandate_data .customer_acceptance @@ -3855,3 +3845,17 @@ pub fn validate_session_expiry(session_expiry: u32) -> Result<(), errors::ApiErr Ok(()) } } + +// This function validates the mandate_data with its setup_future_usage +pub fn validate_mandate_data_and_future_usage( + setup_future_usages: Option<api_enums::FutureUsage>, + mandate_details_present: bool, +) -> Result<(), errors::ApiErrorResponse> { + if Some(api_enums::FutureUsage::OnSession) == setup_future_usages && mandate_details_present { + Err(errors::ApiErrorResponse::PreconditionFailed { + message: "`setup_future_usage` must be `off_session` for mandates".into(), + }) + } else { + Ok(()) + } +} diff --git a/crates/router/src/core/payments/operations/payment_approve.rs b/crates/router/src/core/payments/operations/payment_approve.rs index caca29d8e2a..a38c7bbdd3c 100644 --- a/crates/router/src/core/payments/operations/payment_approve.rs +++ b/crates/router/src/core/payments/operations/payment_approve.rs @@ -147,6 +147,7 @@ impl<F: Send + Clone, Ctx: PaymentMethodRetrieve> mandate_id: None, mandate_connector: None, setup_mandate: None, + customer_acceptance: None, token: None, address: PaymentAddress { shipping: shipping_address.as_ref().map(|a| a.into()), diff --git a/crates/router/src/core/payments/operations/payment_cancel.rs b/crates/router/src/core/payments/operations/payment_cancel.rs index 097b7ab40e1..1b09e9abce5 100644 --- a/crates/router/src/core/payments/operations/payment_cancel.rs +++ b/crates/router/src/core/payments/operations/payment_cancel.rs @@ -155,6 +155,7 @@ impl<F: Send + Clone, Ctx: PaymentMethodRetrieve> mandate_id: None, mandate_connector: None, setup_mandate: None, + customer_acceptance: None, token: None, address: PaymentAddress { shipping: shipping_address.as_ref().map(|a| a.into()), diff --git a/crates/router/src/core/payments/operations/payment_capture.rs b/crates/router/src/core/payments/operations/payment_capture.rs index e9d520e4abc..4a488a07eb3 100644 --- a/crates/router/src/core/payments/operations/payment_capture.rs +++ b/crates/router/src/core/payments/operations/payment_capture.rs @@ -200,6 +200,7 @@ impl<F: Send + Clone, Ctx: PaymentMethodRetrieve> mandate_id: None, mandate_connector: None, setup_mandate: None, + customer_acceptance: None, token: None, address: payments::PaymentAddress { shipping: shipping_address.as_ref().map(|a| a.into()), diff --git a/crates/router/src/core/payments/operations/payment_complete_authorize.rs b/crates/router/src/core/payments/operations/payment_complete_authorize.rs index f7e7598cf73..395f8e59dbc 100644 --- a/crates/router/src/core/payments/operations/payment_complete_authorize.rs +++ b/crates/router/src/core/payments/operations/payment_complete_authorize.rs @@ -215,6 +215,12 @@ impl<F: Send + Clone, Ctx: PaymentMethodRetrieve> // The operation merges mandate data from both request and payment_attempt let setup_mandate = setup_mandate.map(Into::into); + let mandate_details_present = + payment_attempt.mandate_details.is_some() || request.mandate_data.is_some(); + helpers::validate_mandate_data_and_future_usage( + payment_intent.setup_future_usage, + mandate_details_present, + )?; let profile_id = payment_intent .profile_id .as_ref() @@ -239,6 +245,7 @@ impl<F: Send + Clone, Ctx: PaymentMethodRetrieve> mandate_id: None, mandate_connector, setup_mandate, + customer_acceptance: None, token, address: PaymentAddress { shipping: shipping_address.as_ref().map(|a| a.into()), diff --git a/crates/router/src/core/payments/operations/payment_confirm.rs b/crates/router/src/core/payments/operations/payment_confirm.rs index 5c47c3f323e..9117f406040 100644 --- a/crates/router/src/core/payments/operations/payment_confirm.rs +++ b/crates/router/src/core/payments/operations/payment_confirm.rs @@ -361,6 +361,7 @@ impl<F: Send + Clone, Ctx: PaymentMethodRetrieve> .change_context(errors::ApiErrorResponse::InvalidDataValue { field_name: "browser_info", })?; + let customer_acceptance = request.customer_acceptance.clone().map(From::from); helpers::validate_card_data( request @@ -461,6 +462,12 @@ impl<F: Send + Clone, Ctx: PaymentMethodRetrieve> sm }); + let mandate_details_present = + payment_attempt.mandate_details.is_some() || request.mandate_data.is_some(); + helpers::validate_mandate_data_and_future_usage( + payment_intent.setup_future_usage, + mandate_details_present, + )?; let n_request_payment_method_data = request .payment_method_data .as_ref() @@ -539,6 +546,7 @@ impl<F: Send + Clone, Ctx: PaymentMethodRetrieve> mandate_id: None, mandate_connector, setup_mandate, + customer_acceptance, token, address: PaymentAddress { shipping: shipping_address.as_ref().map(|a| a.into()), diff --git a/crates/router/src/core/payments/operations/payment_create.rs b/crates/router/src/core/payments/operations/payment_create.rs index 11ab21b891d..2c07f4249e8 100644 --- a/crates/router/src/core/payments/operations/payment_create.rs +++ b/crates/router/src/core/payments/operations/payment_create.rs @@ -281,6 +281,12 @@ impl<F: Send + Clone, Ctx: PaymentMethodRetrieve> .to_duplicate_response(errors::ApiErrorResponse::DuplicatePayment { payment_id: payment_id.clone(), })?; + let mandate_details_present = payment_attempt.mandate_details.is_some(); + + helpers::validate_mandate_data_and_future_usage( + request.setup_future_usage, + mandate_details_present, + )?; // connector mandate reference update history let mandate_id = request .mandate_id @@ -355,6 +361,8 @@ impl<F: Send + Clone, Ctx: PaymentMethodRetrieve> // The operation merges mandate data from both request and payment_attempt let setup_mandate = setup_mandate.map(MandateData::from); + let customer_acceptance = request.customer_acceptance.clone().map(From::from); + let surcharge_details = request.surcharge_details.map(|request_surcharge_details| { payments::types::SurchargeDetails::from((&request_surcharge_details, &payment_attempt)) }); @@ -368,6 +376,7 @@ impl<F: Send + Clone, Ctx: PaymentMethodRetrieve> .payment_method_data .apply_additional_payment_data(additional_payment_data) }); + let amount = payment_attempt.get_total_amount().into(); let payment_data = PaymentData { flow: PhantomData, @@ -379,6 +388,7 @@ impl<F: Send + Clone, Ctx: PaymentMethodRetrieve> mandate_id, mandate_connector, setup_mandate, + customer_acceptance, token, address: PaymentAddress { shipping: shipping_address.as_ref().map(|a| a.into()), diff --git a/crates/router/src/core/payments/operations/payment_reject.rs b/crates/router/src/core/payments/operations/payment_reject.rs index 281ffdd06f7..a1416ea1908 100644 --- a/crates/router/src/core/payments/operations/payment_reject.rs +++ b/crates/router/src/core/payments/operations/payment_reject.rs @@ -143,6 +143,7 @@ impl<F: Send + Clone, Ctx: PaymentMethodRetrieve> mandate_id: None, mandate_connector: None, setup_mandate: None, + customer_acceptance: None, token: None, address: PaymentAddress { shipping: shipping_address.as_ref().map(|a| a.into()), diff --git a/crates/router/src/core/payments/operations/payment_session.rs b/crates/router/src/core/payments/operations/payment_session.rs index 966600a5498..ed3eda8832b 100644 --- a/crates/router/src/core/payments/operations/payment_session.rs +++ b/crates/router/src/core/payments/operations/payment_session.rs @@ -167,6 +167,7 @@ impl<F: Send + Clone, Ctx: PaymentMethodRetrieve> email: None, mandate_id: None, mandate_connector: None, + customer_acceptance: None, token: None, setup_mandate: None, address: payments::PaymentAddress { diff --git a/crates/router/src/core/payments/operations/payment_start.rs b/crates/router/src/core/payments/operations/payment_start.rs index 2ca413b73aa..650fef7e1bf 100644 --- a/crates/router/src/core/payments/operations/payment_start.rs +++ b/crates/router/src/core/payments/operations/payment_start.rs @@ -145,6 +145,7 @@ impl<F: Send + Clone, Ctx: PaymentMethodRetrieve> mandate_id: None, mandate_connector: None, setup_mandate: None, + customer_acceptance: None, token: payment_attempt.payment_token.clone(), address: PaymentAddress { shipping: shipping_address.as_ref().map(|a| a.into()), diff --git a/crates/router/src/core/payments/operations/payment_status.rs b/crates/router/src/core/payments/operations/payment_status.rs index aa622b3558b..70f04ed364d 100644 --- a/crates/router/src/core/payments/operations/payment_status.rs +++ b/crates/router/src/core/payments/operations/payment_status.rs @@ -414,6 +414,7 @@ async fn get_tracker_for_sync< }), mandate_connector: None, setup_mandate: None, + customer_acceptance: None, token: None, address: PaymentAddress { shipping: shipping_address.as_ref().map(|a| a.into()), diff --git a/crates/router/src/core/payments/operations/payment_update.rs b/crates/router/src/core/payments/operations/payment_update.rs index cd73df26ff3..7661ee515d9 100644 --- a/crates/router/src/core/payments/operations/payment_update.rs +++ b/crates/router/src/core/payments/operations/payment_update.rs @@ -349,7 +349,12 @@ impl<F: Send + Clone, Ctx: PaymentMethodRetrieve> // The operation merges mandate data from both request and payment_attempt let setup_mandate = setup_mandate.map(Into::into); - + let mandate_details_present = + payment_attempt.mandate_details.is_some() || request.mandate_data.is_some(); + helpers::validate_mandate_data_and_future_usage( + payment_intent.setup_future_usage, + mandate_details_present, + )?; let profile_id = payment_intent .profile_id .as_ref() @@ -363,7 +368,7 @@ impl<F: Send + Clone, Ctx: PaymentMethodRetrieve> .to_not_found_response(errors::ApiErrorResponse::BusinessProfileNotFound { id: profile_id.to_string(), })?; - + let customer_acceptance = request.customer_acceptance.clone().map(From::from); let surcharge_details = request.surcharge_details.map(|request_surcharge_details| { payments::types::SurchargeDetails::from((&request_surcharge_details, &payment_attempt)) }); @@ -379,6 +384,7 @@ impl<F: Send + Clone, Ctx: PaymentMethodRetrieve> mandate_connector, token, setup_mandate, + customer_acceptance, address: PaymentAddress { shipping: shipping_address.as_ref().map(|a| a.into()), billing: billing_address.as_ref().map(|a| a.into()), diff --git a/crates/router/src/core/payments/operations/payments_incremental_authorization.rs b/crates/router/src/core/payments/operations/payments_incremental_authorization.rs index 24292507c0e..96cbf9fb9db 100644 --- a/crates/router/src/core/payments/operations/payments_incremental_authorization.rs +++ b/crates/router/src/core/payments/operations/payments_incremental_authorization.rs @@ -120,6 +120,7 @@ impl<F: Send + Clone, Ctx: PaymentMethodRetrieve> mandate_id: None, mandate_connector: None, setup_mandate: None, + customer_acceptance: None, token: None, address: PaymentAddress { billing: None, diff --git a/crates/router/src/core/payments/tokenization.rs b/crates/router/src/core/payments/tokenization.rs index 1f793e2e185..943550ef434 100644 --- a/crates/router/src/core/payments/tokenization.rs +++ b/crates/router/src/core/payments/tokenization.rs @@ -1,6 +1,9 @@ use api_models::payment_methods::PaymentMethodsData; use common_enums::PaymentMethod; -use common_utils::{ext_traits::ValueExt, pii}; +use common_utils::{ + ext_traits::{Encode, ValueExt}, + pii, +}; use error_stack::{report, ResultExt}; use masking::ExposeInterface; use router_env::{instrument, tracing}; @@ -34,7 +37,6 @@ pub async fn save_payment_method<F: Clone, FData>( merchant_account: &domain::MerchantAccount, payment_method_type: Option<storage_enums::PaymentMethodType>, key_store: &domain::MerchantKeyStore, - is_mandate: bool, ) -> RouterResult<Option<String>> where FData: mandate::MandateBehaviour, @@ -67,16 +69,24 @@ where } else { None }; - let future_usage_validation = resp + + let mandate_data_customer_acceptance = resp .request - .get_setup_future_usage() - .map(|future_usage| { - (future_usage == storage_enums::FutureUsage::OffSession && is_mandate) - || (future_usage == storage_enums::FutureUsage::OnSession && !is_mandate) - }) - .unwrap_or(false); + .get_setup_mandate_details() + .and_then(|mandate_data| mandate_data.customer_acceptance.clone()); + + let customer_acceptance = resp + .request + .get_customer_acceptance() + .or(mandate_data_customer_acceptance.clone().map(From::from)) + .map(|ca| ca.encode_to_value()) + .transpose() + .change_context(errors::ApiErrorResponse::InternalServerError) + .attach_printable("Unable to serialize customer acceptance to value")?; - let pm_id = if future_usage_validation { + let pm_id = if resp.request.get_setup_future_usage().is_some() + && customer_acceptance.is_some() + { let customer = maybe_customer.to_owned().get_required_value("customer")?; let payment_method_create_request = helpers::get_payment_method_create_request( Some(&resp.request.get_payment_method_data()), @@ -181,6 +191,7 @@ where locker_id, merchant_id, pm_metadata, + customer_acceptance, pm_data_encrypted, key_store, ) @@ -243,6 +254,7 @@ where &merchant_account.merchant_id, &customer.customer_id, resp.metadata.clone().map(|val| val.expose()), + customer_acceptance, locker_id, ) .await @@ -357,6 +369,7 @@ where locker_id, merchant_id, pm_metadata, + customer_acceptance, pm_data_encrypted, key_store, ) diff --git a/crates/router/src/core/payments/transformers.rs b/crates/router/src/core/payments/transformers.rs index 7c7bac80cf0..8ccab155c69 100644 --- a/crates/router/src/core/payments/transformers.rs +++ b/crates/router/src/core/payments/transformers.rs @@ -1141,6 +1141,7 @@ impl<F: Clone> TryFrom<PaymentAdditionalData<'_, F>> for types::PaymentsAuthoriz | Some(RequestIncrementalAuthorization::Default) ), metadata: additional_data.payment_data.payment_intent.metadata, + customer_acceptance: payment_data.customer_acceptance, }) } } @@ -1436,6 +1437,7 @@ impl<F: Clone> TryFrom<PaymentAdditionalData<'_, F>> for types::SetupMandateRequ off_session: payment_data.mandate_id.as_ref().map(|_| true), mandate_id: payment_data.mandate_id.clone(), setup_mandate_details: payment_data.setup_mandate, + customer_acceptance: payment_data.customer_acceptance, router_return_url, email: payment_data.email, customer_name, diff --git a/crates/router/src/core/payouts/helpers.rs b/crates/router/src/core/payouts/helpers.rs index fcd2569ea99..7005e955dff 100644 --- a/crates/router/src/core/payouts/helpers.rs +++ b/crates/router/src/core/payouts/helpers.rs @@ -382,6 +382,7 @@ pub async fn save_payout_data_to_locker( Some(stored_resp.card_reference), &merchant_account.merchant_id, None, + None, card_details_encrypted, key_store, ) diff --git a/crates/router/src/types.rs b/crates/router/src/types.rs index 07691879d4a..106872fb43f 100644 --- a/crates/router/src/types.rs +++ b/crates/router/src/types.rs @@ -24,7 +24,7 @@ pub use api_models::{ use common_enums::MandateStatus; pub use common_utils::request::{RequestBody, RequestContent}; use common_utils::{pii, pii::Email}; -use data_models::mandates::MandateData; +use data_models::mandates::{CustomerAcceptance, MandateData}; use error_stack::{IntoReport, ResultExt}; use masking::Secret; use serde::Serialize; @@ -408,6 +408,7 @@ pub struct PaymentsAuthorizeData { pub setup_future_usage: Option<storage_enums::FutureUsage>, pub mandate_id: Option<api_models::payments::MandateIds>, pub off_session: Option<bool>, + pub customer_acceptance: Option<CustomerAcceptance>, pub setup_mandate_details: Option<MandateData>, pub browser_info: Option<BrowserInformation>, pub order_details: Option<Vec<api_models::payments::OrderDetailsWithAmount>>, @@ -584,6 +585,7 @@ pub struct SetupMandateRequestData { pub amount: Option<i64>, pub confirm: bool, pub statement_descriptor_suffix: Option<String>, + pub customer_acceptance: Option<CustomerAcceptance>, pub mandate_id: Option<api_models::payments::MandateIds>, pub setup_future_usage: Option<storage_enums::FutureUsage>, pub off_session: Option<bool>, @@ -1423,6 +1425,7 @@ impl From<&SetupMandateRouterData> for PaymentsAuthorizeData { surcharge_details: None, request_incremental_authorization: data.request.request_incremental_authorization, metadata: None, + customer_acceptance: data.request.customer_acceptance.clone(), } } } diff --git a/crates/router/src/types/api/verify_connector.rs b/crates/router/src/types/api/verify_connector.rs index 221d16a8b46..4f3d6f7e296 100644 --- a/crates/router/src/types/api/verify_connector.rs +++ b/crates/router/src/types/api/verify_connector.rs @@ -50,6 +50,7 @@ impl VerifyConnectorData { related_transaction_id: None, statement_descriptor_suffix: None, request_incremental_authorization: false, + customer_acceptance: None, } } diff --git a/crates/router/tests/connectors/aci.rs b/crates/router/tests/connectors/aci.rs index d3f8147fb26..5c4660805fb 100644 --- a/crates/router/tests/connectors/aci.rs +++ b/crates/router/tests/connectors/aci.rs @@ -72,6 +72,7 @@ fn construct_payment_router_data() -> types::PaymentsAuthorizeRouterData { surcharge_details: None, request_incremental_authorization: false, metadata: None, + customer_acceptance: None, }, response: Err(types::ErrorResponse::default()), payment_method_id: None, diff --git a/crates/router/tests/connectors/adyen.rs b/crates/router/tests/connectors/adyen.rs index 12812a70857..55f9f6b4b6b 100644 --- a/crates/router/tests/connectors/adyen.rs +++ b/crates/router/tests/connectors/adyen.rs @@ -170,6 +170,7 @@ impl AdyenTest { surcharge_details: None, request_incremental_authorization: false, metadata: None, + customer_acceptance: None, }) } } diff --git a/crates/router/tests/connectors/bitpay.rs b/crates/router/tests/connectors/bitpay.rs index d24e20cd660..93043f37c9b 100644 --- a/crates/router/tests/connectors/bitpay.rs +++ b/crates/router/tests/connectors/bitpay.rs @@ -96,6 +96,7 @@ fn payment_method_details() -> Option<types::PaymentsAuthorizeData> { surcharge_details: None, request_incremental_authorization: false, metadata: None, + customer_acceptance: None, }) } diff --git a/crates/router/tests/connectors/cashtocode.rs b/crates/router/tests/connectors/cashtocode.rs index a9d81d2bb62..7dd70d86695 100644 --- a/crates/router/tests/connectors/cashtocode.rs +++ b/crates/router/tests/connectors/cashtocode.rs @@ -70,6 +70,7 @@ impl CashtocodeTest { surcharge_details: None, request_incremental_authorization: false, metadata: None, + customer_acceptance: None, }) } diff --git a/crates/router/tests/connectors/coinbase.rs b/crates/router/tests/connectors/coinbase.rs index 7a872ecb585..b1fffb302cb 100644 --- a/crates/router/tests/connectors/coinbase.rs +++ b/crates/router/tests/connectors/coinbase.rs @@ -98,6 +98,7 @@ fn payment_method_details() -> Option<types::PaymentsAuthorizeData> { surcharge_details: None, request_incremental_authorization: false, metadata: None, + customer_acceptance: None, }) } diff --git a/crates/router/tests/connectors/cryptopay.rs b/crates/router/tests/connectors/cryptopay.rs index d61a93c8b82..6eaf514db21 100644 --- a/crates/router/tests/connectors/cryptopay.rs +++ b/crates/router/tests/connectors/cryptopay.rs @@ -96,6 +96,7 @@ fn payment_method_details() -> Option<types::PaymentsAuthorizeData> { surcharge_details: None, request_incremental_authorization: false, metadata: None, + customer_acceptance: None, }) } diff --git a/crates/router/tests/connectors/opennode.rs b/crates/router/tests/connectors/opennode.rs index 8415be949a0..4702012597e 100644 --- a/crates/router/tests/connectors/opennode.rs +++ b/crates/router/tests/connectors/opennode.rs @@ -97,6 +97,7 @@ fn payment_method_details() -> Option<types::PaymentsAuthorizeData> { surcharge_details: None, request_incremental_authorization: false, metadata: None, + customer_acceptance: None, }) } diff --git a/crates/router/tests/connectors/utils.rs b/crates/router/tests/connectors/utils.rs index 8f749a0b2ff..83380f76073 100644 --- a/crates/router/tests/connectors/utils.rs +++ b/crates/router/tests/connectors/utils.rs @@ -915,6 +915,7 @@ impl Default for PaymentAuthorizeType { surcharge_details: None, request_incremental_authorization: false, metadata: None, + customer_acceptance: None, }; Self(data) } diff --git a/crates/router/tests/connectors/worldline.rs b/crates/router/tests/connectors/worldline.rs index c5b12a0b0b2..ba946b296bf 100644 --- a/crates/router/tests/connectors/worldline.rs +++ b/crates/router/tests/connectors/worldline.rs @@ -106,6 +106,7 @@ impl WorldlineTest { surcharge_details: None, request_incremental_authorization: false, metadata: None, + customer_acceptance: None, }) } } diff --git a/openapi/openapi_spec.json b/openapi/openapi_spec.json index 293bfc85a7c..1a3e71f38c0 100644 --- a/openapi/openapi_spec.json +++ b/openapi/openapi_spec.json @@ -12529,6 +12529,14 @@ ], "nullable": true }, + "customer_acceptance": { + "allOf": [ + { + "$ref": "#/components/schemas/CustomerAcceptance" + } + ], + "nullable": true + }, "mandate_id": { "type": "string", "description": "A unique identifier to link the payment to a mandate. To do Recurring payments after a mandate has been created, pass the mandate_id instead of payment_method_data", @@ -12880,6 +12888,14 @@ ], "nullable": true }, + "customer_acceptance": { + "allOf": [ + { + "$ref": "#/components/schemas/CustomerAcceptance" + } + ], + "nullable": true + }, "mandate_id": { "type": "string", "description": "A unique identifier to link the payment to a mandate. To do Recurring payments after a mandate has been created, pass the mandate_id instead of payment_method_data", @@ -13286,6 +13302,14 @@ ], "nullable": true }, + "customer_acceptance": { + "allOf": [ + { + "$ref": "#/components/schemas/CustomerAcceptance" + } + ], + "nullable": true + }, "mandate_id": { "type": "string", "description": "A unique identifier to link the payment to a mandate. To do Recurring payments after a mandate has been created, pass the mandate_id instead of payment_method_data", @@ -14277,6 +14301,14 @@ ], "nullable": true }, + "customer_acceptance": { + "allOf": [ + { + "$ref": "#/components/schemas/CustomerAcceptance" + } + ], + "nullable": true + }, "browser_info": { "allOf": [ { diff --git a/postman/collection-dir/aci/Flow Testcases/Happy Cases/Scenario11-Create a mandate and recurring payment/Payments - Create/request.json b/postman/collection-dir/aci/Flow Testcases/Happy Cases/Scenario11-Create a mandate and recurring payment/Payments - Create/request.json index f7573b64a60..9988d0e2cb1 100644 --- a/postman/collection-dir/aci/Flow Testcases/Happy Cases/Scenario11-Create a mandate and recurring payment/Payments - Create/request.json +++ b/postman/collection-dir/aci/Flow Testcases/Happy Cases/Scenario11-Create a mandate and recurring payment/Payments - Create/request.json @@ -59,6 +59,14 @@ } } }, + "customer_acceptance": { + "acceptance_type": "offline", + "accepted_at": "1963-05-03T04:07:52.723Z", + "online": { + "ip_address": "127.0.0.1", + "user_agent": "amet irure esse" + } + }, "billing": { "address": { "line1": "1467", diff --git a/postman/collection-dir/aci/Flow Testcases/Happy Cases/Scenario11-Refund recurring payment/Payments - Create/request.json b/postman/collection-dir/aci/Flow Testcases/Happy Cases/Scenario11-Refund recurring payment/Payments - Create/request.json index b66df150887..9570f0f0b8d 100644 --- a/postman/collection-dir/aci/Flow Testcases/Happy Cases/Scenario11-Refund recurring payment/Payments - Create/request.json +++ b/postman/collection-dir/aci/Flow Testcases/Happy Cases/Scenario11-Refund recurring payment/Payments - Create/request.json @@ -59,6 +59,14 @@ } } }, + "customer_acceptance": { + "acceptance_type": "offline", + "accepted_at": "1963-05-03T04:07:52.723Z", + "online": { + "ip_address": "127.0.0.1", + "user_agent": "amet irure esse" + } + }, "shipping": { "address": { "line1": "1467", diff --git a/postman/collection-dir/aci/Flow Testcases/Variation Cases/Scenario9-Create a recurring payment with greater mandate amount/Payments - Create/request.json b/postman/collection-dir/aci/Flow Testcases/Variation Cases/Scenario9-Create a recurring payment with greater mandate amount/Payments - Create/request.json index f7573b64a60..9988d0e2cb1 100644 --- a/postman/collection-dir/aci/Flow Testcases/Variation Cases/Scenario9-Create a recurring payment with greater mandate amount/Payments - Create/request.json +++ b/postman/collection-dir/aci/Flow Testcases/Variation Cases/Scenario9-Create a recurring payment with greater mandate amount/Payments - Create/request.json @@ -59,6 +59,14 @@ } } }, + "customer_acceptance": { + "acceptance_type": "offline", + "accepted_at": "1963-05-03T04:07:52.723Z", + "online": { + "ip_address": "127.0.0.1", + "user_agent": "amet irure esse" + } + }, "billing": { "address": { "line1": "1467", diff --git a/postman/collection-dir/adyen_uk/Flow Testcases/Happy Cases/Scenario10-Create a mandate and recurring payment/Payments - Create/request.json b/postman/collection-dir/adyen_uk/Flow Testcases/Happy Cases/Scenario10-Create a mandate and recurring payment/Payments - Create/request.json index 80dad74bb60..0bf892efdf5 100644 --- a/postman/collection-dir/adyen_uk/Flow Testcases/Happy Cases/Scenario10-Create a mandate and recurring payment/Payments - Create/request.json +++ b/postman/collection-dir/adyen_uk/Flow Testcases/Happy Cases/Scenario10-Create a mandate and recurring payment/Payments - Create/request.json @@ -60,6 +60,14 @@ } } }, + "customer_acceptance": { + "acceptance_type": "offline", + "accepted_at": "1963-05-03T04:07:52.723Z", + "online": { + "ip_address": "127.0.0.1", + "user_agent": "amet irure esse" + } + }, "billing": { "address": { "line1": "1467", diff --git a/postman/collection-dir/adyen_uk/Flow Testcases/Happy Cases/Scenario14-Refund recurring payment/Payments - Create/request.json b/postman/collection-dir/adyen_uk/Flow Testcases/Happy Cases/Scenario14-Refund recurring payment/Payments - Create/request.json index 08e62dca6e9..a515beb2661 100644 --- a/postman/collection-dir/adyen_uk/Flow Testcases/Happy Cases/Scenario14-Refund recurring payment/Payments - Create/request.json +++ b/postman/collection-dir/adyen_uk/Flow Testcases/Happy Cases/Scenario14-Refund recurring payment/Payments - Create/request.json @@ -60,6 +60,14 @@ } } }, + "customer_acceptance": { + "acceptance_type": "offline", + "accepted_at": "1963-05-03T04:07:52.723Z", + "online": { + "ip_address": "127.0.0.1", + "user_agent": "amet irure esse" + } + }, "shipping": { "address": { "line1": "1467", diff --git a/postman/collection-dir/adyen_uk/Flow Testcases/Happy Cases/Scenario16-Bank debit-ach/Payments - Create/request.json b/postman/collection-dir/adyen_uk/Flow Testcases/Happy Cases/Scenario16-Bank debit-ach/Payments - Create/request.json index 21c079e0ad0..eecdf810746 100644 --- a/postman/collection-dir/adyen_uk/Flow Testcases/Happy Cases/Scenario16-Bank debit-ach/Payments - Create/request.json +++ b/postman/collection-dir/adyen_uk/Flow Testcases/Happy Cases/Scenario16-Bank debit-ach/Payments - Create/request.json @@ -32,6 +32,14 @@ "authentication_type": "three_ds", "return_url": "https://duck.com", "setup_future_usage": "on_session", + "customer_acceptance": { + "acceptance_type": "offline", + "accepted_at": "1963-05-03T04:07:52.723Z", + "online": { + "ip_address": "127.0.0.1", + "user_agent": "amet irure esse" + } + }, "billing": { "address": { "line1": "1467", diff --git a/postman/collection-dir/adyen_uk/Flow Testcases/Happy Cases/Scenario17-Bank debit-Bacs/Payments - Create/request.json b/postman/collection-dir/adyen_uk/Flow Testcases/Happy Cases/Scenario17-Bank debit-Bacs/Payments - Create/request.json index 1ec9a829a48..660ef06c518 100644 --- a/postman/collection-dir/adyen_uk/Flow Testcases/Happy Cases/Scenario17-Bank debit-Bacs/Payments - Create/request.json +++ b/postman/collection-dir/adyen_uk/Flow Testcases/Happy Cases/Scenario17-Bank debit-Bacs/Payments - Create/request.json @@ -32,6 +32,14 @@ "authentication_type": "no_three_ds", "return_url": "https://duck.com", "setup_future_usage": "on_session", + "customer_acceptance": { + "acceptance_type": "offline", + "accepted_at": "1963-05-03T04:07:52.723Z", + "online": { + "ip_address": "127.0.0.1", + "user_agent": "amet irure esse" + } + }, "billing": { "address": { "line1": "1467", diff --git a/postman/collection-dir/adyen_uk/Flow Testcases/Happy Cases/Scenario19-Add card flow/Payments - Create/request.json b/postman/collection-dir/adyen_uk/Flow Testcases/Happy Cases/Scenario19-Add card flow/Payments - Create/request.json index 9260edb1a99..397f164511f 100644 --- a/postman/collection-dir/adyen_uk/Flow Testcases/Happy Cases/Scenario19-Add card flow/Payments - Create/request.json +++ b/postman/collection-dir/adyen_uk/Flow Testcases/Happy Cases/Scenario19-Add card flow/Payments - Create/request.json @@ -33,6 +33,14 @@ "authentication_type": "no_three_ds", "return_url": "https://google.com", "setup_future_usage": "on_session", + "customer_acceptance": { + "acceptance_type": "offline", + "accepted_at": "1963-05-03T04:07:52.723Z", + "online": { + "ip_address": "127.0.0.1", + "user_agent": "amet irure esse" + } + }, "payment_method": "card", "payment_method_type": "credit", "payment_method_data": { @@ -89,12 +97,8 @@ }, "url": { "raw": "{{baseUrl}}/payments", - "host": [ - "{{baseUrl}}" - ], - "path": [ - "payments" - ] + "host": ["{{baseUrl}}"], + "path": ["payments"] }, "description": "To process a payment you will have to create a payment, attach a payment method and confirm. Depending on the user journey you wish to achieve, you may opt to all the steps in a single request or in a sequence of API request using following APIs: (i) Payments - Update, (ii) Payments - Confirm, and (iii) Payments - Capture" } diff --git a/postman/collection-dir/adyen_uk/Flow Testcases/Happy Cases/Scenario20-Pass Invalid CVV for save card flow and verify failed payment/Payments - Create/request.json b/postman/collection-dir/adyen_uk/Flow Testcases/Happy Cases/Scenario20-Pass Invalid CVV for save card flow and verify failed payment/Payments - Create/request.json index 9260edb1a99..397f164511f 100644 --- a/postman/collection-dir/adyen_uk/Flow Testcases/Happy Cases/Scenario20-Pass Invalid CVV for save card flow and verify failed payment/Payments - Create/request.json +++ b/postman/collection-dir/adyen_uk/Flow Testcases/Happy Cases/Scenario20-Pass Invalid CVV for save card flow and verify failed payment/Payments - Create/request.json @@ -33,6 +33,14 @@ "authentication_type": "no_three_ds", "return_url": "https://google.com", "setup_future_usage": "on_session", + "customer_acceptance": { + "acceptance_type": "offline", + "accepted_at": "1963-05-03T04:07:52.723Z", + "online": { + "ip_address": "127.0.0.1", + "user_agent": "amet irure esse" + } + }, "payment_method": "card", "payment_method_type": "credit", "payment_method_data": { @@ -89,12 +97,8 @@ }, "url": { "raw": "{{baseUrl}}/payments", - "host": [ - "{{baseUrl}}" - ], - "path": [ - "payments" - ] + "host": ["{{baseUrl}}"], + "path": ["payments"] }, "description": "To process a payment you will have to create a payment, attach a payment method and confirm. Depending on the user journey you wish to achieve, you may opt to all the steps in a single request or in a sequence of API request using following APIs: (i) Payments - Update, (ii) Payments - Confirm, and (iii) Payments - Capture" } diff --git a/postman/collection-dir/adyen_uk/Flow Testcases/Happy Cases/Scenario21-Don't Pass CVV for save card flow and verify failed payment Copy/Payments - Create/request.json b/postman/collection-dir/adyen_uk/Flow Testcases/Happy Cases/Scenario21-Don't Pass CVV for save card flow and verify failed payment Copy/Payments - Create/request.json index 9260edb1a99..397f164511f 100644 --- a/postman/collection-dir/adyen_uk/Flow Testcases/Happy Cases/Scenario21-Don't Pass CVV for save card flow and verify failed payment Copy/Payments - Create/request.json +++ b/postman/collection-dir/adyen_uk/Flow Testcases/Happy Cases/Scenario21-Don't Pass CVV for save card flow and verify failed payment Copy/Payments - Create/request.json @@ -33,6 +33,14 @@ "authentication_type": "no_three_ds", "return_url": "https://google.com", "setup_future_usage": "on_session", + "customer_acceptance": { + "acceptance_type": "offline", + "accepted_at": "1963-05-03T04:07:52.723Z", + "online": { + "ip_address": "127.0.0.1", + "user_agent": "amet irure esse" + } + }, "payment_method": "card", "payment_method_type": "credit", "payment_method_data": { @@ -89,12 +97,8 @@ }, "url": { "raw": "{{baseUrl}}/payments", - "host": [ - "{{baseUrl}}" - ], - "path": [ - "payments" - ] + "host": ["{{baseUrl}}"], + "path": ["payments"] }, "description": "To process a payment you will have to create a payment, attach a payment method and confirm. Depending on the user journey you wish to achieve, you may opt to all the steps in a single request or in a sequence of API request using following APIs: (i) Payments - Update, (ii) Payments - Confirm, and (iii) Payments - Capture" } diff --git a/postman/collection-dir/adyen_uk/Flow Testcases/Variation Cases/Scenario9-Create a recurring payment with greater mandate amount/Payments - Create/request.json b/postman/collection-dir/adyen_uk/Flow Testcases/Variation Cases/Scenario9-Create a recurring payment with greater mandate amount/Payments - Create/request.json index 93e802128f2..40a78911a9a 100644 --- a/postman/collection-dir/adyen_uk/Flow Testcases/Variation Cases/Scenario9-Create a recurring payment with greater mandate amount/Payments - Create/request.json +++ b/postman/collection-dir/adyen_uk/Flow Testcases/Variation Cases/Scenario9-Create a recurring payment with greater mandate amount/Payments - Create/request.json @@ -59,6 +59,14 @@ } } }, + "customer_acceptance": { + "acceptance_type": "offline", + "accepted_at": "1963-05-03T04:07:52.723Z", + "online": { + "ip_address": "127.0.0.1", + "user_agent": "amet irure esse" + } + }, "billing": { "address": { "line1": "1467", diff --git a/postman/collection-dir/authorizedotnet/Flow Testcases/Variation Cases/Scenario11-Create a recurring payment with greater mandate amount/Payments - Create/request.json b/postman/collection-dir/authorizedotnet/Flow Testcases/Variation Cases/Scenario11-Create a recurring payment with greater mandate amount/Payments - Create/request.json index e3d19912b79..d152474c374 100644 --- a/postman/collection-dir/authorizedotnet/Flow Testcases/Variation Cases/Scenario11-Create a recurring payment with greater mandate amount/Payments - Create/request.json +++ b/postman/collection-dir/authorizedotnet/Flow Testcases/Variation Cases/Scenario11-Create a recurring payment with greater mandate amount/Payments - Create/request.json @@ -59,6 +59,14 @@ } } }, + "customer_acceptance": { + "acceptance_type": "online", + "accepted_at": "2022-09-10T10:11:12Z", + "online": { + "ip_address": "123.32.25.123", + "user_agent": "Mozilla/5.0 (Linux; Android 12; SM-S906N Build/QP1A.190711.020; wv) AppleWebKit/537.36 (KHTML, like Gecko) Version/4.0 Chrome/80.0.3987.119 Mobile Safari/537.36" + } + }, "billing": { "address": { "line1": "1467", diff --git a/postman/collection-dir/bankofamerica/Flow Testcases/Happy Cases/Scenario1-Create payment with confirm true/Payments - Create/request.json b/postman/collection-dir/bankofamerica/Flow Testcases/Happy Cases/Scenario1-Create payment with confirm true/Payments - Create/request.json index e37391b78b5..43eb0c9cc12 100644 --- a/postman/collection-dir/bankofamerica/Flow Testcases/Happy Cases/Scenario1-Create payment with confirm true/Payments - Create/request.json +++ b/postman/collection-dir/bankofamerica/Flow Testcases/Happy Cases/Scenario1-Create payment with confirm true/Payments - Create/request.json @@ -35,6 +35,14 @@ "authentication_type": "no_three_ds", "return_url": "https://duck.com", "setup_future_usage": "on_session", + "customer_acceptance": { + "acceptance_type": "online", + "accepted_at": "2022-09-10T10:11:12Z", + "online": { + "ip_address": "123.32.25.123", + "user_agent": "Mozilla/5.0 (Linux; Android 12; SM-S906N Build/QP1A.190711.020; wv) AppleWebKit/537.36 (KHTML, like Gecko) Version/4.0 Chrome/80.0.3987.119 Mobile Safari/537.36" + } + }, "payment_method": "card", "payment_method_type": "debit", "payment_method_data": { @@ -87,12 +95,8 @@ }, "url": { "raw": "{{baseUrl}}/payments", - "host": [ - "{{baseUrl}}" - ], - "path": [ - "payments" - ] + "host": ["{{baseUrl}}"], + "path": ["payments"] }, "description": "To process a payment you will have to create a payment, attach a payment method and confirm. Depending on the user journey you wish to achieve, you may opt to all the steps in a single request or in a sequence of API request using following APIs: (i) Payments - Update, (ii) Payments - Confirm, and (iii) Payments - Capture" } diff --git a/postman/collection-dir/nmi/Flow Testcases/Happy Cases/Scenario12-Add card flow/Payments - Create/request.json b/postman/collection-dir/nmi/Flow Testcases/Happy Cases/Scenario12-Add card flow/Payments - Create/request.json index 056b9269a29..d0320b09975 100644 --- a/postman/collection-dir/nmi/Flow Testcases/Happy Cases/Scenario12-Add card flow/Payments - Create/request.json +++ b/postman/collection-dir/nmi/Flow Testcases/Happy Cases/Scenario12-Add card flow/Payments - Create/request.json @@ -33,6 +33,14 @@ "authentication_type": "no_three_ds", "return_url": "https://duck.com", "setup_future_usage": "on_session", + "customer_acceptance": { + "acceptance_type": "online", + "accepted_at": "2022-09-10T10:11:12Z", + "online": { + "ip_address": "123.32.25.123", + "user_agent": "Mozilla/5.0 (Linux; Android 12; SM-S906N Build/QP1A.190711.020; wv) AppleWebKit/537.36 (KHTML, like Gecko) Version/4.0 Chrome/80.0.3987.119 Mobile Safari/537.36" + } + }, "payment_method": "card", "payment_method_type": "credit", "payment_method_data": { diff --git a/postman/collection-dir/nmi/Flow Testcases/Happy Cases/Scenario13-Don't Pass CVV for save card flow and verify success payment/Payments - Create/request.json b/postman/collection-dir/nmi/Flow Testcases/Happy Cases/Scenario13-Don't Pass CVV for save card flow and verify success payment/Payments - Create/request.json index 1d85fee7356..fe4adccda47 100644 --- a/postman/collection-dir/nmi/Flow Testcases/Happy Cases/Scenario13-Don't Pass CVV for save card flow and verify success payment/Payments - Create/request.json +++ b/postman/collection-dir/nmi/Flow Testcases/Happy Cases/Scenario13-Don't Pass CVV for save card flow and verify success payment/Payments - Create/request.json @@ -33,6 +33,14 @@ "authentication_type": "no_three_ds", "return_url": "https://duck.com", "setup_future_usage": "on_session", + "customer_acceptance": { + "acceptance_type": "online", + "accepted_at": "2022-09-10T10:11:12Z", + "online": { + "ip_address": "123.32.25.123", + "user_agent": "Mozilla/5.0 (Linux; Android 12; SM-S906N Build/QP1A.190711.020; wv) AppleWebKit/537.36 (KHTML, like Gecko) Version/4.0 Chrome/80.0.3987.119 Mobile Safari/537.36" + } + }, "payment_method": "card", "payment_method_type": "credit", "payment_method_data": { diff --git a/postman/collection-dir/nmi/Flow Testcases/Happy Cases/Scenario14-Save card payment with manual capture/Payments - Create/request.json b/postman/collection-dir/nmi/Flow Testcases/Happy Cases/Scenario14-Save card payment with manual capture/Payments - Create/request.json index 73457bf3197..aaa993e4eef 100644 --- a/postman/collection-dir/nmi/Flow Testcases/Happy Cases/Scenario14-Save card payment with manual capture/Payments - Create/request.json +++ b/postman/collection-dir/nmi/Flow Testcases/Happy Cases/Scenario14-Save card payment with manual capture/Payments - Create/request.json @@ -33,6 +33,14 @@ "authentication_type": "no_three_ds", "return_url": "https://duck.com", "setup_future_usage": "on_session", + "customer_acceptance": { + "acceptance_type": "online", + "accepted_at": "2022-09-10T10:11:12Z", + "online": { + "ip_address": "123.32.25.123", + "user_agent": "Mozilla/5.0 (Linux; Android 12; SM-S906N Build/QP1A.190711.020; wv) AppleWebKit/537.36 (KHTML, like Gecko) Version/4.0 Chrome/80.0.3987.119 Mobile Safari/537.36" + } + }, "payment_method": "card", "payment_method_type": "credit", "payment_method_data": { diff --git a/postman/collection-dir/nmi/Flow Testcases/Happy Cases/Scenario15-Create payment without customer_id and with billing address and shipping address/Payments - Create/request.json b/postman/collection-dir/nmi/Flow Testcases/Happy Cases/Scenario15-Create payment without customer_id and with billing address and shipping address/Payments - Create/request.json index ffda1aef2d7..050f353af53 100644 --- a/postman/collection-dir/nmi/Flow Testcases/Happy Cases/Scenario15-Create payment without customer_id and with billing address and shipping address/Payments - Create/request.json +++ b/postman/collection-dir/nmi/Flow Testcases/Happy Cases/Scenario15-Create payment without customer_id and with billing address and shipping address/Payments - Create/request.json @@ -35,6 +35,14 @@ "authentication_type": "no_three_ds", "return_url": "https://duck.com", "setup_future_usage": "on_session", + "customer_acceptance": { + "acceptance_type": "online", + "accepted_at": "2022-09-10T10:11:12Z", + "online": { + "ip_address": "123.32.25.123", + "user_agent": "Mozilla/5.0 (Linux; Android 12; SM-S906N Build/QP1A.190711.020; wv) AppleWebKit/537.36 (KHTML, like Gecko) Version/4.0 Chrome/80.0.3987.119 Mobile Safari/537.36" + } + }, "payment_method": "card", "payment_method_type": "debit", "payment_method_data": { diff --git a/postman/collection-dir/nmi/Flow Testcases/Happy Cases/Scenario8-Create a failure card payment with confirm true/Payments - Create/request.json b/postman/collection-dir/nmi/Flow Testcases/Happy Cases/Scenario8-Create a failure card payment with confirm true/Payments - Create/request.json index 97cce7936c4..63d1eeba233 100644 --- a/postman/collection-dir/nmi/Flow Testcases/Happy Cases/Scenario8-Create a failure card payment with confirm true/Payments - Create/request.json +++ b/postman/collection-dir/nmi/Flow Testcases/Happy Cases/Scenario8-Create a failure card payment with confirm true/Payments - Create/request.json @@ -35,6 +35,14 @@ "authentication_type": "no_three_ds", "return_url": "https://duck.com", "setup_future_usage": "on_session", + "customer_acceptance": { + "acceptance_type": "online", + "accepted_at": "2022-09-10T10:11:12Z", + "online": { + "ip_address": "123.32.25.123", + "user_agent": "Mozilla/5.0 (Linux; Android 12; SM-S906N Build/QP1A.190711.020; wv) AppleWebKit/537.36 (KHTML, like Gecko) Version/4.0 Chrome/80.0.3987.119 Mobile Safari/537.36" + } + }, "payment_method": "card", "payment_method_type": "debit", "payment_method_data": { diff --git a/postman/collection-dir/nmi/Flow Testcases/Happy Cases/Scenario9-Update amount with automatic capture/Payments - Confirm/request.json b/postman/collection-dir/nmi/Flow Testcases/Happy Cases/Scenario9-Update amount with automatic capture/Payments - Confirm/request.json index 7b72495e5c4..962144d6bc6 100644 --- a/postman/collection-dir/nmi/Flow Testcases/Happy Cases/Scenario9-Update amount with automatic capture/Payments - Confirm/request.json +++ b/postman/collection-dir/nmi/Flow Testcases/Happy Cases/Scenario9-Update amount with automatic capture/Payments - Confirm/request.json @@ -29,7 +29,6 @@ "key": "Accept", "value": "application/json" }, - , { "key": "publishable_key", "value": "", @@ -58,6 +57,14 @@ } }, "setup_future_usage": "on_session", + "customer_acceptance": { + "acceptance_type": "online", + "accepted_at": "2022-09-10T10:11:12Z", + "online": { + "ip_address": "123.32.25.123", + "user_agent": "Mozilla/5.0 (Linux; Android 12; SM-S906N Build/QP1A.190711.020; wv) AppleWebKit/537.36 (KHTML, like Gecko) Version/4.0 Chrome/80.0.3987.119 Mobile Safari/537.36" + } + }, "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", diff --git a/postman/collection-dir/nmi/Flow Testcases/Happy Cases/Scenario9a-Update amount with manual capture/Payments - Confirm/request.json b/postman/collection-dir/nmi/Flow Testcases/Happy Cases/Scenario9a-Update amount with manual capture/Payments - Confirm/request.json index 7b72495e5c4..962144d6bc6 100644 --- a/postman/collection-dir/nmi/Flow Testcases/Happy Cases/Scenario9a-Update amount with manual capture/Payments - Confirm/request.json +++ b/postman/collection-dir/nmi/Flow Testcases/Happy Cases/Scenario9a-Update amount with manual capture/Payments - Confirm/request.json @@ -29,7 +29,6 @@ "key": "Accept", "value": "application/json" }, - , { "key": "publishable_key", "value": "", @@ -58,6 +57,14 @@ } }, "setup_future_usage": "on_session", + "customer_acceptance": { + "acceptance_type": "online", + "accepted_at": "2022-09-10T10:11:12Z", + "online": { + "ip_address": "123.32.25.123", + "user_agent": "Mozilla/5.0 (Linux; Android 12; SM-S906N Build/QP1A.190711.020; wv) AppleWebKit/537.36 (KHTML, like Gecko) Version/4.0 Chrome/80.0.3987.119 Mobile Safari/537.36" + } + }, "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", diff --git a/postman/collection-dir/nmi/Flow Testcases/Variation Cases/Scenario9-Create a recurring payment with greater mandate amount Copy/Payments - Create/request.json b/postman/collection-dir/nmi/Flow Testcases/Variation Cases/Scenario9-Create a recurring payment with greater mandate amount Copy/Payments - Create/request.json index 7aeaf601cc6..2cbfe4a20f1 100644 --- a/postman/collection-dir/nmi/Flow Testcases/Variation Cases/Scenario9-Create a recurring payment with greater mandate amount Copy/Payments - Create/request.json +++ b/postman/collection-dir/nmi/Flow Testcases/Variation Cases/Scenario9-Create a recurring payment with greater mandate amount Copy/Payments - Create/request.json @@ -59,6 +59,14 @@ } } }, + "customer_acceptance": { + "acceptance_type": "online", + "accepted_at": "2022-09-10T10:11:12Z", + "online": { + "ip_address": "123.32.25.123", + "user_agent": "Mozilla/5.0 (Linux; Android 12; SM-S906N Build/QP1A.190711.020; wv) AppleWebKit/537.36 (KHTML, like Gecko) Version/4.0 Chrome/80.0.3987.119 Mobile Safari/537.36" + } + }, "billing": { "address": { "line1": "1467", diff --git a/postman/collection-dir/paypal/Flow Testcases/Happy Cases/Scenario6-Create Wallet - Paypal/Payments - Create/request.json b/postman/collection-dir/paypal/Flow Testcases/Happy Cases/Scenario6-Create Wallet - Paypal/Payments - Create/request.json index 824bfb49230..7201fa121be 100644 --- a/postman/collection-dir/paypal/Flow Testcases/Happy Cases/Scenario6-Create Wallet - Paypal/Payments - Create/request.json +++ b/postman/collection-dir/paypal/Flow Testcases/Happy Cases/Scenario6-Create Wallet - Paypal/Payments - Create/request.json @@ -33,6 +33,14 @@ "authentication_type": "three_ds", "return_url": "https://duck.com", "setup_future_usage": "on_session", + "customer_acceptance": { + "acceptance_type": "online", + "accepted_at": "2022-09-10T10:11:12Z", + "online": { + "ip_address": "123.32.25.123", + "user_agent": "Mozilla/5.0 (Linux; Android 12; SM-S906N Build/QP1A.190711.020; wv) AppleWebKit/537.36 (KHTML, like Gecko) Version/4.0 Chrome/80.0.3987.119 Mobile Safari/537.36" + } + }, "billing": { "address": { "line1": "1467", diff --git a/postman/collection-dir/paypal/Flow Testcases/Happy Cases/Scenario7-Create Wallet - Paypal with confrm false/Payments - Confirm/request.json b/postman/collection-dir/paypal/Flow Testcases/Happy Cases/Scenario7-Create Wallet - Paypal with confrm false/Payments - Confirm/request.json index efa17534b1d..f5da408b2f3 100644 --- a/postman/collection-dir/paypal/Flow Testcases/Happy Cases/Scenario7-Create Wallet - Paypal with confrm false/Payments - Confirm/request.json +++ b/postman/collection-dir/paypal/Flow Testcases/Happy Cases/Scenario7-Create Wallet - Paypal with confrm false/Payments - Confirm/request.json @@ -45,6 +45,14 @@ "wallet": { "paypal_redirect": {} } + }, + "customer_acceptance": { + "acceptance_type": "online", + "accepted_at": "2022-09-10T10:11:12Z", + "online": { + "ip_address": "123.32.25.123", + "user_agent": "Mozilla/5.0 (Linux; Android 12; SM-S906N Build/QP1A.190711.020; wv) AppleWebKit/537.36 (KHTML, like Gecko) Version/4.0 Chrome/80.0.3987.119 Mobile Safari/537.36" + } } } }, diff --git a/postman/collection-dir/shift4/Flow Testcases/Variation Cases/Scenario9-Create a recurring payment with greater mandate amount/Payments - Create/request.json b/postman/collection-dir/shift4/Flow Testcases/Variation Cases/Scenario9-Create a recurring payment with greater mandate amount/Payments - Create/request.json index 57d625e7c39..fbbd60339e9 100644 --- a/postman/collection-dir/shift4/Flow Testcases/Variation Cases/Scenario9-Create a recurring payment with greater mandate amount/Payments - Create/request.json +++ b/postman/collection-dir/shift4/Flow Testcases/Variation Cases/Scenario9-Create a recurring payment with greater mandate amount/Payments - Create/request.json @@ -59,6 +59,14 @@ } } }, + "customer_acceptance": { + "acceptance_type": "online", + "accepted_at": "2022-09-10T10:11:12Z", + "online": { + "ip_address": "123.32.25.123", + "user_agent": "Mozilla/5.0 (Linux; Android 12; SM-S906N Build/QP1A.190711.020; wv) AppleWebKit/537.36 (KHTML, like Gecko) Version/4.0 Chrome/80.0.3987.119 Mobile Safari/537.36" + } + }, "billing": { "address": { "line1": "1467", diff --git a/postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario1-Create payment with confirm true/Payments - Create/request.json b/postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario1-Create payment with confirm true/Payments - Create/request.json index 93bcc23194f..9d0fac32c1f 100644 --- a/postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario1-Create payment with confirm true/Payments - Create/request.json +++ b/postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario1-Create payment with confirm true/Payments - Create/request.json @@ -35,6 +35,14 @@ "authentication_type": "no_three_ds", "return_url": "https://duck.com", "setup_future_usage": "on_session", + "customer_acceptance": { + "acceptance_type": "online", + "accepted_at": "2022-09-10T10:11:12Z", + "online": { + "ip_address": "123.32.25.123", + "user_agent": "Mozilla/5.0 (Linux; Android 12; SM-S906N Build/QP1A.190711.020; wv) AppleWebKit/537.36 (KHTML, like Gecko) Version/4.0 Chrome/80.0.3987.119 Mobile Safari/537.36" + } + }, "payment_method": "card", "payment_method_type": "debit", "payment_method_data": { diff --git a/postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario10-Create a mandate and recurring payment/Payments - Create/request.json b/postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario10-Create a mandate and recurring payment/Payments - Create/request.json index 3ffbe03a605..b5ef6b1afe2 100644 --- a/postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario10-Create a mandate and recurring payment/Payments - Create/request.json +++ b/postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario10-Create a mandate and recurring payment/Payments - Create/request.json @@ -59,6 +59,14 @@ } } }, + "customer_acceptance": { + "acceptance_type": "offline", + "accepted_at": "1963-05-03T04:07:52.723Z", + "online": { + "ip_address": "127.0.0.1", + "user_agent": "amet irure esse" + } + }, "billing": { "address": { "line1": "1467", @@ -98,12 +106,8 @@ }, "url": { "raw": "{{baseUrl}}/payments", - "host": [ - "{{baseUrl}}" - ], - "path": [ - "payments" - ] + "host": ["{{baseUrl}}"], + "path": ["payments"] }, "description": "To process a payment you will have to create a payment, attach a payment method and confirm. Depending on the user journey you wish to achieve, you may opt to all the steps in a single request or in a sequence of API request using following APIs: (i) Payments - Update, (ii) Payments - Confirm, and (iii) Payments - Capture" } diff --git a/postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario11-Refund recurring payment/Payments - Create/request.json b/postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario11-Refund recurring payment/Payments - Create/request.json index 9df18b5e886..61f007ede68 100644 --- a/postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario11-Refund recurring payment/Payments - Create/request.json +++ b/postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario11-Refund recurring payment/Payments - Create/request.json @@ -59,6 +59,14 @@ } } }, + "customer_acceptance": { + "acceptance_type": "online", + "accepted_at": "2022-09-10T10:11:12Z", + "online": { + "ip_address": "123.32.25.123", + "user_agent": "Mozilla/5.0 (Linux; Android 12; SM-S906N Build/QP1A.190711.020; wv) AppleWebKit/537.36 (KHTML, like Gecko) Version/4.0 Chrome/80.0.3987.119 Mobile Safari/537.36" + } + }, "shipping": { "address": { "line1": "1467", @@ -86,12 +94,8 @@ }, "url": { "raw": "{{baseUrl}}/payments", - "host": [ - "{{baseUrl}}" - ], - "path": [ - "payments" - ] + "host": ["{{baseUrl}}"], + "path": ["payments"] }, "description": "To process a payment you will have to create a payment, attach a payment method and confirm. Depending on the user journey you wish to achieve, you may opt to all the steps in a single request or in a sequence of API request using following APIs: (i) Payments - Update, (ii) Payments - Confirm, and (iii) Payments - Capture" } diff --git a/postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario20-Bank Debit-ach/Payments - Create/request.json b/postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario20-Bank Debit-ach/Payments - Create/request.json index eda0801c9cc..78d949505f4 100644 --- a/postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario20-Bank Debit-ach/Payments - Create/request.json +++ b/postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario20-Bank Debit-ach/Payments - Create/request.json @@ -23,9 +23,7 @@ "confirm": true, "business_label": "default", "capture_method": "automatic", - "connector": [ - "stripe" - ], + "connector": ["stripe"], "customer_id": "klarna", "capture_on": "2022-09-10T10:11:12Z", "authentication_type": "three_ds", @@ -55,6 +53,14 @@ } } }, + "customer_acceptance": { + "acceptance_type": "online", + "accepted_at": "2022-09-10T10:11:12Z", + "online": { + "ip_address": "123.32.25.123", + "user_agent": "Mozilla/5.0 (Linux; Android 12; SM-S906N Build/QP1A.190711.020; wv) AppleWebKit/537.36 (KHTML, like Gecko) Version/4.0 Chrome/80.0.3987.119 Mobile Safari/537.36" + } + }, "payment_method": "bank_debit", "payment_method_type": "ach", "payment_method_data": { @@ -85,12 +91,8 @@ }, "url": { "raw": "{{baseUrl}}/payments", - "host": [ - "{{baseUrl}}" - ], - "path": [ - "payments" - ] + "host": ["{{baseUrl}}"], + "path": ["payments"] }, "description": "To process a payment you will have to create a payment, attach a payment method and confirm. Depending on the user journey you wish to achieve, you may opt to all the steps in a single request or in a sequence of API request using following APIs: (i) Payments - Update, (ii) Payments - Confirm, and (iii) Payments - Capture" } diff --git a/postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario22- Update address and List Payment method/Payments - Confirm/request.json b/postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario22- Update address and List Payment method/Payments - Confirm/request.json index 20b99223ac4..43515f184b5 100644 --- a/postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario22- Update address and List Payment method/Payments - Confirm/request.json +++ b/postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario22- Update address and List Payment method/Payments - Confirm/request.json @@ -52,6 +52,7 @@ } } }, + "setup_future_usage": "off_session", "mandate_data": { "customer_acceptance": { "acceptance_type": "offline", @@ -73,7 +74,14 @@ } } }, - "setup_future_usage": "off_session", + "customer_acceptance": { + "acceptance_type": "offline", + "accepted_at": "1963-05-03T04:07:52.723Z", + "online": { + "ip_address": "127.0.0.1", + "user_agent": "amet irure esse" + } + }, "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", @@ -90,14 +98,8 @@ }, "url": { "raw": "{{baseUrl}}/payments/:id/confirm", - "host": [ - "{{baseUrl}}" - ], - "path": [ - "payments", - ":id", - "confirm" - ], + "host": ["{{baseUrl}}"], + "path": ["payments", ":id", "confirm"], "variable": [ { "key": "id", diff --git a/postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario22- Update address and List Payment method/Payments - Create/request.json b/postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario22- Update address and List Payment method/Payments - Create/request.json index 785122a83c5..beeb5b3983f 100644 --- a/postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario22- Update address and List Payment method/Payments - Create/request.json +++ b/postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario22- Update address and List Payment method/Payments - Create/request.json @@ -71,12 +71,8 @@ }, "url": { "raw": "{{baseUrl}}/payments", - "host": [ - "{{baseUrl}}" - ], - "path": [ - "payments" - ] + "host": ["{{baseUrl}}"], + "path": ["payments"] }, "description": "To process a payment you will have to create a payment, attach a payment method and confirm. Depending on the user journey you wish to achieve, you may opt to all the steps in a single request or in a sequence of API request using following APIs: (i) Payments - Update, (ii) Payments - Confirm, and (iii) Payments - Capture" } diff --git a/postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario23- Update Amount/Payments - Confirm/request.json b/postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario23- Update Amount/Payments - Confirm/request.json index 5a51941cf64..1b1757b9a49 100644 --- a/postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario23- Update Amount/Payments - Confirm/request.json +++ b/postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario23- Update Amount/Payments - Confirm/request.json @@ -29,7 +29,6 @@ "key": "Accept", "value": "application/json" }, - , { "key": "publishable_key", "value": "", @@ -58,6 +57,14 @@ } }, "setup_future_usage": "on_session", + "customer_acceptance": { + "acceptance_type": "offline", + "accepted_at": "1963-05-03T04:07:52.723Z", + "online": { + "ip_address": "127.0.0.1", + "user_agent": "amet irure esse" + } + }, "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", diff --git a/postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario24-Add card flow/Payments - Create/request.json b/postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario24-Add card flow/Payments - Create/request.json index 2019bae8790..2ac0cacfb99 100644 --- a/postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario24-Add card flow/Payments - Create/request.json +++ b/postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario24-Add card flow/Payments - Create/request.json @@ -33,6 +33,14 @@ "authentication_type": "no_three_ds", "return_url": "https://google.com", "setup_future_usage": "on_session", + "customer_acceptance": { + "acceptance_type": "offline", + "accepted_at": "1963-05-03T04:07:52.723Z", + "online": { + "ip_address": "127.0.0.1", + "user_agent": "amet irure esse" + } + }, "payment_method": "card", "payment_method_type": "credit", "payment_method_data": { @@ -93,12 +101,8 @@ }, "url": { "raw": "{{baseUrl}}/payments", - "host": [ - "{{baseUrl}}" - ], - "path": [ - "payments" - ] + "host": ["{{baseUrl}}"], + "path": ["payments"] }, "description": "To process a payment you will have to create a payment, attach a payment method and confirm. Depending on the user journey you wish to achieve, you may opt to all the steps in a single request or in a sequence of API request using following APIs: (i) Payments - Update, (ii) Payments - Confirm, and (iii) Payments - Capture" } diff --git a/postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario25-Don't Pass CVV for save card flow and verifysuccess payment/Payments - Create/request.json b/postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario25-Don't Pass CVV for save card flow and verifysuccess payment/Payments - Create/request.json index 4f02f7b6809..150106cfded 100644 --- a/postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario25-Don't Pass CVV for save card flow and verifysuccess payment/Payments - Create/request.json +++ b/postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario25-Don't Pass CVV for save card flow and verifysuccess payment/Payments - Create/request.json @@ -33,6 +33,14 @@ "authentication_type": "no_three_ds", "return_url": "https://google.com", "setup_future_usage": "on_session", + "customer_acceptance": { + "acceptance_type": "offline", + "accepted_at": "1963-05-03T04:07:52.723Z", + "online": { + "ip_address": "127.0.0.1", + "user_agent": "amet irure esse" + } + }, "payment_method": "card", "payment_method_type": "credit", "payment_method_data": { @@ -93,12 +101,8 @@ }, "url": { "raw": "{{baseUrl}}/payments", - "host": [ - "{{baseUrl}}" - ], - "path": [ - "payments" - ] + "host": ["{{baseUrl}}"], + "path": ["payments"] }, "description": "To process a payment you will have to create a payment, attach a payment method and confirm. Depending on the user journey you wish to achieve, you may opt to all the steps in a single request or in a sequence of API request using following APIs: (i) Payments - Update, (ii) Payments - Confirm, and (iii) Payments - Capture" } diff --git a/postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario26-Save card payment with manual capture/Payments - Create/request.json b/postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario26-Save card payment with manual capture/Payments - Create/request.json index 988bc4b800b..d73166871cd 100644 --- a/postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario26-Save card payment with manual capture/Payments - Create/request.json +++ b/postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario26-Save card payment with manual capture/Payments - Create/request.json @@ -33,6 +33,14 @@ "authentication_type": "no_three_ds", "return_url": "https://google.com", "setup_future_usage": "on_session", + "customer_acceptance": { + "acceptance_type": "offline", + "accepted_at": "1963-05-03T04:07:52.723Z", + "online": { + "ip_address": "127.0.0.1", + "user_agent": "amet irure esse" + } + }, "payment_method": "card", "payment_method_type": "credit", "payment_method_data": { @@ -93,12 +101,8 @@ }, "url": { "raw": "{{baseUrl}}/payments", - "host": [ - "{{baseUrl}}" - ], - "path": [ - "payments" - ] + "host": ["{{baseUrl}}"], + "path": ["payments"] }, "description": "To process a payment you will have to create a payment, attach a payment method and confirm. Depending on the user journey you wish to achieve, you may opt to all the steps in a single request or in a sequence of API request using following APIs: (i) Payments - Update, (ii) Payments - Confirm, and (iii) Payments - Capture" } diff --git a/postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario27-Create payment without customer_id and with billing address and shipping address/Payments - Create/request.json b/postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario27-Create payment without customer_id and with billing address and shipping address/Payments - Create/request.json index 60e56bb581c..6a9836d232c 100644 --- a/postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario27-Create payment without customer_id and with billing address and shipping address/Payments - Create/request.json +++ b/postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario27-Create payment without customer_id and with billing address and shipping address/Payments - Create/request.json @@ -35,6 +35,14 @@ "authentication_type": "no_three_ds", "return_url": "https://duck.com", "setup_future_usage": "on_session", + "customer_acceptance": { + "acceptance_type": "offline", + "accepted_at": "1963-05-03T04:07:52.723Z", + "online": { + "ip_address": "127.0.0.1", + "user_agent": "amet irure esse" + } + }, "payment_method": "card", "payment_method_type": "debit", "payment_method_data": { @@ -87,12 +95,8 @@ }, "url": { "raw": "{{baseUrl}}/payments", - "host": [ - "{{baseUrl}}" - ], - "path": [ - "payments" - ] + "host": ["{{baseUrl}}"], + "path": ["payments"] }, "description": "To process a payment you will have to create a payment, attach a payment method and confirm. Depending on the user journey you wish to achieve, you may opt to all the steps in a single request or in a sequence of API request using following APIs: (i) Payments - Update, (ii) Payments - Confirm, and (iii) Payments - Capture" } diff --git a/postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario28-Confirm a payment with requires_customer_action status/Payments - Create with confirm true/request.json b/postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario28-Confirm a payment with requires_customer_action status/Payments - Create with confirm true/request.json index d14ae6582c8..7e28058ccf6 100644 --- a/postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario28-Confirm a payment with requires_customer_action status/Payments - Create with confirm true/request.json +++ b/postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario28-Confirm a payment with requires_customer_action status/Payments - Create with confirm true/request.json @@ -35,6 +35,14 @@ "authentication_type": "three_ds", "return_url": "https://duck.com", "setup_future_usage": "on_session", + "customer_acceptance": { + "acceptance_type": "offline", + "accepted_at": "1963-05-03T04:07:52.723Z", + "online": { + "ip_address": "127.0.0.1", + "user_agent": "amet irure esse" + } + }, "payment_method": "card", "payment_method_data": { "card": { diff --git a/postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario6-Create 3DS payment/Payments - Create/request.json b/postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario6-Create 3DS payment/Payments - Create/request.json index d14ae6582c8..7e28058ccf6 100644 --- a/postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario6-Create 3DS payment/Payments - Create/request.json +++ b/postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario6-Create 3DS payment/Payments - Create/request.json @@ -35,6 +35,14 @@ "authentication_type": "three_ds", "return_url": "https://duck.com", "setup_future_usage": "on_session", + "customer_acceptance": { + "acceptance_type": "offline", + "accepted_at": "1963-05-03T04:07:52.723Z", + "online": { + "ip_address": "127.0.0.1", + "user_agent": "amet irure esse" + } + }, "payment_method": "card", "payment_method_data": { "card": { diff --git a/postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario8-Create a failure card payment with confirm true/Payments - Create/request.json b/postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario8-Create a failure card payment with confirm true/Payments - Create/request.json index 6d1bc5e0a0d..a3e0f52b8d7 100644 --- a/postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario8-Create a failure card payment with confirm true/Payments - Create/request.json +++ b/postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario8-Create a failure card payment with confirm true/Payments - Create/request.json @@ -35,6 +35,14 @@ "authentication_type": "no_three_ds", "return_url": "https://duck.com", "setup_future_usage": "on_session", + "customer_acceptance": { + "acceptance_type": "offline", + "accepted_at": "1963-05-03T04:07:52.723Z", + "online": { + "ip_address": "127.0.0.1", + "user_agent": "amet irure esse" + } + }, "payment_method": "card", "payment_method_type": "debit", "payment_method_data": { @@ -87,12 +95,8 @@ }, "url": { "raw": "{{baseUrl}}/payments", - "host": [ - "{{baseUrl}}" - ], - "path": [ - "payments" - ] + "host": ["{{baseUrl}}"], + "path": ["payments"] }, "description": "To process a payment you will have to create a payment, attach a payment method and confirm. Depending on the user journey you wish to achieve, you may opt to all the steps in a single request or in a sequence of API request using following APIs: (i) Payments - Update, (ii) Payments - Confirm, and (iii) Payments - Capture" } diff --git a/postman/collection-dir/stripe/Flow Testcases/Variation Cases/Scenario9-Create a recurring payment with greater mandate amount/Payments - Create/request.json b/postman/collection-dir/stripe/Flow Testcases/Variation Cases/Scenario9-Create a recurring payment with greater mandate amount/Payments - Create/request.json index a5c9391cf74..b5ef6b1afe2 100644 --- a/postman/collection-dir/stripe/Flow Testcases/Variation Cases/Scenario9-Create a recurring payment with greater mandate amount/Payments - Create/request.json +++ b/postman/collection-dir/stripe/Flow Testcases/Variation Cases/Scenario9-Create a recurring payment with greater mandate amount/Payments - Create/request.json @@ -59,6 +59,14 @@ } } }, + "customer_acceptance": { + "acceptance_type": "offline", + "accepted_at": "1963-05-03T04:07:52.723Z", + "online": { + "ip_address": "127.0.0.1", + "user_agent": "amet irure esse" + } + }, "billing": { "address": { "line1": "1467", diff --git a/postman/collection-dir/stripe/PaymentMethods/Payments - Create/request.json b/postman/collection-dir/stripe/PaymentMethods/Payments - Create/request.json index ac22dac750c..cc330f3c8f7 100644 --- a/postman/collection-dir/stripe/PaymentMethods/Payments - Create/request.json +++ b/postman/collection-dir/stripe/PaymentMethods/Payments - Create/request.json @@ -33,6 +33,14 @@ "authentication_type": "no_three_ds", "return_url": "https://duck.com", "setup_future_usage": "on_session", + "customer_acceptance": { + "acceptance_type": "offline", + "accepted_at": "1963-05-03T04:07:52.723Z", + "online": { + "ip_address": "127.0.0.1", + "user_agent": "amet irure esse" + } + }, "payment_method": "card", "payment_method_type": "debit", "payment_method_data": { diff --git a/postman/collection-dir/zen/Flow Testcases/Happy Cases/Scenario1-Create payment with confirm true/Payments - Create/request.json b/postman/collection-dir/zen/Flow Testcases/Happy Cases/Scenario1-Create payment with confirm true/Payments - Create/request.json index 7afc6d61c49..fd84bcaadb5 100644 --- a/postman/collection-dir/zen/Flow Testcases/Happy Cases/Scenario1-Create payment with confirm true/Payments - Create/request.json +++ b/postman/collection-dir/zen/Flow Testcases/Happy Cases/Scenario1-Create payment with confirm true/Payments - Create/request.json @@ -32,6 +32,14 @@ "authentication_type": "no_three_ds", "return_url": "https://duck.com", "setup_future_usage": "on_session", + "customer_acceptance": { + "acceptance_type": "offline", + "accepted_at": "1963-05-03T04:07:52.723Z", + "online": { + "ip_address": "127.0.0.1", + "user_agent": "amet irure esse" + } + }, "billing": { "address": { "line1": "1467", diff --git a/postman/collection-dir/zen/Flow Testcases/Happy Cases/Scenario2-Create payment with confirm false/Payments - Confirm/request.json b/postman/collection-dir/zen/Flow Testcases/Happy Cases/Scenario2-Create payment with confirm false/Payments - Confirm/request.json index 778f8872687..2f295eba3a8 100644 --- a/postman/collection-dir/zen/Flow Testcases/Happy Cases/Scenario2-Create payment with confirm false/Payments - Confirm/request.json +++ b/postman/collection-dir/zen/Flow Testcases/Happy Cases/Scenario2-Create payment with confirm false/Payments - Confirm/request.json @@ -51,6 +51,14 @@ "java_script_enabled": true, "ip_address": "127.0.0.1" }, + "customer_acceptance": { + "acceptance_type": "offline", + "accepted_at": "1963-05-03T04:07:52.723Z", + "online": { + "ip_address": "127.0.0.1", + "user_agent": "amet irure esse" + } + }, "order_details": [ { "amount": 6540, @@ -60,6 +68,7 @@ ] } }, + "url": { "raw": "{{baseUrl}}/payments/:id/confirm", "host": ["{{baseUrl}}"], diff --git a/postman/collection-dir/zen/Flow Testcases/Happy Cases/Scenario3-Create payment without PMD/Payments - Create/request.json b/postman/collection-dir/zen/Flow Testcases/Happy Cases/Scenario3-Create payment without PMD/Payments - Create/request.json index a6aef6ecb71..042a4bc1f73 100644 --- a/postman/collection-dir/zen/Flow Testcases/Happy Cases/Scenario3-Create payment without PMD/Payments - Create/request.json +++ b/postman/collection-dir/zen/Flow Testcases/Happy Cases/Scenario3-Create payment without PMD/Payments - Create/request.json @@ -32,6 +32,14 @@ "authentication_type": "no_three_ds", "return_url": "https://duck.com", "setup_future_usage": "on_session", + "customer_acceptance": { + "acceptance_type": "offline", + "accepted_at": "1963-05-03T04:07:52.723Z", + "online": { + "ip_address": "127.0.0.1", + "user_agent": "amet irure esse" + } + }, "billing": { "address": { "line1": "1467", diff --git a/postman/collection-dir/zen/Flow Testcases/Happy Cases/Scenario4-Create 3DS payment/Payments - Create/request.json b/postman/collection-dir/zen/Flow Testcases/Happy Cases/Scenario4-Create 3DS payment/Payments - Create/request.json index ee354325323..bed15211eea 100644 --- a/postman/collection-dir/zen/Flow Testcases/Happy Cases/Scenario4-Create 3DS payment/Payments - Create/request.json +++ b/postman/collection-dir/zen/Flow Testcases/Happy Cases/Scenario4-Create 3DS payment/Payments - Create/request.json @@ -32,6 +32,14 @@ "authentication_type": "no_three_ds", "return_url": "https://duck.com", "setup_future_usage": "off_session", + "customer_acceptance": { + "acceptance_type": "offline", + "accepted_at": "1963-05-03T04:07:52.723Z", + "online": { + "ip_address": "127.0.0.1", + "user_agent": "amet irure esse" + } + }, "order_details": [ { "amount": 6540, diff --git a/postman/collection-dir/zen/Flow Testcases/Happy Cases/Scenario5-Create 3DS payment with confrm false/Payments - Create/request.json b/postman/collection-dir/zen/Flow Testcases/Happy Cases/Scenario5-Create 3DS payment with confrm false/Payments - Create/request.json index 01fa4013653..91a932b12d9 100644 --- a/postman/collection-dir/zen/Flow Testcases/Happy Cases/Scenario5-Create 3DS payment with confrm false/Payments - Create/request.json +++ b/postman/collection-dir/zen/Flow Testcases/Happy Cases/Scenario5-Create 3DS payment with confrm false/Payments - Create/request.json @@ -32,6 +32,14 @@ "authentication_type": "no_three_ds", "return_url": "https://duck.com", "setup_future_usage": "on_session", + "customer_acceptance": { + "acceptance_type": "offline", + "accepted_at": "1963-05-03T04:07:52.723Z", + "online": { + "ip_address": "127.0.0.1", + "user_agent": "amet irure esse" + } + }, "billing": { "address": { "line1": "1467", diff --git a/postman/collection-dir/zen/Flow Testcases/QuickStart/Payments - Create/request.json b/postman/collection-dir/zen/Flow Testcases/QuickStart/Payments - Create/request.json index ee354325323..aa51751ae1e 100644 --- a/postman/collection-dir/zen/Flow Testcases/QuickStart/Payments - Create/request.json +++ b/postman/collection-dir/zen/Flow Testcases/QuickStart/Payments - Create/request.json @@ -31,7 +31,15 @@ "description": "Its my first payment request", "authentication_type": "no_three_ds", "return_url": "https://duck.com", - "setup_future_usage": "off_session", + "setup_future_usage": "on_session", + "customer_acceptance": { + "acceptance_type": "offline", + "accepted_at": "1963-05-03T04:07:52.723Z", + "online": { + "ip_address": "127.0.0.1", + "user_agent": "amet irure esse" + } + }, "order_details": [ { "amount": 6540, diff --git a/postman/collection-dir/zen/Flow Testcases/Variation Cases/Scenario2-Confirming the payment without PMD/Payments - Create/request.json b/postman/collection-dir/zen/Flow Testcases/Variation Cases/Scenario2-Confirming the payment without PMD/Payments - Create/request.json index a6aef6ecb71..042a4bc1f73 100644 --- a/postman/collection-dir/zen/Flow Testcases/Variation Cases/Scenario2-Confirming the payment without PMD/Payments - Create/request.json +++ b/postman/collection-dir/zen/Flow Testcases/Variation Cases/Scenario2-Confirming the payment without PMD/Payments - Create/request.json @@ -32,6 +32,14 @@ "authentication_type": "no_three_ds", "return_url": "https://duck.com", "setup_future_usage": "on_session", + "customer_acceptance": { + "acceptance_type": "offline", + "accepted_at": "1963-05-03T04:07:52.723Z", + "online": { + "ip_address": "127.0.0.1", + "user_agent": "amet irure esse" + } + }, "billing": { "address": { "line1": "1467",
2024-02-29T07:39:24Z
## Type of Change <!-- Put an `x` in the boxes that apply --> - [ ] Bugfix - [x] New feature - [ ] Enhancement - [ ] Refactoring - [ ] Dependency updates - [ ] Documentation - [ ] CI/CD ## Description store customer_acceptance in the payment_methods table and some changes to setup_future_usage - setup_future_usage should be inferred from the create and if passed in confirm should override the one in create - If customer_acceptance is passed then only the card will be saved on hyper switch's end ### 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? -make a on_session payment without customer_acceptance, card will not be saved -> Create ``` curl --location 'http://localhost:8080/payments' \ --header 'Content-Type: application/json' \ --header 'Accept: application/json' \ --header 'api-key: dev_O7Znp5PhvGpSeE22Hxn4K8snHW6ObRfbA8R1isvLhUXpJRGHOINvlGufM4mGDAqj' \ --data-raw ' {"amount": 6677, "currency": "USD", "confirm": false, "capture_method": "automatic", "authentication_type": "no_three_ds", "customer_id": "97cc", "email": "something@gmail.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" } }, "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" } }, "metadata": { "order_details": { "product_name": "Apple iphone 15", "quantity": 1 } }, "business_country": "US", "business_label": "default", "setup_future_usage": "on_session" }' ``` -> Confirm ``` curl --location 'http://localhost:8080/payments/pay_IHI92Rlo3i6kwihECXVr/confirm' \ --header 'Content-Type: application/json' \ --header 'Accept: application/json' \ --header 'api-key: dev_O7Znp5PhvGpSeE22Hxn4K8snHW6ObRfbA8R1isvLhUXpJRGHOINvlGufM4mGDAqj' \ --data '{ "confirm": true, "payment_type": "normal", "payment_method": "card", "payment_method_type": "debit", "payment_method_data": { "card": { "card_number":"4242424242424242", "card_exp_month": "11", "card_exp_year": "2040", "card_holder_name": "AKA", "card_cvc": "123", "nick_name": "HELO" } } }' ``` ![Screenshot 2024-03-05 at 1 47 56 PM](https://github.com/juspay/hyperswitch/assets/55580080/334f668c-fcd2-4b89-b31b-a5992865f1f4) -make a off_session payment without mandate_type ,i.e., MIT with customer_acceptance, the card will be saved on our end -> Create ``` curl --location 'http://localhost:8080/payments' \ --header 'Content-Type: application/json' \ --header 'Accept: application/json' \ --header 'api-key: dev_O7Znp5PhvGpSeE22Hxn4K8snHW6ObRfbA8R1isvLhUXpJRGHOINvlGufM4mGDAqj' \ --data-raw ' {"amount":0, "currency": "USD", "confirm": false, "capture_method": "automatic", "authentication_type": "no_three_ds", "customer_id": "q7cc", "email": "something@gmail.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" } }, "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" } }, "metadata": { "order_details": { "product_name": "Apple iphone 15", "quantity": 1 } }, "business_country": "US", "business_label": "default", "setup_future_usage": "off_session" }' ``` -> Confirm ``` curl --location 'http://localhost:8080/payments/pay_IHI92Rlo3i6kwihECXVr/confirm' \ --header 'Content-Type: application/json' \ --header 'Accept: application/json' \ --header 'api-key: dev_O7Znp5PhvGpSeE22Hxn4K8snHW6ObRfbA8R1isvLhUXpJRGHOINvlGufM4mGDAqj' \ --data '{ "confirm": true, "payment_type": "setup_mandate", "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_type": "debit", "payment_method_data": { "card": { "card_number":"4242424242424242", "card_exp_month": "11", "card_exp_year": "2040", "card_holder_name": "AKA", "card_cvc": "123", "nick_name": "HELO" } } }' ``` ![Screenshot 2024-03-05 at 1 45 30 PM](https://github.com/juspay/hyperswitch/assets/55580080/b7826fc2-08c7-4d82-84c8-f5bee65c7fef) <img width="1720" alt="Screenshot 2024-03-05 at 1 46 40 PM" src="https://github.com/juspay/hyperswitch/assets/55580080/ab269405-fa54-45d9-a1a3-f9135d94f839"> -to save the card both, customer_acceptance and setup_future_usage must be passed - if its a mandate_payment , we can have off_session in create with mandate type and customer_acceptance in confirm and also we can have customer_acceptance inside the mandate_data field which is for backwards compatibility currently there in mandate_data ## 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 - [ ] I added a [CHANGELOG](/CHANGELOG.md) entry if applicable
5eff9d47d3e53d380ef792a8fbdf06ecf78d3d16
-make a on_session payment without customer_acceptance, card will not be saved -> Create ``` curl --location 'http://localhost:8080/payments' \ --header 'Content-Type: application/json' \ --header 'Accept: application/json' \ --header 'api-key: dev_O7Znp5PhvGpSeE22Hxn4K8snHW6ObRfbA8R1isvLhUXpJRGHOINvlGufM4mGDAqj' \ --data-raw ' {"amount": 6677, "currency": "USD", "confirm": false, "capture_method": "automatic", "authentication_type": "no_three_ds", "customer_id": "97cc", "email": "something@gmail.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" } }, "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" } }, "metadata": { "order_details": { "product_name": "Apple iphone 15", "quantity": 1 } }, "business_country": "US", "business_label": "default", "setup_future_usage": "on_session" }' ``` -> Confirm ``` curl --location 'http://localhost:8080/payments/pay_IHI92Rlo3i6kwihECXVr/confirm' \ --header 'Content-Type: application/json' \ --header 'Accept: application/json' \ --header 'api-key: dev_O7Znp5PhvGpSeE22Hxn4K8snHW6ObRfbA8R1isvLhUXpJRGHOINvlGufM4mGDAqj' \ --data '{ "confirm": true, "payment_type": "normal", "payment_method": "card", "payment_method_type": "debit", "payment_method_data": { "card": { "card_number":"4242424242424242", "card_exp_month": "11", "card_exp_year": "2040", "card_holder_name": "AKA", "card_cvc": "123", "nick_name": "HELO" } } }' ``` ![Screenshot 2024-03-05 at 1 47 56 PM](https://github.com/juspay/hyperswitch/assets/55580080/334f668c-fcd2-4b89-b31b-a5992865f1f4) -make a off_session payment without mandate_type ,i.e., MIT with customer_acceptance, the card will be saved on our end -> Create ``` curl --location 'http://localhost:8080/payments' \ --header 'Content-Type: application/json' \ --header 'Accept: application/json' \ --header 'api-key: dev_O7Znp5PhvGpSeE22Hxn4K8snHW6ObRfbA8R1isvLhUXpJRGHOINvlGufM4mGDAqj' \ --data-raw ' {"amount":0, "currency": "USD", "confirm": false, "capture_method": "automatic", "authentication_type": "no_three_ds", "customer_id": "q7cc", "email": "something@gmail.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" } }, "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" } }, "metadata": { "order_details": { "product_name": "Apple iphone 15", "quantity": 1 } }, "business_country": "US", "business_label": "default", "setup_future_usage": "off_session" }' ``` -> Confirm ``` curl --location 'http://localhost:8080/payments/pay_IHI92Rlo3i6kwihECXVr/confirm' \ --header 'Content-Type: application/json' \ --header 'Accept: application/json' \ --header 'api-key: dev_O7Znp5PhvGpSeE22Hxn4K8snHW6ObRfbA8R1isvLhUXpJRGHOINvlGufM4mGDAqj' \ --data '{ "confirm": true, "payment_type": "setup_mandate", "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_type": "debit", "payment_method_data": { "card": { "card_number":"4242424242424242", "card_exp_month": "11", "card_exp_year": "2040", "card_holder_name": "AKA", "card_cvc": "123", "nick_name": "HELO" } } }' ``` ![Screenshot 2024-03-05 at 1 45 30 PM](https://github.com/juspay/hyperswitch/assets/55580080/b7826fc2-08c7-4d82-84c8-f5bee65c7fef) <img width="1720" alt="Screenshot 2024-03-05 at 1 46 40 PM" src="https://github.com/juspay/hyperswitch/assets/55580080/ab269405-fa54-45d9-a1a3-f9135d94f839"> -to save the card both, customer_acceptance and setup_future_usage must be passed - if its a mandate_payment , we can have off_session in create with mandate type and customer_acceptance in confirm and also we can have customer_acceptance inside the mandate_data field which is for backwards compatibility currently there in mandate_data
juspay/hyperswitch
juspay__hyperswitch-3729
Bug: refactor: remove permissions from files and forex apis
diff --git a/crates/api_models/src/user_role.rs b/crates/api_models/src/user_role.rs index 78df1d6823e..215227b91a3 100644 --- a/crates/api_models/src/user_role.rs +++ b/crates/api_models/src/user_role.rs @@ -29,7 +29,6 @@ pub enum Permission { MerchantAccountWrite, MerchantConnectorAccountRead, MerchantConnectorAccountWrite, - ForexRead, RoutingRead, RoutingWrite, DisputeRead, @@ -38,8 +37,6 @@ pub enum Permission { MandateWrite, CustomerRead, CustomerWrite, - FileRead, - FileWrite, Analytics, ThreeDsDecisionManagerWrite, ThreeDsDecisionManagerRead, @@ -55,14 +52,12 @@ pub enum PermissionModule { Payments, Refunds, MerchantAccount, - Forex, Connectors, Routing, Analytics, Mandates, Customer, Disputes, - Files, ThreeDsDecisionManager, SurchargeDecisionManager, AccountCreate, diff --git a/crates/common_enums/src/enums.rs b/crates/common_enums/src/enums.rs index 82569579cfc..b8168fc5329 100644 --- a/crates/common_enums/src/enums.rs +++ b/crates/common_enums/src/enums.rs @@ -2167,3 +2167,51 @@ pub enum ConnectorStatus { Inactive, Active, } + +#[derive( + Clone, + Copy, + Debug, + Eq, + PartialEq, + serde::Deserialize, + serde::Serialize, + strum::Display, + strum::EnumString, +)] +#[router_derive::diesel_enum(storage_type = "db_enum")] +#[serde(rename_all = "snake_case")] +#[strum(serialize_all = "snake_case")] +pub enum RoleScope { + Merchant, + Organization, +} + +#[derive( + Clone, + Copy, + Debug, + Eq, + PartialEq, + serde::Serialize, + serde::Deserialize, + strum::Display, + strum::EnumString, +)] +#[router_derive::diesel_enum(storage_type = "text")] +#[serde(rename_all = "snake_case")] +#[strum(serialize_all = "snake_case")] +pub enum PermissionGroup { + OperationsView, + OperationsManage, + ConnectorsView, + ConnectorsManage, + WorkflowsView, + WorkflowsManage, + AnalyticsView, + UsersView, + UsersManage, + MerchantDetailsView, + MerchantDetailsManage, + OrganizationManage, +} diff --git a/crates/diesel_models/src/enums.rs b/crates/diesel_models/src/enums.rs index 4ca5b4c986c..3ee7e811873 100644 --- a/crates/diesel_models/src/enums.rs +++ b/crates/diesel_models/src/enums.rs @@ -501,53 +501,3 @@ pub enum DashboardMetadata { IsMultipleConfiguration, IsChangePasswordRequired, } - -#[derive( - Clone, - Copy, - Debug, - Eq, - PartialEq, - serde::Deserialize, - serde::Serialize, - strum::Display, - strum::EnumString, - frunk::LabelledGeneric, -)] -#[diesel_enum(storage_type = "db_enum")] -#[serde(rename_all = "snake_case")] -#[strum(serialize_all = "snake_case")] -pub enum RoleScope { - Merchant, - Organization, -} - -#[derive( - Clone, - Copy, - Debug, - Eq, - PartialEq, - serde::Serialize, - serde::Deserialize, - strum::Display, - strum::EnumString, - frunk::LabelledGeneric, -)] -#[diesel_enum(storage_type = "text")] -#[serde(rename_all = "snake_case")] -#[strum(serialize_all = "snake_case")] -pub enum PermissionGroup { - OperationsView, - OperationsManage, - ConnectorsView, - ConnectorsManage, - WorkflowsView, - WorkflowsManage, - AnalyticsView, - UsersView, - UsersManage, - MerchantDetailsView, - MerchantDetailsManage, - OrganizationManage, -} diff --git a/crates/diesel_models/src/query/role.rs b/crates/diesel_models/src/query/role.rs index b8704aebbd0..a54576cc91b 100644 --- a/crates/diesel_models/src/query/role.rs +++ b/crates/diesel_models/src/query/role.rs @@ -21,6 +21,23 @@ impl Role { .await } + pub async fn find_by_role_id_in_merchant_scope( + conn: &PgPooledConn, + role_id: &str, + merchant_id: &str, + org_id: &str, + ) -> StorageResult<Self> { + generics::generic_find_one::<<Self as HasTable>::Table, _, _>( + conn, + dsl::role_id.eq(role_id.to_owned()).and( + dsl::merchant_id.eq(merchant_id.to_owned()).or(dsl::org_id + .eq(org_id.to_owned()) + .and(dsl::scope.eq(RoleScope::Organization))), + ), + ) + .await + } + pub async fn update_by_role_id( conn: &PgPooledConn, role_id: &str, diff --git a/crates/router/src/core/user.rs b/crates/router/src/core/user.rs index 54fbecc64f3..e7639af3918 100644 --- a/crates/router/src/core/user.rs +++ b/crates/router/src/core/user.rs @@ -617,9 +617,9 @@ async fn handle_invitation( user_from_token: &auth::UserFromToken, request: &user_api::InviteUserRequest, ) -> UserResult<InviteMultipleUserResponse> { - let inviter_user = user_from_token.get_user(state).await?; + let inviter_user = user_from_token.get_user_from_db(state).await?; - if inviter_user.email == request.email { + if inviter_user.get_email() == request.email { return Err(UserErrors::InvalidRoleOperationWithMessage( "User Inviting themselves".to_string(), ) @@ -926,7 +926,7 @@ pub async fn switch_merchant_id( .filter(|role| role.status == UserStatus::Active) .collect::<Vec<_>>(); - let user = user_from_token.get_user(&state).await?.into(); + let user = user_from_token.get_user_from_db(&state).await?; let (token, role_id) = if utils::user_role::is_internal_role(&user_from_token.role_id) { let key_store = state @@ -995,7 +995,7 @@ pub async fn create_merchant_account( user_from_token: auth::UserFromToken, req: user_api::UserMerchantCreate, ) -> UserResponse<()> { - let user_from_db: domain::UserFromStorage = user_from_token.get_user(&state).await?.into(); + let user_from_db = user_from_token.get_user_from_db(&state).await?; let new_user = domain::NewUser::try_from((user_from_db, req, user_from_token))?; let new_merchant = new_user.get_new_merchant(); diff --git a/crates/router/src/core/user/dashboard_metadata.rs b/crates/router/src/core/user/dashboard_metadata.rs index 7318f9973f1..3f6180158a5 100644 --- a/crates/router/src/core/user/dashboard_metadata.rs +++ b/crates/router/src/core/user/dashboard_metadata.rs @@ -459,8 +459,8 @@ async fn insert_metadata( #[cfg(feature = "email")] { - let user_data = user.get_user(state).await?; - let user_email = domain::UserEmail::from_pii_email(user_data.email.clone()) + let user_data = user.get_user_from_db(state).await?; + let user_email = domain::UserEmail::from_pii_email(user_data.get_email()) .change_context(UserErrors::InternalServerError)? .get_secret() .expose(); diff --git a/crates/router/src/core/user_role.rs b/crates/router/src/core/user_role.rs index 14be9bb6991..16047bc3eb7 100644 --- a/crates/router/src/core/user_role.rs +++ b/crates/router/src/core/user_role.rs @@ -172,7 +172,7 @@ pub async fn transfer_org_ownership( 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?; - let user_from_db = domain::UserFromStorage::from(user_from_token.get_user(&state).await?); + 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 diff --git a/crates/router/src/db/kafka_store.rs b/crates/router/src/db/kafka_store.rs index 0897deb87e5..213417b1318 100644 --- a/crates/router/src/db/kafka_store.rs +++ b/crates/router/src/db/kafka_store.rs @@ -2274,6 +2274,17 @@ impl RoleInterface for KafkaStore { self.diesel_store.find_role_by_role_id(role_id).await } + async fn find_role_by_role_id_in_merchant_scope( + &self, + role_id: &str, + merchant_id: &str, + org_id: &str, + ) -> CustomResult<storage::Role, errors::StorageError> { + self.diesel_store + .find_role_by_role_id_in_merchant_scope(role_id, merchant_id, org_id) + .await + } + async fn update_role_by_role_id( &self, role_id: &str, diff --git a/crates/router/src/db/role.rs b/crates/router/src/db/role.rs index da2abf15ff7..90e1e97e377 100644 --- a/crates/router/src/db/role.rs +++ b/crates/router/src/db/role.rs @@ -1,3 +1,4 @@ +use common_enums::enums; use diesel_models::role as storage; use error_stack::{IntoReport, ResultExt}; @@ -20,6 +21,13 @@ pub trait RoleInterface { role_id: &str, ) -> CustomResult<storage::Role, errors::StorageError>; + async fn find_role_by_role_id_in_merchant_scope( + &self, + role_id: &str, + merchant_id: &str, + org_id: &str, + ) -> CustomResult<storage::Role, errors::StorageError>; + async fn update_role_by_role_id( &self, role_id: &str, @@ -59,6 +67,19 @@ impl RoleInterface for Store { .into_report() } + async fn find_role_by_role_id_in_merchant_scope( + &self, + role_id: &str, + merchant_id: &str, + org_id: &str, + ) -> CustomResult<storage::Role, errors::StorageError> { + let conn = connection::pg_connection_write(self).await?; + storage::Role::find_by_role_id_in_merchant_scope(&conn, role_id, merchant_id, org_id) + .await + .map_err(Into::into) + .into_report() + } + async fn update_role_by_role_id( &self, role_id: &str, @@ -149,6 +170,30 @@ impl RoleInterface for MockDb { ) } + async fn find_role_by_role_id_in_merchant_scope( + &self, + role_id: &str, + merchant_id: &str, + org_id: &str, + ) -> CustomResult<storage::Role, errors::StorageError> { + let roles = self.roles.lock().await; + roles + .iter() + .find(|role| { + role.role_id == role_id + && (role.merchant_id == merchant_id + || (role.org_id == org_id && role.scope == enums::RoleScope::Organization)) + }) + .cloned() + .ok_or( + errors::StorageError::ValueNotFound(format!( + "No role available in merchant scope for role_id = {role_id}, \ + merchant_id = {merchant_id} and org_id = {org_id}" + )) + .into(), + ) + } + async fn update_role_by_role_id( &self, role_id: &str, diff --git a/crates/router/src/routes/currency.rs b/crates/router/src/routes/currency.rs index 1e185851717..74a559e88e9 100644 --- a/crates/router/src/routes/currency.rs +++ b/crates/router/src/routes/currency.rs @@ -4,7 +4,7 @@ use router_env::Flow; use crate::{ core::{api_locking, currency}, routes::AppState, - services::{api, authentication as auth, authorization::permissions::Permission}, + services::{api, authentication as auth}, }; pub async fn retrieve_forex(state: web::Data<AppState>, req: HttpRequest) -> HttpResponse { @@ -17,7 +17,7 @@ pub async fn retrieve_forex(state: web::Data<AppState>, req: HttpRequest) -> Htt |state, _auth: auth::AuthenticationData, _| currency::retrieve_forex(state), auth::auth_type( &auth::ApiKeyAuth, - &auth::JWTAuth(Permission::ForexRead), + &auth::DashboardNoPermissionAuth, req.headers(), ), api_locking::LockAction::NotApplicable, @@ -49,7 +49,7 @@ pub async fn convert_forex( }, auth::auth_type( &auth::ApiKeyAuth, - &auth::JWTAuth(Permission::ForexRead), + &auth::DashboardNoPermissionAuth, req.headers(), ), api_locking::LockAction::NotApplicable, diff --git a/crates/router/src/routes/files.rs b/crates/router/src/routes/files.rs index 95f4007cb91..63dfb38c614 100644 --- a/crates/router/src/routes/files.rs +++ b/crates/router/src/routes/files.rs @@ -2,7 +2,7 @@ use actix_multipart::Multipart; use actix_web::{web, HttpRequest, HttpResponse}; use router_env::{instrument, tracing, Flow}; -use crate::{core::api_locking, services::authorization::permissions::Permission}; +use crate::core::api_locking; pub mod transformers; use super::app::AppState; @@ -47,7 +47,7 @@ pub async fn files_create( |state, auth, req| files_create_core(state, auth.merchant_account, auth.key_store, req), auth::auth_type( &auth::ApiKeyAuth, - &auth::JWTAuth(Permission::FileWrite), + &auth::DashboardNoPermissionAuth, req.headers(), ), api_locking::LockAction::NotApplicable, @@ -89,7 +89,7 @@ pub async fn files_delete( |state, auth, req| files_delete_core(state, auth.merchant_account, req), auth::auth_type( &auth::ApiKeyAuth, - &auth::JWTAuth(Permission::FileWrite), + &auth::DashboardNoPermissionAuth, req.headers(), ), api_locking::LockAction::NotApplicable, @@ -131,7 +131,7 @@ pub async fn files_retrieve( |state, auth, req| files_retrieve_core(state, auth.merchant_account, auth.key_store, req), auth::auth_type( &auth::ApiKeyAuth, - &auth::JWTAuth(Permission::FileRead), + &auth::DashboardNoPermissionAuth, req.headers(), ), api_locking::LockAction::NotApplicable, diff --git a/crates/router/src/services/authentication.rs b/crates/router/src/services/authentication.rs index 990e0785306..1004982d292 100644 --- a/crates/router/src/services/authentication.rs +++ b/crates/router/src/services/authentication.rs @@ -749,6 +749,48 @@ where } } +#[async_trait] +impl<A> AuthenticateAndFetch<AuthenticationData, A> for DashboardNoPermissionAuth +where + A: AppStateInfo + 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?; + + let key_store = state + .store() + .get_merchant_key_store_by_merchant_id( + &payload.merchant_id, + &state.store().get_master_key().to_vec().into(), + ) + .await + .change_context(errors::ApiErrorResponse::Unauthorized) + .attach_printable("Failed to fetch merchant key store for the merchant id")?; + + let merchant = state + .store() + .find_merchant_account_by_merchant_id(&payload.merchant_id, &key_store) + .await + .to_not_found_response(errors::ApiErrorResponse::Unauthorized)?; + + let auth = AuthenticationData { + merchant_account: merchant, + key_store, + }; + Ok(( + auth.clone(), + AuthenticationType::MerchantJwt { + merchant_id: auth.merchant_account.merchant_id.clone(), + user_id: Some(payload.user_id), + }, + )) + } +} + pub trait ClientSecretFetch { fn get_client_secret(&self) -> Option<&String>; } diff --git a/crates/router/src/services/authorization/info.rs b/crates/router/src/services/authorization/info.rs index 450a5a738c3..d982317e023 100644 --- a/crates/router/src/services/authorization/info.rs +++ b/crates/router/src/services/authorization/info.rs @@ -31,13 +31,11 @@ pub enum PermissionModule { Refunds, MerchantAccount, Connectors, - Forex, Routing, Analytics, Mandates, Customer, Disputes, - Files, ThreeDsDecisionManager, SurchargeDecisionManager, AccountCreate, @@ -51,12 +49,10 @@ impl PermissionModule { Self::MerchantAccount => "Accounts module permissions allow the user to view and update account details, configure webhooks and much more", Self::Connectors => "All connector related actions - like configuring new connectors, viewing and updating connector configuration lies with this module", Self::Routing => "All actions related to new, active, and past routing stacks take place here", - Self::Forex => "Forex module permissions allow the user to view and query the forex rates", Self::Analytics => "Permission to view and analyse the data relating to payments, refunds, sdk etc.", Self::Mandates => "Everything related to mandates - like creating and viewing mandate related information are within this module", Self::Customer => "Everything related to customers - like creating and viewing customer related information are within this module", Self::Disputes => "Everything related to disputes - like creating and viewing dispute related information are within this module", - Self::Files => "Permissions for uploading, deleting and viewing files for disputes", Self::ThreeDsDecisionManager => "View and configure 3DS decision rules configured for a merchant", Self::SurchargeDecisionManager =>"View and configure surcharge decision rules configured for a merchant", Self::AccountCreate => "Create new account within your organization" @@ -108,11 +104,6 @@ impl ModuleInfo { Permission::MerchantConnectorAccountWrite, ]), }, - PermissionModule::Forex => Self { - module: module_name, - description, - permissions: PermissionInfo::new(&[Permission::ForexRead]), - }, PermissionModule::Routing => Self { module: module_name, description, @@ -150,11 +141,6 @@ impl ModuleInfo { Permission::DisputeWrite, ]), }, - PermissionModule::Files => Self { - module: module_name, - description, - permissions: PermissionInfo::new(&[Permission::FileRead, Permission::FileWrite]), - }, PermissionModule::ThreeDsDecisionManager => Self { module: module_name, description, diff --git a/crates/router/src/services/authorization/permissions.rs b/crates/router/src/services/authorization/permissions.rs index 5c5e3ecce30..3e022e8f666 100644 --- a/crates/router/src/services/authorization/permissions.rs +++ b/crates/router/src/services/authorization/permissions.rs @@ -12,7 +12,6 @@ pub enum Permission { MerchantAccountWrite, MerchantConnectorAccountRead, MerchantConnectorAccountWrite, - ForexRead, RoutingRead, RoutingWrite, DisputeRead, @@ -21,8 +20,6 @@ pub enum Permission { MandateWrite, CustomerRead, CustomerWrite, - FileRead, - FileWrite, Analytics, ThreeDsDecisionManagerWrite, ThreeDsDecisionManagerRead, @@ -50,7 +47,6 @@ impl Permission { Self::MerchantConnectorAccountWrite => { "Create, update, verify and delete connector configurations" } - Self::ForexRead => "Query Forex data", Self::RoutingRead => "View routing configuration", Self::RoutingWrite => "Create and activate routing configurations", Self::DisputeRead => "View disputes", @@ -59,8 +55,6 @@ impl Permission { Self::MandateWrite => "Create and update mandates", Self::CustomerRead => "View customers", Self::CustomerWrite => "Create, update and delete customers", - Self::FileRead => "View files", - Self::FileWrite => "Create, update and delete files", Self::Analytics => "Access to analytics module", Self::ThreeDsDecisionManagerWrite => "Create and update 3DS decision rules", Self::ThreeDsDecisionManagerRead => { diff --git a/crates/router/src/services/authorization/predefined_permissions.rs b/crates/router/src/services/authorization/predefined_permissions.rs index fd98d90c191..bd0f37e2a0d 100644 --- a/crates/router/src/services/authorization/predefined_permissions.rs +++ b/crates/router/src/services/authorization/predefined_permissions.rs @@ -50,7 +50,6 @@ pub static PREDEFINED_PERMISSIONS: Lazy<HashMap<&'static str, RoleInfo>> = Lazy: Permission::MerchantConnectorAccountWrite, Permission::RoutingRead, Permission::RoutingWrite, - Permission::ForexRead, Permission::ThreeDsDecisionManagerWrite, Permission::ThreeDsDecisionManagerRead, Permission::SurchargeDecisionManagerWrite, @@ -61,8 +60,6 @@ pub static PREDEFINED_PERMISSIONS: Lazy<HashMap<&'static str, RoleInfo>> = Lazy: Permission::MandateWrite, Permission::CustomerRead, Permission::CustomerWrite, - Permission::FileRead, - Permission::FileWrite, Permission::Analytics, Permission::UsersRead, Permission::UsersWrite, @@ -84,14 +81,12 @@ pub static PREDEFINED_PERMISSIONS: Lazy<HashMap<&'static str, RoleInfo>> = Lazy: Permission::MerchantAccountRead, Permission::MerchantConnectorAccountRead, Permission::RoutingRead, - Permission::ForexRead, Permission::ThreeDsDecisionManagerRead, Permission::SurchargeDecisionManagerRead, Permission::Analytics, Permission::DisputeRead, Permission::MandateRead, Permission::CustomerRead, - Permission::FileRead, Permission::UsersRead, ], name: None, @@ -117,7 +112,6 @@ pub static PREDEFINED_PERMISSIONS: Lazy<HashMap<&'static str, RoleInfo>> = Lazy: Permission::MerchantConnectorAccountWrite, Permission::RoutingRead, Permission::RoutingWrite, - Permission::ForexRead, Permission::ThreeDsDecisionManagerWrite, Permission::ThreeDsDecisionManagerRead, Permission::SurchargeDecisionManagerWrite, @@ -128,8 +122,6 @@ pub static PREDEFINED_PERMISSIONS: Lazy<HashMap<&'static str, RoleInfo>> = Lazy: Permission::MandateWrite, Permission::CustomerRead, Permission::CustomerWrite, - Permission::FileRead, - Permission::FileWrite, Permission::Analytics, Permission::UsersRead, Permission::UsersWrite, @@ -156,7 +148,6 @@ pub static PREDEFINED_PERMISSIONS: Lazy<HashMap<&'static str, RoleInfo>> = Lazy: Permission::MerchantAccountRead, Permission::MerchantAccountWrite, Permission::MerchantConnectorAccountRead, - Permission::ForexRead, Permission::MerchantConnectorAccountWrite, Permission::RoutingRead, Permission::RoutingWrite, @@ -170,8 +161,6 @@ pub static PREDEFINED_PERMISSIONS: Lazy<HashMap<&'static str, RoleInfo>> = Lazy: Permission::MandateWrite, Permission::CustomerRead, Permission::CustomerWrite, - Permission::FileRead, - Permission::FileWrite, Permission::Analytics, Permission::UsersRead, Permission::UsersWrite, @@ -190,7 +179,6 @@ pub static PREDEFINED_PERMISSIONS: Lazy<HashMap<&'static str, RoleInfo>> = Lazy: Permission::RefundRead, Permission::ApiKeyRead, Permission::MerchantAccountRead, - Permission::ForexRead, Permission::MerchantConnectorAccountRead, Permission::RoutingRead, Permission::ThreeDsDecisionManagerRead, @@ -198,7 +186,6 @@ pub static PREDEFINED_PERMISSIONS: Lazy<HashMap<&'static str, RoleInfo>> = Lazy: Permission::DisputeRead, Permission::MandateRead, Permission::CustomerRead, - Permission::FileRead, Permission::Analytics, Permission::UsersRead, ], @@ -216,7 +203,6 @@ pub static PREDEFINED_PERMISSIONS: Lazy<HashMap<&'static str, RoleInfo>> = Lazy: Permission::RefundRead, Permission::ApiKeyRead, Permission::MerchantAccountRead, - Permission::ForexRead, Permission::MerchantConnectorAccountRead, Permission::RoutingRead, Permission::ThreeDsDecisionManagerRead, @@ -224,7 +210,6 @@ pub static PREDEFINED_PERMISSIONS: Lazy<HashMap<&'static str, RoleInfo>> = Lazy: Permission::DisputeRead, Permission::MandateRead, Permission::CustomerRead, - Permission::FileRead, Permission::Analytics, Permission::UsersRead, Permission::UsersWrite, @@ -244,7 +229,6 @@ pub static PREDEFINED_PERMISSIONS: Lazy<HashMap<&'static str, RoleInfo>> = Lazy: Permission::ApiKeyRead, Permission::ApiKeyWrite, Permission::MerchantAccountRead, - Permission::ForexRead, Permission::MerchantConnectorAccountRead, Permission::RoutingRead, Permission::ThreeDsDecisionManagerRead, @@ -252,7 +236,6 @@ pub static PREDEFINED_PERMISSIONS: Lazy<HashMap<&'static str, RoleInfo>> = Lazy: Permission::DisputeRead, Permission::MandateRead, Permission::CustomerRead, - Permission::FileRead, Permission::Analytics, Permission::UsersRead, ], @@ -272,7 +255,6 @@ pub static PREDEFINED_PERMISSIONS: Lazy<HashMap<&'static str, RoleInfo>> = Lazy: Permission::RefundWrite, Permission::ApiKeyRead, Permission::MerchantAccountRead, - Permission::ForexRead, Permission::MerchantConnectorAccountRead, Permission::MerchantConnectorAccountWrite, Permission::RoutingRead, @@ -284,7 +266,6 @@ pub static PREDEFINED_PERMISSIONS: Lazy<HashMap<&'static str, RoleInfo>> = Lazy: Permission::DisputeRead, Permission::MandateRead, Permission::CustomerRead, - Permission::FileRead, Permission::Analytics, Permission::UsersRead, ], @@ -301,15 +282,12 @@ pub static PREDEFINED_PERMISSIONS: Lazy<HashMap<&'static str, RoleInfo>> = Lazy: Permission::PaymentRead, Permission::RefundRead, Permission::RefundWrite, - Permission::ForexRead, Permission::DisputeRead, Permission::DisputeWrite, Permission::MerchantAccountRead, Permission::MerchantConnectorAccountRead, Permission::MandateRead, Permission::CustomerRead, - Permission::FileRead, - Permission::FileWrite, Permission::Analytics, ], name: Some("Customer Support"), diff --git a/crates/router/src/types/domain/user.rs b/crates/router/src/types/domain/user.rs index 468fa8e4cd2..ab32febf9b4 100644 --- a/crates/router/src/types/domain/user.rs +++ b/crates/router/src/types/domain/user.rs @@ -802,14 +802,12 @@ impl From<info::PermissionModule> for user_role_api::PermissionModule { info::PermissionModule::Payments => Self::Payments, info::PermissionModule::Refunds => Self::Refunds, info::PermissionModule::MerchantAccount => Self::MerchantAccount, - info::PermissionModule::Forex => Self::Forex, info::PermissionModule::Connectors => Self::Connectors, info::PermissionModule::Routing => Self::Routing, info::PermissionModule::Analytics => Self::Analytics, info::PermissionModule::Mandates => Self::Mandates, info::PermissionModule::Customer => Self::Customer, info::PermissionModule::Disputes => Self::Disputes, - info::PermissionModule::Files => Self::Files, info::PermissionModule::ThreeDsDecisionManager => Self::ThreeDsDecisionManager, info::PermissionModule::SurchargeDecisionManager => Self::SurchargeDecisionManager, info::PermissionModule::AccountCreate => Self::AccountCreate, diff --git a/crates/router/src/utils/user.rs b/crates/router/src/utils/user.rs index 9c2d2c1fd3f..86b298822ac 100644 --- a/crates/router/src/utils/user.rs +++ b/crates/router/src/utils/user.rs @@ -48,13 +48,13 @@ impl UserFromToken { Ok(merchant_account) } - pub async fn get_user(&self, state: &AppState) -> UserResult<diesel_models::user::User> { + pub async fn get_user_from_db(&self, state: &AppState) -> UserResult<UserFromStorage> { let user = state .store .find_user_by_id(&self.user_id) .await .change_context(UserErrors::InternalServerError)?; - Ok(user) + Ok(user.into()) } } diff --git a/crates/router/src/utils/user_role.rs b/crates/router/src/utils/user_role.rs index 9c7150c08da..b677e89269e 100644 --- a/crates/router/src/utils/user_role.rs +++ b/crates/router/src/utils/user_role.rs @@ -38,7 +38,6 @@ impl From<Permission> for user_role_api::Permission { Permission::MerchantAccountWrite => Self::MerchantAccountWrite, Permission::MerchantConnectorAccountRead => Self::MerchantConnectorAccountRead, Permission::MerchantConnectorAccountWrite => Self::MerchantConnectorAccountWrite, - Permission::ForexRead => Self::ForexRead, Permission::RoutingRead => Self::RoutingRead, Permission::RoutingWrite => Self::RoutingWrite, Permission::DisputeRead => Self::DisputeRead, @@ -47,8 +46,6 @@ impl From<Permission> for user_role_api::Permission { Permission::MandateWrite => Self::MandateWrite, Permission::CustomerRead => Self::CustomerRead, Permission::CustomerWrite => Self::CustomerWrite, - Permission::FileRead => Self::FileRead, - Permission::FileWrite => Self::FileWrite, Permission::Analytics => Self::Analytics, Permission::ThreeDsDecisionManagerWrite => Self::ThreeDsDecisionManagerWrite, Permission::ThreeDsDecisionManagerRead => Self::ThreeDsDecisionManagerRead,
2024-02-20T13:56:27Z
## 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 will remove permissions for Files and Forex apis. It also adds `find_role_by_role_id_in_merchant_scope` db function. ### 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 #3729 ## 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)? --> Postman. - Files - Read (`/files` POST) ``` curl --location 'http://localhost:8080/files' \ --header 'Accept: application/json' \ --header 'Authorization: Bearer {{user_token}}' \ --form 'purpose="dispute_evidence"' \ --form 'file=@"/Users/mani.dchandra/Pictures/sample.pdf"' \ --form 'dispute_id="{{dispute_id}}"' ``` ``` { "file_id": "file_id" } ``` - Files - Delete (`/files/{file_id}` DELETE) ``` curl --location --request DELETE 'http://localhost:8080/files/file_z4giuhfczJqbXwNhazqS' \ --header 'Accept: application/json' \ --header 'Authorization: Bearer {{user_token}}' ``` ``` { "error": { "type": "invalid_request", "message": "Not Supported because provider is not Router", "code": "IR_23" } } ``` Currently deletion will not be possible for dispute evidence. But you can hit this api without the `FileWrite` permission. - Files - Retrieve (`/files/{file_id}` GET) ``` curl --location 'http://localhost:8080/files/file_Uy7bK9lFFaBDXGhivUjo' \ --header 'Accept: application/json' \ --header 'Authorization: Bearer {{user_token}}' ``` This api will return contents of the uploaded files. Above APIs will now work with JWTs with roles which doesn't have `FileRead`/`FileWrite` permissions. - Forex - Rates (`/forex/rates` GET) ``` curl --location 'http://localhost:8080/forex/rates' \ --header 'Accept: application/json' \ --header 'Authorization: Bearer {{user_token}}' ``` - Forex - Convert from minor (`/forex/convert_from_minor` GET) ``` curl --location 'http://localhost:8080/forex/convert_from_minor?amount=100&from_currency=USD&to_currency=INR' \ --header 'Accept: application/json' \ --header 'Authorization: Bearer {{user_token}}' ``` ``` { "converted_amount": "82.89544400", "currency": "INR" } ``` will now work with JWTs with roles which doesn't have `ForexRead` permission. ## 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 - [ ] I added a [CHANGELOG](/CHANGELOG.md) entry if applicable
cf3c66636ffee30cdd4353b276a89a8f9fc2d9d0
Postman. - Files - Read (`/files` POST) ``` curl --location 'http://localhost:8080/files' \ --header 'Accept: application/json' \ --header 'Authorization: Bearer {{user_token}}' \ --form 'purpose="dispute_evidence"' \ --form 'file=@"/Users/mani.dchandra/Pictures/sample.pdf"' \ --form 'dispute_id="{{dispute_id}}"' ``` ``` { "file_id": "file_id" } ``` - Files - Delete (`/files/{file_id}` DELETE) ``` curl --location --request DELETE 'http://localhost:8080/files/file_z4giuhfczJqbXwNhazqS' \ --header 'Accept: application/json' \ --header 'Authorization: Bearer {{user_token}}' ``` ``` { "error": { "type": "invalid_request", "message": "Not Supported because provider is not Router", "code": "IR_23" } } ``` Currently deletion will not be possible for dispute evidence. But you can hit this api without the `FileWrite` permission. - Files - Retrieve (`/files/{file_id}` GET) ``` curl --location 'http://localhost:8080/files/file_Uy7bK9lFFaBDXGhivUjo' \ --header 'Accept: application/json' \ --header 'Authorization: Bearer {{user_token}}' ``` This api will return contents of the uploaded files. Above APIs will now work with JWTs with roles which doesn't have `FileRead`/`FileWrite` permissions. - Forex - Rates (`/forex/rates` GET) ``` curl --location 'http://localhost:8080/forex/rates' \ --header 'Accept: application/json' \ --header 'Authorization: Bearer {{user_token}}' ``` - Forex - Convert from minor (`/forex/convert_from_minor` GET) ``` curl --location 'http://localhost:8080/forex/convert_from_minor?amount=100&from_currency=USD&to_currency=INR' \ --header 'Accept: application/json' \ --header 'Authorization: Bearer {{user_token}}' ``` ``` { "converted_amount": "82.89544400", "currency": "INR" } ``` will now work with JWTs with roles which doesn't have `ForexRead` permission.
juspay/hyperswitch
juspay__hyperswitch-3726
Bug: [FEATURE]: [Adyen] populate connector_transaction_id for Adyen Payment Response ### :memo: Feature Description - populate connector_transaction_id for Adyen Payment Response ### :package: Have you spent some time checking if this feature request has been raised before? - [X] I checked and didn't find a similar issue ### :package: Have you read the Contributing Guidelines? - [X] I have read the [Contributing Guidelines](https://github.com/juspay/hyperswitch/blob/main/docs/CONTRIBUTING.md) ### :sparkles: Are you willing to submit a PR? - yes
diff --git a/crates/router/src/connector/adyen/transformers.rs b/crates/router/src/connector/adyen/transformers.rs index 072b542eee0..d8213e2db98 100644 --- a/crates/router/src/connector/adyen/transformers.rs +++ b/crates/router/src/connector/adyen/transformers.rs @@ -3159,9 +3159,11 @@ pub fn get_redirection_response( let connector_metadata = get_wait_screen_metadata(&response)?; - // We don't get connector transaction id for redirections in Adyen. let payments_response_data = types::PaymentsResponseData::TransactionResponse { - resource_id: types::ResponseId::NoResponseId, + resource_id: match response.psp_reference.as_ref() { + Some(psp) => types::ResponseId::ConnectorTransactionId(psp.to_string()), + None => types::ResponseId::NoResponseId, + }, redirection_data, mandate_reference: None, connector_metadata, @@ -3264,9 +3266,11 @@ pub fn get_qr_code_response( }; let connector_metadata = get_qr_metadata(&response)?; - // We don't get connector transaction id for redirections in Adyen. let payments_response_data = types::PaymentsResponseData::TransactionResponse { - resource_id: types::ResponseId::NoResponseId, + resource_id: match response.psp_reference.as_ref() { + Some(psp) => types::ResponseId::ConnectorTransactionId(psp.to_string()), + None => types::ResponseId::NoResponseId, + }, redirection_data: None, mandate_reference: None, connector_metadata,
2024-02-20T13:26:34Z
## 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 --> populate connector_transaction_id for Adyen Payment Response - (RedirectionResponse and QrCodeResponseResponse) ### 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? PIx via Adyen request - (it uses QrCodeResponseResponse) ``` { "amount": 5000, "currency": "BRL", "confirm": true, "capture_method": "automatic", "capture_on": "2022-09-10T10:11:12Z", "amount_to_capture": 5000, "customer_id": "StripeCustomer", "email": "abcdef123@gmail.com", "name": "John Doe", "phone": "999999999", "phone_country_code": "+65", "profile_id": "pro_sx78reJN0zgRzB5UGicx", "description": "Its my first payment request", "authentication_type": "three_ds", "return_url": "https://duck.com", "payment_method": "bank_transfer", "payment_method_type": "pix", "payment_method_data": { "bank_transfer": { "pix": {} } }, "billing": { "address": { "first_name": "John", "last_name": "Doe", "line1": "1467", "line2": "Harrison Street", "line3": "Harrison Street", "city": "San Fransico", "state": "California", "zip": "94122", "country": "BR" } }, "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": "BR", "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" } } ``` Pix response ``` { "payment_id": "pay_HciK53YclKPcpOY7J4Zx", "merchant_id": "merchant_1708428346", "status": "requires_customer_action", "amount": 5000, "net_amount": 5000, "amount_capturable": 5000, "amount_received": null, "connector": "adyen", "client_secret": "pay_HciK53YclKPcpOY7J4Zx_secret_mhOJoO92ETjFntcpFlzd", "created": "2024-02-20T13:27:59.206Z", "currency": "BRL", "customer_id": "StripeCustomer", "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": "bank_transfer", "payment_method_data": "bank_transfer", "payment_token": null, "shipping": { "address": { "city": "San Fransico", "country": "BR", "line1": "1467", "line2": "Harrison Street", "line3": "Harrison Street", "zip": "94122", "state": "California", "first_name": "John", "last_name": "Doe" }, "phone": { "number": null, "country_code": null } }, "billing": { "address": { "city": "San Fransico", "country": "BR", "line1": "1467", "line2": "Harrison Street", "line3": "Harrison Street", "zip": "94122", "state": "California", "first_name": "John", "last_name": "Doe" }, "phone": { "number": null, "country_code": null } }, "order_details": null, "email": "abcdef123@gmail.com", "name": "John Doe", "phone": "999999999", "return_url": "https://duck.com/", "authentication_type": "three_ds", "statement_descriptor_name": "joseph", "statement_descriptor_suffix": "JS", "next_action": { "type": "qr_code_information", "image_data_url": "data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAQgAAAEICAAAAACGnTUjAAADfUlEQVR4nO3QS25dOQwA0c7+F90foGpCgKCeE3cGqQN4QEq6fqgff/+V/xQChUAhUAgUAoVAIVAIFAKFQCFQCBQChUAhUAgUAoVAIVAIFAKFQCFQCBQChUAhUAgUAoVAIXCG+PHv31f4Xd87y708n3td5xffbwqBQqAQKAQKgUKgEHgOcd3Tdn/uneV+8p7nc7683i8ECoFCoBAoBAqBQuDjEM7TPHee5vmc9bp3nua586YQKAQKgUKgECgECoFvD+G88d4033nP/Zynee68KQQKgUKgECgECoFC4H8PMffOcj95z/M5T/PceVMIFAKFQCFQCBQChcDHIS7zvvPF+5PvPZ/z5fV+IVAIFAKFQCFQCBQCzyE+5Xd9/6vnT/l+UwgUAoVAIVAIFAKFwBniZ/nD/T/bLPfyfO5/tUKgECgECoFCoBAoBM4Q1w+Z584b72ne99z9nC/el+/mfioECoFCoBAoBAqBQuAMcfEfye/Nva7zje8mvzPPt/2mECgECoFCoBAoBAqBj0P4Dya/4/mcde3l+dx/l0KgECgECoFCoBAoBM4Q/qCN773nrGsvz907b7Z72/5SCBQChUAhUAgUAoXAcwjvOV+8r/nuOpf3vnou720KgUKgECgECoFCoBB4DqHtvvc832bNvbPcy3P3c5b7TxUChUAhUAgUAoVAIXCG2PgD5vvXvfMr3+l6P+9fCoFCoBAoBAqBQqAQ+HIIzR80v+f5tb/myXN5b9tfCoFCoBAoBAqBQqAQOEPMD2t7N+/Pe567d5Z7zfOL7+c795tCoBAoBAqBQqAQKATOED/LH3T9H+9ttve+m+fuNc+nQqAQKAQKgUKgECgEzhDzg6/8ru+dX/lOvnf/Or8qBAqBQqAQKAQKgULgOcR1T9v91/01T/PcefJ8UwgUAoVAIVAIFAKFwMchnKd5fs36dH/xnXw/91MhUAgUAoVAIVAIFALfHkLu5bl758nzzeu77Z4KgUKgECgECoFCoBD4bSEuvp/v5v51vhQChUAhUAgUAoVAIfBxiMvr/Xlvzpp752k7d38pBAqBQqAQKAQKgULgOcSn/K7vr1lzP+eN9zTvz/OpECgECoFCoBAoBAqBM8SfohAoBAqBQqAQKAQKgUKgECgECoFCoBAoBAqBQqAQKAQKgUKgECgECoFCoBAoBAqBQqAQKAQKgX8A/Ak4Wyhn58sAAAAASUVORK5CYII=", "display_to_timestamp": 1708439280000, "qr_code_url": "https://test.adyen.com/hpp/generateQRCodeImage.shtml?url=TestQRCodeEMVToken" }, "cancellation_reason": null, "error_code": null, "error_message": null, "unified_code": null, "unified_message": null, "payment_experience": null, "payment_method_type": "pix", "connector_label": null, "business_country": null, "business_label": "default", "business_sub_label": null, "allowed_payment_method_types": null, "ephemeral_key": { "customer_id": "StripeCustomer", "created_at": 1708435679, "expires": 1708439279, "secret": "epk_286a4b57f8a34e969f09879055c1ecca" }, "manual_retry_allowed": null, "connector_transaction_id": "QS3SDRRC564DCG65", (it should not be 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": null, "payment_link": null, "profile_id": "pro_qisu2wRsK4dq0H3hKKpM", "surcharge_details": null, "attempt_count": 1, "merchant_decision": null, "merchant_connector_id": "mca_wkHJMOOIYr9gbxJRXn5g", "incremental_authorization_allowed": null, "authorization_count": null, "incremental_authorizations": null, "expires_on": "2024-02-20T13:42:59.206Z", "fingerprint": null } ``` In Response check for `"connector_transaction_id": "some string"`, (it should not be null) Payment Request for Blik via Adyen - (it uses RedirectionResponse) ``` { "amount": 10000, "currency": "PLN", "confirm": true, "capture_method": "automatic", "capture_on": "2022-09-10T10:11:12Z", "amount_to_capture": 10000, "customer_id": "StripeCustomer", "email": "abcdef123@gmail.com", "name": "John Doe", "phone": "999999999", "phone_country_code": "+65", "profile_id": "pro_sx78reJN0zgRzB5UGicx", "description": "Its my first payment request", "authentication_type": "three_ds", "return_url": "https://duck.com", "payment_method": "bank_redirect", "payment_method_type": "blik", "payment_method_data": { "bank_redirect": { "blik": { "blik_code":"777987" } } }, "billing": { "address": { "first_name": "John", "last_name": "Doe", "line1": "1467", "line2": "Harrison Street", "line3": "Harrison Street", "city": "San Fransico", "state": "California", "zip": "94122", "country": "PL" } }, "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": "PL", "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" } } ``` Blik Response ``` { "payment_id": "pay_brzqtt6cdm5rL3HAYPxk", "merchant_id": "merchant_1708428346", "status": "processing", "amount": 10000, "net_amount": 10000, "amount_capturable": 0, "amount_received": null, "connector": "adyen", "client_secret": "pay_brzqtt6cdm5rL3HAYPxk_secret_eY8ZA1UonKsrJnmGRVC3", "created": "2024-02-20T13:30:26.642Z", "currency": "PLN", "customer_id": "StripeCustomer", "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": "bank_redirect", "payment_method_data": "bank_redirect", "payment_token": null, "shipping": { "address": { "city": "San Fransico", "country": "PL", "line1": "1467", "line2": "Harrison Street", "line3": "Harrison Street", "zip": "94122", "state": "California", "first_name": "John", "last_name": "Doe" }, "phone": { "number": null, "country_code": null } }, "billing": { "address": { "city": "San Fransico", "country": "PL", "line1": "1467", "line2": "Harrison Street", "line3": "Harrison Street", "zip": "94122", "state": "California", "first_name": "John", "last_name": "Doe" }, "phone": { "number": null, "country_code": null } }, "order_details": null, "email": "abcdef123@gmail.com", "name": "John Doe", "phone": "999999999", "return_url": "https://duck.com/", "authentication_type": "three_ds", "statement_descriptor_name": "joseph", "statement_descriptor_suffix": "JS", "next_action": { "type": "wait_screen_information", "display_from_timestamp": 1708435828625707000, "display_to_timestamp": 1708435888625707000 }, "cancellation_reason": null, "error_code": null, "error_message": null, "unified_code": null, "unified_message": null, "payment_experience": null, "payment_method_type": "blik", "connector_label": null, "business_country": null, "business_label": "default", "business_sub_label": null, "allowed_payment_method_types": null, "ephemeral_key": { "customer_id": "StripeCustomer", "created_at": 1708435826, "expires": 1708439426, "secret": "epk_940c1cecdd6b49928d2047f91ff5659c" }, "manual_retry_allowed": false, "connector_transaction_id": "DQ7M74SBGTGLNK82", "frm_message": null, "metadata": { "udf1": "value1", "login_date": "2019-09-10T10:11:12Z", "new_customer": "true" }, "connector_metadata": null, "feature_metadata": null, "reference_id": null, "payment_link": null, "profile_id": "pro_qisu2wRsK4dq0H3hKKpM", "surcharge_details": null, "attempt_count": 1, "merchant_decision": null, "merchant_connector_id": "mca_wkHJMOOIYr9gbxJRXn5g", "incremental_authorization_allowed": null, "authorization_count": null, "incremental_authorizations": null, "expires_on": "2024-02-20T13:45:26.642Z", "fingerprint": null } ``` In Response check for `"connector_transaction_id": "some string"`, (it should not be 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 - [ ] I added a [CHANGELOG](/CHANGELOG.md) entry if applicable
cf3c66636ffee30cdd4353b276a89a8f9fc2d9d0
PIx via Adyen request - (it uses QrCodeResponseResponse) ``` { "amount": 5000, "currency": "BRL", "confirm": true, "capture_method": "automatic", "capture_on": "2022-09-10T10:11:12Z", "amount_to_capture": 5000, "customer_id": "StripeCustomer", "email": "abcdef123@gmail.com", "name": "John Doe", "phone": "999999999", "phone_country_code": "+65", "profile_id": "pro_sx78reJN0zgRzB5UGicx", "description": "Its my first payment request", "authentication_type": "three_ds", "return_url": "https://duck.com", "payment_method": "bank_transfer", "payment_method_type": "pix", "payment_method_data": { "bank_transfer": { "pix": {} } }, "billing": { "address": { "first_name": "John", "last_name": "Doe", "line1": "1467", "line2": "Harrison Street", "line3": "Harrison Street", "city": "San Fransico", "state": "California", "zip": "94122", "country": "BR" } }, "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": "BR", "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" } } ``` Pix response ``` { "payment_id": "pay_HciK53YclKPcpOY7J4Zx", "merchant_id": "merchant_1708428346", "status": "requires_customer_action", "amount": 5000, "net_amount": 5000, "amount_capturable": 5000, "amount_received": null, "connector": "adyen", "client_secret": "pay_HciK53YclKPcpOY7J4Zx_secret_mhOJoO92ETjFntcpFlzd", "created": "2024-02-20T13:27:59.206Z", "currency": "BRL", "customer_id": "StripeCustomer", "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": "bank_transfer", "payment_method_data": "bank_transfer", "payment_token": null, "shipping": { "address": { "city": "San Fransico", "country": "BR", "line1": "1467", "line2": "Harrison Street", "line3": "Harrison Street", "zip": "94122", "state": "California", "first_name": "John", "last_name": "Doe" }, "phone": { "number": null, "country_code": null } }, "billing": { "address": { "city": "San Fransico", "country": "BR", "line1": "1467", "line2": "Harrison Street", "line3": "Harrison Street", "zip": "94122", "state": "California", "first_name": "John", "last_name": "Doe" }, "phone": { "number": null, "country_code": null } }, "order_details": null, "email": "abcdef123@gmail.com", "name": "John Doe", "phone": "999999999", "return_url": "https://duck.com/", "authentication_type": "three_ds", "statement_descriptor_name": "joseph", "statement_descriptor_suffix": "JS", "next_action": { "type": "qr_code_information", "image_data_url": "data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAQgAAAEICAAAAACGnTUjAAADfUlEQVR4nO3QS25dOQwA0c7+F90foGpCgKCeE3cGqQN4QEq6fqgff/+V/xQChUAhUAgUAoVAIVAIFAKFQCFQCBQChUAhUAgUAoVAIVAIFAKFQCFQCBQChUAhUAgUAoVAIXCG+PHv31f4Xd87y708n3td5xffbwqBQqAQKAQKgUKgEHgOcd3Tdn/uneV+8p7nc7683i8ECoFCoBAoBAqBQuDjEM7TPHee5vmc9bp3nua586YQKAQKgUKgECgECoFvD+G88d4033nP/Zynee68KQQKgUKgECgECoFC4H8PMffOcj95z/M5T/PceVMIFAKFQCFQCBQChcDHIS7zvvPF+5PvPZ/z5fV+IVAIFAKFQCFQCBQCzyE+5Xd9/6vnT/l+UwgUAoVAIVAIFAKFwBniZ/nD/T/bLPfyfO5/tUKgECgECoFCoBAoBM4Q1w+Z584b72ne99z9nC/el+/mfioECoFCoBAoBAqBQuAMcfEfye/Nva7zje8mvzPPt/2mECgECoFCoBAoBAqBj0P4Dya/4/mcde3l+dx/l0KgECgECoFCoBAoBM4Q/qCN773nrGsvz907b7Z72/5SCBQChUAhUAgUAoXAcwjvOV+8r/nuOpf3vnou720KgUKgECgECoFCoBB4DqHtvvc832bNvbPcy3P3c5b7TxUChUAhUAgUAoVAIXCG2PgD5vvXvfMr3+l6P+9fCoFCoBAoBAqBQqAQ+HIIzR80v+f5tb/myXN5b9tfCoFCoBAoBAqBQqAQOEPMD2t7N+/Pe567d5Z7zfOL7+c795tCoBAoBAqBQqAQKATOED/LH3T9H+9ttve+m+fuNc+nQqAQKAQKgUKgECgEzhDzg6/8ru+dX/lOvnf/Or8qBAqBQqAQKAQKgULgOcR1T9v91/01T/PcefJ8UwgUAoVAIVAIFAKFwMchnKd5fs36dH/xnXw/91MhUAgUAoVAIVAIFALfHkLu5bl758nzzeu77Z4KgUKgECgECoFCoBD4bSEuvp/v5v51vhQChUAhUAgUAoVAIfBxiMvr/Xlvzpp752k7d38pBAqBQqAQKAQKgULgOcSn/K7vr1lzP+eN9zTvz/OpECgECoFCoBAoBAqBM8SfohAoBAqBQqAQKAQKgUKgECgECoFCoBAoBAqBQqAQKAQKgUKgECgECoFCoBAoBAqBQqAQKAQKgX8A/Ak4Wyhn58sAAAAASUVORK5CYII=", "display_to_timestamp": 1708439280000, "qr_code_url": "https://test.adyen.com/hpp/generateQRCodeImage.shtml?url=TestQRCodeEMVToken" }, "cancellation_reason": null, "error_code": null, "error_message": null, "unified_code": null, "unified_message": null, "payment_experience": null, "payment_method_type": "pix", "connector_label": null, "business_country": null, "business_label": "default", "business_sub_label": null, "allowed_payment_method_types": null, "ephemeral_key": { "customer_id": "StripeCustomer", "created_at": 1708435679, "expires": 1708439279, "secret": "epk_286a4b57f8a34e969f09879055c1ecca" }, "manual_retry_allowed": null, "connector_transaction_id": "QS3SDRRC564DCG65", (it should not be 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": null, "payment_link": null, "profile_id": "pro_qisu2wRsK4dq0H3hKKpM", "surcharge_details": null, "attempt_count": 1, "merchant_decision": null, "merchant_connector_id": "mca_wkHJMOOIYr9gbxJRXn5g", "incremental_authorization_allowed": null, "authorization_count": null, "incremental_authorizations": null, "expires_on": "2024-02-20T13:42:59.206Z", "fingerprint": null } ``` In Response check for `"connector_transaction_id": "some string"`, (it should not be null) Payment Request for Blik via Adyen - (it uses RedirectionResponse) ``` { "amount": 10000, "currency": "PLN", "confirm": true, "capture_method": "automatic", "capture_on": "2022-09-10T10:11:12Z", "amount_to_capture": 10000, "customer_id": "StripeCustomer", "email": "abcdef123@gmail.com", "name": "John Doe", "phone": "999999999", "phone_country_code": "+65", "profile_id": "pro_sx78reJN0zgRzB5UGicx", "description": "Its my first payment request", "authentication_type": "three_ds", "return_url": "https://duck.com", "payment_method": "bank_redirect", "payment_method_type": "blik", "payment_method_data": { "bank_redirect": { "blik": { "blik_code":"777987" } } }, "billing": { "address": { "first_name": "John", "last_name": "Doe", "line1": "1467", "line2": "Harrison Street", "line3": "Harrison Street", "city": "San Fransico", "state": "California", "zip": "94122", "country": "PL" } }, "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": "PL", "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" } } ``` Blik Response ``` { "payment_id": "pay_brzqtt6cdm5rL3HAYPxk", "merchant_id": "merchant_1708428346", "status": "processing", "amount": 10000, "net_amount": 10000, "amount_capturable": 0, "amount_received": null, "connector": "adyen", "client_secret": "pay_brzqtt6cdm5rL3HAYPxk_secret_eY8ZA1UonKsrJnmGRVC3", "created": "2024-02-20T13:30:26.642Z", "currency": "PLN", "customer_id": "StripeCustomer", "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": "bank_redirect", "payment_method_data": "bank_redirect", "payment_token": null, "shipping": { "address": { "city": "San Fransico", "country": "PL", "line1": "1467", "line2": "Harrison Street", "line3": "Harrison Street", "zip": "94122", "state": "California", "first_name": "John", "last_name": "Doe" }, "phone": { "number": null, "country_code": null } }, "billing": { "address": { "city": "San Fransico", "country": "PL", "line1": "1467", "line2": "Harrison Street", "line3": "Harrison Street", "zip": "94122", "state": "California", "first_name": "John", "last_name": "Doe" }, "phone": { "number": null, "country_code": null } }, "order_details": null, "email": "abcdef123@gmail.com", "name": "John Doe", "phone": "999999999", "return_url": "https://duck.com/", "authentication_type": "three_ds", "statement_descriptor_name": "joseph", "statement_descriptor_suffix": "JS", "next_action": { "type": "wait_screen_information", "display_from_timestamp": 1708435828625707000, "display_to_timestamp": 1708435888625707000 }, "cancellation_reason": null, "error_code": null, "error_message": null, "unified_code": null, "unified_message": null, "payment_experience": null, "payment_method_type": "blik", "connector_label": null, "business_country": null, "business_label": "default", "business_sub_label": null, "allowed_payment_method_types": null, "ephemeral_key": { "customer_id": "StripeCustomer", "created_at": 1708435826, "expires": 1708439426, "secret": "epk_940c1cecdd6b49928d2047f91ff5659c" }, "manual_retry_allowed": false, "connector_transaction_id": "DQ7M74SBGTGLNK82", "frm_message": null, "metadata": { "udf1": "value1", "login_date": "2019-09-10T10:11:12Z", "new_customer": "true" }, "connector_metadata": null, "feature_metadata": null, "reference_id": null, "payment_link": null, "profile_id": "pro_qisu2wRsK4dq0H3hKKpM", "surcharge_details": null, "attempt_count": 1, "merchant_decision": null, "merchant_connector_id": "mca_wkHJMOOIYr9gbxJRXn5g", "incremental_authorization_allowed": null, "authorization_count": null, "incremental_authorizations": null, "expires_on": "2024-02-20T13:45:26.642Z", "fingerprint": null } ``` In Response check for `"connector_transaction_id": "some string"`, (it should not be null)
juspay/hyperswitch
juspay__hyperswitch-3740
Bug: Customer Payment Method List updates for MIT payments Since we are deprecating Mandates for unscheduled MIT use cases, the customer payment method list will undergo the following changes: - List only PMs that are in active state - Add auth support for Ephemeral Key - Default PM to be communicated in Customer PM list response
diff --git a/config/development.toml b/config/development.toml index d69719bd419..59d73a4b8b2 100644 --- a/config/development.toml +++ b/config/development.toml @@ -71,7 +71,6 @@ mock_locker = true basilisk_host = "" locker_enabled = true - [forex_api] call_delay = 21600 local_fetch_retry_count = 5 diff --git a/crates/api_models/src/customers.rs b/crates/api_models/src/customers.rs index d8c864746a8..eeb10e62286 100644 --- a/crates/api_models/src/customers.rs +++ b/crates/api_models/src/customers.rs @@ -73,6 +73,9 @@ pub struct CustomerResponse { /// object. #[schema(value_type = Option<Object>,example = json!({ "city": "NY", "unit": "245" }))] pub metadata: Option<pii::SecretSerdeValue>, + /// The identifier for the default payment method. + #[schema(max_length = 64, example = "pm_djh2837dwduh890123")] + pub default_payment_method_id: Option<String>, } #[derive(Default, Clone, Debug, Deserialize, Serialize)] diff --git a/crates/api_models/src/events/payment.rs b/crates/api_models/src/events/payment.rs index 32d3dc30bd8..92f69933900 100644 --- a/crates/api_models/src/events/payment.rs +++ b/crates/api_models/src/events/payment.rs @@ -2,7 +2,8 @@ use common_utils::events::{ApiEventMetric, ApiEventsType}; use crate::{ payment_methods::{ - CustomerPaymentMethodsListResponse, PaymentMethodDeleteResponse, PaymentMethodListRequest, + CustomerDefaultPaymentMethodResponse, CustomerPaymentMethodsListResponse, + DefaultPaymentMethod, PaymentMethodDeleteResponse, PaymentMethodListRequest, PaymentMethodListResponse, PaymentMethodResponse, PaymentMethodUpdate, }, payments::{ @@ -95,6 +96,16 @@ impl ApiEventMetric for PaymentMethodResponse { impl ApiEventMetric for PaymentMethodUpdate {} +impl ApiEventMetric for DefaultPaymentMethod { + fn get_api_event_type(&self) -> Option<ApiEventsType> { + Some(ApiEventsType::PaymentMethod { + payment_method_id: self.payment_method_id.clone(), + payment_method: None, + payment_method_type: None, + }) + } +} + impl ApiEventMetric for PaymentMethodDeleteResponse { fn get_api_event_type(&self) -> Option<ApiEventsType> { Some(ApiEventsType::PaymentMethod { @@ -121,6 +132,16 @@ impl ApiEventMetric for PaymentMethodListRequest { impl ApiEventMetric for PaymentMethodListResponse {} +impl ApiEventMetric for CustomerDefaultPaymentMethodResponse { + fn get_api_event_type(&self) -> Option<ApiEventsType> { + Some(ApiEventsType::PaymentMethod { + payment_method_id: self.default_payment_method_id.clone().unwrap_or_default(), + payment_method: Some(self.payment_method), + payment_method_type: self.payment_method_type, + }) + } +} + impl ApiEventMetric for PaymentListFilterConstraints { fn get_api_event_type(&self) -> Option<ApiEventsType> { Some(ApiEventsType::ResourceListAPI) diff --git a/crates/api_models/src/payment_methods.rs b/crates/api_models/src/payment_methods.rs index 83e1a2c4887..35193b958f2 100644 --- a/crates/api_models/src/payment_methods.rs +++ b/crates/api_models/src/payment_methods.rs @@ -185,6 +185,10 @@ pub struct PaymentMethodResponse { #[cfg(feature = "payouts")] #[schema(value_type = Option<Bank>)] pub bank_transfer: Option<payouts::Bank>, + + #[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>, } #[derive(Clone, Debug, Eq, PartialEq, serde::Deserialize, serde::Serialize)] @@ -550,6 +554,10 @@ pub struct PaymentMethodListRequest { /// 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>, } impl<'de> serde::Deserialize<'de> for PaymentMethodListRequest { @@ -618,6 +626,9 @@ impl<'de> serde::Deserialize<'de> for PaymentMethodListRequest { 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()?)?; + } _ => {} } } @@ -731,12 +742,30 @@ pub struct PaymentMethodDeleteResponse { #[schema(example = true)] pub deleted: bool, } +#[derive(Debug, serde::Serialize, ToSchema)] +pub struct CustomerDefaultPaymentMethodResponse { + /// The unique identifier of the Payment method + #[schema(example = "card_rGK4Vi5iSW70MY7J2mIy")] + pub default_payment_method_id: Option<String>, + /// The unique identifier of the customer. + #[schema(example = "cus_meowerunwiuwiwqw")] + pub customer_id: String, + /// The type of payment method use for the payment. + #[schema(value_type = PaymentMethod,example = "card")] + pub payment_method: api_enums::PaymentMethod, + /// This is a sub-category of payment method. + #[schema(value_type = Option<PaymentMethodType>,example = "credit")] + pub payment_method_type: Option<api_enums::PaymentMethodType>, +} #[derive(Debug, Clone, serde::Serialize, ToSchema)] pub struct CustomerPaymentMethod { /// Token for payment method in temporary card locker which gets refreshed often #[schema(example = "7ebf443f-a050-4067-84e5-e6f6d4800aef")] pub payment_token: String, + /// The unique identifier of the customer. + #[schema(example = "pm_iouuy468iyuowqs")] + pub payment_method_id: String, /// The unique identifier of the customer. #[schema(example = "cus_meowerunwiuwiwqw")] @@ -798,6 +827,14 @@ pub struct CustomerPaymentMethod { /// Whether this payment method requires CVV to be collected #[schema(example = true)] pub requires_cvv: bool, + + /// A timestamp (ISO 8601 code) that determines when the payment method was last used + #[schema(value_type = Option<PrimitiveDateTime>,example = "2024-02-24T11:04:09.922Z")] + #[serde(default, with = "common_utils::custom_serde::iso8601::option")] + pub last_used_at: Option<time::PrimitiveDateTime>, + /// Indicates if the payment method has been set to default or not + #[schema(example = true)] + pub default_payment_method_set: bool, } #[derive(Debug, Clone, serde::Serialize, serde::Deserialize, ToSchema)] @@ -810,6 +847,11 @@ pub struct PaymentMethodId { pub payment_method_id: String, } +#[derive(Debug, serde::Serialize, serde::Deserialize, Clone, ToSchema)] +pub struct DefaultPaymentMethod { + pub customer_id: String, + pub payment_method_id: String, +} //------------------------------------------------TokenizeService------------------------------------------------ #[derive(Debug, serde::Serialize, serde::Deserialize)] pub struct TokenizePayloadEncrypted { diff --git a/crates/diesel_models/src/customers.rs b/crates/diesel_models/src/customers.rs index c0cebba7755..cefb0c240ec 100644 --- a/crates/diesel_models/src/customers.rs +++ b/crates/diesel_models/src/customers.rs @@ -37,6 +37,7 @@ pub struct Customer { pub connector_customer: Option<serde_json::Value>, pub modified_at: PrimitiveDateTime, pub address_id: Option<String>, + pub default_payment_method_id: Option<String>, } #[derive(Clone, Debug, Default, AsChangeset, router_derive::DebugAsDisplay)] @@ -51,4 +52,5 @@ pub struct CustomerUpdateInternal { pub modified_at: Option<PrimitiveDateTime>, pub connector_customer: Option<serde_json::Value>, pub address_id: Option<String>, + pub default_payment_method_id: Option<String>, } diff --git a/crates/diesel_models/src/payment_method.rs b/crates/diesel_models/src/payment_method.rs index 09be739581e..6191a768efe 100644 --- a/crates/diesel_models/src/payment_method.rs +++ b/crates/diesel_models/src/payment_method.rs @@ -34,12 +34,13 @@ pub struct PaymentMethod { 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<serde_json::Value>, pub customer_acceptance: Option<pii::SecretSerdeValue>, pub status: storage_enums::PaymentMethodStatus, } -#[derive(Clone, Debug, Eq, PartialEq, Insertable, Queryable, router_derive::DebugAsDisplay)] +#[derive(Clone, Debug, Eq, PartialEq, Insertable, router_derive::DebugAsDisplay)] #[diesel(table_name = payment_methods)] pub struct PaymentMethodNew { pub customer_id: String, @@ -64,6 +65,7 @@ pub struct PaymentMethodNew { 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<serde_json::Value>, pub customer_acceptance: Option<pii::SecretSerdeValue>, pub status: storage_enums::PaymentMethodStatus, @@ -96,6 +98,7 @@ impl Default for PaymentMethodNew { last_modified: now, metadata: Option::default(), payment_method_data: Option::default(), + last_used_at: now, connector_mandate_details: Option::default(), customer_acceptance: Option::default(), status: storage_enums::PaymentMethodStatus::Active, @@ -117,6 +120,9 @@ pub enum PaymentMethodUpdate { PaymentMethodDataUpdate { payment_method_data: Option<Encryption>, }, + LastUsedUpdate { + last_used_at: PrimitiveDateTime, + }, } #[derive(Clone, Debug, Default, AsChangeset, router_derive::DebugAsDisplay)] @@ -124,6 +130,7 @@ pub enum PaymentMethodUpdate { pub struct PaymentMethodUpdateInternal { metadata: Option<serde_json::Value>, payment_method_data: Option<Encryption>, + last_used_at: Option<PrimitiveDateTime>, } impl PaymentMethodUpdateInternal { @@ -140,12 +147,19 @@ impl From<PaymentMethodUpdate> for PaymentMethodUpdateInternal { PaymentMethodUpdate::MetadataUpdate { metadata } => Self { metadata, payment_method_data: None, + last_used_at: None, }, PaymentMethodUpdate::PaymentMethodDataUpdate { payment_method_data, } => Self { metadata: None, payment_method_data, + last_used_at: None, + }, + PaymentMethodUpdate::LastUsedUpdate { last_used_at } => Self { + metadata: None, + payment_method_data: None, + last_used_at: Some(last_used_at), }, } } diff --git a/crates/diesel_models/src/query/payment_method.rs b/crates/diesel_models/src/query/payment_method.rs index aa227962760..e3f2e511378 100644 --- a/crates/diesel_models/src/query/payment_method.rs +++ b/crates/diesel_models/src/query/payment_method.rs @@ -90,20 +90,16 @@ impl PaymentMethod { conn: &PgPooledConn, customer_id: &str, merchant_id: &str, + limit: Option<i64>, ) -> StorageResult<Vec<Self>> { - generics::generic_filter::< - <Self as HasTable>::Table, - _, - <<Self as HasTable>::Table as Table>::PrimaryKey, - _, - >( + 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())), + limit, None, - None, - None, + Some(dsl::last_used_at.desc()), ) .await } @@ -114,21 +110,17 @@ impl PaymentMethod { customer_id: &str, merchant_id: &str, status: storage_enums::PaymentMethodStatus, + limit: Option<i64>, ) -> StorageResult<Vec<Self>> { - generics::generic_filter::< - <Self as HasTable>::Table, - _, - <<Self as HasTable>::Table as Table>::PrimaryKey, - _, - >( + 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, - None, - None, + Some(dsl::last_used_at.desc()), ) .await } diff --git a/crates/diesel_models/src/schema.rs b/crates/diesel_models/src/schema.rs index f3c6f23e086..97ef8b974dc 100644 --- a/crates/diesel_models/src/schema.rs +++ b/crates/diesel_models/src/schema.rs @@ -227,6 +227,8 @@ diesel::table! { modified_at -> Timestamp, #[max_length = 64] address_id -> Nullable<Varchar>, + #[max_length = 64] + default_payment_method_id -> Nullable<Varchar>, } } @@ -831,6 +833,7 @@ diesel::table! { payment_method_data -> Nullable<Bytea>, #[max_length = 64] locker_id -> Nullable<Varchar>, + last_used_at -> Timestamp, connector_mandate_details -> Nullable<Jsonb>, customer_acceptance -> Nullable<Jsonb>, #[max_length = 64] diff --git a/crates/openapi/src/openapi.rs b/crates/openapi/src/openapi.rs index ef573093be5..e21797d2eef 100644 --- a/crates/openapi/src/openapi.rs +++ b/crates/openapi/src/openapi.rs @@ -115,6 +115,7 @@ Never share your secret api keys. Keep them guarded and secure. routes::customers::customers_update, routes::customers::customers_delete, routes::customers::customers_mandates_list, + routes::customers::default_payment_method_set_api, //Routes for payment methods routes::payment_method::create_payment_method_api, @@ -188,6 +189,7 @@ Never share your secret api keys. Keep them guarded and secure. api_models::payment_methods::CustomerPaymentMethodsListResponse, api_models::payment_methods::PaymentMethodDeleteResponse, api_models::payment_methods::PaymentMethodUpdate, + api_models::payment_methods::CustomerDefaultPaymentMethodResponse, api_models::payment_methods::CardDetailFromLocker, api_models::payment_methods::CardDetail, api_models::payment_methods::RequestPaymentMethodTypes, @@ -374,6 +376,7 @@ Never share your secret api keys. Keep them guarded and secure. api_models::payments::BrowserInformation, api_models::payments::PaymentCreatePaymentLinkConfig, api_models::payment_methods::RequiredFieldInfo, + api_models::payment_methods::DefaultPaymentMethod, api_models::payment_methods::MaskedBankDetails, api_models::payment_methods::SurchargeDetailsResponse, api_models::payment_methods::SurchargeResponse, diff --git a/crates/openapi/src/routes/customers.rs b/crates/openapi/src/routes/customers.rs index 19901cbbeb9..6011621fc13 100644 --- a/crates/openapi/src/routes/customers.rs +++ b/crates/openapi/src/routes/customers.rs @@ -116,3 +116,23 @@ pub async fn customers_list() {} security(("api_key" = [])) )] pub async fn customers_mandates_list() {} + +/// Customers - Set Default Payment Method +/// +/// Set the Payment Method as Default for the Customer. +#[utoipa::path( + get, + path = "/{customer_id}/payment_methods/{payment_method_id}/default", + params ( + ("method_id" = String, Path, description = "Set the Payment Method as Default for the Customer"), + ), + responses( + (status = 200, description = "Payment Method has been set as default", body =CustomerDefaultPaymentMethodResponse ), + (status = 400, description = "Payment Method has already been set as default for that customer"), + (status = 404, description = "Payment Method not found for the customer") + ), + tag = "Customer Set Default Payment Method", + operation_id = "Set the Payment Method as Default", + security(("ephemeral_key" = [])) +)] +pub async fn default_payment_method_set_api() {} diff --git a/crates/router/src/core/customers.rs b/crates/router/src/core/customers.rs index 521e3a22166..02127efe6de 100644 --- a/crates/router/src/core/customers.rs +++ b/crates/router/src/core/customers.rs @@ -108,6 +108,7 @@ pub async fn create_customer( address_id: address.clone().map(|addr| addr.address_id), created_at: common_utils::date_time::now(), modified_at: common_utils::date_time::now(), + default_payment_method_id: None, }) } .await @@ -208,6 +209,7 @@ pub async fn delete_customer( .find_payment_method_by_customer_id_merchant_id_list( &req.customer_id, &merchant_account.merchant_id, + None, ) .await { diff --git a/crates/router/src/core/locker_migration.rs b/crates/router/src/core/locker_migration.rs index 1347bb8ffd0..c5ddb1ed6bb 100644 --- a/crates/router/src/core/locker_migration.rs +++ b/crates/router/src/core/locker_migration.rs @@ -43,7 +43,11 @@ pub async fn rust_locker_migration( for customer in domain_customers { let result = db - .find_payment_method_by_customer_id_merchant_id_list(&customer.customer_id, merchant_id) + .find_payment_method_by_customer_id_merchant_id_list( + &customer.customer_id, + merchant_id, + None, + ) .change_context(errors::ApiErrorResponse::InternalServerError) .and_then(|pm| { call_to_locker( diff --git a/crates/router/src/core/payment_methods.rs b/crates/router/src/core/payment_methods.rs index bdbd9b02d9e..df1fb1e358d 100644 --- a/crates/router/src/core/payment_methods.rs +++ b/crates/router/src/core/payment_methods.rs @@ -156,6 +156,10 @@ impl PaymentMethodRetrieve for Oss { helpers::retrieve_card_with_permanent_token( state, card_token.locker_id.as_ref().unwrap_or(&card_token.token), + card_token + .payment_method_id + .as_ref() + .unwrap_or(&card_token.token), payment_intent, card_token_data, ) @@ -167,6 +171,10 @@ impl PaymentMethodRetrieve for Oss { helpers::retrieve_card_with_permanent_token( state, card_token.locker_id.as_ref().unwrap_or(&card_token.token), + card_token + .payment_method_id + .as_ref() + .unwrap_or(&card_token.token), payment_intent, card_token_data, ) diff --git a/crates/router/src/core/payment_methods/cards.rs b/crates/router/src/core/payment_methods/cards.rs index a92215936a0..8c00938cadc 100644 --- a/crates/router/src/core/payment_methods/cards.rs +++ b/crates/router/src/core/payment_methods/cards.rs @@ -7,8 +7,9 @@ use api_models::{ admin::{self, PaymentMethodsEnabled}, enums::{self as api_enums}, payment_methods::{ - BankAccountConnectorDetails, CardDetailsPaymentMethod, CardNetworkTypes, MaskedBankDetails, - PaymentExperienceTypes, PaymentMethodsData, RequestPaymentMethodTypes, RequiredFieldInfo, + BankAccountConnectorDetails, CardDetailsPaymentMethod, CardNetworkTypes, + CustomerDefaultPaymentMethodResponse, MaskedBankDetails, PaymentExperienceTypes, + PaymentMethodsData, RequestPaymentMethodTypes, RequiredFieldInfo, ResponsePaymentMethodIntermediate, ResponsePaymentMethodTypes, ResponsePaymentMethodsEnabled, }, @@ -25,6 +26,7 @@ use diesel_models::{ business_profile::BusinessProfile, encryption::Encryption, enums as storage_enums, payment_method, }; +use domain::CustomerUpdate; use error_stack::{report, IntoReport, ResultExt}; use masking::Secret; use router_env::{instrument, tracing}; @@ -128,11 +130,12 @@ pub fn store_default_payment_method( created: Some(common_utils::date_time::now()), recurring_enabled: false, //[#219] installment_payment_enabled: false, //[#219] - payment_experience: Some(vec![api_models::enums::PaymentExperience::RedirectToUrl]), //[#219] + payment_experience: Some(vec![api_models::enums::PaymentExperience::RedirectToUrl]), + last_used_at: Some(common_utils::date_time::now()), }; + (payment_method_response, None) } - #[instrument(skip_all)] pub async fn get_or_insert_payment_method( db: &dyn db::StorageInterface, @@ -2584,6 +2587,8 @@ pub async fn do_list_customer_pm_fetch_customer_if_not_passed( customer_id: Option<&str>, ) -> errors::RouterResponse<api::CustomerPaymentMethodsListResponse> { let db = state.store.as_ref(); + let limit = req.clone().and_then(|pml_req| pml_req.limit); + if let Some(customer_id) = customer_id { Box::pin(list_customer_payment_method( &state, @@ -2591,6 +2596,7 @@ pub async fn do_list_customer_pm_fetch_customer_if_not_passed( key_store, None, customer_id, + limit, )) .await } else { @@ -2614,6 +2620,7 @@ pub async fn do_list_customer_pm_fetch_customer_if_not_passed( key_store, payment_intent, &customer_id, + limit, )) .await } @@ -2634,6 +2641,7 @@ pub async fn list_customer_payment_method( key_store: domain::MerchantKeyStore, payment_intent: Option<storage::PaymentIntent>, customer_id: &str, + limit: Option<i64>, ) -> errors::RouterResponse<api::CustomerPaymentMethodsListResponse> { let db = &*state.store; @@ -2645,13 +2653,14 @@ pub async fn list_customer_payment_method( } }; - db.find_customer_by_customer_id_merchant_id( - customer_id, - &merchant_account.merchant_id, - &key_store, - ) - .await - .to_not_found_response(errors::ApiErrorResponse::CustomerNotFound)?; + let customer = db + .find_customer_by_customer_id_merchant_id( + customer_id, + &merchant_account.merchant_id, + &key_store, + ) + .await + .to_not_found_response(errors::ApiErrorResponse::CustomerNotFound)?; let key = key_store.key.get_inner().peek(); @@ -2671,6 +2680,7 @@ pub async fn list_customer_payment_method( customer_id, &merchant_account.merchant_id, common_enums::PaymentMethodStatus::Active, + limit, ) .await .to_not_found_response(errors::ApiErrorResponse::PaymentMethodNotFound)?; @@ -2758,6 +2768,7 @@ pub async fn list_customer_payment_method( let pma = api::CustomerPaymentMethod { payment_token: parent_payment_method_token.to_owned(), + payment_method_id: pm.payment_method_id.clone(), customer_id: pm.customer_id, payment_method: pm.payment_method, payment_method_type: pm.payment_method_type, @@ -2773,6 +2784,9 @@ pub async fn list_customer_payment_method( bank: bank_details, surcharge_details: None, requires_cvv, + last_used_at: Some(pm.last_used_at), + default_payment_method_set: customer.default_payment_method_id.is_some() + && customer.default_payment_method_id == Some(pm.payment_method_id), }; customer_pms.push(pma.to_owned()); @@ -3059,7 +3073,96 @@ async fn get_bank_account_connector_details( None => Ok(None), } } +pub async fn set_default_payment_method( + state: routes::AppState, + merchant_account: domain::MerchantAccount, + key_store: domain::MerchantKeyStore, + customer_id: &str, + payment_method_id: String, +) -> errors::RouterResponse<CustomerDefaultPaymentMethodResponse> { + let db = &*state.store; + //check for the customer + let customer = db + .find_customer_by_customer_id_merchant_id( + customer_id, + &merchant_account.merchant_id, + &key_store, + ) + .await + .to_not_found_response(errors::ApiErrorResponse::CustomerNotFound)?; + // check for the presence of payment_method + let payment_method = db + .find_payment_method(&payment_method_id) + .await + .to_not_found_response(errors::ApiErrorResponse::PaymentMethodNotFound)?; + utils::when( + payment_method.customer_id != customer_id + && payment_method.merchant_id != merchant_account.merchant_id, + || { + Err(errors::ApiErrorResponse::PreconditionFailed { + message: "The payment_method_id is not valid".to_string(), + }) + .into_report() + }, + )?; + + utils::when( + Some(payment_method_id.clone()) == customer.default_payment_method_id, + || { + Err(errors::ApiErrorResponse::PreconditionFailed { + message: "Payment Method is already set as default".to_string(), + }) + .into_report() + }, + )?; + + let customer_update = CustomerUpdate::UpdateDefaultPaymentMethod { + default_payment_method_id: Some(payment_method_id.clone()), + }; + + // update the db with the default payment method id + let updated_customer_details = db + .update_customer_by_customer_id_merchant_id( + customer_id.to_owned(), + merchant_account.merchant_id, + customer_update, + &key_store, + ) + .await + .change_context(errors::ApiErrorResponse::InternalServerError) + .attach_printable("Failed to update the default payment method id for the customer")?; + let resp = CustomerDefaultPaymentMethodResponse { + default_payment_method_id: updated_customer_details.default_payment_method_id, + customer_id: customer.customer_id, + payment_method_type: payment_method.payment_method_type, + payment_method: payment_method.payment_method, + }; + + Ok(services::ApplicationResponse::Json(resp)) +} + +pub async fn update_last_used_at( + pm_id: &str, + state: &routes::AppState, +) -> errors::RouterResult<()> { + let update_last_used = storage::PaymentMethodUpdate::LastUsedUpdate { + last_used_at: common_utils::date_time::now(), + }; + let payment_method = state + .store + .find_payment_method(pm_id) + .await + .to_not_found_response(errors::ApiErrorResponse::PaymentMethodNotFound)?; + state + .store + .update_payment_method(payment_method, update_last_used) + .await + .change_context(errors::ApiErrorResponse::InternalServerError) + .attach_printable("Failed to update the last_used_at in db")?; + + Ok(()) +} #[cfg(feature = "payouts")] pub async fn get_bank_from_hs_locker( state: &routes::AppState, @@ -3243,9 +3346,10 @@ pub async fn retrieve_payment_method( card, metadata: pm.metadata, created: Some(pm.created_at), - recurring_enabled: false, //[#219] - installment_payment_enabled: false, //[#219] - payment_experience: Some(vec![api_models::enums::PaymentExperience::RedirectToUrl]), //[#219], + recurring_enabled: false, + installment_payment_enabled: false, + payment_experience: Some(vec![api_models::enums::PaymentExperience::RedirectToUrl]), + last_used_at: Some(pm.last_used_at), }, )) } diff --git a/crates/router/src/core/payment_methods/transformers.rs b/crates/router/src/core/payment_methods/transformers.rs index 19ecf733dfb..35491d747ef 100644 --- a/crates/router/src/core/payment_methods/transformers.rs +++ b/crates/router/src/core/payment_methods/transformers.rs @@ -327,7 +327,8 @@ pub fn mk_add_bank_response_hs( created: Some(common_utils::date_time::now()), recurring_enabled: false, // [#256] installment_payment_enabled: false, // #[#256] - payment_experience: Some(vec![api_models::enums::PaymentExperience::RedirectToUrl]), // [#256] + payment_experience: Some(vec![api_models::enums::PaymentExperience::RedirectToUrl]), + last_used_at: Some(common_utils::date_time::now()), } } @@ -370,7 +371,8 @@ pub fn mk_add_card_response_hs( created: Some(common_utils::date_time::now()), recurring_enabled: false, // [#256] installment_payment_enabled: false, // #[#256] - payment_experience: Some(vec![api_models::enums::PaymentExperience::RedirectToUrl]), // [#256] + payment_experience: Some(vec![api_models::enums::PaymentExperience::RedirectToUrl]), + last_used_at: Some(common_utils::date_time::now()), // [#256] } } diff --git a/crates/router/src/core/payments.rs b/crates/router/src/core/payments.rs index b94b8627ef9..782d1814cc6 100644 --- a/crates/router/src/core/payments.rs +++ b/crates/router/src/core/payments.rs @@ -1070,7 +1070,6 @@ where customer, ) .await?; - *payment_data = pd; // Validating the blocklist guard and generate the fingerprint @@ -1141,7 +1140,6 @@ where let pm_token = router_data .add_payment_method_token(state, &connector, &tokenization_action) .await?; - if let Some(payment_method_token) = pm_token.clone() { router_data.payment_method_token = Some(router_types::PaymentMethodToken::Token( payment_method_token, @@ -1846,7 +1844,7 @@ async fn decide_payment_method_tokenize_action( } } -#[derive(Clone)] +#[derive(Clone, Debug)] pub enum TokenizationAction { TokenizeInRouter, TokenizeInConnector, diff --git a/crates/router/src/core/payments/helpers.rs b/crates/router/src/core/payments/helpers.rs index 0baba7035ce..e0b8a5f6232 100644 --- a/crates/router/src/core/payments/helpers.rs +++ b/crates/router/src/core/payments/helpers.rs @@ -1131,6 +1131,7 @@ pub(crate) async fn get_payment_method_create_request( customer_id: Some(customer.customer_id.to_owned()), card_network: None, }; + Ok(payment_method_request) } }, @@ -1402,6 +1403,7 @@ pub async fn create_customer_if_not_exist<'a, F: Clone, R, Ctx>( modified_at: common_utils::date_time::now(), connector_customer: None, address_id: None, + default_payment_method_id: None, }) } .await @@ -1545,7 +1547,8 @@ pub async fn retrieve_payment_method_with_temporary_token( pub async fn retrieve_card_with_permanent_token( state: &AppState, - token: &str, + locker_id: &str, + payment_method_id: &str, payment_intent: &PaymentIntent, card_token_data: Option<&CardToken>, ) -> RouterResult<api::PaymentMethodData> { @@ -1556,11 +1559,11 @@ pub async fn retrieve_card_with_permanent_token( .change_context(errors::ApiErrorResponse::UnprocessableEntity { message: "no customer id provided for the payment".to_string(), })?; - - let card = cards::get_card_from_locker(state, customer_id, &payment_intent.merchant_id, token) - .await - .change_context(errors::ApiErrorResponse::InternalServerError) - .attach_printable("failed to fetch card information from the permanent locker")?; + let card = + cards::get_card_from_locker(state, customer_id, &payment_intent.merchant_id, locker_id) + .await + .change_context(errors::ApiErrorResponse::InternalServerError) + .attach_printable("failed to fetch card information from the permanent locker")?; // The card_holder_name from locker retrieved card is considered if it is a non-empty string or else card_holder_name is picked // from payment_method_data.card_token object @@ -1593,7 +1596,7 @@ pub async fn retrieve_card_with_permanent_token( card_issuing_country: None, bank_code: None, }; - + cards::update_last_used_at(payment_method_id, state).await?; Ok(api::PaymentMethodData::Card(api_card)) } diff --git a/crates/router/src/core/payments/tokenization.rs b/crates/router/src/core/payments/tokenization.rs index d08f0208500..21fd4cf85e8 100644 --- a/crates/router/src/core/payments/tokenization.rs +++ b/crates/router/src/core/payments/tokenization.rs @@ -426,6 +426,7 @@ async fn skip_saving_card_in_locker( metadata: None, created: Some(common_utils::date_time::now()), bank_transfer: None, + last_used_at: Some(common_utils::date_time::now()), }; Ok((pm_resp, None)) @@ -445,6 +446,7 @@ async fn skip_saving_card_in_locker( installment_payment_enabled: false, payment_experience: Some(vec![api_models::enums::PaymentExperience::RedirectToUrl]), bank_transfer: None, + last_used_at: Some(common_utils::date_time::now()), }; Ok((payment_method_response, None)) } @@ -491,6 +493,7 @@ pub async fn save_in_locker( recurring_enabled: false, //[#219] installment_payment_enabled: false, //[#219] payment_experience: Some(vec![api_models::enums::PaymentExperience::RedirectToUrl]), //[#219] + last_used_at: Some(common_utils::date_time::now()), }; Ok((payment_method_response, None)) } diff --git a/crates/router/src/core/payouts/helpers.rs b/crates/router/src/core/payouts/helpers.rs index 7b5ec096248..75a8483e06c 100644 --- a/crates/router/src/core/payouts/helpers.rs +++ b/crates/router/src/core/payouts/helpers.rs @@ -432,6 +432,7 @@ pub async fn get_or_create_customer_details( created_at: common_utils::date_time::now(), modified_at: common_utils::date_time::now(), address_id: None, + default_payment_method_id: None, }; Ok(Some( diff --git a/crates/router/src/core/pm_auth.rs b/crates/router/src/core/pm_auth.rs index 982ed9cae94..2987370f280 100644 --- a/crates/router/src/core/pm_auth.rs +++ b/crates/router/src/core/pm_auth.rs @@ -297,6 +297,7 @@ async fn store_bank_details_in_payment_methods( .find_payment_method_by_customer_id_merchant_id_list( &customer_id, &merchant_account.merchant_id, + None, ) .await .change_context(ApiErrorResponse::InternalServerError)?; diff --git a/crates/router/src/db/kafka_store.rs b/crates/router/src/db/kafka_store.rs index 1c1ec00ce79..0c4cf01aa0e 100644 --- a/crates/router/src/db/kafka_store.rs +++ b/crates/router/src/db/kafka_store.rs @@ -1267,9 +1267,10 @@ impl PaymentMethodInterface for KafkaStore { &self, customer_id: &str, merchant_id: &str, + limit: Option<i64>, ) -> CustomResult<Vec<storage::PaymentMethod>, errors::StorageError> { self.diesel_store - .find_payment_method_by_customer_id_merchant_id_list(customer_id, merchant_id) + .find_payment_method_by_customer_id_merchant_id_list(customer_id, merchant_id, limit) .await } @@ -1278,9 +1279,15 @@ impl PaymentMethodInterface for KafkaStore { customer_id: &str, merchant_id: &str, status: common_enums::PaymentMethodStatus, + limit: Option<i64>, ) -> CustomResult<Vec<storage::PaymentMethod>, errors::StorageError> { self.diesel_store - .find_payment_method_by_customer_id_merchant_id_status(customer_id, merchant_id, status) + .find_payment_method_by_customer_id_merchant_id_status( + customer_id, + merchant_id, + status, + limit, + ) .await } diff --git a/crates/router/src/db/payment_method.rs b/crates/router/src/db/payment_method.rs index f15ceecd1c4..ddd2857cc22 100644 --- a/crates/router/src/db/payment_method.rs +++ b/crates/router/src/db/payment_method.rs @@ -24,6 +24,7 @@ pub trait PaymentMethodInterface { &self, customer_id: &str, merchant_id: &str, + limit: Option<i64>, ) -> CustomResult<Vec<storage::PaymentMethod>, errors::StorageError>; async fn find_payment_method_by_customer_id_merchant_id_status( @@ -31,6 +32,7 @@ pub trait PaymentMethodInterface { customer_id: &str, merchant_id: &str, status: common_enums::PaymentMethodStatus, + limit: Option<i64>, ) -> CustomResult<Vec<storage::PaymentMethod>, errors::StorageError>; async fn insert_payment_method( @@ -104,12 +106,18 @@ impl PaymentMethodInterface for Store { &self, customer_id: &str, merchant_id: &str, + limit: Option<i64>, ) -> CustomResult<Vec<storage::PaymentMethod>, errors::StorageError> { let conn = connection::pg_connection_read(self).await?; - storage::PaymentMethod::find_by_customer_id_merchant_id(&conn, customer_id, merchant_id) - .await - .map_err(Into::into) - .into_report() + storage::PaymentMethod::find_by_customer_id_merchant_id( + &conn, + customer_id, + merchant_id, + limit, + ) + .await + .map_err(Into::into) + .into_report() } async fn find_payment_method_by_customer_id_merchant_id_status( @@ -117,6 +125,7 @@ impl PaymentMethodInterface for Store { customer_id: &str, merchant_id: &str, status: common_enums::PaymentMethodStatus, + limit: Option<i64>, ) -> CustomResult<Vec<storage::PaymentMethod>, errors::StorageError> { let conn = connection::pg_connection_read(self).await?; storage::PaymentMethod::find_by_customer_id_merchant_id_status( @@ -124,6 +133,7 @@ impl PaymentMethodInterface for Store { customer_id, merchant_id, status, + limit, ) .await .map_err(Into::into) @@ -221,6 +231,7 @@ impl PaymentMethodInterface for MockDb { 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, @@ -233,6 +244,7 @@ impl PaymentMethodInterface for MockDb { &self, customer_id: &str, merchant_id: &str, + _limit: Option<i64>, ) -> CustomResult<Vec<storage::PaymentMethod>, errors::StorageError> { let payment_methods = self.payment_methods.lock().await; let payment_methods_found: Vec<storage::PaymentMethod> = payment_methods @@ -256,6 +268,7 @@ impl PaymentMethodInterface for MockDb { customer_id: &str, merchant_id: &str, status: common_enums::PaymentMethodStatus, + _limit: Option<i64>, ) -> CustomResult<Vec<storage::PaymentMethod>, errors::StorageError> { let payment_methods = self.payment_methods.lock().await; let payment_methods_found: Vec<storage::PaymentMethod> = payment_methods diff --git a/crates/router/src/routes/app.rs b/crates/router/src/routes/app.rs index 73558c78d7b..1d82bc7539f 100644 --- a/crates/router/src/routes/app.rs +++ b/crates/router/src/routes/app.rs @@ -632,6 +632,10 @@ impl Customers { web::resource("/{customer_id}/payment_methods") .route(web::get().to(list_customer_payment_method_api)), ) + .service( + web::resource("/{customer_id}/payment_methods/{payment_method_id}/default") + .route(web::post().to(default_payment_method_set_api)), + ) .service( web::resource("/{customer_id}") .route(web::get().to(customers_retrieve)) diff --git a/crates/router/src/routes/lock_utils.rs b/crates/router/src/routes/lock_utils.rs index 9471289a0c8..edbdee7bf6f 100644 --- a/crates/router/src/routes/lock_utils.rs +++ b/crates/router/src/routes/lock_utils.rs @@ -96,7 +96,8 @@ impl From<Flow> for ApiIdentifier { | Flow::PaymentMethodsRetrieve | Flow::PaymentMethodsUpdate | Flow::PaymentMethodsDelete - | Flow::ValidatePaymentMethod => Self::PaymentMethods, + | Flow::ValidatePaymentMethod + | Flow::DefaultPaymentMethodsSet => Self::PaymentMethods, Flow::PmAuthLinkTokenCreate | Flow::PmAuthExchangeToken => Self::PaymentMethodAuth, diff --git a/crates/router/src/routes/payment_methods.rs b/crates/router/src/routes/payment_methods.rs index 89ca36c8c15..5469f981659 100644 --- a/crates/router/src/routes/payment_methods.rs +++ b/crates/router/src/routes/payment_methods.rs @@ -102,6 +102,12 @@ pub async fn list_customer_payment_method_api( let flow = Flow::CustomerPaymentMethodsList; let payload = query_payload.into_inner(); let customer_id = customer_id.into_inner().0; + + let ephemeral_auth = + match auth::is_ephemeral_auth(req.headers(), &*state.store, &customer_id).await { + Ok(auth) => auth, + Err(err) => return api::log_and_return_error_response(err), + }; Box::pin(api::server_wrap( flow, state, @@ -116,7 +122,7 @@ pub async fn list_customer_payment_method_api( Some(&customer_id), ) }, - &auth::ApiKeyAuth, + &*ephemeral_auth, api_locking::LockAction::NotApplicable, )) .await @@ -157,6 +163,7 @@ pub async fn list_customer_payment_method_api_client( Ok((auth, _auth_flow)) => (auth, _auth_flow), Err(e) => return api::log_and_return_error_response(e), }; + Box::pin(api::server_wrap( flow, state, @@ -252,6 +259,42 @@ pub async fn payment_method_delete_api( )) .await } + +#[instrument(skip_all, fields(flow = ?Flow::DefaultPaymentMethodsSet))] +pub async fn default_payment_method_set_api( + state: web::Data<AppState>, + req: HttpRequest, + path: web::Path<payment_methods::DefaultPaymentMethod>, +) -> HttpResponse { + let flow = Flow::DefaultPaymentMethodsSet; + let payload = path.into_inner(); + let customer_id = payload.clone().customer_id; + + let ephemeral_auth = + match auth::is_ephemeral_auth(req.headers(), &*state.store, &customer_id).await { + Ok(auth) => auth, + Err(err) => return api::log_and_return_error_response(err), + }; + Box::pin(api::server_wrap( + flow, + state, + &req, + payload, + |state, auth: auth::AuthenticationData, default_payment_method| { + cards::set_default_payment_method( + state, + auth.merchant_account, + auth.key_store, + &customer_id, + default_payment_method.payment_method_id, + ) + }, + &*ephemeral_auth, + api_locking::LockAction::NotApplicable, + )) + .await +} + #[cfg(test)] mod tests { #![allow(clippy::unwrap_used)] diff --git a/crates/router/src/types/api.rs b/crates/router/src/types/api.rs index 894b3d830dd..009033d5341 100644 --- a/crates/router/src/types/api.rs +++ b/crates/router/src/types/api.rs @@ -204,7 +204,7 @@ type BoxedConnector = Box<&'static (dyn Connector + Sync)>; // Normal flow will call the connector and follow the flow specific operations (capture, authorize) // SessionTokenFromMetadata will avoid calling the connector instead create the session token ( for sdk ) -#[derive(Clone, Eq, PartialEq)] +#[derive(Clone, Eq, PartialEq, Debug)] pub enum GetToken { GpayMetadata, ApplePayMetadata, @@ -214,7 +214,7 @@ pub enum GetToken { /// Routing algorithm will output merchant connector identifier instead of connector name /// In order to support backwards compatibility for older routing algorithms and merchant accounts /// the support for connector name is retained -#[derive(Clone)] +#[derive(Clone, Debug)] pub struct ConnectorData { pub connector: BoxedConnector, pub connector_name: types::Connector, diff --git a/crates/router/src/types/api/customers.rs b/crates/router/src/types/api/customers.rs index 32430c0918a..6f08a7fd7e4 100644 --- a/crates/router/src/types/api/customers.rs +++ b/crates/router/src/types/api/customers.rs @@ -32,6 +32,7 @@ impl From<(domain::Customer, Option<payments::AddressDetails>)> for CustomerResp created_at: cust.created_at, metadata: cust.metadata, address, + default_payment_method_id: cust.default_payment_method_id, } .into() } diff --git a/crates/router/src/types/api/payment_methods.rs b/crates/router/src/types/api/payment_methods.rs index ca852f832ee..642e94ad69e 100644 --- a/crates/router/src/types/api/payment_methods.rs +++ b/crates/router/src/types/api/payment_methods.rs @@ -1,10 +1,11 @@ pub use api_models::payment_methods::{ CardDetail, CardDetailFromLocker, CardDetailsPaymentMethod, CustomerPaymentMethod, - CustomerPaymentMethodsListResponse, DeleteTokenizeByTokenRequest, GetTokenizePayloadRequest, - GetTokenizePayloadResponse, PaymentMethodCreate, PaymentMethodDeleteResponse, PaymentMethodId, - PaymentMethodList, PaymentMethodListRequest, PaymentMethodListResponse, PaymentMethodResponse, - PaymentMethodUpdate, PaymentMethodsData, TokenizePayloadEncrypted, TokenizePayloadRequest, - TokenizedCardValue1, TokenizedCardValue2, TokenizedWalletValue1, TokenizedWalletValue2, + CustomerPaymentMethodsListResponse, DefaultPaymentMethod, DeleteTokenizeByTokenRequest, + GetTokenizePayloadRequest, GetTokenizePayloadResponse, PaymentMethodCreate, + PaymentMethodDeleteResponse, PaymentMethodId, PaymentMethodList, PaymentMethodListRequest, + PaymentMethodListResponse, PaymentMethodResponse, PaymentMethodUpdate, PaymentMethodsData, + TokenizePayloadEncrypted, TokenizePayloadRequest, TokenizedCardValue1, TokenizedCardValue2, + TokenizedWalletValue1, TokenizedWalletValue2, }; use error_stack::report; diff --git a/crates/router/src/types/domain/customer.rs b/crates/router/src/types/domain/customer.rs index fe575851dc4..5437d06a2e6 100644 --- a/crates/router/src/types/domain/customer.rs +++ b/crates/router/src/types/domain/customer.rs @@ -22,6 +22,7 @@ pub struct Customer { pub modified_at: PrimitiveDateTime, pub connector_customer: Option<serde_json::Value>, pub address_id: Option<String>, + pub default_payment_method_id: Option<String>, } #[async_trait::async_trait] @@ -45,6 +46,7 @@ impl super::behaviour::Conversion for Customer { modified_at: self.modified_at, connector_customer: self.connector_customer, address_id: self.address_id, + default_payment_method_id: self.default_payment_method_id, }) } @@ -72,6 +74,7 @@ impl super::behaviour::Conversion for Customer { modified_at: item.modified_at, connector_customer: item.connector_customer, address_id: item.address_id, + default_payment_method_id: item.default_payment_method_id, }) } .await @@ -114,6 +117,9 @@ pub enum CustomerUpdate { ConnectorCustomer { connector_customer: Option<serde_json::Value>, }, + UpdateDefaultPaymentMethod { + default_payment_method_id: Option<String>, + }, } impl From<CustomerUpdate> for CustomerUpdateInternal { @@ -138,12 +144,20 @@ impl From<CustomerUpdate> for CustomerUpdateInternal { connector_customer, modified_at: Some(date_time::now()), address_id, + ..Default::default() }, CustomerUpdate::ConnectorCustomer { connector_customer } => Self { connector_customer, modified_at: Some(common_utils::date_time::now()), ..Default::default() }, + CustomerUpdate::UpdateDefaultPaymentMethod { + default_payment_method_id, + } => Self { + default_payment_method_id, + modified_at: Some(common_utils::date_time::now()), + ..Default::default() + }, } } } diff --git a/crates/router_env/src/logger/types.rs b/crates/router_env/src/logger/types.rs index 62c09c42455..4790e60acb1 100644 --- a/crates/router_env/src/logger/types.rs +++ b/crates/router_env/src/logger/types.rs @@ -123,6 +123,8 @@ pub enum Flow { PaymentMethodsUpdate, /// Payment methods delete flow. PaymentMethodsDelete, + /// Default Payment method flow. + DefaultPaymentMethodsSet, /// Payments create flow. PaymentsCreate, /// Payments Retrieve flow. diff --git a/migrations/2024-02-21-120100_add_last_used_at_in_payment_methods/down.sql b/migrations/2024-02-21-120100_add_last_used_at_in_payment_methods/down.sql new file mode 100644 index 00000000000..fc9fc6350ed --- /dev/null +++ b/migrations/2024-02-21-120100_add_last_used_at_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 last_used_at; \ No newline at end of file diff --git a/migrations/2024-02-21-120100_add_last_used_at_in_payment_methods/up.sql b/migrations/2024-02-21-120100_add_last_used_at_in_payment_methods/up.sql new file mode 100644 index 00000000000..f1c0aab4def --- /dev/null +++ b/migrations/2024-02-21-120100_add_last_used_at_in_payment_methods/up.sql @@ -0,0 +1,2 @@ +-- Your SQL goes here +ALTER TABLE payment_methods ADD COLUMN IF NOT EXISTS last_used_at TIMESTAMP NOT NULL DEFAULT now()::TIMESTAMP; \ No newline at end of file diff --git a/migrations/2024-02-21-143530_add_default_payment_method_in_customers/down.sql b/migrations/2024-02-21-143530_add_default_payment_method_in_customers/down.sql new file mode 100644 index 00000000000..948123ce7e2 --- /dev/null +++ b/migrations/2024-02-21-143530_add_default_payment_method_in_customers/down.sql @@ -0,0 +1,2 @@ +-- This file should undo anything in `up.sql` +ALTER TABLE customers DROP COLUMN IF EXISTS default_payment_method; diff --git a/migrations/2024-02-21-143530_add_default_payment_method_in_customers/up.sql b/migrations/2024-02-21-143530_add_default_payment_method_in_customers/up.sql new file mode 100644 index 00000000000..abaeb1df718 --- /dev/null +++ b/migrations/2024-02-21-143530_add_default_payment_method_in_customers/up.sql @@ -0,0 +1,3 @@ +-- Your SQL goes here +ALTER TABLE customers +ADD COLUMN IF NOT EXISTS default_payment_method_id VARCHAR(64); \ No newline at end of file diff --git a/openapi/openapi_spec.json b/openapi/openapi_spec.json index 30e75c028d5..3fcf6bca79f 100644 --- a/openapi/openapi_spec.json +++ b/openapi/openapi_spec.json @@ -4080,6 +4080,50 @@ } ] } + }, + "/{customer_id}/payment_methods/{payment_method_id}/default": { + "get": { + "tags": [ + "Customer Set Default Payment Method" + ], + "summary": "Customers - Set Default Payment Method", + "description": "Customers - Set Default Payment Method\n\nSet the Payment Method as Default for the Customer.", + "operationId": "Set the Payment Method as Default", + "parameters": [ + { + "name": "method_id", + "in": "path", + "description": "Set the Payment Method as Default for the Customer", + "required": true, + "schema": { + "type": "string" + } + } + ], + "responses": { + "200": { + "description": "Payment Method has been set as default", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/CustomerDefaultPaymentMethodResponse" + } + } + } + }, + "400": { + "description": "Payment Method has already been set as default for that customer" + }, + "404": { + "description": "Payment Method not found for the customer" + } + }, + "security": [ + { + "ephemeral_key": [] + } + ] + } } }, "components": { @@ -7308,6 +7352,37 @@ } } }, + "CustomerDefaultPaymentMethodResponse": { + "type": "object", + "required": [ + "customer_id", + "payment_method" + ], + "properties": { + "default_payment_method_id": { + "type": "string", + "description": "The unique identifier of the Payment method", + "example": "card_rGK4Vi5iSW70MY7J2mIy", + "nullable": true + }, + "customer_id": { + "type": "string", + "description": "The unique identifier of the customer.", + "example": "cus_meowerunwiuwiwqw" + }, + "payment_method": { + "$ref": "#/components/schemas/PaymentMethod" + }, + "payment_method_type": { + "allOf": [ + { + "$ref": "#/components/schemas/PaymentMethodType" + } + ], + "nullable": true + } + } + }, "CustomerDeleteResponse": { "type": "object", "required": [ @@ -7384,11 +7459,13 @@ "type": "object", "required": [ "payment_token", + "payment_method_id", "customer_id", "payment_method", "recurring_enabled", "installment_payment_enabled", - "requires_cvv" + "requires_cvv", + "default_payment_method_set" ], "properties": { "payment_token": { @@ -7396,6 +7473,11 @@ "description": "Token for payment method in temporary card locker which gets refreshed often", "example": "7ebf443f-a050-4067-84e5-e6f6d4800aef" }, + "payment_method_id": { + "type": "string", + "description": "The unique identifier of the customer.", + "example": "pm_iouuy468iyuowqs" + }, "customer_id": { "type": "string", "description": "The unique identifier of the customer.", @@ -7495,6 +7577,18 @@ "type": "boolean", "description": "Whether this payment method requires CVV to be collected", "example": true + }, + "last_used_at": { + "type": "string", + "format": "date-time", + "description": "A timestamp (ISO 8601 code) that determines when the payment method was last used", + "example": "2024-02-24T11:04:09.922Z", + "nullable": true + }, + "default_payment_method_set": { + "type": "boolean", + "description": "Indicates if the payment method has been set to default or not", + "example": true } } }, @@ -7644,6 +7738,28 @@ "type": "object", "description": "You can specify up to 50 keys, with key names up to 40 characters long and values up to 500\ncharacters long. Metadata is useful for storing additional, structured information on an\nobject.", "nullable": true + }, + "default_payment_method_id": { + "type": "string", + "description": "The identifier for the default payment method.", + "example": "pm_djh2837dwduh890123", + "nullable": true, + "maxLength": 64 + } + } + }, + "DefaultPaymentMethod": { + "type": "object", + "required": [ + "customer_id", + "payment_method_id" + ], + "properties": { + "customer_id": { + "type": "string" + }, + "payment_method_id": { + "type": "string" } } }, @@ -11888,6 +12004,12 @@ } ], "nullable": true + }, + "last_used_at": { + "type": "string", + "format": "date-time", + "example": "2024-02-24T11:04:09.922Z", + "nullable": true } } },
2024-02-23T04:00:53Z
## Type of Change <!-- Put an `x` in the boxes that apply --> - [ ] Bugfix - [x] New feature - [ ] Enhancement - [ ] Refactoring - [ ] Dependency updates - [ ] Documentation - [ ] CI/CD ## Description - Add default payment method column in customers table and last used column in payment_methods table. - Last used would be updated depending on every payment_method usages. - And the CustomerPaymentMethodList would be sorted on the basis of last_used at. - A query param was added , to show the list on the basis of limit, i.e., if limit is 1 we will show only the 1st payment_method while doing a CustomerPaymentMethodList - CustomerPaymentMethodList Authentication from ApiKey to EphemeralKey - Made a new Api Route, `/payment_methods/{customer_id}/{payment_method_id}/default` for explicitly setting up the default payment method for a particular customer, which would require , customer_id and payment_method_id to be passed in the path - In CustomerPaymentMethodList we would show the Default Payment Method was either set or not , based on its entry in the Customer Table - Also in CustomerPaymentMethodList we would show payment_method_id now ### 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? To test `set_default_payment_method` - Create an MA and and MCA - Create an ApiKey and EphemeralKey for that particular customer - Make a payment , using one card and then do a ListCustomerPaymentMethods - > Create ``` curl --location 'http://localhost:8080/payments' \ --header 'Content-Type: application/json' \ --header 'Accept: application/json' \ --header 'api-key: dev_RHgvB0yPOTVA4xK4zTjXzxrnSVmnXlJz80hnEHIocTKplSc6sYqwRu2yHD8iJyuA' \ --data-raw ' {"amount": 6540, "currency": "USD", "confirm": false, "capture_method": "automatic", "authentication_type": "no_three_ds", "customer_id": "7cc", "email": "something@gmail.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" } }, "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" } }, "metadata": { "order_details": { "product_name": "Apple iphone 15", "quantity": 1 } }, "business_country": "US", "business_label": "default", "setup_future_usage": "on_session" }' ``` -> Confirm ``` curl --location 'http://localhost:8080/payments/pay_nIQnyrfS15jQja2OocCX/confirm' \ --header 'Content-Type: application/json' \ --header 'Accept: application/json' \ --header 'api-key: dev_RHgvB0yPOTVA4xK4zTjXzxrnSVmnXlJz80hnEHIocTKplSc6sYqwRu2yHD8iJyuA' \ --data '{ "confirm": true, "payment_type": "normal", "setup_future_usage":"on_session", "payment_method": "card", "payment_method_type": "debit", "payment_method_data": { "card": { "card_number": "4111111111111111", "card_exp_month": "11", "card_exp_year": "2040", "card_holder_name": "AKA", "card_cvc": "123", "nick_name": "HELO" } } }' ``` - The `default_payment_method` would be false , there also will be `payment_method_id` field (refer the screenshots below) - The following curl can be used to set the particular payment_method as default, the ``` curl --location --request POST 'http://localhost:8080/customers/{customer_id}/payment_methods/{payment_method_id}/set' \ --header 'Accept: application/json' \ --header 'api-key: epk_bf2209db8af14c04b811bce74e0d1202' ``` - do a ListCustomerPaymentMethods, The `default_payment_method` would be true To test `last_used_at` - Create an MA and and MCA - Create an ApiKey and EphemeralKey for that particular customer - Make a payment , using one card and then do a ListCustomerPaymentMethods - > Create ``` curl --location 'http://localhost:8080/payments' \ --header 'Content-Type: application/json' \ --header 'Accept: application/json' \ --header 'api-key: dev_RHgvB0yPOTVA4xK4zTjXzxrnSVmnXlJz80hnEHIocTKplSc6sYqwRu2yHD8iJyuA' \ --data-raw ' {"amount": 6540, "currency": "USD", "confirm": false, "capture_method": "automatic", "authentication_type": "no_three_ds", "customer_id": "7cc", "email": "something@gmail.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" } }, "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" } }, "metadata": { "order_details": { "product_name": "Apple iphone 15", "quantity": 1 } }, "business_country": "US", "business_label": "default", "setup_future_usage": "on_session" }' ``` -> Confirm ``` curl --location 'http://localhost:8080/payments/pay_nIQnyrfS15jQja2OocCX/confirm' \ --header 'Content-Type: application/json' \ --header 'Accept: application/json' \ --header 'api-key: dev_RHgvB0yPOTVA4xK4zTjXzxrnSVmnXlJz80hnEHIocTKplSc6sYqwRu2yHD8iJyuA' \ --data '{ "confirm": true, "payment_type": "normal", "setup_future_usage":"on_session", "payment_method": "card", "payment_method_type": "debit", "payment_method_data": { "card": { "card_number": "4111111111111111", "card_exp_month": "11", "card_exp_year": "2040", "card_holder_name": "AKA", "card_cvc": "123", "nick_name": "HELO" } } }' ``` - The last_used_at field would show the current timestamp - Make a payment , using another card and then do a ListCustomerPaymentMethods - > Create ``` curl --location 'http://localhost:8080/payments' \ --header 'Content-Type: application/json' \ --header 'Accept: application/json' \ --header 'api-key: dev_RHgvB0yPOTVA4xK4zTjXzxrnSVmnXlJz80hnEHIocTKplSc6sYqwRu2yHD8iJyuA' \ --data-raw ' {"amount": 6540, "currency": "USD", "confirm": false, "capture_method": "automatic", "authentication_type": "no_three_ds", "customer_id": "7cc", "email": "something@gmail.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" } }, "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" } }, "metadata": { "order_details": { "product_name": "Apple iphone 15", "quantity": 1 } }, "business_country": "US", "business_label": "default", "setup_future_usage": "on_session" }' ``` -> Confirm ``` curl --location 'http://localhost:8080/payments/pay_nIQnyrfS15jQja2OocCX/confirm' \ --header 'Content-Type: application/json' \ --header 'Accept: application/json' \ --header 'api-key: dev_RHgvB0yPOTVA4xK4zTjXzxrnSVmnXlJz80hnEHIocTKplSc6sYqwRu2yHD8iJyuA' \ --data '{ "confirm": true, "payment_type": "normal", "setup_future_usage":"on_session", "payment_method": "card", "payment_method_type": "debit", "payment_method_data": { "card": { "card_number": "4242424242424242", "card_exp_month": "11", "card_exp_year": "2040", "card_holder_name": "AKA", "card_cvc": "123", "nick_name": "HELO" } } }' ``` - The last_used_at field would show the current timestamp - Do The list customer and then select a payment_token of the last card - Make a payment using the `payment_token` - The last_used_at field would show the current timestamp, and would be sorted in the order that PaymentMethod was used at - The following curl can be used to list the customer payment methods with a limit , the limit if set as 1 would show the last used payment method ``` curl --location 'http://localhost:8080/customers/{customer_id}/payment_methods?limit=1' \ --header 'Accept: application/json' \ --header 'api-key: dev_OS3aZUsCeqV3eTW2Nlaba7yThKEUAZGXlEysuL15ZIoPP0McJ4YB9zRr9mWc9NFW' ``` ![image](https://github.com/juspay/hyperswitch/assets/55580080/9597cd08-bf23-4fea-978c-fecae7e5c848) <img width="1728" alt="Screenshot 2024-02-26 at 4 42 43 PM" src="https://github.com/juspay/hyperswitch/assets/55580080/64231527-bce6-4483-9997-b0cfb0669733"> ![Screenshot 2024-02-26 at 4 11 50 PM](https://github.com/juspay/hyperswitch/assets/55580080/0618a89e-e6ae-43d1-911c-f46e365f38c3) ![image](https://github.com/juspay/hyperswitch/assets/55580080/c07d3f76-863e-4beb-a897-06de49390c63) ## 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 - [ ] I added a [CHANGELOG](/CHANGELOG.md) entry if applicable
f4d0e2b441a25048186be4b9d0871e2473a6f357
To test `set_default_payment_method` - Create an MA and and MCA - Create an ApiKey and EphemeralKey for that particular customer - Make a payment , using one card and then do a ListCustomerPaymentMethods - > Create ``` curl --location 'http://localhost:8080/payments' \ --header 'Content-Type: application/json' \ --header 'Accept: application/json' \ --header 'api-key: dev_RHgvB0yPOTVA4xK4zTjXzxrnSVmnXlJz80hnEHIocTKplSc6sYqwRu2yHD8iJyuA' \ --data-raw ' {"amount": 6540, "currency": "USD", "confirm": false, "capture_method": "automatic", "authentication_type": "no_three_ds", "customer_id": "7cc", "email": "something@gmail.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" } }, "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" } }, "metadata": { "order_details": { "product_name": "Apple iphone 15", "quantity": 1 } }, "business_country": "US", "business_label": "default", "setup_future_usage": "on_session" }' ``` -> Confirm ``` curl --location 'http://localhost:8080/payments/pay_nIQnyrfS15jQja2OocCX/confirm' \ --header 'Content-Type: application/json' \ --header 'Accept: application/json' \ --header 'api-key: dev_RHgvB0yPOTVA4xK4zTjXzxrnSVmnXlJz80hnEHIocTKplSc6sYqwRu2yHD8iJyuA' \ --data '{ "confirm": true, "payment_type": "normal", "setup_future_usage":"on_session", "payment_method": "card", "payment_method_type": "debit", "payment_method_data": { "card": { "card_number": "4111111111111111", "card_exp_month": "11", "card_exp_year": "2040", "card_holder_name": "AKA", "card_cvc": "123", "nick_name": "HELO" } } }' ``` - The `default_payment_method` would be false , there also will be `payment_method_id` field (refer the screenshots below) - The following curl can be used to set the particular payment_method as default, the ``` curl --location --request POST 'http://localhost:8080/customers/{customer_id}/payment_methods/{payment_method_id}/set' \ --header 'Accept: application/json' \ --header 'api-key: epk_bf2209db8af14c04b811bce74e0d1202' ``` - do a ListCustomerPaymentMethods, The `default_payment_method` would be true To test `last_used_at` - Create an MA and and MCA - Create an ApiKey and EphemeralKey for that particular customer - Make a payment , using one card and then do a ListCustomerPaymentMethods - > Create ``` curl --location 'http://localhost:8080/payments' \ --header 'Content-Type: application/json' \ --header 'Accept: application/json' \ --header 'api-key: dev_RHgvB0yPOTVA4xK4zTjXzxrnSVmnXlJz80hnEHIocTKplSc6sYqwRu2yHD8iJyuA' \ --data-raw ' {"amount": 6540, "currency": "USD", "confirm": false, "capture_method": "automatic", "authentication_type": "no_three_ds", "customer_id": "7cc", "email": "something@gmail.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" } }, "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" } }, "metadata": { "order_details": { "product_name": "Apple iphone 15", "quantity": 1 } }, "business_country": "US", "business_label": "default", "setup_future_usage": "on_session" }' ``` -> Confirm ``` curl --location 'http://localhost:8080/payments/pay_nIQnyrfS15jQja2OocCX/confirm' \ --header 'Content-Type: application/json' \ --header 'Accept: application/json' \ --header 'api-key: dev_RHgvB0yPOTVA4xK4zTjXzxrnSVmnXlJz80hnEHIocTKplSc6sYqwRu2yHD8iJyuA' \ --data '{ "confirm": true, "payment_type": "normal", "setup_future_usage":"on_session", "payment_method": "card", "payment_method_type": "debit", "payment_method_data": { "card": { "card_number": "4111111111111111", "card_exp_month": "11", "card_exp_year": "2040", "card_holder_name": "AKA", "card_cvc": "123", "nick_name": "HELO" } } }' ``` - The last_used_at field would show the current timestamp - Make a payment , using another card and then do a ListCustomerPaymentMethods - > Create ``` curl --location 'http://localhost:8080/payments' \ --header 'Content-Type: application/json' \ --header 'Accept: application/json' \ --header 'api-key: dev_RHgvB0yPOTVA4xK4zTjXzxrnSVmnXlJz80hnEHIocTKplSc6sYqwRu2yHD8iJyuA' \ --data-raw ' {"amount": 6540, "currency": "USD", "confirm": false, "capture_method": "automatic", "authentication_type": "no_three_ds", "customer_id": "7cc", "email": "something@gmail.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" } }, "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" } }, "metadata": { "order_details": { "product_name": "Apple iphone 15", "quantity": 1 } }, "business_country": "US", "business_label": "default", "setup_future_usage": "on_session" }' ``` -> Confirm ``` curl --location 'http://localhost:8080/payments/pay_nIQnyrfS15jQja2OocCX/confirm' \ --header 'Content-Type: application/json' \ --header 'Accept: application/json' \ --header 'api-key: dev_RHgvB0yPOTVA4xK4zTjXzxrnSVmnXlJz80hnEHIocTKplSc6sYqwRu2yHD8iJyuA' \ --data '{ "confirm": true, "payment_type": "normal", "setup_future_usage":"on_session", "payment_method": "card", "payment_method_type": "debit", "payment_method_data": { "card": { "card_number": "4242424242424242", "card_exp_month": "11", "card_exp_year": "2040", "card_holder_name": "AKA", "card_cvc": "123", "nick_name": "HELO" } } }' ``` - The last_used_at field would show the current timestamp - Do The list customer and then select a payment_token of the last card - Make a payment using the `payment_token` - The last_used_at field would show the current timestamp, and would be sorted in the order that PaymentMethod was used at - The following curl can be used to list the customer payment methods with a limit , the limit if set as 1 would show the last used payment method ``` curl --location 'http://localhost:8080/customers/{customer_id}/payment_methods?limit=1' \ --header 'Accept: application/json' \ --header 'api-key: dev_OS3aZUsCeqV3eTW2Nlaba7yThKEUAZGXlEysuL15ZIoPP0McJ4YB9zRr9mWc9NFW' ``` ![image](https://github.com/juspay/hyperswitch/assets/55580080/9597cd08-bf23-4fea-978c-fecae7e5c848) <img width="1728" alt="Screenshot 2024-02-26 at 4 42 43 PM" src="https://github.com/juspay/hyperswitch/assets/55580080/64231527-bce6-4483-9997-b0cfb0669733"> ![Screenshot 2024-02-26 at 4 11 50 PM](https://github.com/juspay/hyperswitch/assets/55580080/0618a89e-e6ae-43d1-911c-f46e365f38c3) ![image](https://github.com/juspay/hyperswitch/assets/55580080/c07d3f76-863e-4beb-a897-06de49390c63)
juspay/hyperswitch
juspay__hyperswitch-3739
Bug: Support Default Payment Method for customer Add support for having a default payment method option for a customer. This can be used to increase conversion rates by using the preferred saved payment method for payments, reducing the friction. Solution: - Customers table to have a column for 'default_payment_method' - API to set and retrieve the default PM for a customer - If default has not been set, use the `last_used` PM as the default - Customer Payment Method List to indicate the default PM
diff --git a/config/development.toml b/config/development.toml index d69719bd419..59d73a4b8b2 100644 --- a/config/development.toml +++ b/config/development.toml @@ -71,7 +71,6 @@ mock_locker = true basilisk_host = "" locker_enabled = true - [forex_api] call_delay = 21600 local_fetch_retry_count = 5 diff --git a/crates/api_models/src/customers.rs b/crates/api_models/src/customers.rs index d8c864746a8..eeb10e62286 100644 --- a/crates/api_models/src/customers.rs +++ b/crates/api_models/src/customers.rs @@ -73,6 +73,9 @@ pub struct CustomerResponse { /// object. #[schema(value_type = Option<Object>,example = json!({ "city": "NY", "unit": "245" }))] pub metadata: Option<pii::SecretSerdeValue>, + /// The identifier for the default payment method. + #[schema(max_length = 64, example = "pm_djh2837dwduh890123")] + pub default_payment_method_id: Option<String>, } #[derive(Default, Clone, Debug, Deserialize, Serialize)] diff --git a/crates/api_models/src/events/payment.rs b/crates/api_models/src/events/payment.rs index 32d3dc30bd8..92f69933900 100644 --- a/crates/api_models/src/events/payment.rs +++ b/crates/api_models/src/events/payment.rs @@ -2,7 +2,8 @@ use common_utils::events::{ApiEventMetric, ApiEventsType}; use crate::{ payment_methods::{ - CustomerPaymentMethodsListResponse, PaymentMethodDeleteResponse, PaymentMethodListRequest, + CustomerDefaultPaymentMethodResponse, CustomerPaymentMethodsListResponse, + DefaultPaymentMethod, PaymentMethodDeleteResponse, PaymentMethodListRequest, PaymentMethodListResponse, PaymentMethodResponse, PaymentMethodUpdate, }, payments::{ @@ -95,6 +96,16 @@ impl ApiEventMetric for PaymentMethodResponse { impl ApiEventMetric for PaymentMethodUpdate {} +impl ApiEventMetric for DefaultPaymentMethod { + fn get_api_event_type(&self) -> Option<ApiEventsType> { + Some(ApiEventsType::PaymentMethod { + payment_method_id: self.payment_method_id.clone(), + payment_method: None, + payment_method_type: None, + }) + } +} + impl ApiEventMetric for PaymentMethodDeleteResponse { fn get_api_event_type(&self) -> Option<ApiEventsType> { Some(ApiEventsType::PaymentMethod { @@ -121,6 +132,16 @@ impl ApiEventMetric for PaymentMethodListRequest { impl ApiEventMetric for PaymentMethodListResponse {} +impl ApiEventMetric for CustomerDefaultPaymentMethodResponse { + fn get_api_event_type(&self) -> Option<ApiEventsType> { + Some(ApiEventsType::PaymentMethod { + payment_method_id: self.default_payment_method_id.clone().unwrap_or_default(), + payment_method: Some(self.payment_method), + payment_method_type: self.payment_method_type, + }) + } +} + impl ApiEventMetric for PaymentListFilterConstraints { fn get_api_event_type(&self) -> Option<ApiEventsType> { Some(ApiEventsType::ResourceListAPI) diff --git a/crates/api_models/src/payment_methods.rs b/crates/api_models/src/payment_methods.rs index 83e1a2c4887..35193b958f2 100644 --- a/crates/api_models/src/payment_methods.rs +++ b/crates/api_models/src/payment_methods.rs @@ -185,6 +185,10 @@ pub struct PaymentMethodResponse { #[cfg(feature = "payouts")] #[schema(value_type = Option<Bank>)] pub bank_transfer: Option<payouts::Bank>, + + #[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>, } #[derive(Clone, Debug, Eq, PartialEq, serde::Deserialize, serde::Serialize)] @@ -550,6 +554,10 @@ pub struct PaymentMethodListRequest { /// 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>, } impl<'de> serde::Deserialize<'de> for PaymentMethodListRequest { @@ -618,6 +626,9 @@ impl<'de> serde::Deserialize<'de> for PaymentMethodListRequest { 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()?)?; + } _ => {} } } @@ -731,12 +742,30 @@ pub struct PaymentMethodDeleteResponse { #[schema(example = true)] pub deleted: bool, } +#[derive(Debug, serde::Serialize, ToSchema)] +pub struct CustomerDefaultPaymentMethodResponse { + /// The unique identifier of the Payment method + #[schema(example = "card_rGK4Vi5iSW70MY7J2mIy")] + pub default_payment_method_id: Option<String>, + /// The unique identifier of the customer. + #[schema(example = "cus_meowerunwiuwiwqw")] + pub customer_id: String, + /// The type of payment method use for the payment. + #[schema(value_type = PaymentMethod,example = "card")] + pub payment_method: api_enums::PaymentMethod, + /// This is a sub-category of payment method. + #[schema(value_type = Option<PaymentMethodType>,example = "credit")] + pub payment_method_type: Option<api_enums::PaymentMethodType>, +} #[derive(Debug, Clone, serde::Serialize, ToSchema)] pub struct CustomerPaymentMethod { /// Token for payment method in temporary card locker which gets refreshed often #[schema(example = "7ebf443f-a050-4067-84e5-e6f6d4800aef")] pub payment_token: String, + /// The unique identifier of the customer. + #[schema(example = "pm_iouuy468iyuowqs")] + pub payment_method_id: String, /// The unique identifier of the customer. #[schema(example = "cus_meowerunwiuwiwqw")] @@ -798,6 +827,14 @@ pub struct CustomerPaymentMethod { /// Whether this payment method requires CVV to be collected #[schema(example = true)] pub requires_cvv: bool, + + /// A timestamp (ISO 8601 code) that determines when the payment method was last used + #[schema(value_type = Option<PrimitiveDateTime>,example = "2024-02-24T11:04:09.922Z")] + #[serde(default, with = "common_utils::custom_serde::iso8601::option")] + pub last_used_at: Option<time::PrimitiveDateTime>, + /// Indicates if the payment method has been set to default or not + #[schema(example = true)] + pub default_payment_method_set: bool, } #[derive(Debug, Clone, serde::Serialize, serde::Deserialize, ToSchema)] @@ -810,6 +847,11 @@ pub struct PaymentMethodId { pub payment_method_id: String, } +#[derive(Debug, serde::Serialize, serde::Deserialize, Clone, ToSchema)] +pub struct DefaultPaymentMethod { + pub customer_id: String, + pub payment_method_id: String, +} //------------------------------------------------TokenizeService------------------------------------------------ #[derive(Debug, serde::Serialize, serde::Deserialize)] pub struct TokenizePayloadEncrypted { diff --git a/crates/diesel_models/src/customers.rs b/crates/diesel_models/src/customers.rs index c0cebba7755..cefb0c240ec 100644 --- a/crates/diesel_models/src/customers.rs +++ b/crates/diesel_models/src/customers.rs @@ -37,6 +37,7 @@ pub struct Customer { pub connector_customer: Option<serde_json::Value>, pub modified_at: PrimitiveDateTime, pub address_id: Option<String>, + pub default_payment_method_id: Option<String>, } #[derive(Clone, Debug, Default, AsChangeset, router_derive::DebugAsDisplay)] @@ -51,4 +52,5 @@ pub struct CustomerUpdateInternal { pub modified_at: Option<PrimitiveDateTime>, pub connector_customer: Option<serde_json::Value>, pub address_id: Option<String>, + pub default_payment_method_id: Option<String>, } diff --git a/crates/diesel_models/src/payment_method.rs b/crates/diesel_models/src/payment_method.rs index 09be739581e..6191a768efe 100644 --- a/crates/diesel_models/src/payment_method.rs +++ b/crates/diesel_models/src/payment_method.rs @@ -34,12 +34,13 @@ pub struct PaymentMethod { 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<serde_json::Value>, pub customer_acceptance: Option<pii::SecretSerdeValue>, pub status: storage_enums::PaymentMethodStatus, } -#[derive(Clone, Debug, Eq, PartialEq, Insertable, Queryable, router_derive::DebugAsDisplay)] +#[derive(Clone, Debug, Eq, PartialEq, Insertable, router_derive::DebugAsDisplay)] #[diesel(table_name = payment_methods)] pub struct PaymentMethodNew { pub customer_id: String, @@ -64,6 +65,7 @@ pub struct PaymentMethodNew { 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<serde_json::Value>, pub customer_acceptance: Option<pii::SecretSerdeValue>, pub status: storage_enums::PaymentMethodStatus, @@ -96,6 +98,7 @@ impl Default for PaymentMethodNew { last_modified: now, metadata: Option::default(), payment_method_data: Option::default(), + last_used_at: now, connector_mandate_details: Option::default(), customer_acceptance: Option::default(), status: storage_enums::PaymentMethodStatus::Active, @@ -117,6 +120,9 @@ pub enum PaymentMethodUpdate { PaymentMethodDataUpdate { payment_method_data: Option<Encryption>, }, + LastUsedUpdate { + last_used_at: PrimitiveDateTime, + }, } #[derive(Clone, Debug, Default, AsChangeset, router_derive::DebugAsDisplay)] @@ -124,6 +130,7 @@ pub enum PaymentMethodUpdate { pub struct PaymentMethodUpdateInternal { metadata: Option<serde_json::Value>, payment_method_data: Option<Encryption>, + last_used_at: Option<PrimitiveDateTime>, } impl PaymentMethodUpdateInternal { @@ -140,12 +147,19 @@ impl From<PaymentMethodUpdate> for PaymentMethodUpdateInternal { PaymentMethodUpdate::MetadataUpdate { metadata } => Self { metadata, payment_method_data: None, + last_used_at: None, }, PaymentMethodUpdate::PaymentMethodDataUpdate { payment_method_data, } => Self { metadata: None, payment_method_data, + last_used_at: None, + }, + PaymentMethodUpdate::LastUsedUpdate { last_used_at } => Self { + metadata: None, + payment_method_data: None, + last_used_at: Some(last_used_at), }, } } diff --git a/crates/diesel_models/src/query/payment_method.rs b/crates/diesel_models/src/query/payment_method.rs index aa227962760..e3f2e511378 100644 --- a/crates/diesel_models/src/query/payment_method.rs +++ b/crates/diesel_models/src/query/payment_method.rs @@ -90,20 +90,16 @@ impl PaymentMethod { conn: &PgPooledConn, customer_id: &str, merchant_id: &str, + limit: Option<i64>, ) -> StorageResult<Vec<Self>> { - generics::generic_filter::< - <Self as HasTable>::Table, - _, - <<Self as HasTable>::Table as Table>::PrimaryKey, - _, - >( + 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())), + limit, None, - None, - None, + Some(dsl::last_used_at.desc()), ) .await } @@ -114,21 +110,17 @@ impl PaymentMethod { customer_id: &str, merchant_id: &str, status: storage_enums::PaymentMethodStatus, + limit: Option<i64>, ) -> StorageResult<Vec<Self>> { - generics::generic_filter::< - <Self as HasTable>::Table, - _, - <<Self as HasTable>::Table as Table>::PrimaryKey, - _, - >( + 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, - None, - None, + Some(dsl::last_used_at.desc()), ) .await } diff --git a/crates/diesel_models/src/schema.rs b/crates/diesel_models/src/schema.rs index f3c6f23e086..97ef8b974dc 100644 --- a/crates/diesel_models/src/schema.rs +++ b/crates/diesel_models/src/schema.rs @@ -227,6 +227,8 @@ diesel::table! { modified_at -> Timestamp, #[max_length = 64] address_id -> Nullable<Varchar>, + #[max_length = 64] + default_payment_method_id -> Nullable<Varchar>, } } @@ -831,6 +833,7 @@ diesel::table! { payment_method_data -> Nullable<Bytea>, #[max_length = 64] locker_id -> Nullable<Varchar>, + last_used_at -> Timestamp, connector_mandate_details -> Nullable<Jsonb>, customer_acceptance -> Nullable<Jsonb>, #[max_length = 64] diff --git a/crates/openapi/src/openapi.rs b/crates/openapi/src/openapi.rs index ef573093be5..e21797d2eef 100644 --- a/crates/openapi/src/openapi.rs +++ b/crates/openapi/src/openapi.rs @@ -115,6 +115,7 @@ Never share your secret api keys. Keep them guarded and secure. routes::customers::customers_update, routes::customers::customers_delete, routes::customers::customers_mandates_list, + routes::customers::default_payment_method_set_api, //Routes for payment methods routes::payment_method::create_payment_method_api, @@ -188,6 +189,7 @@ Never share your secret api keys. Keep them guarded and secure. api_models::payment_methods::CustomerPaymentMethodsListResponse, api_models::payment_methods::PaymentMethodDeleteResponse, api_models::payment_methods::PaymentMethodUpdate, + api_models::payment_methods::CustomerDefaultPaymentMethodResponse, api_models::payment_methods::CardDetailFromLocker, api_models::payment_methods::CardDetail, api_models::payment_methods::RequestPaymentMethodTypes, @@ -374,6 +376,7 @@ Never share your secret api keys. Keep them guarded and secure. api_models::payments::BrowserInformation, api_models::payments::PaymentCreatePaymentLinkConfig, api_models::payment_methods::RequiredFieldInfo, + api_models::payment_methods::DefaultPaymentMethod, api_models::payment_methods::MaskedBankDetails, api_models::payment_methods::SurchargeDetailsResponse, api_models::payment_methods::SurchargeResponse, diff --git a/crates/openapi/src/routes/customers.rs b/crates/openapi/src/routes/customers.rs index 19901cbbeb9..6011621fc13 100644 --- a/crates/openapi/src/routes/customers.rs +++ b/crates/openapi/src/routes/customers.rs @@ -116,3 +116,23 @@ pub async fn customers_list() {} security(("api_key" = [])) )] pub async fn customers_mandates_list() {} + +/// Customers - Set Default Payment Method +/// +/// Set the Payment Method as Default for the Customer. +#[utoipa::path( + get, + path = "/{customer_id}/payment_methods/{payment_method_id}/default", + params ( + ("method_id" = String, Path, description = "Set the Payment Method as Default for the Customer"), + ), + responses( + (status = 200, description = "Payment Method has been set as default", body =CustomerDefaultPaymentMethodResponse ), + (status = 400, description = "Payment Method has already been set as default for that customer"), + (status = 404, description = "Payment Method not found for the customer") + ), + tag = "Customer Set Default Payment Method", + operation_id = "Set the Payment Method as Default", + security(("ephemeral_key" = [])) +)] +pub async fn default_payment_method_set_api() {} diff --git a/crates/router/src/core/customers.rs b/crates/router/src/core/customers.rs index 521e3a22166..02127efe6de 100644 --- a/crates/router/src/core/customers.rs +++ b/crates/router/src/core/customers.rs @@ -108,6 +108,7 @@ pub async fn create_customer( address_id: address.clone().map(|addr| addr.address_id), created_at: common_utils::date_time::now(), modified_at: common_utils::date_time::now(), + default_payment_method_id: None, }) } .await @@ -208,6 +209,7 @@ pub async fn delete_customer( .find_payment_method_by_customer_id_merchant_id_list( &req.customer_id, &merchant_account.merchant_id, + None, ) .await { diff --git a/crates/router/src/core/locker_migration.rs b/crates/router/src/core/locker_migration.rs index 1347bb8ffd0..c5ddb1ed6bb 100644 --- a/crates/router/src/core/locker_migration.rs +++ b/crates/router/src/core/locker_migration.rs @@ -43,7 +43,11 @@ pub async fn rust_locker_migration( for customer in domain_customers { let result = db - .find_payment_method_by_customer_id_merchant_id_list(&customer.customer_id, merchant_id) + .find_payment_method_by_customer_id_merchant_id_list( + &customer.customer_id, + merchant_id, + None, + ) .change_context(errors::ApiErrorResponse::InternalServerError) .and_then(|pm| { call_to_locker( diff --git a/crates/router/src/core/payment_methods.rs b/crates/router/src/core/payment_methods.rs index bdbd9b02d9e..df1fb1e358d 100644 --- a/crates/router/src/core/payment_methods.rs +++ b/crates/router/src/core/payment_methods.rs @@ -156,6 +156,10 @@ impl PaymentMethodRetrieve for Oss { helpers::retrieve_card_with_permanent_token( state, card_token.locker_id.as_ref().unwrap_or(&card_token.token), + card_token + .payment_method_id + .as_ref() + .unwrap_or(&card_token.token), payment_intent, card_token_data, ) @@ -167,6 +171,10 @@ impl PaymentMethodRetrieve for Oss { helpers::retrieve_card_with_permanent_token( state, card_token.locker_id.as_ref().unwrap_or(&card_token.token), + card_token + .payment_method_id + .as_ref() + .unwrap_or(&card_token.token), payment_intent, card_token_data, ) diff --git a/crates/router/src/core/payment_methods/cards.rs b/crates/router/src/core/payment_methods/cards.rs index a92215936a0..8c00938cadc 100644 --- a/crates/router/src/core/payment_methods/cards.rs +++ b/crates/router/src/core/payment_methods/cards.rs @@ -7,8 +7,9 @@ use api_models::{ admin::{self, PaymentMethodsEnabled}, enums::{self as api_enums}, payment_methods::{ - BankAccountConnectorDetails, CardDetailsPaymentMethod, CardNetworkTypes, MaskedBankDetails, - PaymentExperienceTypes, PaymentMethodsData, RequestPaymentMethodTypes, RequiredFieldInfo, + BankAccountConnectorDetails, CardDetailsPaymentMethod, CardNetworkTypes, + CustomerDefaultPaymentMethodResponse, MaskedBankDetails, PaymentExperienceTypes, + PaymentMethodsData, RequestPaymentMethodTypes, RequiredFieldInfo, ResponsePaymentMethodIntermediate, ResponsePaymentMethodTypes, ResponsePaymentMethodsEnabled, }, @@ -25,6 +26,7 @@ use diesel_models::{ business_profile::BusinessProfile, encryption::Encryption, enums as storage_enums, payment_method, }; +use domain::CustomerUpdate; use error_stack::{report, IntoReport, ResultExt}; use masking::Secret; use router_env::{instrument, tracing}; @@ -128,11 +130,12 @@ pub fn store_default_payment_method( created: Some(common_utils::date_time::now()), recurring_enabled: false, //[#219] installment_payment_enabled: false, //[#219] - payment_experience: Some(vec![api_models::enums::PaymentExperience::RedirectToUrl]), //[#219] + payment_experience: Some(vec![api_models::enums::PaymentExperience::RedirectToUrl]), + last_used_at: Some(common_utils::date_time::now()), }; + (payment_method_response, None) } - #[instrument(skip_all)] pub async fn get_or_insert_payment_method( db: &dyn db::StorageInterface, @@ -2584,6 +2587,8 @@ pub async fn do_list_customer_pm_fetch_customer_if_not_passed( customer_id: Option<&str>, ) -> errors::RouterResponse<api::CustomerPaymentMethodsListResponse> { let db = state.store.as_ref(); + let limit = req.clone().and_then(|pml_req| pml_req.limit); + if let Some(customer_id) = customer_id { Box::pin(list_customer_payment_method( &state, @@ -2591,6 +2596,7 @@ pub async fn do_list_customer_pm_fetch_customer_if_not_passed( key_store, None, customer_id, + limit, )) .await } else { @@ -2614,6 +2620,7 @@ pub async fn do_list_customer_pm_fetch_customer_if_not_passed( key_store, payment_intent, &customer_id, + limit, )) .await } @@ -2634,6 +2641,7 @@ pub async fn list_customer_payment_method( key_store: domain::MerchantKeyStore, payment_intent: Option<storage::PaymentIntent>, customer_id: &str, + limit: Option<i64>, ) -> errors::RouterResponse<api::CustomerPaymentMethodsListResponse> { let db = &*state.store; @@ -2645,13 +2653,14 @@ pub async fn list_customer_payment_method( } }; - db.find_customer_by_customer_id_merchant_id( - customer_id, - &merchant_account.merchant_id, - &key_store, - ) - .await - .to_not_found_response(errors::ApiErrorResponse::CustomerNotFound)?; + let customer = db + .find_customer_by_customer_id_merchant_id( + customer_id, + &merchant_account.merchant_id, + &key_store, + ) + .await + .to_not_found_response(errors::ApiErrorResponse::CustomerNotFound)?; let key = key_store.key.get_inner().peek(); @@ -2671,6 +2680,7 @@ pub async fn list_customer_payment_method( customer_id, &merchant_account.merchant_id, common_enums::PaymentMethodStatus::Active, + limit, ) .await .to_not_found_response(errors::ApiErrorResponse::PaymentMethodNotFound)?; @@ -2758,6 +2768,7 @@ pub async fn list_customer_payment_method( let pma = api::CustomerPaymentMethod { payment_token: parent_payment_method_token.to_owned(), + payment_method_id: pm.payment_method_id.clone(), customer_id: pm.customer_id, payment_method: pm.payment_method, payment_method_type: pm.payment_method_type, @@ -2773,6 +2784,9 @@ pub async fn list_customer_payment_method( bank: bank_details, surcharge_details: None, requires_cvv, + last_used_at: Some(pm.last_used_at), + default_payment_method_set: customer.default_payment_method_id.is_some() + && customer.default_payment_method_id == Some(pm.payment_method_id), }; customer_pms.push(pma.to_owned()); @@ -3059,7 +3073,96 @@ async fn get_bank_account_connector_details( None => Ok(None), } } +pub async fn set_default_payment_method( + state: routes::AppState, + merchant_account: domain::MerchantAccount, + key_store: domain::MerchantKeyStore, + customer_id: &str, + payment_method_id: String, +) -> errors::RouterResponse<CustomerDefaultPaymentMethodResponse> { + let db = &*state.store; + //check for the customer + let customer = db + .find_customer_by_customer_id_merchant_id( + customer_id, + &merchant_account.merchant_id, + &key_store, + ) + .await + .to_not_found_response(errors::ApiErrorResponse::CustomerNotFound)?; + // check for the presence of payment_method + let payment_method = db + .find_payment_method(&payment_method_id) + .await + .to_not_found_response(errors::ApiErrorResponse::PaymentMethodNotFound)?; + utils::when( + payment_method.customer_id != customer_id + && payment_method.merchant_id != merchant_account.merchant_id, + || { + Err(errors::ApiErrorResponse::PreconditionFailed { + message: "The payment_method_id is not valid".to_string(), + }) + .into_report() + }, + )?; + + utils::when( + Some(payment_method_id.clone()) == customer.default_payment_method_id, + || { + Err(errors::ApiErrorResponse::PreconditionFailed { + message: "Payment Method is already set as default".to_string(), + }) + .into_report() + }, + )?; + + let customer_update = CustomerUpdate::UpdateDefaultPaymentMethod { + default_payment_method_id: Some(payment_method_id.clone()), + }; + + // update the db with the default payment method id + let updated_customer_details = db + .update_customer_by_customer_id_merchant_id( + customer_id.to_owned(), + merchant_account.merchant_id, + customer_update, + &key_store, + ) + .await + .change_context(errors::ApiErrorResponse::InternalServerError) + .attach_printable("Failed to update the default payment method id for the customer")?; + let resp = CustomerDefaultPaymentMethodResponse { + default_payment_method_id: updated_customer_details.default_payment_method_id, + customer_id: customer.customer_id, + payment_method_type: payment_method.payment_method_type, + payment_method: payment_method.payment_method, + }; + + Ok(services::ApplicationResponse::Json(resp)) +} + +pub async fn update_last_used_at( + pm_id: &str, + state: &routes::AppState, +) -> errors::RouterResult<()> { + let update_last_used = storage::PaymentMethodUpdate::LastUsedUpdate { + last_used_at: common_utils::date_time::now(), + }; + let payment_method = state + .store + .find_payment_method(pm_id) + .await + .to_not_found_response(errors::ApiErrorResponse::PaymentMethodNotFound)?; + state + .store + .update_payment_method(payment_method, update_last_used) + .await + .change_context(errors::ApiErrorResponse::InternalServerError) + .attach_printable("Failed to update the last_used_at in db")?; + + Ok(()) +} #[cfg(feature = "payouts")] pub async fn get_bank_from_hs_locker( state: &routes::AppState, @@ -3243,9 +3346,10 @@ pub async fn retrieve_payment_method( card, metadata: pm.metadata, created: Some(pm.created_at), - recurring_enabled: false, //[#219] - installment_payment_enabled: false, //[#219] - payment_experience: Some(vec![api_models::enums::PaymentExperience::RedirectToUrl]), //[#219], + recurring_enabled: false, + installment_payment_enabled: false, + payment_experience: Some(vec![api_models::enums::PaymentExperience::RedirectToUrl]), + last_used_at: Some(pm.last_used_at), }, )) } diff --git a/crates/router/src/core/payment_methods/transformers.rs b/crates/router/src/core/payment_methods/transformers.rs index 19ecf733dfb..35491d747ef 100644 --- a/crates/router/src/core/payment_methods/transformers.rs +++ b/crates/router/src/core/payment_methods/transformers.rs @@ -327,7 +327,8 @@ pub fn mk_add_bank_response_hs( created: Some(common_utils::date_time::now()), recurring_enabled: false, // [#256] installment_payment_enabled: false, // #[#256] - payment_experience: Some(vec![api_models::enums::PaymentExperience::RedirectToUrl]), // [#256] + payment_experience: Some(vec![api_models::enums::PaymentExperience::RedirectToUrl]), + last_used_at: Some(common_utils::date_time::now()), } } @@ -370,7 +371,8 @@ pub fn mk_add_card_response_hs( created: Some(common_utils::date_time::now()), recurring_enabled: false, // [#256] installment_payment_enabled: false, // #[#256] - payment_experience: Some(vec![api_models::enums::PaymentExperience::RedirectToUrl]), // [#256] + payment_experience: Some(vec![api_models::enums::PaymentExperience::RedirectToUrl]), + last_used_at: Some(common_utils::date_time::now()), // [#256] } } diff --git a/crates/router/src/core/payments.rs b/crates/router/src/core/payments.rs index b94b8627ef9..782d1814cc6 100644 --- a/crates/router/src/core/payments.rs +++ b/crates/router/src/core/payments.rs @@ -1070,7 +1070,6 @@ where customer, ) .await?; - *payment_data = pd; // Validating the blocklist guard and generate the fingerprint @@ -1141,7 +1140,6 @@ where let pm_token = router_data .add_payment_method_token(state, &connector, &tokenization_action) .await?; - if let Some(payment_method_token) = pm_token.clone() { router_data.payment_method_token = Some(router_types::PaymentMethodToken::Token( payment_method_token, @@ -1846,7 +1844,7 @@ async fn decide_payment_method_tokenize_action( } } -#[derive(Clone)] +#[derive(Clone, Debug)] pub enum TokenizationAction { TokenizeInRouter, TokenizeInConnector, diff --git a/crates/router/src/core/payments/helpers.rs b/crates/router/src/core/payments/helpers.rs index 0baba7035ce..e0b8a5f6232 100644 --- a/crates/router/src/core/payments/helpers.rs +++ b/crates/router/src/core/payments/helpers.rs @@ -1131,6 +1131,7 @@ pub(crate) async fn get_payment_method_create_request( customer_id: Some(customer.customer_id.to_owned()), card_network: None, }; + Ok(payment_method_request) } }, @@ -1402,6 +1403,7 @@ pub async fn create_customer_if_not_exist<'a, F: Clone, R, Ctx>( modified_at: common_utils::date_time::now(), connector_customer: None, address_id: None, + default_payment_method_id: None, }) } .await @@ -1545,7 +1547,8 @@ pub async fn retrieve_payment_method_with_temporary_token( pub async fn retrieve_card_with_permanent_token( state: &AppState, - token: &str, + locker_id: &str, + payment_method_id: &str, payment_intent: &PaymentIntent, card_token_data: Option<&CardToken>, ) -> RouterResult<api::PaymentMethodData> { @@ -1556,11 +1559,11 @@ pub async fn retrieve_card_with_permanent_token( .change_context(errors::ApiErrorResponse::UnprocessableEntity { message: "no customer id provided for the payment".to_string(), })?; - - let card = cards::get_card_from_locker(state, customer_id, &payment_intent.merchant_id, token) - .await - .change_context(errors::ApiErrorResponse::InternalServerError) - .attach_printable("failed to fetch card information from the permanent locker")?; + let card = + cards::get_card_from_locker(state, customer_id, &payment_intent.merchant_id, locker_id) + .await + .change_context(errors::ApiErrorResponse::InternalServerError) + .attach_printable("failed to fetch card information from the permanent locker")?; // The card_holder_name from locker retrieved card is considered if it is a non-empty string or else card_holder_name is picked // from payment_method_data.card_token object @@ -1593,7 +1596,7 @@ pub async fn retrieve_card_with_permanent_token( card_issuing_country: None, bank_code: None, }; - + cards::update_last_used_at(payment_method_id, state).await?; Ok(api::PaymentMethodData::Card(api_card)) } diff --git a/crates/router/src/core/payments/tokenization.rs b/crates/router/src/core/payments/tokenization.rs index d08f0208500..21fd4cf85e8 100644 --- a/crates/router/src/core/payments/tokenization.rs +++ b/crates/router/src/core/payments/tokenization.rs @@ -426,6 +426,7 @@ async fn skip_saving_card_in_locker( metadata: None, created: Some(common_utils::date_time::now()), bank_transfer: None, + last_used_at: Some(common_utils::date_time::now()), }; Ok((pm_resp, None)) @@ -445,6 +446,7 @@ async fn skip_saving_card_in_locker( installment_payment_enabled: false, payment_experience: Some(vec![api_models::enums::PaymentExperience::RedirectToUrl]), bank_transfer: None, + last_used_at: Some(common_utils::date_time::now()), }; Ok((payment_method_response, None)) } @@ -491,6 +493,7 @@ pub async fn save_in_locker( recurring_enabled: false, //[#219] installment_payment_enabled: false, //[#219] payment_experience: Some(vec![api_models::enums::PaymentExperience::RedirectToUrl]), //[#219] + last_used_at: Some(common_utils::date_time::now()), }; Ok((payment_method_response, None)) } diff --git a/crates/router/src/core/payouts/helpers.rs b/crates/router/src/core/payouts/helpers.rs index 7b5ec096248..75a8483e06c 100644 --- a/crates/router/src/core/payouts/helpers.rs +++ b/crates/router/src/core/payouts/helpers.rs @@ -432,6 +432,7 @@ pub async fn get_or_create_customer_details( created_at: common_utils::date_time::now(), modified_at: common_utils::date_time::now(), address_id: None, + default_payment_method_id: None, }; Ok(Some( diff --git a/crates/router/src/core/pm_auth.rs b/crates/router/src/core/pm_auth.rs index 982ed9cae94..2987370f280 100644 --- a/crates/router/src/core/pm_auth.rs +++ b/crates/router/src/core/pm_auth.rs @@ -297,6 +297,7 @@ async fn store_bank_details_in_payment_methods( .find_payment_method_by_customer_id_merchant_id_list( &customer_id, &merchant_account.merchant_id, + None, ) .await .change_context(ApiErrorResponse::InternalServerError)?; diff --git a/crates/router/src/db/kafka_store.rs b/crates/router/src/db/kafka_store.rs index 1c1ec00ce79..0c4cf01aa0e 100644 --- a/crates/router/src/db/kafka_store.rs +++ b/crates/router/src/db/kafka_store.rs @@ -1267,9 +1267,10 @@ impl PaymentMethodInterface for KafkaStore { &self, customer_id: &str, merchant_id: &str, + limit: Option<i64>, ) -> CustomResult<Vec<storage::PaymentMethod>, errors::StorageError> { self.diesel_store - .find_payment_method_by_customer_id_merchant_id_list(customer_id, merchant_id) + .find_payment_method_by_customer_id_merchant_id_list(customer_id, merchant_id, limit) .await } @@ -1278,9 +1279,15 @@ impl PaymentMethodInterface for KafkaStore { customer_id: &str, merchant_id: &str, status: common_enums::PaymentMethodStatus, + limit: Option<i64>, ) -> CustomResult<Vec<storage::PaymentMethod>, errors::StorageError> { self.diesel_store - .find_payment_method_by_customer_id_merchant_id_status(customer_id, merchant_id, status) + .find_payment_method_by_customer_id_merchant_id_status( + customer_id, + merchant_id, + status, + limit, + ) .await } diff --git a/crates/router/src/db/payment_method.rs b/crates/router/src/db/payment_method.rs index f15ceecd1c4..ddd2857cc22 100644 --- a/crates/router/src/db/payment_method.rs +++ b/crates/router/src/db/payment_method.rs @@ -24,6 +24,7 @@ pub trait PaymentMethodInterface { &self, customer_id: &str, merchant_id: &str, + limit: Option<i64>, ) -> CustomResult<Vec<storage::PaymentMethod>, errors::StorageError>; async fn find_payment_method_by_customer_id_merchant_id_status( @@ -31,6 +32,7 @@ pub trait PaymentMethodInterface { customer_id: &str, merchant_id: &str, status: common_enums::PaymentMethodStatus, + limit: Option<i64>, ) -> CustomResult<Vec<storage::PaymentMethod>, errors::StorageError>; async fn insert_payment_method( @@ -104,12 +106,18 @@ impl PaymentMethodInterface for Store { &self, customer_id: &str, merchant_id: &str, + limit: Option<i64>, ) -> CustomResult<Vec<storage::PaymentMethod>, errors::StorageError> { let conn = connection::pg_connection_read(self).await?; - storage::PaymentMethod::find_by_customer_id_merchant_id(&conn, customer_id, merchant_id) - .await - .map_err(Into::into) - .into_report() + storage::PaymentMethod::find_by_customer_id_merchant_id( + &conn, + customer_id, + merchant_id, + limit, + ) + .await + .map_err(Into::into) + .into_report() } async fn find_payment_method_by_customer_id_merchant_id_status( @@ -117,6 +125,7 @@ impl PaymentMethodInterface for Store { customer_id: &str, merchant_id: &str, status: common_enums::PaymentMethodStatus, + limit: Option<i64>, ) -> CustomResult<Vec<storage::PaymentMethod>, errors::StorageError> { let conn = connection::pg_connection_read(self).await?; storage::PaymentMethod::find_by_customer_id_merchant_id_status( @@ -124,6 +133,7 @@ impl PaymentMethodInterface for Store { customer_id, merchant_id, status, + limit, ) .await .map_err(Into::into) @@ -221,6 +231,7 @@ impl PaymentMethodInterface for MockDb { 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, @@ -233,6 +244,7 @@ impl PaymentMethodInterface for MockDb { &self, customer_id: &str, merchant_id: &str, + _limit: Option<i64>, ) -> CustomResult<Vec<storage::PaymentMethod>, errors::StorageError> { let payment_methods = self.payment_methods.lock().await; let payment_methods_found: Vec<storage::PaymentMethod> = payment_methods @@ -256,6 +268,7 @@ impl PaymentMethodInterface for MockDb { customer_id: &str, merchant_id: &str, status: common_enums::PaymentMethodStatus, + _limit: Option<i64>, ) -> CustomResult<Vec<storage::PaymentMethod>, errors::StorageError> { let payment_methods = self.payment_methods.lock().await; let payment_methods_found: Vec<storage::PaymentMethod> = payment_methods diff --git a/crates/router/src/routes/app.rs b/crates/router/src/routes/app.rs index 73558c78d7b..1d82bc7539f 100644 --- a/crates/router/src/routes/app.rs +++ b/crates/router/src/routes/app.rs @@ -632,6 +632,10 @@ impl Customers { web::resource("/{customer_id}/payment_methods") .route(web::get().to(list_customer_payment_method_api)), ) + .service( + web::resource("/{customer_id}/payment_methods/{payment_method_id}/default") + .route(web::post().to(default_payment_method_set_api)), + ) .service( web::resource("/{customer_id}") .route(web::get().to(customers_retrieve)) diff --git a/crates/router/src/routes/lock_utils.rs b/crates/router/src/routes/lock_utils.rs index 9471289a0c8..edbdee7bf6f 100644 --- a/crates/router/src/routes/lock_utils.rs +++ b/crates/router/src/routes/lock_utils.rs @@ -96,7 +96,8 @@ impl From<Flow> for ApiIdentifier { | Flow::PaymentMethodsRetrieve | Flow::PaymentMethodsUpdate | Flow::PaymentMethodsDelete - | Flow::ValidatePaymentMethod => Self::PaymentMethods, + | Flow::ValidatePaymentMethod + | Flow::DefaultPaymentMethodsSet => Self::PaymentMethods, Flow::PmAuthLinkTokenCreate | Flow::PmAuthExchangeToken => Self::PaymentMethodAuth, diff --git a/crates/router/src/routes/payment_methods.rs b/crates/router/src/routes/payment_methods.rs index 89ca36c8c15..5469f981659 100644 --- a/crates/router/src/routes/payment_methods.rs +++ b/crates/router/src/routes/payment_methods.rs @@ -102,6 +102,12 @@ pub async fn list_customer_payment_method_api( let flow = Flow::CustomerPaymentMethodsList; let payload = query_payload.into_inner(); let customer_id = customer_id.into_inner().0; + + let ephemeral_auth = + match auth::is_ephemeral_auth(req.headers(), &*state.store, &customer_id).await { + Ok(auth) => auth, + Err(err) => return api::log_and_return_error_response(err), + }; Box::pin(api::server_wrap( flow, state, @@ -116,7 +122,7 @@ pub async fn list_customer_payment_method_api( Some(&customer_id), ) }, - &auth::ApiKeyAuth, + &*ephemeral_auth, api_locking::LockAction::NotApplicable, )) .await @@ -157,6 +163,7 @@ pub async fn list_customer_payment_method_api_client( Ok((auth, _auth_flow)) => (auth, _auth_flow), Err(e) => return api::log_and_return_error_response(e), }; + Box::pin(api::server_wrap( flow, state, @@ -252,6 +259,42 @@ pub async fn payment_method_delete_api( )) .await } + +#[instrument(skip_all, fields(flow = ?Flow::DefaultPaymentMethodsSet))] +pub async fn default_payment_method_set_api( + state: web::Data<AppState>, + req: HttpRequest, + path: web::Path<payment_methods::DefaultPaymentMethod>, +) -> HttpResponse { + let flow = Flow::DefaultPaymentMethodsSet; + let payload = path.into_inner(); + let customer_id = payload.clone().customer_id; + + let ephemeral_auth = + match auth::is_ephemeral_auth(req.headers(), &*state.store, &customer_id).await { + Ok(auth) => auth, + Err(err) => return api::log_and_return_error_response(err), + }; + Box::pin(api::server_wrap( + flow, + state, + &req, + payload, + |state, auth: auth::AuthenticationData, default_payment_method| { + cards::set_default_payment_method( + state, + auth.merchant_account, + auth.key_store, + &customer_id, + default_payment_method.payment_method_id, + ) + }, + &*ephemeral_auth, + api_locking::LockAction::NotApplicable, + )) + .await +} + #[cfg(test)] mod tests { #![allow(clippy::unwrap_used)] diff --git a/crates/router/src/types/api.rs b/crates/router/src/types/api.rs index 894b3d830dd..009033d5341 100644 --- a/crates/router/src/types/api.rs +++ b/crates/router/src/types/api.rs @@ -204,7 +204,7 @@ type BoxedConnector = Box<&'static (dyn Connector + Sync)>; // Normal flow will call the connector and follow the flow specific operations (capture, authorize) // SessionTokenFromMetadata will avoid calling the connector instead create the session token ( for sdk ) -#[derive(Clone, Eq, PartialEq)] +#[derive(Clone, Eq, PartialEq, Debug)] pub enum GetToken { GpayMetadata, ApplePayMetadata, @@ -214,7 +214,7 @@ pub enum GetToken { /// Routing algorithm will output merchant connector identifier instead of connector name /// In order to support backwards compatibility for older routing algorithms and merchant accounts /// the support for connector name is retained -#[derive(Clone)] +#[derive(Clone, Debug)] pub struct ConnectorData { pub connector: BoxedConnector, pub connector_name: types::Connector, diff --git a/crates/router/src/types/api/customers.rs b/crates/router/src/types/api/customers.rs index 32430c0918a..6f08a7fd7e4 100644 --- a/crates/router/src/types/api/customers.rs +++ b/crates/router/src/types/api/customers.rs @@ -32,6 +32,7 @@ impl From<(domain::Customer, Option<payments::AddressDetails>)> for CustomerResp created_at: cust.created_at, metadata: cust.metadata, address, + default_payment_method_id: cust.default_payment_method_id, } .into() } diff --git a/crates/router/src/types/api/payment_methods.rs b/crates/router/src/types/api/payment_methods.rs index ca852f832ee..642e94ad69e 100644 --- a/crates/router/src/types/api/payment_methods.rs +++ b/crates/router/src/types/api/payment_methods.rs @@ -1,10 +1,11 @@ pub use api_models::payment_methods::{ CardDetail, CardDetailFromLocker, CardDetailsPaymentMethod, CustomerPaymentMethod, - CustomerPaymentMethodsListResponse, DeleteTokenizeByTokenRequest, GetTokenizePayloadRequest, - GetTokenizePayloadResponse, PaymentMethodCreate, PaymentMethodDeleteResponse, PaymentMethodId, - PaymentMethodList, PaymentMethodListRequest, PaymentMethodListResponse, PaymentMethodResponse, - PaymentMethodUpdate, PaymentMethodsData, TokenizePayloadEncrypted, TokenizePayloadRequest, - TokenizedCardValue1, TokenizedCardValue2, TokenizedWalletValue1, TokenizedWalletValue2, + CustomerPaymentMethodsListResponse, DefaultPaymentMethod, DeleteTokenizeByTokenRequest, + GetTokenizePayloadRequest, GetTokenizePayloadResponse, PaymentMethodCreate, + PaymentMethodDeleteResponse, PaymentMethodId, PaymentMethodList, PaymentMethodListRequest, + PaymentMethodListResponse, PaymentMethodResponse, PaymentMethodUpdate, PaymentMethodsData, + TokenizePayloadEncrypted, TokenizePayloadRequest, TokenizedCardValue1, TokenizedCardValue2, + TokenizedWalletValue1, TokenizedWalletValue2, }; use error_stack::report; diff --git a/crates/router/src/types/domain/customer.rs b/crates/router/src/types/domain/customer.rs index fe575851dc4..5437d06a2e6 100644 --- a/crates/router/src/types/domain/customer.rs +++ b/crates/router/src/types/domain/customer.rs @@ -22,6 +22,7 @@ pub struct Customer { pub modified_at: PrimitiveDateTime, pub connector_customer: Option<serde_json::Value>, pub address_id: Option<String>, + pub default_payment_method_id: Option<String>, } #[async_trait::async_trait] @@ -45,6 +46,7 @@ impl super::behaviour::Conversion for Customer { modified_at: self.modified_at, connector_customer: self.connector_customer, address_id: self.address_id, + default_payment_method_id: self.default_payment_method_id, }) } @@ -72,6 +74,7 @@ impl super::behaviour::Conversion for Customer { modified_at: item.modified_at, connector_customer: item.connector_customer, address_id: item.address_id, + default_payment_method_id: item.default_payment_method_id, }) } .await @@ -114,6 +117,9 @@ pub enum CustomerUpdate { ConnectorCustomer { connector_customer: Option<serde_json::Value>, }, + UpdateDefaultPaymentMethod { + default_payment_method_id: Option<String>, + }, } impl From<CustomerUpdate> for CustomerUpdateInternal { @@ -138,12 +144,20 @@ impl From<CustomerUpdate> for CustomerUpdateInternal { connector_customer, modified_at: Some(date_time::now()), address_id, + ..Default::default() }, CustomerUpdate::ConnectorCustomer { connector_customer } => Self { connector_customer, modified_at: Some(common_utils::date_time::now()), ..Default::default() }, + CustomerUpdate::UpdateDefaultPaymentMethod { + default_payment_method_id, + } => Self { + default_payment_method_id, + modified_at: Some(common_utils::date_time::now()), + ..Default::default() + }, } } } diff --git a/crates/router_env/src/logger/types.rs b/crates/router_env/src/logger/types.rs index 62c09c42455..4790e60acb1 100644 --- a/crates/router_env/src/logger/types.rs +++ b/crates/router_env/src/logger/types.rs @@ -123,6 +123,8 @@ pub enum Flow { PaymentMethodsUpdate, /// Payment methods delete flow. PaymentMethodsDelete, + /// Default Payment method flow. + DefaultPaymentMethodsSet, /// Payments create flow. PaymentsCreate, /// Payments Retrieve flow. diff --git a/migrations/2024-02-21-120100_add_last_used_at_in_payment_methods/down.sql b/migrations/2024-02-21-120100_add_last_used_at_in_payment_methods/down.sql new file mode 100644 index 00000000000..fc9fc6350ed --- /dev/null +++ b/migrations/2024-02-21-120100_add_last_used_at_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 last_used_at; \ No newline at end of file diff --git a/migrations/2024-02-21-120100_add_last_used_at_in_payment_methods/up.sql b/migrations/2024-02-21-120100_add_last_used_at_in_payment_methods/up.sql new file mode 100644 index 00000000000..f1c0aab4def --- /dev/null +++ b/migrations/2024-02-21-120100_add_last_used_at_in_payment_methods/up.sql @@ -0,0 +1,2 @@ +-- Your SQL goes here +ALTER TABLE payment_methods ADD COLUMN IF NOT EXISTS last_used_at TIMESTAMP NOT NULL DEFAULT now()::TIMESTAMP; \ No newline at end of file diff --git a/migrations/2024-02-21-143530_add_default_payment_method_in_customers/down.sql b/migrations/2024-02-21-143530_add_default_payment_method_in_customers/down.sql new file mode 100644 index 00000000000..948123ce7e2 --- /dev/null +++ b/migrations/2024-02-21-143530_add_default_payment_method_in_customers/down.sql @@ -0,0 +1,2 @@ +-- This file should undo anything in `up.sql` +ALTER TABLE customers DROP COLUMN IF EXISTS default_payment_method; diff --git a/migrations/2024-02-21-143530_add_default_payment_method_in_customers/up.sql b/migrations/2024-02-21-143530_add_default_payment_method_in_customers/up.sql new file mode 100644 index 00000000000..abaeb1df718 --- /dev/null +++ b/migrations/2024-02-21-143530_add_default_payment_method_in_customers/up.sql @@ -0,0 +1,3 @@ +-- Your SQL goes here +ALTER TABLE customers +ADD COLUMN IF NOT EXISTS default_payment_method_id VARCHAR(64); \ No newline at end of file diff --git a/openapi/openapi_spec.json b/openapi/openapi_spec.json index 30e75c028d5..3fcf6bca79f 100644 --- a/openapi/openapi_spec.json +++ b/openapi/openapi_spec.json @@ -4080,6 +4080,50 @@ } ] } + }, + "/{customer_id}/payment_methods/{payment_method_id}/default": { + "get": { + "tags": [ + "Customer Set Default Payment Method" + ], + "summary": "Customers - Set Default Payment Method", + "description": "Customers - Set Default Payment Method\n\nSet the Payment Method as Default for the Customer.", + "operationId": "Set the Payment Method as Default", + "parameters": [ + { + "name": "method_id", + "in": "path", + "description": "Set the Payment Method as Default for the Customer", + "required": true, + "schema": { + "type": "string" + } + } + ], + "responses": { + "200": { + "description": "Payment Method has been set as default", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/CustomerDefaultPaymentMethodResponse" + } + } + } + }, + "400": { + "description": "Payment Method has already been set as default for that customer" + }, + "404": { + "description": "Payment Method not found for the customer" + } + }, + "security": [ + { + "ephemeral_key": [] + } + ] + } } }, "components": { @@ -7308,6 +7352,37 @@ } } }, + "CustomerDefaultPaymentMethodResponse": { + "type": "object", + "required": [ + "customer_id", + "payment_method" + ], + "properties": { + "default_payment_method_id": { + "type": "string", + "description": "The unique identifier of the Payment method", + "example": "card_rGK4Vi5iSW70MY7J2mIy", + "nullable": true + }, + "customer_id": { + "type": "string", + "description": "The unique identifier of the customer.", + "example": "cus_meowerunwiuwiwqw" + }, + "payment_method": { + "$ref": "#/components/schemas/PaymentMethod" + }, + "payment_method_type": { + "allOf": [ + { + "$ref": "#/components/schemas/PaymentMethodType" + } + ], + "nullable": true + } + } + }, "CustomerDeleteResponse": { "type": "object", "required": [ @@ -7384,11 +7459,13 @@ "type": "object", "required": [ "payment_token", + "payment_method_id", "customer_id", "payment_method", "recurring_enabled", "installment_payment_enabled", - "requires_cvv" + "requires_cvv", + "default_payment_method_set" ], "properties": { "payment_token": { @@ -7396,6 +7473,11 @@ "description": "Token for payment method in temporary card locker which gets refreshed often", "example": "7ebf443f-a050-4067-84e5-e6f6d4800aef" }, + "payment_method_id": { + "type": "string", + "description": "The unique identifier of the customer.", + "example": "pm_iouuy468iyuowqs" + }, "customer_id": { "type": "string", "description": "The unique identifier of the customer.", @@ -7495,6 +7577,18 @@ "type": "boolean", "description": "Whether this payment method requires CVV to be collected", "example": true + }, + "last_used_at": { + "type": "string", + "format": "date-time", + "description": "A timestamp (ISO 8601 code) that determines when the payment method was last used", + "example": "2024-02-24T11:04:09.922Z", + "nullable": true + }, + "default_payment_method_set": { + "type": "boolean", + "description": "Indicates if the payment method has been set to default or not", + "example": true } } }, @@ -7644,6 +7738,28 @@ "type": "object", "description": "You can specify up to 50 keys, with key names up to 40 characters long and values up to 500\ncharacters long. Metadata is useful for storing additional, structured information on an\nobject.", "nullable": true + }, + "default_payment_method_id": { + "type": "string", + "description": "The identifier for the default payment method.", + "example": "pm_djh2837dwduh890123", + "nullable": true, + "maxLength": 64 + } + } + }, + "DefaultPaymentMethod": { + "type": "object", + "required": [ + "customer_id", + "payment_method_id" + ], + "properties": { + "customer_id": { + "type": "string" + }, + "payment_method_id": { + "type": "string" } } }, @@ -11888,6 +12004,12 @@ } ], "nullable": true + }, + "last_used_at": { + "type": "string", + "format": "date-time", + "example": "2024-02-24T11:04:09.922Z", + "nullable": true } } },
2024-02-23T04:00:53Z
## Type of Change <!-- Put an `x` in the boxes that apply --> - [ ] Bugfix - [x] New feature - [ ] Enhancement - [ ] Refactoring - [ ] Dependency updates - [ ] Documentation - [ ] CI/CD ## Description - Add default payment method column in customers table and last used column in payment_methods table. - Last used would be updated depending on every payment_method usages. - And the CustomerPaymentMethodList would be sorted on the basis of last_used at. - A query param was added , to show the list on the basis of limit, i.e., if limit is 1 we will show only the 1st payment_method while doing a CustomerPaymentMethodList - CustomerPaymentMethodList Authentication from ApiKey to EphemeralKey - Made a new Api Route, `/payment_methods/{customer_id}/{payment_method_id}/default` for explicitly setting up the default payment method for a particular customer, which would require , customer_id and payment_method_id to be passed in the path - In CustomerPaymentMethodList we would show the Default Payment Method was either set or not , based on its entry in the Customer Table - Also in CustomerPaymentMethodList we would show payment_method_id now ### 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? To test `set_default_payment_method` - Create an MA and and MCA - Create an ApiKey and EphemeralKey for that particular customer - Make a payment , using one card and then do a ListCustomerPaymentMethods - > Create ``` curl --location 'http://localhost:8080/payments' \ --header 'Content-Type: application/json' \ --header 'Accept: application/json' \ --header 'api-key: dev_RHgvB0yPOTVA4xK4zTjXzxrnSVmnXlJz80hnEHIocTKplSc6sYqwRu2yHD8iJyuA' \ --data-raw ' {"amount": 6540, "currency": "USD", "confirm": false, "capture_method": "automatic", "authentication_type": "no_three_ds", "customer_id": "7cc", "email": "something@gmail.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" } }, "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" } }, "metadata": { "order_details": { "product_name": "Apple iphone 15", "quantity": 1 } }, "business_country": "US", "business_label": "default", "setup_future_usage": "on_session" }' ``` -> Confirm ``` curl --location 'http://localhost:8080/payments/pay_nIQnyrfS15jQja2OocCX/confirm' \ --header 'Content-Type: application/json' \ --header 'Accept: application/json' \ --header 'api-key: dev_RHgvB0yPOTVA4xK4zTjXzxrnSVmnXlJz80hnEHIocTKplSc6sYqwRu2yHD8iJyuA' \ --data '{ "confirm": true, "payment_type": "normal", "setup_future_usage":"on_session", "payment_method": "card", "payment_method_type": "debit", "payment_method_data": { "card": { "card_number": "4111111111111111", "card_exp_month": "11", "card_exp_year": "2040", "card_holder_name": "AKA", "card_cvc": "123", "nick_name": "HELO" } } }' ``` - The `default_payment_method` would be false , there also will be `payment_method_id` field (refer the screenshots below) - The following curl can be used to set the particular payment_method as default, the ``` curl --location --request POST 'http://localhost:8080/customers/{customer_id}/payment_methods/{payment_method_id}/set' \ --header 'Accept: application/json' \ --header 'api-key: epk_bf2209db8af14c04b811bce74e0d1202' ``` - do a ListCustomerPaymentMethods, The `default_payment_method` would be true To test `last_used_at` - Create an MA and and MCA - Create an ApiKey and EphemeralKey for that particular customer - Make a payment , using one card and then do a ListCustomerPaymentMethods - > Create ``` curl --location 'http://localhost:8080/payments' \ --header 'Content-Type: application/json' \ --header 'Accept: application/json' \ --header 'api-key: dev_RHgvB0yPOTVA4xK4zTjXzxrnSVmnXlJz80hnEHIocTKplSc6sYqwRu2yHD8iJyuA' \ --data-raw ' {"amount": 6540, "currency": "USD", "confirm": false, "capture_method": "automatic", "authentication_type": "no_three_ds", "customer_id": "7cc", "email": "something@gmail.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" } }, "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" } }, "metadata": { "order_details": { "product_name": "Apple iphone 15", "quantity": 1 } }, "business_country": "US", "business_label": "default", "setup_future_usage": "on_session" }' ``` -> Confirm ``` curl --location 'http://localhost:8080/payments/pay_nIQnyrfS15jQja2OocCX/confirm' \ --header 'Content-Type: application/json' \ --header 'Accept: application/json' \ --header 'api-key: dev_RHgvB0yPOTVA4xK4zTjXzxrnSVmnXlJz80hnEHIocTKplSc6sYqwRu2yHD8iJyuA' \ --data '{ "confirm": true, "payment_type": "normal", "setup_future_usage":"on_session", "payment_method": "card", "payment_method_type": "debit", "payment_method_data": { "card": { "card_number": "4111111111111111", "card_exp_month": "11", "card_exp_year": "2040", "card_holder_name": "AKA", "card_cvc": "123", "nick_name": "HELO" } } }' ``` - The last_used_at field would show the current timestamp - Make a payment , using another card and then do a ListCustomerPaymentMethods - > Create ``` curl --location 'http://localhost:8080/payments' \ --header 'Content-Type: application/json' \ --header 'Accept: application/json' \ --header 'api-key: dev_RHgvB0yPOTVA4xK4zTjXzxrnSVmnXlJz80hnEHIocTKplSc6sYqwRu2yHD8iJyuA' \ --data-raw ' {"amount": 6540, "currency": "USD", "confirm": false, "capture_method": "automatic", "authentication_type": "no_three_ds", "customer_id": "7cc", "email": "something@gmail.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" } }, "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" } }, "metadata": { "order_details": { "product_name": "Apple iphone 15", "quantity": 1 } }, "business_country": "US", "business_label": "default", "setup_future_usage": "on_session" }' ``` -> Confirm ``` curl --location 'http://localhost:8080/payments/pay_nIQnyrfS15jQja2OocCX/confirm' \ --header 'Content-Type: application/json' \ --header 'Accept: application/json' \ --header 'api-key: dev_RHgvB0yPOTVA4xK4zTjXzxrnSVmnXlJz80hnEHIocTKplSc6sYqwRu2yHD8iJyuA' \ --data '{ "confirm": true, "payment_type": "normal", "setup_future_usage":"on_session", "payment_method": "card", "payment_method_type": "debit", "payment_method_data": { "card": { "card_number": "4242424242424242", "card_exp_month": "11", "card_exp_year": "2040", "card_holder_name": "AKA", "card_cvc": "123", "nick_name": "HELO" } } }' ``` - The last_used_at field would show the current timestamp - Do The list customer and then select a payment_token of the last card - Make a payment using the `payment_token` - The last_used_at field would show the current timestamp, and would be sorted in the order that PaymentMethod was used at - The following curl can be used to list the customer payment methods with a limit , the limit if set as 1 would show the last used payment method ``` curl --location 'http://localhost:8080/customers/{customer_id}/payment_methods?limit=1' \ --header 'Accept: application/json' \ --header 'api-key: dev_OS3aZUsCeqV3eTW2Nlaba7yThKEUAZGXlEysuL15ZIoPP0McJ4YB9zRr9mWc9NFW' ``` ![image](https://github.com/juspay/hyperswitch/assets/55580080/9597cd08-bf23-4fea-978c-fecae7e5c848) <img width="1728" alt="Screenshot 2024-02-26 at 4 42 43 PM" src="https://github.com/juspay/hyperswitch/assets/55580080/64231527-bce6-4483-9997-b0cfb0669733"> ![Screenshot 2024-02-26 at 4 11 50 PM](https://github.com/juspay/hyperswitch/assets/55580080/0618a89e-e6ae-43d1-911c-f46e365f38c3) ![image](https://github.com/juspay/hyperswitch/assets/55580080/c07d3f76-863e-4beb-a897-06de49390c63) ## 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 - [ ] I added a [CHANGELOG](/CHANGELOG.md) entry if applicable
f4d0e2b441a25048186be4b9d0871e2473a6f357
To test `set_default_payment_method` - Create an MA and and MCA - Create an ApiKey and EphemeralKey for that particular customer - Make a payment , using one card and then do a ListCustomerPaymentMethods - > Create ``` curl --location 'http://localhost:8080/payments' \ --header 'Content-Type: application/json' \ --header 'Accept: application/json' \ --header 'api-key: dev_RHgvB0yPOTVA4xK4zTjXzxrnSVmnXlJz80hnEHIocTKplSc6sYqwRu2yHD8iJyuA' \ --data-raw ' {"amount": 6540, "currency": "USD", "confirm": false, "capture_method": "automatic", "authentication_type": "no_three_ds", "customer_id": "7cc", "email": "something@gmail.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" } }, "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" } }, "metadata": { "order_details": { "product_name": "Apple iphone 15", "quantity": 1 } }, "business_country": "US", "business_label": "default", "setup_future_usage": "on_session" }' ``` -> Confirm ``` curl --location 'http://localhost:8080/payments/pay_nIQnyrfS15jQja2OocCX/confirm' \ --header 'Content-Type: application/json' \ --header 'Accept: application/json' \ --header 'api-key: dev_RHgvB0yPOTVA4xK4zTjXzxrnSVmnXlJz80hnEHIocTKplSc6sYqwRu2yHD8iJyuA' \ --data '{ "confirm": true, "payment_type": "normal", "setup_future_usage":"on_session", "payment_method": "card", "payment_method_type": "debit", "payment_method_data": { "card": { "card_number": "4111111111111111", "card_exp_month": "11", "card_exp_year": "2040", "card_holder_name": "AKA", "card_cvc": "123", "nick_name": "HELO" } } }' ``` - The `default_payment_method` would be false , there also will be `payment_method_id` field (refer the screenshots below) - The following curl can be used to set the particular payment_method as default, the ``` curl --location --request POST 'http://localhost:8080/customers/{customer_id}/payment_methods/{payment_method_id}/set' \ --header 'Accept: application/json' \ --header 'api-key: epk_bf2209db8af14c04b811bce74e0d1202' ``` - do a ListCustomerPaymentMethods, The `default_payment_method` would be true To test `last_used_at` - Create an MA and and MCA - Create an ApiKey and EphemeralKey for that particular customer - Make a payment , using one card and then do a ListCustomerPaymentMethods - > Create ``` curl --location 'http://localhost:8080/payments' \ --header 'Content-Type: application/json' \ --header 'Accept: application/json' \ --header 'api-key: dev_RHgvB0yPOTVA4xK4zTjXzxrnSVmnXlJz80hnEHIocTKplSc6sYqwRu2yHD8iJyuA' \ --data-raw ' {"amount": 6540, "currency": "USD", "confirm": false, "capture_method": "automatic", "authentication_type": "no_three_ds", "customer_id": "7cc", "email": "something@gmail.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" } }, "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" } }, "metadata": { "order_details": { "product_name": "Apple iphone 15", "quantity": 1 } }, "business_country": "US", "business_label": "default", "setup_future_usage": "on_session" }' ``` -> Confirm ``` curl --location 'http://localhost:8080/payments/pay_nIQnyrfS15jQja2OocCX/confirm' \ --header 'Content-Type: application/json' \ --header 'Accept: application/json' \ --header 'api-key: dev_RHgvB0yPOTVA4xK4zTjXzxrnSVmnXlJz80hnEHIocTKplSc6sYqwRu2yHD8iJyuA' \ --data '{ "confirm": true, "payment_type": "normal", "setup_future_usage":"on_session", "payment_method": "card", "payment_method_type": "debit", "payment_method_data": { "card": { "card_number": "4111111111111111", "card_exp_month": "11", "card_exp_year": "2040", "card_holder_name": "AKA", "card_cvc": "123", "nick_name": "HELO" } } }' ``` - The last_used_at field would show the current timestamp - Make a payment , using another card and then do a ListCustomerPaymentMethods - > Create ``` curl --location 'http://localhost:8080/payments' \ --header 'Content-Type: application/json' \ --header 'Accept: application/json' \ --header 'api-key: dev_RHgvB0yPOTVA4xK4zTjXzxrnSVmnXlJz80hnEHIocTKplSc6sYqwRu2yHD8iJyuA' \ --data-raw ' {"amount": 6540, "currency": "USD", "confirm": false, "capture_method": "automatic", "authentication_type": "no_three_ds", "customer_id": "7cc", "email": "something@gmail.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" } }, "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" } }, "metadata": { "order_details": { "product_name": "Apple iphone 15", "quantity": 1 } }, "business_country": "US", "business_label": "default", "setup_future_usage": "on_session" }' ``` -> Confirm ``` curl --location 'http://localhost:8080/payments/pay_nIQnyrfS15jQja2OocCX/confirm' \ --header 'Content-Type: application/json' \ --header 'Accept: application/json' \ --header 'api-key: dev_RHgvB0yPOTVA4xK4zTjXzxrnSVmnXlJz80hnEHIocTKplSc6sYqwRu2yHD8iJyuA' \ --data '{ "confirm": true, "payment_type": "normal", "setup_future_usage":"on_session", "payment_method": "card", "payment_method_type": "debit", "payment_method_data": { "card": { "card_number": "4242424242424242", "card_exp_month": "11", "card_exp_year": "2040", "card_holder_name": "AKA", "card_cvc": "123", "nick_name": "HELO" } } }' ``` - The last_used_at field would show the current timestamp - Do The list customer and then select a payment_token of the last card - Make a payment using the `payment_token` - The last_used_at field would show the current timestamp, and would be sorted in the order that PaymentMethod was used at - The following curl can be used to list the customer payment methods with a limit , the limit if set as 1 would show the last used payment method ``` curl --location 'http://localhost:8080/customers/{customer_id}/payment_methods?limit=1' \ --header 'Accept: application/json' \ --header 'api-key: dev_OS3aZUsCeqV3eTW2Nlaba7yThKEUAZGXlEysuL15ZIoPP0McJ4YB9zRr9mWc9NFW' ``` ![image](https://github.com/juspay/hyperswitch/assets/55580080/9597cd08-bf23-4fea-978c-fecae7e5c848) <img width="1728" alt="Screenshot 2024-02-26 at 4 42 43 PM" src="https://github.com/juspay/hyperswitch/assets/55580080/64231527-bce6-4483-9997-b0cfb0669733"> ![Screenshot 2024-02-26 at 4 11 50 PM](https://github.com/juspay/hyperswitch/assets/55580080/0618a89e-e6ae-43d1-911c-f46e365f38c3) ![image](https://github.com/juspay/hyperswitch/assets/55580080/c07d3f76-863e-4beb-a897-06de49390c63)
juspay/hyperswitch
juspay__hyperswitch-3731
Bug: [REFACTOR] introduce `locker_id` column in payment_methods table Currently we are mapping `locker_id` from locker to `payment_method_id` in Hyperswitch. This refactor involves changes to store the locker id in the `locker_id` column as opposed to the `payment_method_id` column, and store a unique ID in place of the `payment_method_id`. While reading the locker id, read from the `locker_id` column with `payment_method_id` as fallback.
diff --git a/crates/diesel_models/src/payment_method.rs b/crates/diesel_models/src/payment_method.rs index d8b46c1932e..f9767e2939b 100644 --- a/crates/diesel_models/src/payment_method.rs +++ b/crates/diesel_models/src/payment_method.rs @@ -33,6 +33,7 @@ pub struct PaymentMethod { pub payment_method_issuer_code: Option<storage_enums::PaymentMethodIssuerCode>, pub metadata: Option<pii::SecretSerdeValue>, pub payment_method_data: Option<Encryption>, + pub locker_id: Option<String>, } #[derive(Clone, Debug, Eq, PartialEq, Insertable, Queryable, router_derive::DebugAsDisplay)] @@ -59,6 +60,7 @@ pub struct PaymentMethodNew { pub last_modified: PrimitiveDateTime, pub metadata: Option<pii::SecretSerdeValue>, pub payment_method_data: Option<Encryption>, + pub locker_id: Option<String>, } impl Default for PaymentMethodNew { @@ -69,6 +71,7 @@ impl Default for PaymentMethodNew { customer_id: String::default(), merchant_id: String::default(), payment_method_id: String::default(), + locker_id: Option::default(), payment_method: storage_enums::PaymentMethod::default(), payment_method_type: Option::default(), payment_method_issuer: Option::default(), diff --git a/crates/diesel_models/src/query/payment_method.rs b/crates/diesel_models/src/query/payment_method.rs index b1ea3ee388a..298db2a234b 100644 --- a/crates/diesel_models/src/query/payment_method.rs +++ b/crates/diesel_models/src/query/payment_method.rs @@ -44,6 +44,15 @@ impl PaymentMethod { .await } + #[instrument(skip(conn))] + pub async fn find_by_locker_id(conn: &PgPooledConn, locker_id: &str) -> StorageResult<Self> { + generics::generic_find_one::<<Self as HasTable>::Table, _, _>( + conn, + dsl::locker_id.eq(locker_id.to_owned()), + ) + .await + } + #[instrument(skip(conn))] pub async fn find_by_payment_method_id( conn: &PgPooledConn, diff --git a/crates/diesel_models/src/schema.rs b/crates/diesel_models/src/schema.rs index 5093f0df7d0..3364e560277 100644 --- a/crates/diesel_models/src/schema.rs +++ b/crates/diesel_models/src/schema.rs @@ -828,6 +828,8 @@ diesel::table! { payment_method_issuer_code -> Nullable<PaymentMethodIssuerCode>, metadata -> Nullable<Json>, payment_method_data -> Nullable<Bytea>, + #[max_length = 64] + locker_id -> Nullable<Varchar>, } } diff --git a/crates/router/src/core/customers.rs b/crates/router/src/core/customers.rs index 9442bf2ff34..be306112873 100644 --- a/crates/router/src/core/customers.rs +++ b/crates/router/src/core/customers.rs @@ -218,7 +218,7 @@ pub async fn delete_customer( &state, &req.customer_id, &merchant_account.merchant_id, - &pm.payment_method_id, + pm.locker_id.as_ref().unwrap_or(&pm.payment_method_id), ) .await .switch()?; diff --git a/crates/router/src/core/locker_migration.rs b/crates/router/src/core/locker_migration.rs index 2ebec569b38..1347bb8ffd0 100644 --- a/crates/router/src/core/locker_migration.rs +++ b/crates/router/src/core/locker_migration.rs @@ -83,9 +83,13 @@ pub async fn call_to_locker( .into_iter() .filter(|pm| matches!(pm.payment_method, storage_enums::PaymentMethod::Card)) { - let card = - cards::get_card_from_locker(state, customer_id, merchant_id, &pm.payment_method_id) - .await; + let card = cards::get_card_from_locker( + state, + customer_id, + merchant_id, + pm.locker_id.as_ref().unwrap_or(&pm.payment_method_id), + ) + .await; let card = match card { Ok(card) => card, @@ -127,7 +131,7 @@ pub async fn call_to_locker( customer_id.to_string(), merchant_account, api_enums::LockerChoice::HyperswitchCardVault, - Some(&pm.payment_method_id), + Some(pm.locker_id.as_ref().unwrap_or(&pm.payment_method_id)), ) .await .change_context(errors::ApiErrorResponse::InternalServerError) diff --git a/crates/router/src/core/payment_methods.rs b/crates/router/src/core/payment_methods.rs index c1617fa77c9..bdbd9b02d9e 100644 --- a/crates/router/src/core/payment_methods.rs +++ b/crates/router/src/core/payment_methods.rs @@ -155,7 +155,7 @@ impl PaymentMethodRetrieve for Oss { storage::PaymentTokenData::Permanent(card_token) => { helpers::retrieve_card_with_permanent_token( state, - &card_token.token, + card_token.locker_id.as_ref().unwrap_or(&card_token.token), payment_intent, card_token_data, ) @@ -166,7 +166,7 @@ impl PaymentMethodRetrieve for Oss { storage::PaymentTokenData::PermanentCard(card_token) => { helpers::retrieve_card_with_permanent_token( state, - &card_token.token, + card_token.locker_id.as_ref().unwrap_or(&card_token.token), payment_intent, card_token_data, ) diff --git a/crates/router/src/core/payment_methods/cards.rs b/crates/router/src/core/payment_methods/cards.rs index dbd8efcd1cf..7bf956be9ff 100644 --- a/crates/router/src/core/payment_methods/cards.rs +++ b/crates/router/src/core/payment_methods/cards.rs @@ -76,6 +76,7 @@ pub async fn create_payment_method( req: &api::PaymentMethodCreate, customer_id: &str, payment_method_id: &str, + locker_id: Option<String>, merchant_id: &str, pm_metadata: Option<serde_json::Value>, payment_method_data: Option<Encryption>, @@ -90,6 +91,7 @@ pub async fn create_payment_method( customer_id: customer_id.to_string(), merchant_id: merchant_id.to_string(), payment_method_id: payment_method_id.to_string(), + locker_id, payment_method: req.payment_method, payment_method_type: req.payment_method_type, payment_method_issuer: req.payment_method_issuer.clone(), @@ -131,6 +133,65 @@ pub fn store_default_payment_method( (payment_method_response, None) } +#[instrument(skip_all)] +pub async fn get_or_insert_payment_method( + db: &dyn db::StorageInterface, + req: api::PaymentMethodCreate, + resp: &mut api::PaymentMethodResponse, + merchant_account: &domain::MerchantAccount, + customer_id: &str, + key_store: &domain::MerchantKeyStore, +) -> errors::RouterResult<diesel_models::PaymentMethod> { + let mut payment_method_id = resp.payment_method_id.clone(); + let mut locker_id = None; + let payment_method = { + let existing_pm_by_pmid = db.find_payment_method(&payment_method_id).await; + + if let Err(err) = existing_pm_by_pmid { + if err.current_context().is_db_not_found() { + locker_id = Some(payment_method_id.clone()); + let existing_pm_by_locker_id = db + .find_payment_method_by_locker_id(&payment_method_id) + .await; + + match &existing_pm_by_locker_id { + Ok(pm) => payment_method_id = pm.payment_method_id.clone(), + Err(_) => payment_method_id = generate_id(consts::ID_LENGTH, "pm"), + }; + existing_pm_by_locker_id + } else { + Err(err) + } + } else { + existing_pm_by_pmid + } + }; + resp.payment_method_id = payment_method_id.to_owned(); + + match payment_method { + Ok(pm) => Ok(pm), + Err(err) => { + if err.current_context().is_db_not_found() { + insert_payment_method( + db, + resp, + req, + key_store, + &merchant_account.merchant_id, + customer_id, + resp.metadata.clone().map(|val| val.expose()), + locker_id, + ) + .await + } else { + Err(err) + .change_context(errors::ApiErrorResponse::InternalServerError) + .attach_printable("Error while finding payment method") + } + } + } +} + #[instrument(skip_all)] pub async fn add_payment_method( state: routes::AppState, @@ -182,40 +243,41 @@ pub async fn add_payment_method( )), }; - let (resp, duplication_check) = response?; + let (mut resp, duplication_check) = response?; match duplication_check { Some(duplication_check) => match duplication_check { payment_methods::DataDuplicationCheck::Duplicated => { - let existing_pm = db.find_payment_method(&resp.payment_method_id).await; - - if let Err(err) = existing_pm { - if err.current_context().is_db_not_found() { - insert_payment_method( - db, - &resp, - req, - key_store, - merchant_id, - &customer_id, - None, - ) - .await - } else { - Err(err) - .change_context(errors::ApiErrorResponse::InternalServerError) - .attach_printable("Error while finding payment method") - }? - }; + get_or_insert_payment_method( + db, + req.clone(), + &mut resp, + merchant_account, + &customer_id, + key_store, + ) + .await?; } - payment_methods::DataDuplicationCheck::MetaDataChanged => { if let Some(card) = req.card.clone() { + let existing_pm = get_or_insert_payment_method( + db, + req.clone(), + &mut resp, + merchant_account, + &customer_id, + key_store, + ) + .await?; + delete_card_from_locker( &state, &customer_id, merchant_id, - &resp.payment_method_id, + existing_pm + .locker_id + .as_ref() + .unwrap_or(&existing_pm.payment_method_id), ) .await?; @@ -226,7 +288,12 @@ pub async fn add_payment_method( customer_id.clone(), merchant_account, api::enums::LockerChoice::HyperswitchCardVault, - Some(&resp.payment_method_id), + Some( + existing_pm + .locker_id + .as_ref() + .unwrap_or(&existing_pm.payment_method_id), + ), ) .await; @@ -243,69 +310,46 @@ pub async fn add_payment_method( .attach_printable("Failed while updating card metadata changes"))? }; - let existing_pm = db.find_payment_method(&resp.payment_method_id).await; - match existing_pm { - Ok(pm) => { - let updated_card = Some(api::CardDetailFromLocker { - scheme: None, - last4_digits: Some(card.card_number.clone().get_last4()), - issuer_country: None, - card_number: Some(card.card_number), - expiry_month: Some(card.card_exp_month), - expiry_year: Some(card.card_exp_year), - card_token: None, - card_fingerprint: None, - card_holder_name: card.card_holder_name, - nick_name: card.nick_name, - card_network: None, - card_isin: None, - card_issuer: None, - card_type: None, - saved_to_locker: true, - }); - - let updated_pmd = updated_card.as_ref().map(|card| { - PaymentMethodsData::Card(CardDetailsPaymentMethod::from( - card.clone(), - )) - }); - let pm_data_encrypted = - create_encrypted_payment_method_data(key_store, updated_pmd).await; - - let pm_update = storage::PaymentMethodUpdate::PaymentMethodDataUpdate { - payment_method_data: pm_data_encrypted, - }; - - db.update_payment_method(pm, pm_update) - .await - .change_context(errors::ApiErrorResponse::InternalServerError) - .attach_printable("Failed to add payment method in db")?; - } - Err(err) => { - if err.current_context().is_db_not_found() { - insert_payment_method( - db, - &resp, - req, - key_store, - merchant_id, - &customer_id, - None, - ) - .await - } else { - Err(err) - .change_context(errors::ApiErrorResponse::InternalServerError) - .attach_printable("Error while finding payment method") - }?; - } - } + let updated_card = Some(api::CardDetailFromLocker { + scheme: None, + last4_digits: Some(card.card_number.clone().get_last4()), + issuer_country: None, + card_number: Some(card.card_number), + expiry_month: Some(card.card_exp_month), + expiry_year: Some(card.card_exp_year), + card_token: None, + card_fingerprint: None, + card_holder_name: card.card_holder_name, + nick_name: card.nick_name, + card_network: None, + card_isin: None, + card_issuer: None, + card_type: None, + saved_to_locker: true, + }); + + let updated_pmd = updated_card.as_ref().map(|card| { + PaymentMethodsData::Card(CardDetailsPaymentMethod::from(card.clone())) + }); + let pm_data_encrypted = + create_encrypted_payment_method_data(key_store, updated_pmd).await; + + let pm_update = storage::PaymentMethodUpdate::PaymentMethodDataUpdate { + payment_method_data: pm_data_encrypted, + }; + + db.update_payment_method(existing_pm, pm_update) + .await + .change_context(errors::ApiErrorResponse::InternalServerError) + .attach_printable("Failed to add payment method in db")?; } } }, None => { let pm_metadata = resp.metadata.as_ref().map(|data| data.peek()); + let locker_id = Some(resp.payment_method_id); + resp.payment_method_id = generate_id(consts::ID_LENGTH, "pm"); insert_payment_method( db, &resp, @@ -314,14 +358,16 @@ pub async fn add_payment_method( merchant_id, &customer_id, pm_metadata.cloned(), + locker_id, ) .await?; } - }; + } Ok(services::ApplicationResponse::Json(resp)) } +#[allow(clippy::too_many_arguments)] pub async fn insert_payment_method( db: &dyn db::StorageInterface, resp: &api::PaymentMethodResponse, @@ -330,7 +376,8 @@ pub async fn insert_payment_method( merchant_id: &str, customer_id: &str, pm_metadata: Option<serde_json::Value>, -) -> errors::RouterResult<()> { + locker_id: Option<String>, +) -> errors::RouterResult<diesel_models::PaymentMethod> { let pm_card_details = resp .card .as_ref() @@ -341,14 +388,13 @@ pub async fn insert_payment_method( &req, customer_id, &resp.payment_method_id, + locker_id, merchant_id, pm_metadata, pm_data_encrypted, key_store, ) - .await?; - - Ok(()) + .await } #[instrument(skip_all)] @@ -372,7 +418,7 @@ pub async fn update_customer_payment_method( &state, &pm.customer_id, &pm.merchant_id, - &pm.payment_method_id, + pm.locker_id.as_ref().unwrap_or(&pm.payment_method_id), ) .await?; }; @@ -927,7 +973,7 @@ pub async fn mock_call_to_locker_hs<'a>( duplication_check: None, }; Ok(payment_methods::StoreCardResp { - status: "SUCCESS".to_string(), + status: "Ok".to_string(), error_code: None, error_message: None, payload: Some(payload), @@ -1013,7 +1059,7 @@ pub async fn mock_delete_card_hs<'a>( .await .change_context(errors::VaultError::FetchCardFailed)?; Ok(payment_methods::DeleteCardResp { - status: "SUCCESS".to_string(), + status: "Ok".to_string(), error_code: None, error_message: None, }) @@ -1032,7 +1078,7 @@ pub async fn mock_delete_card<'a>( card_id: Some(locker_mock_up.card_id), external_id: Some(locker_mock_up.external_id), card_isin: None, - status: "SUCCESS".to_string(), + status: "Ok".to_string(), }) } //------------------------------------------------------------------------------ @@ -2642,7 +2688,11 @@ pub async fn list_customer_payment_method( ( card_details, None, - PaymentTokenData::permanent_card(pm.payment_method_id.clone()), + 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()), + ), ) } else { continue; @@ -2662,7 +2712,7 @@ pub async fn list_customer_payment_method( &token, &pm.customer_id, &pm.merchant_id, - &pm.payment_method_id, + pm.locker_id.as_ref().unwrap_or(&pm.payment_method_id), ) .await?, ), @@ -2902,7 +2952,7 @@ pub async fn get_card_details_from_locker( state, &pm.customer_id, &pm.merchant_id, - &pm.payment_method_id, + pm.locker_id.as_ref().unwrap_or(&pm.payment_method_id), ) .await .change_context(errors::ApiErrorResponse::InternalServerError) @@ -3167,7 +3217,7 @@ pub async fn retrieve_payment_method( &state, &pm.customer_id, &pm.merchant_id, - &pm.payment_method_id, + pm.locker_id.as_ref().unwrap_or(&pm.payment_method_id), ) .await .change_context(errors::ApiErrorResponse::InternalServerError) @@ -3217,11 +3267,11 @@ pub async fn delete_payment_method( &state, &key.customer_id, &key.merchant_id, - pm_id.payment_method_id.as_str(), + key.locker_id.as_ref().unwrap_or(&key.payment_method_id), ) .await?; - if response.status == "SUCCESS" { + if response.status == "Ok" { logger::info!("Card From locker deleted Successfully!"); } else { logger::error!("Error: Deleting Card From Locker!\n{:#?}", response); diff --git a/crates/router/src/core/payment_methods/transformers.rs b/crates/router/src/core/payment_methods/transformers.rs index 57e46bc9769..6bad41630b5 100644 --- a/crates/router/src/core/payment_methods/transformers.rs +++ b/crates/router/src/core/payment_methods/transformers.rs @@ -397,46 +397,6 @@ pub fn mk_add_card_response_hs( } } -pub fn mk_add_card_response( - card: api::CardDetail, - response: AddCardResponse, - req: api::PaymentMethodCreate, - merchant_id: &str, -) -> api::PaymentMethodResponse { - let mut card_number = card.card_number.peek().to_owned(); - let card = api::CardDetailFromLocker { - scheme: None, - last4_digits: Some(card_number.split_off(card_number.len() - 4)), - issuer_country: None, // [#256] bin mapping - card_number: Some(card.card_number), - expiry_month: Some(card.card_exp_month), - expiry_year: Some(card.card_exp_year), - card_token: Some(response.external_id.into()), // [#256] - card_fingerprint: Some(response.card_fingerprint), - card_holder_name: card.card_holder_name, - nick_name: card.nick_name, - card_isin: None, - card_issuer: None, - card_network: None, - card_type: None, - saved_to_locker: true, - }; - api::PaymentMethodResponse { - merchant_id: merchant_id.to_owned(), - customer_id: req.customer_id, - payment_method_id: response.card_id, - payment_method: req.payment_method, - payment_method_type: req.payment_method_type, - bank_transfer: None, - card: Some(card), - metadata: req.metadata, - created: Some(common_utils::date_time::now()), - recurring_enabled: false, // [#256] - installment_payment_enabled: false, // [#256] Pending on discussion, and not stored in the card locker - payment_experience: None, // [#256] - } -} - pub fn mk_add_card_request( locker: &settings::Locker, card: &api::CardDetail, diff --git a/crates/router/src/core/payments/tokenization.rs b/crates/router/src/core/payments/tokenization.rs index 2d7a09bdae1..d08f0208500 100644 --- a/crates/router/src/core/payments/tokenization.rs +++ b/crates/router/src/core/payments/tokenization.rs @@ -6,6 +6,7 @@ use router_env::{instrument, tracing}; use super::helpers; use crate::{ + consts, core::{ errors::{self, ConnectorErrorExt, RouterResult, StorageErrorExt}, mandate, payment_methods, payments, @@ -19,7 +20,7 @@ use crate::{ domain, storage::{self, enums as storage_enums}, }, - utils::OptionExt, + utils::{generate_id, OptionExt}, }; #[instrument(skip_all)] @@ -85,7 +86,7 @@ where .await?; let merchant_id = &merchant_account.merchant_id; - let locker_response = if !state.conf.locker.locker_enabled { + let (mut resp, duplication_check) = if !state.conf.locker.locker_enabled { skip_saving_card_in_locker( merchant_account, payment_method_create_request.to_owned(), @@ -100,9 +101,7 @@ where .await? }; - let duplication_check = locker_response.1; - - let pm_card_details = locker_response.0.card.as_ref().map(|card| { + let pm_card_details = resp.card.as_ref().map(|card| { api::payment_methods::PaymentMethodsData::Card(CardDetailsPaymentMethod::from( card.clone(), )) @@ -115,13 +114,44 @@ where ) .await; + let mut payment_method_id = resp.payment_method_id.clone(); + let mut locker_id = None; + match duplication_check { Some(duplication_check) => match duplication_check { payment_methods::transformers::DataDuplicationCheck::Duplicated => { - let existing_pm = db - .find_payment_method(&locker_response.0.payment_method_id) - .await; - match existing_pm { + let payment_method = { + let existing_pm_by_pmid = + db.find_payment_method(&payment_method_id).await; + + if let Err(err) = existing_pm_by_pmid { + if err.current_context().is_db_not_found() { + locker_id = Some(payment_method_id.clone()); + let existing_pm_by_locker_id = db + .find_payment_method_by_locker_id(&payment_method_id) + .await; + + match &existing_pm_by_locker_id { + Ok(pm) => { + payment_method_id = pm.payment_method_id.clone() + } + Err(_) => { + payment_method_id = + generate_id(consts::ID_LENGTH, "pm") + } + }; + existing_pm_by_locker_id + } else { + Err(err) + } + } else { + existing_pm_by_pmid + } + }; + + resp.payment_method_id = payment_method_id; + + match payment_method { Ok(pm) => { let pm_metadata = create_payment_method_metadata( pm.metadata.as_ref(), @@ -146,7 +176,8 @@ where db, &payment_method_create_request, &customer.customer_id, - &locker_response.0.payment_method_id, + &resp.payment_method_id, + locker_id, merchant_id, pm_metadata, pm_data_encrypted, @@ -165,22 +196,87 @@ where } payment_methods::transformers::DataDuplicationCheck::MetaDataChanged => { if let Some(card) = payment_method_create_request.card.clone() { + let payment_method = { + let existing_pm_by_pmid = + db.find_payment_method(&payment_method_id).await; + + if let Err(err) = existing_pm_by_pmid { + if err.current_context().is_db_not_found() { + locker_id = Some(payment_method_id.clone()); + let existing_pm_by_locker_id = db + .find_payment_method_by_locker_id( + &payment_method_id, + ) + .await; + + match &existing_pm_by_locker_id { + Ok(pm) => { + payment_method_id = pm.payment_method_id.clone() + } + Err(_) => { + payment_method_id = + generate_id(consts::ID_LENGTH, "pm") + } + }; + existing_pm_by_locker_id + } else { + Err(err) + } + } else { + existing_pm_by_pmid + } + }; + + resp.payment_method_id = payment_method_id; + + let existing_pm = + match payment_method { + Ok(pm) => Ok(pm), + Err(err) => { + if err.current_context().is_db_not_found() { + payment_methods::cards::insert_payment_method( + db, + &resp, + payment_method_create_request.clone(), + key_store, + &merchant_account.merchant_id, + &customer.customer_id, + resp.metadata.clone().map(|val| val.expose()), + locker_id, + ) + .await + } else { + Err(err) + .change_context(errors::ApiErrorResponse::InternalServerError) + .attach_printable("Error while finding payment method") + } + } + }?; + payment_methods::cards::delete_card_from_locker( state, &customer.customer_id, merchant_id, - &locker_response.0.payment_method_id, + existing_pm + .locker_id + .as_ref() + .unwrap_or(&existing_pm.payment_method_id), ) .await?; let add_card_resp = payment_methods::cards::add_card_hs( state, - payment_method_create_request.clone(), + payment_method_create_request, &card, customer.customer_id.clone(), merchant_account, api::enums::LockerChoice::HyperswitchCardVault, - Some(&locker_response.0.payment_method_id), + Some( + existing_pm + .locker_id + .as_ref() + .unwrap_or(&existing_pm.payment_method_id), + ), ) .await; @@ -188,7 +284,7 @@ where logger::error!(vault_err=?err); db.delete_payment_method_by_merchant_id_payment_method_id( merchant_id, - &locker_response.0.payment_method_id, + &resp.payment_method_id, ) .await .to_not_found_response( @@ -201,90 +297,59 @@ where ))? }; - let existing_pm = db - .find_payment_method(&locker_response.0.payment_method_id) + let updated_card = Some(CardDetailFromLocker { + scheme: None, + last4_digits: Some(card.card_number.clone().get_last4()), + issuer_country: None, + card_number: Some(card.card_number), + expiry_month: Some(card.card_exp_month), + expiry_year: Some(card.card_exp_year), + card_token: None, + card_fingerprint: None, + card_holder_name: card.card_holder_name, + nick_name: card.nick_name, + card_network: None, + card_isin: None, + card_issuer: None, + card_type: None, + saved_to_locker: true, + }); + + let updated_pmd = updated_card.as_ref().map(|card| { + PaymentMethodsData::Card(CardDetailsPaymentMethod::from( + card.clone(), + )) + }); + let pm_data_encrypted = + payment_methods::cards::create_encrypted_payment_method_data( + key_store, + updated_pmd, + ) .await; - match existing_pm { - Ok(pm) => { - let updated_card = Some(CardDetailFromLocker { - scheme: None, - last4_digits: Some( - card.card_number.clone().get_last4(), - ), - issuer_country: None, - card_number: Some(card.card_number), - expiry_month: Some(card.card_exp_month), - expiry_year: Some(card.card_exp_year), - card_token: None, - card_fingerprint: None, - card_holder_name: card.card_holder_name, - nick_name: card.nick_name, - card_network: None, - card_isin: None, - card_issuer: None, - card_type: None, - saved_to_locker: true, - }); - - let updated_pmd = updated_card.as_ref().map(|card| { - PaymentMethodsData::Card( - CardDetailsPaymentMethod::from(card.clone()), - ) - }); - let pm_data_encrypted = - payment_methods::cards::create_encrypted_payment_method_data( - key_store, - updated_pmd, - ) - .await; - let pm_update = - storage::PaymentMethodUpdate::PaymentMethodDataUpdate { - payment_method_data: pm_data_encrypted, - }; + let pm_update = + storage::PaymentMethodUpdate::PaymentMethodDataUpdate { + payment_method_data: pm_data_encrypted, + }; - db.update_payment_method(pm, pm_update) - .await - .change_context( - errors::ApiErrorResponse::InternalServerError, - ) - .attach_printable( - "Failed to add payment method in db", - )?; - } - Err(err) => { - if err.current_context().is_db_not_found() { - payment_methods::cards::insert_payment_method( - db, - &locker_response.0, - payment_method_create_request, - key_store, - merchant_id, - &customer.customer_id, - None, - ) - .await - } else { - Err(err) - .change_context( - errors::ApiErrorResponse::InternalServerError, - ) - .attach_printable( - "Error while finding payment method", - ) - }?; - } - } + db.update_payment_method(existing_pm, pm_update) + .await + .change_context(errors::ApiErrorResponse::InternalServerError) + .attach_printable("Failed to add payment method in db")?; } } }, None => { let pm_metadata = create_payment_method_metadata(None, connector_token)?; + + locker_id = Some(resp.payment_method_id); + resp.payment_method_id = generate_id(consts::ID_LENGTH, "pm"); payment_methods::cards::create_payment_method( db, &payment_method_create_request, &customer.customer_id, - &locker_response.0.payment_method_id, + &resp.payment_method_id, + locker_id, merchant_id, pm_metadata, pm_data_encrypted, @@ -294,7 +359,7 @@ where } } - Some(locker_response.0.payment_method_id) + Some(resp.payment_method_id) } else { None }; diff --git a/crates/router/src/core/payouts/helpers.rs b/crates/router/src/core/payouts/helpers.rs index 7fb6fa3bde6..de57f8549db 100644 --- a/crates/router/src/core/payouts/helpers.rs +++ b/crates/router/src/core/payouts/helpers.rs @@ -78,9 +78,11 @@ pub async fn make_payout_method_data<'a>( .attach_printable("failed to deserialize hyperswitch token data")?; let payment_token = match payment_token_data { - storage::PaymentTokenData::PermanentCard(storage::CardTokenData { token }) => { - Some(token) - } + storage::PaymentTokenData::PermanentCard(storage::CardTokenData { + locker_id, + token, + .. + }) => locker_id.or(Some(token)), storage::PaymentTokenData::TemporaryGeneric(storage::GenericTokenData { token, }) => Some(token), @@ -364,11 +366,13 @@ pub async fn save_payout_data_to_locker( card_network: None, }; + let payment_method_id = common_utils::generate_id(crate::consts::ID_LENGTH, "pm"); cards::create_payment_method( db, &payment_method, &payout_attempt.customer_id, - &stored_resp.card_reference, + &payment_method_id, + Some(stored_resp.card_reference), &merchant_account.merchant_id, None, card_details_encrypted, diff --git a/crates/router/src/db/kafka_store.rs b/crates/router/src/db/kafka_store.rs index 78b95544ca1..9dbecd82485 100644 --- a/crates/router/src/db/kafka_store.rs +++ b/crates/router/src/db/kafka_store.rs @@ -1270,6 +1270,15 @@ impl PaymentMethodInterface for KafkaStore { .await } + async fn find_payment_method_by_locker_id( + &self, + locker_id: &str, + ) -> CustomResult<storage::PaymentMethod, errors::StorageError> { + self.diesel_store + .find_payment_method_by_locker_id(locker_id) + .await + } + async fn insert_payment_method( &self, m: storage::PaymentMethodNew, diff --git a/crates/router/src/db/payment_method.rs b/crates/router/src/db/payment_method.rs index b109d1fe5bd..4f4087f552e 100644 --- a/crates/router/src/db/payment_method.rs +++ b/crates/router/src/db/payment_method.rs @@ -15,6 +15,11 @@ pub trait PaymentMethodInterface { payment_method_id: &str, ) -> CustomResult<storage::PaymentMethod, errors::StorageError>; + async fn find_payment_method_by_locker_id( + &self, + locker_id: &str, + ) -> CustomResult<storage::PaymentMethod, errors::StorageError>; + async fn find_payment_method_by_customer_id_merchant_id_list( &self, customer_id: &str, @@ -52,6 +57,17 @@ impl PaymentMethodInterface for Store { .into_report() } + async fn find_payment_method_by_locker_id( + &self, + locker_id: &str, + ) -> CustomResult<storage::PaymentMethod, errors::StorageError> { + let conn = connection::pg_connection_read(self).await?; + storage::PaymentMethod::find_by_locker_id(&conn, locker_id) + .await + .map_err(Into::into) + .into_report() + } + async fn insert_payment_method( &self, payment_method_new: storage::PaymentMethodNew, @@ -127,6 +143,25 @@ impl PaymentMethodInterface for MockDb { } } + async fn find_payment_method_by_locker_id( + &self, + locker_id: &str, + ) -> CustomResult<storage::PaymentMethod, errors::StorageError> { + let payment_methods = self.payment_methods.lock().await; + let payment_method = payment_methods + .iter() + .find(|pm| pm.locker_id == Some(locker_id.to_string())) + .cloned(); + + match payment_method { + Some(pm) => Ok(pm), + None => Err(errors::StorageError::ValueNotFound( + "cannot find payment method".to_string(), + ) + .into()), + } + } + async fn insert_payment_method( &self, payment_method_new: storage::PaymentMethodNew, @@ -142,6 +177,7 @@ impl PaymentMethodInterface for MockDb { 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, diff --git a/crates/router/src/types/api/mandates.rs b/crates/router/src/types/api/mandates.rs index 051547dfa92..10c56973dd3 100644 --- a/crates/router/src/types/api/mandates.rs +++ b/crates/router/src/types/api/mandates.rs @@ -51,7 +51,10 @@ impl MandateResponseExt for MandateResponse { state, &payment_method.customer_id, &payment_method.merchant_id, - &payment_method.payment_method_id, + payment_method + .locker_id + .as_ref() + .unwrap_or(&payment_method.payment_method_id), ) .await?; diff --git a/crates/router/src/types/storage/payment_method.rs b/crates/router/src/types/storage/payment_method.rs index 096303446dc..a787a4d932c 100644 --- a/crates/router/src/types/storage/payment_method.rs +++ b/crates/router/src/types/storage/payment_method.rs @@ -13,6 +13,8 @@ pub enum PaymentTokenKind { #[derive(Debug, Clone, serde::Serialize, serde::Deserialize)] pub struct CardTokenData { + pub payment_method_id: Option<String>, + pub locker_id: Option<String>, pub token: String, } @@ -34,8 +36,16 @@ pub enum PaymentTokenData { } impl PaymentTokenData { - pub fn permanent_card(token: String) -> Self { - Self::PermanentCard(CardTokenData { token }) + pub fn permanent_card( + payment_method_id: Option<String>, + locker_id: Option<String>, + token: String, + ) -> Self { + Self::PermanentCard(CardTokenData { + payment_method_id, + locker_id, + token, + }) } pub fn temporary_generic(token: String) -> Self { diff --git a/migrations/2024-02-20-142032_add_locker_id_to_payment_methods/down.sql b/migrations/2024-02-20-142032_add_locker_id_to_payment_methods/down.sql new file mode 100644 index 00000000000..90eaebaf4da --- /dev/null +++ b/migrations/2024-02-20-142032_add_locker_id_to_payment_methods/down.sql @@ -0,0 +1,3 @@ +-- This file should undo anything in `up.sql` + +ALTER TABLE payment_methods DROP COLUMN IF EXISTS locker_id; diff --git a/migrations/2024-02-20-142032_add_locker_id_to_payment_methods/up.sql b/migrations/2024-02-20-142032_add_locker_id_to_payment_methods/up.sql new file mode 100644 index 00000000000..516dc8a8818 --- /dev/null +++ b/migrations/2024-02-20-142032_add_locker_id_to_payment_methods/up.sql @@ -0,0 +1,3 @@ +-- Your SQL goes here + +ALTER TABLE payment_methods ADD COLUMN IF NOT EXISTS locker_id VARCHAR(64) DEFAULT NULL; \ No newline at end of file
2024-02-21T17:18:08Z
## 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 we are mapping `locker_id` from locker to `payment_method_id` in Hyperswitch. This refactor involves changes to store the locker id in the `locker_id` column as opposed to the `payment_method_id` column, and store a unique ID in place of the `payment_method_id`. While reading the locker id, read from the `locker_id` column with `payment_method_id` as fallback. ### 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)? --> Sandbox testing - * Should be tested similar to https://github.com/juspay/hyperswitch/pull/3146 * Test it for both old card already saved before this PR went in along with new card * Both `/payment_methods` and `/payment` card flow has to be tested with metadata changes too. Everything should work fine Test cases (`payment_methods` table) - (Card 1): Db entry before this code changes :- `locker_id` should be null ![image](https://github.com/juspay/hyperswitch/assets/70657455/f6677536-a3ea-4db3-af1d-2493e30cbbae) (Card 1): MetaData updation :- Both `payment_method_id` and `locker_id` will remain same but with updated `payment_method_data` ![image](https://github.com/juspay/hyperswitch/assets/70657455/45cebebf-f96c-4101-94bf-d8604d57c5eb) (Card 2): Db entry when new card is added :- `locker_id` will now be the id from locker, `payment_method_id` will be nano_id ![image](https://github.com/juspay/hyperswitch/assets/70657455/210a0adb-2050-4fc2-9752-ca314284e4ec) (Card 2): MetaData updation :- Both `payment_method_id` and `locker_id` will remain same but with updated `payment_method_data` ![image](https://github.com/juspay/hyperswitch/assets/70657455/0aba88f8-72b1-4269-9d2c-35d20f075929) Redis entry (Local testing) - Old card (both locker_id and payment_method_id will be same): ![image](https://github.com/juspay/hyperswitch/assets/70657455/6ad1e019-69e6-444d-8b56-dde2543dc6b7) New card (payment_method_id will be nano_id and locker_id will be the id returned from locker): ![image](https://github.com/juspay/hyperswitch/assets/70657455/400f09b9-da64-4497-bfe5-25429feab4d9) ## 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 - [ ] I added a [CHANGELOG](/CHANGELOG.md) entry if applicable
75c633fc7c37341177597041ccbcdfc3cf9e236f
Sandbox testing - * Should be tested similar to https://github.com/juspay/hyperswitch/pull/3146 * Test it for both old card already saved before this PR went in along with new card * Both `/payment_methods` and `/payment` card flow has to be tested with metadata changes too. Everything should work fine Test cases (`payment_methods` table) - (Card 1): Db entry before this code changes :- `locker_id` should be null ![image](https://github.com/juspay/hyperswitch/assets/70657455/f6677536-a3ea-4db3-af1d-2493e30cbbae) (Card 1): MetaData updation :- Both `payment_method_id` and `locker_id` will remain same but with updated `payment_method_data` ![image](https://github.com/juspay/hyperswitch/assets/70657455/45cebebf-f96c-4101-94bf-d8604d57c5eb) (Card 2): Db entry when new card is added :- `locker_id` will now be the id from locker, `payment_method_id` will be nano_id ![image](https://github.com/juspay/hyperswitch/assets/70657455/210a0adb-2050-4fc2-9752-ca314284e4ec) (Card 2): MetaData updation :- Both `payment_method_id` and `locker_id` will remain same but with updated `payment_method_data` ![image](https://github.com/juspay/hyperswitch/assets/70657455/0aba88f8-72b1-4269-9d2c-35d20f075929) Redis entry (Local testing) - Old card (both locker_id and payment_method_id will be same): ![image](https://github.com/juspay/hyperswitch/assets/70657455/6ad1e019-69e6-444d-8b56-dde2543dc6b7) New card (payment_method_id will be nano_id and locker_id will be the id returned from locker): ![image](https://github.com/juspay/hyperswitch/assets/70657455/400f09b9-da64-4497-bfe5-25429feab4d9)
juspay/hyperswitch
juspay__hyperswitch-3725
Bug: Feat(analytics): dispute filter api
diff --git a/crates/analytics/src/clickhouse.rs b/crates/analytics/src/clickhouse.rs index ead3b1699ec..fed029f2edb 100644 --- a/crates/analytics/src/clickhouse.rs +++ b/crates/analytics/src/clickhouse.rs @@ -23,6 +23,7 @@ use crate::{ metrics::{latency::LatencyAvg, ApiEventMetricRow}, }, connector_events::events::ConnectorEventsResult, + disputes::filters::DisputeFilterRow, outgoing_webhook_event::events::OutgoingWebhookLogsResult, sdk_events::events::SdkEventsResult, types::TableEngine, @@ -168,6 +169,7 @@ impl super::outgoing_webhook_event::events::OutgoingWebhookLogsFilterAnalytics for ClickhouseClient { } +impl super::disputes::filters::DisputeFilterAnalytics for ClickhouseClient {} #[derive(Debug, serde::Serialize)] struct CkhQuery { @@ -277,6 +279,18 @@ impl TryInto<RefundFilterRow> for serde_json::Value { } } +impl TryInto<DisputeFilterRow> for serde_json::Value { + type Error = Report<ParsingError>; + + fn try_into(self) -> Result<DisputeFilterRow, Self::Error> { + serde_json::from_value(self) + .into_report() + .change_context(ParsingError::StructParseFailure( + "Failed to parse DisputeFilterRow in clickhouse results", + )) + } +} + impl TryInto<ApiEventMetricRow> for serde_json::Value { type Error = Report<ParsingError>; diff --git a/crates/analytics/src/disputes.rs b/crates/analytics/src/disputes.rs new file mode 100644 index 00000000000..b6d7e6280c7 --- /dev/null +++ b/crates/analytics/src/disputes.rs @@ -0,0 +1,5 @@ +mod core; + +pub mod filters; + +pub use self::core::get_filters; diff --git a/crates/analytics/src/disputes/core.rs b/crates/analytics/src/disputes/core.rs new file mode 100644 index 00000000000..8ccbbdea6d2 --- /dev/null +++ b/crates/analytics/src/disputes/core.rs @@ -0,0 +1,91 @@ +use api_models::analytics::{ + disputes::DisputeDimensions, DisputeFilterValue, DisputeFiltersResponse, + GetDisputeFilterRequest, +}; +use error_stack::ResultExt; + +use super::filters::{get_dispute_filter_for_dimension, DisputeFilterRow}; +use crate::{ + errors::{AnalyticsError, AnalyticsResult}, + AnalyticsProvider, +}; + +pub async fn get_filters( + pool: &AnalyticsProvider, + req: GetDisputeFilterRequest, + merchant_id: &String, +) -> AnalyticsResult<DisputeFiltersResponse> { + let mut res = DisputeFiltersResponse::default(); + for dim in req.group_by_names { + let values = match pool { + AnalyticsProvider::Sqlx(pool) => { + get_dispute_filter_for_dimension(dim, merchant_id, &req.time_range, pool) + .await + } + AnalyticsProvider::Clickhouse(pool) => { + get_dispute_filter_for_dimension(dim, merchant_id, &req.time_range, pool) + .await + } + AnalyticsProvider::CombinedCkh(sqlx_pool, ckh_pool) => { + let ckh_result = get_dispute_filter_for_dimension( + dim, + merchant_id, + &req.time_range, + ckh_pool, + ) + .await; + let sqlx_result = get_dispute_filter_for_dimension( + dim, + merchant_id, + &req.time_range, + sqlx_pool, + ) + .await; + match (&sqlx_result, &ckh_result) { + (Ok(ref sqlx_res), Ok(ref ckh_res)) if sqlx_res != ckh_res => { + router_env::logger::error!(clickhouse_result=?ckh_res, postgres_result=?sqlx_res, "Mismatch between clickhouse & postgres disputes analytics filters") + }, + _ => {} + }; + ckh_result + } + AnalyticsProvider::CombinedSqlx(sqlx_pool, ckh_pool) => { + let ckh_result = get_dispute_filter_for_dimension( + dim, + merchant_id, + &req.time_range, + ckh_pool, + ) + .await; + let sqlx_result = get_dispute_filter_for_dimension( + dim, + merchant_id, + &req.time_range, + sqlx_pool, + ) + .await; + match (&sqlx_result, &ckh_result) { + (Ok(ref sqlx_res), Ok(ref ckh_res)) if sqlx_res != ckh_res => { + router_env::logger::error!(clickhouse_result=?ckh_res, postgres_result=?sqlx_res, "Mismatch between clickhouse & postgres disputes analytics filters") + }, + _ => {} + }; + sqlx_result + } + } + .change_context(AnalyticsError::UnknownError)? + .into_iter() + .filter_map(|fil: DisputeFilterRow| match dim { + DisputeDimensions::DisputeStatus => fil.dispute_status, + DisputeDimensions::DisputeStage => fil.dispute_stage, + DisputeDimensions::ConnectorStatus => fil.connector_status, + DisputeDimensions::Connector => fil.connector, + }) + .collect::<Vec<String>>(); + res.query_data.push(DisputeFilterValue { + dimension: dim, + values, + }) + } + Ok(res) +} diff --git a/crates/analytics/src/disputes/filters.rs b/crates/analytics/src/disputes/filters.rs new file mode 100644 index 00000000000..9b03c4de940 --- /dev/null +++ b/crates/analytics/src/disputes/filters.rs @@ -0,0 +1,52 @@ +use api_models::analytics::{disputes::DisputeDimensions, Granularity, TimeRange}; +use common_utils::errors::ReportSwitchExt; +use error_stack::ResultExt; +use time::PrimitiveDateTime; + +use crate::{ + query::{Aggregate, GroupByClause, QueryBuilder, QueryFilter, ToSql, Window}, + types::{AnalyticsCollection, AnalyticsDataSource, FiltersError, FiltersResult, LoadRow}, +}; +pub trait DisputeFilterAnalytics: LoadRow<DisputeFilterRow> {} + +pub async fn get_dispute_filter_for_dimension<T>( + dimension: DisputeDimensions, + merchant: &String, + time_range: &TimeRange, + pool: &T, +) -> FiltersResult<Vec<DisputeFilterRow>> +where + T: AnalyticsDataSource + DisputeFilterAnalytics, + PrimitiveDateTime: ToSql<T>, + AnalyticsCollection: ToSql<T>, + Granularity: GroupByClause<T>, + Aggregate<&'static str>: ToSql<T>, + Window<&'static str>: ToSql<T>, +{ + let mut query_builder: QueryBuilder<T> = QueryBuilder::new(AnalyticsCollection::Dispute); + + query_builder.add_select_column(dimension).switch()?; + time_range + .set_filter_clause(&mut query_builder) + .attach_printable("Error filtering time range") + .switch()?; + + query_builder + .add_filter_clause("merchant_id", merchant) + .switch()?; + + query_builder.set_distinct(); + + query_builder + .execute_query::<DisputeFilterRow, _>(pool) + .await + .change_context(FiltersError::QueryBuildingError)? + .change_context(FiltersError::QueryExecutionFailure) +} +#[derive(Debug, serde::Serialize, Eq, PartialEq, serde::Deserialize)] +pub struct DisputeFilterRow { + pub connector: Option<String>, + pub dispute_status: Option<String>, + pub connector_status: Option<String>, + pub dispute_stage: Option<String>, +} diff --git a/crates/analytics/src/lib.rs b/crates/analytics/src/lib.rs index a4e925519ce..0fb8d9eea6e 100644 --- a/crates/analytics/src/lib.rs +++ b/crates/analytics/src/lib.rs @@ -1,5 +1,6 @@ mod clickhouse; pub mod core; +pub mod disputes; pub mod errors; pub mod metrics; pub mod payments; diff --git a/crates/analytics/src/query.rs b/crates/analytics/src/query.rs index b924987f004..bc21ab8f0f4 100644 --- a/crates/analytics/src/query.rs +++ b/crates/analytics/src/query.rs @@ -4,6 +4,7 @@ use api_models::{ analytics::{ self as analytics_api, api_event::ApiEventDimensions, + disputes::DisputeDimensions, payments::{PaymentDimensions, PaymentDistributions}, refunds::{RefundDimensions, RefundType}, sdk_events::{SdkEventDimensions, SdkEventNames}, @@ -362,6 +363,8 @@ impl_to_sql_for_to_string!( PaymentDimensions, &PaymentDistributions, RefundDimensions, + &DisputeDimensions, + DisputeDimensions, PaymentMethod, PaymentMethodType, AuthenticationType, diff --git a/crates/analytics/src/sqlx.rs b/crates/analytics/src/sqlx.rs index 1fb7a9b4509..0aeffeafa9e 100644 --- a/crates/analytics/src/sqlx.rs +++ b/crates/analytics/src/sqlx.rs @@ -144,6 +144,7 @@ impl super::payments::metrics::PaymentMetricAnalytics for SqlxClient {} impl super::payments::distribution::PaymentDistributionAnalytics for SqlxClient {} impl super::refunds::metrics::RefundMetricAnalytics for SqlxClient {} impl super::refunds::filters::RefundFilterAnalytics for SqlxClient {} +impl super::disputes::filters::DisputeFilterAnalytics for SqlxClient {} #[async_trait::async_trait] impl AnalyticsDataSource for SqlxClient { @@ -425,6 +426,35 @@ impl<'a> FromRow<'a, PgRow> for super::refunds::filters::RefundFilterRow { } } +impl<'a> FromRow<'a, PgRow> for super::disputes::filters::DisputeFilterRow { + fn from_row(row: &'a PgRow) -> sqlx::Result<Self> { + let dispute_stage: Option<String> = row.try_get("dispute_stage").or_else(|e| match e { + ColumnNotFound(_) => Ok(Default::default()), + e => Err(e), + })?; + let dispute_status: Option<String> = + row.try_get("dispute_status").or_else(|e| match e { + ColumnNotFound(_) => Ok(Default::default()), + e => Err(e), + })?; + let connector: Option<String> = row.try_get("connector").or_else(|e| match e { + ColumnNotFound(_) => Ok(Default::default()), + e => Err(e), + })?; + let connector_status: Option<String> = + row.try_get("connector_status").or_else(|e| match e { + ColumnNotFound(_) => Ok(Default::default()), + e => Err(e), + })?; + Ok(Self { + dispute_stage, + dispute_status, + connector, + connector_status, + }) + } +} + impl ToSql<SqlxClient> for PrimitiveDateTime { fn to_sql(&self, _table_engine: &TableEngine) -> error_stack::Result<String, ParsingError> { Ok(self.to_string()) diff --git a/crates/api_models/src/analytics.rs b/crates/api_models/src/analytics.rs index 1115d40b19d..c12f8e7adfe 100644 --- a/crates/api_models/src/analytics.rs +++ b/crates/api_models/src/analytics.rs @@ -5,6 +5,7 @@ use masking::Secret; use self::{ api_event::{ApiEventDimensions, ApiEventMetrics}, + disputes::DisputeDimensions, payments::{PaymentDimensions, PaymentDistributions, PaymentMetrics}, refunds::{RefundDimensions, RefundMetrics}, sdk_events::{SdkEventDimensions, SdkEventMetrics}, @@ -247,3 +248,26 @@ pub struct GetApiEventMetricRequest { #[serde(default)] pub delta: bool, } + +#[derive(Debug, serde::Deserialize, serde::Serialize)] +#[serde(rename_all = "camelCase")] + +pub struct GetDisputeFilterRequest { + pub time_range: TimeRange, + #[serde(default)] + pub group_by_names: Vec<DisputeDimensions>, +} + +#[derive(Debug, Default, serde::Serialize, Eq, PartialEq)] +#[serde(rename_all = "camelCase")] +pub struct DisputeFiltersResponse { + pub query_data: Vec<DisputeFilterValue>, +} + +#[derive(Debug, serde::Serialize, Eq, PartialEq)] +#[serde(rename_all = "camelCase")] + +pub struct DisputeFilterValue { + pub dimension: DisputeDimensions, + pub values: Vec<String>, +} diff --git a/crates/api_models/src/analytics/disputes.rs b/crates/api_models/src/analytics/disputes.rs index 19d552d45d4..4b4b7ba3830 100644 --- a/crates/api_models/src/analytics/disputes.rs +++ b/crates/api_models/src/analytics/disputes.rs @@ -44,6 +44,7 @@ pub enum DisputeDimensions { Connector, DisputeStatus, ConnectorStatus, + DisputeStage, } impl From<DisputeDimensions> for NameDescription { diff --git a/crates/api_models/src/events.rs b/crates/api_models/src/events.rs index ae0525ac609..59b2d54016a 100644 --- a/crates/api_models/src/events.rs +++ b/crates/api_models/src/events.rs @@ -95,7 +95,9 @@ impl_misc_api_event_type!( SdkEventsRequest, ReportRequest, ConnectorEventsRequest, - OutgoingWebhookLogsRequest + OutgoingWebhookLogsRequest, + GetDisputeFilterRequest, + DisputeFiltersResponse ); #[cfg(feature = "stripe")] diff --git a/crates/router/src/analytics.rs b/crates/router/src/analytics.rs index 325ca980243..d126d23c8ae 100644 --- a/crates/router/src/analytics.rs +++ b/crates/router/src/analytics.rs @@ -88,6 +88,10 @@ pub mod routes { web::resource("metrics/api_events") .route(web::post().to(get_api_events_metrics)), ) + .service( + web::resource("filters/disputes") + .route(web::post().to(get_dispute_filters)), + ) } route } @@ -582,4 +586,30 @@ pub mod routes { )) .await } + + pub async fn get_dispute_filters( + state: web::Data<AppState>, + req: actix_web::HttpRequest, + json_payload: web::Json<api_models::analytics::GetDisputeFilterRequest>, + ) -> impl Responder { + let flow = AnalyticsFlow::GetDisputeFilters; + Box::pin(api::server_wrap( + flow, + state, + &req, + json_payload.into_inner(), + |state, auth: AuthenticationData, req| async move { + analytics::disputes::get_filters( + &state.pool, + req, + &auth.merchant_account.merchant_id, + ) + .await + .map(ApplicationResponse::Json) + }, + &auth::JWTAuth(Permission::Analytics), + api_locking::LockAction::NotApplicable, + )) + .await + } } diff --git a/crates/router_env/src/lib.rs b/crates/router_env/src/lib.rs index 9139b5eed41..be6aa257d74 100644 --- a/crates/router_env/src/lib.rs +++ b/crates/router_env/src/lib.rs @@ -54,6 +54,7 @@ pub enum AnalyticsFlow { GetApiEventFilters, GetConnectorEvents, GetOutgoingWebhookEvents, + GetDisputeFilters, } impl FlowMetric for AnalyticsFlow {}
2024-02-20T10:56:43Z
## Type of Change <!-- Put an `x` in the boxes that apply --> - [ ] Bugfix - [x] New feature - [ ] Enhancement - [ ] Refactoring - [ ] Dependency updates - [ ] Documentation - [ ] CI/CD ## Description added filter api for dispute analytics ### 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? Hit the curl mentioned in the comment below. response should be the distinct value of dispute dimension given in request To get the dispute dimensions hit dispute info api follow the link below https://github.com/juspay/hyperswitch/pull/3693 ## 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 - [ ] I added a [CHANGELOG](/CHANGELOG.md) entry if applicable
cf3c66636ffee30cdd4353b276a89a8f9fc2d9d0
Hit the curl mentioned in the comment below. response should be the distinct value of dispute dimension given in request To get the dispute dimensions hit dispute info api follow the link below https://github.com/juspay/hyperswitch/pull/3693
juspay/hyperswitch
juspay__hyperswitch-3716
Bug: [BUG] Payment status changes when capture method validation fails ### Bug Description If a connector doesn't support a particular capture method, confirm call fails and payment status changes to processing. ### Expected Behavior If a connector doesn't support a particular capture method, confirm call should fail and payment status should remain unchanged. ### Actual Behavior If a connector doesn't support a particular capture method, confirm call fails and payment status changes to processing. ### Steps To Reproduce Provide an unambiguous set of steps to reproduce this bug. Include code or configuration to reproduce, if relevant. 1. Create a merchant with stripe connector 2. Create a payment with capture method `manual_multiple` and `cofirm = false`. Status with be `requires_confirmation`. 3. Confirm the payment. Confirm operation will fail and status will change to processing. ### 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/router/src/core/payments/flows/authorize_flow.rs b/crates/router/src/core/payments/flows/authorize_flow.rs index 7842678a92a..d7d122c3252 100644 --- a/crates/router/src/core/payments/flows/authorize_flow.rs +++ b/crates/router/src/core/payments/flows/authorize_flow.rs @@ -72,13 +72,6 @@ impl Feature<api::Authorize, types::PaymentsAuthorizeData> for types::PaymentsAu types::PaymentsAuthorizeData, types::PaymentsResponseData, > = connector.connector.get_connector_integration(); - connector - .connector - .validate_capture_method( - self.request.capture_method, - self.request.payment_method_type, - ) - .to_payment_failed_response()?; if self.should_proceed_with_authorize() { self.decide_authentication_type(); @@ -210,13 +203,19 @@ impl Feature<api::Authorize, types::PaymentsAuthorizeData> for types::PaymentsAu ) -> RouterResult<(Option<services::Request>, bool)> { match call_connector_action { payments::CallConnectorAction::Trigger => { + connector + .connector + .validate_capture_method( + self.request.capture_method, + self.request.payment_method_type, + ) + .to_payment_failed_response()?; let connector_integration: services::BoxedConnectorIntegration< '_, api::Authorize, types::PaymentsAuthorizeData, types::PaymentsResponseData, > = connector.connector.get_connector_integration(); - connector_integration .execute_pretasks(self, state) .await
2024-02-20T07:43:54Z
## 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 capture method validation is done in `decide_flows`(after update_trackers). Because of this intent status changes to `processing`. In this PR, I have validated capture method in `build_flow_specific_connector_request`(before udpate_trackers). Hence intent status will remain same as before. ### 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)? --> Manual 1. Create a merchant with stripe connector 2. Create a payment without payment_method_data and confirm: false and capture_method : manual_multiple. <img width="1728" alt="Screenshot 2024-02-20 at 1 03 21 PM" src="https://github.com/juspay/hyperswitch/assets/61539176/78b52bb8-42a6-499d-b588-3d7dc9cdde3c"> 3. Confirm the payment <img width="1728" alt="Screenshot 2024-02-20 at 1 03 37 PM" src="https://github.com/juspay/hyperswitch/assets/61539176/c318010e-9245-4adc-9e61-a6fce7c979c3"> 4. Do Psyn -> Status remains `requires payment method` <img width="1728" alt="Screenshot 2024-02-20 at 1 03 48 PM" src="https://github.com/juspay/hyperswitch/assets/61539176/fad5b52e-955a-405c-bc28-685a1ea58686"> ## 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 - [ ] I added a [CHANGELOG](/CHANGELOG.md) entry if applicable
073310c1f671ccbb71cc5c8725eca9771e511589
Manual 1. Create a merchant with stripe connector 2. Create a payment without payment_method_data and confirm: false and capture_method : manual_multiple. <img width="1728" alt="Screenshot 2024-02-20 at 1 03 21 PM" src="https://github.com/juspay/hyperswitch/assets/61539176/78b52bb8-42a6-499d-b588-3d7dc9cdde3c"> 3. Confirm the payment <img width="1728" alt="Screenshot 2024-02-20 at 1 03 37 PM" src="https://github.com/juspay/hyperswitch/assets/61539176/c318010e-9245-4adc-9e61-a6fce7c979c3"> 4. Do Psyn -> Status remains `requires payment method` <img width="1728" alt="Screenshot 2024-02-20 at 1 03 48 PM" src="https://github.com/juspay/hyperswitch/assets/61539176/fad5b52e-955a-405c-bc28-685a1ea58686">
juspay/hyperswitch
juspay__hyperswitch-3706
Bug: feat(invite): Send email to user if user already exist
diff --git a/crates/api_models/src/events/user.rs b/crates/api_models/src/events/user.rs index d7150af9bc7..ec3e2dce9b2 100644 --- a/crates/api_models/src/events/user.rs +++ b/crates/api_models/src/events/user.rs @@ -10,11 +10,12 @@ use crate::user::{ dashboard_metadata::{ GetMetaDataRequest, GetMetaDataResponse, GetMultipleMetaDataPayload, SetMetaDataRequest, }, - AuthorizeResponse, ChangePasswordRequest, ConnectAccountRequest, CreateInternalUserRequest, - DashboardEntryResponse, ForgotPasswordRequest, GetUsersResponse, InviteUserRequest, - InviteUserResponse, ReInviteUserRequest, ResetPasswordRequest, SendVerifyEmailRequest, - SignInResponse, SignUpRequest, SignUpWithMerchantIdRequest, SwitchMerchantIdRequest, - UpdateUserAccountDetailsRequest, UserMerchantCreate, VerifyEmailRequest, + AcceptInviteFromEmailRequest, AuthorizeResponse, ChangePasswordRequest, ConnectAccountRequest, + CreateInternalUserRequest, DashboardEntryResponse, ForgotPasswordRequest, GetUsersResponse, + InviteUserRequest, InviteUserResponse, ReInviteUserRequest, ResetPasswordRequest, + SendVerifyEmailRequest, SignInResponse, SignUpRequest, SignUpWithMerchantIdRequest, + SwitchMerchantIdRequest, UpdateUserAccountDetailsRequest, UserMerchantCreate, + VerifyEmailRequest, }; impl ApiEventMetric for DashboardEntryResponse { @@ -57,6 +58,7 @@ common_utils::impl_misc_api_event_type!( ReInviteUserRequest, VerifyEmailRequest, SendVerifyEmailRequest, + AcceptInviteFromEmailRequest, SignInResponse, UpdateUserAccountDetailsRequest ); diff --git a/crates/api_models/src/user.rs b/crates/api_models/src/user.rs index c3e6908c733..8f77f72aad5 100644 --- a/crates/api_models/src/user.rs +++ b/crates/api_models/src/user.rs @@ -118,6 +118,11 @@ pub struct ReInviteUserRequest { pub email: pii::Email, } +#[derive(Debug, serde::Deserialize, serde::Serialize, Clone)] +pub struct AcceptInviteFromEmailRequest { + pub token: Secret<String>, +} + #[derive(Debug, serde::Deserialize, serde::Serialize)] pub struct SwitchMerchantIdRequest { pub merchant_id: String, diff --git a/crates/router/src/core/user.rs b/crates/router/src/core/user.rs index e7639af3918..dfcfe8dbcd4 100644 --- a/crates/router/src/core/user.rs +++ b/crates/router/src/core/user.rs @@ -464,7 +464,7 @@ pub async fn invite_user( .store .insert_user_role(UserRoleNew { user_id: invitee_user_from_db.get_user_id().to_owned(), - merchant_id: user_from_token.merchant_id, + merchant_id: user_from_token.merchant_id.clone(), role_id: request.role_id, org_id: user_from_token.org_id, status: { @@ -488,8 +488,34 @@ pub async fn invite_user( } })?; + let is_email_sent; + #[cfg(feature = "email")] + { + let email_contents = email_types::InviteRegisteredUser { + 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, + }; + + is_email_sent = state + .email_client + .compose_and_send_email( + Box::new(email_contents), + state.conf.proxy.https_url.as_ref(), + ) + .await + .map(|email_result| logger::info!(?email_result)) + .map_err(|email_result| logger::error!(?email_result)) + .is_ok(); + } + #[cfg(not(feature = "email"))] + { + is_email_sent = false; + } Ok(ApplicationResponse::Json(user_api::InviteUserResponse { - is_email_sent: false, + is_email_sent, password: None, })) } else if invitee_user @@ -681,9 +707,37 @@ async fn handle_existing_user_invitation( } })?; + let is_email_sent; + #[cfg(feature = "email")] + { + let invitee_email = domain::UserEmail::from_pii_email(request.email.clone())?; + let email_contents = email_types::InviteRegisteredUser { + 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(), + }; + + is_email_sent = state + .email_client + .compose_and_send_email( + Box::new(email_contents), + state.conf.proxy.https_url.as_ref(), + ) + .await + .map(|email_result| logger::info!(?email_result)) + .map_err(|email_result| logger::error!(?email_result)) + .is_ok(); + } + #[cfg(not(feature = "email"))] + { + is_email_sent = false; + } + Ok(InviteMultipleUserResponse { email: request.email.clone(), - is_email_sent: false, + is_email_sent, password: None, error: None, }) @@ -840,6 +894,67 @@ pub async fn resend_invite( Ok(ApplicationResponse::StatusOk) } +#[cfg(feature = "email")] +pub async fn accept_invite_from_email( + state: AppState, + 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 + .store + .find_user_by_email(email_token.get_email()) + .await + .change_context(UserErrors::InternalServerError)? + .into(); + + let merchant_id = email_token + .get_merchant_id() + .ok_or(UserErrors::InternalServerError)?; + + let update_status_result = state + .store + .update_user_role_by_user_id_merchant_id( + user.get_user_id(), + merchant_id, + UserRoleUpdate::UpdateStatus { + status: UserStatus::Active, + modified_by: user.get_user_id().to_string(), + }, + ) + .await + .change_context(UserErrors::InternalServerError)?; + + let _ = auth::blacklist::insert_email_token_in_blacklist(&state, &token) + .await + .map_err(|e| logger::error!(?e)); + + let user_from_db: domain::UserFromStorage = state + .store + .update_user_by_user_id(user.get_user_id(), storage_user::UserUpdate::VerifyUser) + .await + .change_context(UserErrors::InternalServerError)? + .into(); + + let token = + utils::user::generate_jwt_auth_token(&state, &user_from_db, &update_status_result).await?; + + Ok(ApplicationResponse::Json( + utils::user::get_dashboard_entry_response( + &state, + user_from_db, + update_status_result, + token, + )?, + )) +} + pub async fn create_internal_user( state: AppState, request: user_api::CreateInternalUserRequest, diff --git a/crates/router/src/routes/app.rs b/crates/router/src/routes/app.rs index 41881c60ff7..e9e4b67c782 100644 --- a/crates/router/src/routes/app.rs +++ b/crates/router/src/routes/app.rs @@ -1020,7 +1020,11 @@ impl User { web::resource("/verify_email_request") .route(web::post().to(verify_email_request)), ) - .service(web::resource("/user/resend_invite").route(web::post().to(resend_invite))); + .service(web::resource("/user/resend_invite").route(web::post().to(resend_invite))) + .service( + web::resource("/accept_invite_from_email") + .route(web::post().to(accept_invite_from_email)), + ); } #[cfg(not(feature = "email"))] { diff --git a/crates/router/src/routes/lock_utils.rs b/crates/router/src/routes/lock_utils.rs index 9393e8ae212..efdbb57b33c 100644 --- a/crates/router/src/routes/lock_utils.rs +++ b/crates/router/src/routes/lock_utils.rs @@ -188,6 +188,7 @@ impl From<Flow> for ApiIdentifier { | Flow::UserSignUpWithMerchantId | Flow::VerifyEmailWithoutInviteChecks | Flow::VerifyEmail + | Flow::AcceptInviteFromEmail | Flow::VerifyEmailRequest | Flow::UpdateUserAccountDetails => Self::User, diff --git a/crates/router/src/routes/user.rs b/crates/router/src/routes/user.rs index a863bc2b662..dacfe0e59a6 100644 --- a/crates/router/src/routes/user.rs +++ b/crates/router/src/routes/user.rs @@ -420,6 +420,25 @@ pub async fn resend_invite( .await } +#[cfg(feature = "email")] +pub async fn accept_invite_from_email( + state: web::Data<AppState>, + req: HttpRequest, + payload: web::Json<user_api::AcceptInviteFromEmailRequest>, +) -> HttpResponse { + let flow = Flow::AcceptInviteFromEmail; + 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 +} + #[cfg(feature = "email")] pub async fn verify_email_without_invite_checks( state: web::Data<AppState>, diff --git a/crates/router/src/services/email/types.rs b/crates/router/src/services/email/types.rs index 598a2620937..46cfad08783 100644 --- a/crates/router/src/services/email/types.rs +++ b/crates/router/src/services/email/types.rs @@ -28,6 +28,10 @@ pub enum EmailBody { link: String, user_name: String, }, + AcceptInviteFromEmail { + link: String, + user_name: String, + }, BizEmailProd { user_name: String, poc_email: String, @@ -78,6 +82,14 @@ pub mod html { link = link ) } + // TODO: Change the linked html for accept invite from email + EmailBody::AcceptInviteFromEmail { link, user_name } => { + format!( + include_str!("assets/invite.html"), + username = user_name, + link = link + ) + } EmailBody::ReconActivation { user_name } => { format!( include_str!("assets/recon_activation.html"), @@ -287,6 +299,42 @@ impl EmailData for InviteUser { }) } } +pub struct InviteRegisteredUser { + pub recipient_email: domain::UserEmail, + pub user_name: domain::UserName, + pub settings: std::sync::Arc<configs::settings::Settings>, + pub subject: &'static str, + pub merchant_id: 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()), + &self.settings, + ) + .await + .change_context(EmailError::TokenGenerationFailure)?; + + let invite_user_link = get_link_with_token( + &self.settings.email.base_url, + token, + "accept_invite_from_email", + ); + let body = html::get_html_body(EmailBody::AcceptInviteFromEmail { + 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 ReconActivation { pub recipient_email: domain::UserEmail, diff --git a/crates/router_env/src/logger/types.rs b/crates/router_env/src/logger/types.rs index 6649b89911a..994b134520e 100644 --- a/crates/router_env/src/logger/types.rs +++ b/crates/router_env/src/logger/types.rs @@ -339,6 +339,8 @@ pub enum Flow { InviteMultipleUser, /// Reinvite user ReInviteUser, + /// Accept invite from email + AcceptInviteFromEmail, /// Delete user role DeleteUserRole, /// Incremental Authorization flow
2024-02-19T13:29:01Z
## 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 will send an email to the user if the user already exist ### 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). --> If the user was already exists then we were directly activating the user. With this PR it will send an email to the user and it will redirect it directly to the dashboard ## How did you test it? 1. Request: ``` curl --location 'http://localhost:8080/user/user/invite_user \ --header 'Content-Type: application/json' \ --header 'Authorization: Bearer JWT of org_admin user' \ --data-raw '{ "email": "email of the user who already signed up“, "name":"some name", "role_id":"some valid role" } ``` Response ``` {"is_email_sent":true,"password":null} ``` 2. Email will be sent to the user email 3. Copy token from the link 4. Request ``` curl --location 'http://localhost:8080/user/activate_from_email\ --header 'Content-Type: application/json' \ --header 'Authorization: Bearer JWT of org_admin user' \ --data-raw '{ "token": copied token } ``` Response ``` { "token": "JWT", "merchant_id": "merchant_id", "name": "name from email", "email": "invited_email ", "verification_days_left": null, "user_role": "invited_role" } ``` ## 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 - [ ] I added a [CHANGELOG](/CHANGELOG.md) entry if applicable
deec8b4eb5493b072eaef0352a735748979cd95d
1. Request: ``` curl --location 'http://localhost:8080/user/user/invite_user \ --header 'Content-Type: application/json' \ --header 'Authorization: Bearer JWT of org_admin user' \ --data-raw '{ "email": "email of the user who already signed up“, "name":"some name", "role_id":"some valid role" } ``` Response ``` {"is_email_sent":true,"password":null} ``` 2. Email will be sent to the user email 3. Copy token from the link 4. Request ``` curl --location 'http://localhost:8080/user/activate_from_email\ --header 'Content-Type: application/json' \ --header 'Authorization: Bearer JWT of org_admin user' \ --data-raw '{ "token": copied token } ``` Response ``` { "token": "JWT", "merchant_id": "merchant_id", "name": "name from email", "email": "invited_email ", "verification_days_left": null, "user_role": "invited_role" } ```
juspay/hyperswitch
juspay__hyperswitch-3699
Bug: [FIX] add unresponsive timeout for redis This will check if a connection is unresponsive, if it is it will try to re-construct the connection
diff --git a/Cargo.lock b/Cargo.lock index 2c9293c1701..b466a161097 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -2610,9 +2610,9 @@ dependencies = [ [[package]] name = "fred" -version = "7.1.0" +version = "7.1.2" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "9282e65613822eea90c99872c51afa1de61542215cb11f91456a93f50a5a131a" +checksum = "b99c2b48934cd02a81032dd7428b7ae831a27794275bc94eba367418db8a9e55" dependencies = [ "arc-swap", "async-trait", diff --git a/config/config.example.toml b/config/config.example.toml index abe3f6b4e08..028f689d796 100644 --- a/config/config.example.toml +++ b/config/config.example.toml @@ -54,9 +54,10 @@ use_legacy_version = false # Resp protocol for fred crate (set this to tr stream_read_count = 1 # Default number of entries to read from stream if not provided in stream read options auto_pipeline = true # Whether or not the client should automatically pipeline commands across tasks when possible. disable_auto_backpressure = false # Whether or not to disable the automatic backpressure features when pipelining is enabled. -max_in_flight_commands = 5000 # The maximum number of in-flight commands (per connection) before backpressure will be applied. -default_command_timeout = 0 # An optional timeout to apply to all commands. -max_feed_count = 200 # The maximum number of frames that will be fed to a socket before flushing. +max_in_flight_commands = 5000 # The maximum number of in-flight commands (per connection) before backpressure will be applied. +default_command_timeout = 30 # An optional timeout to apply to all commands. In seconds +unresponsive_timeout = 10 # An optional timeout for Unresponsive commands in seconds. This should be less than default_command_timeout. +max_feed_count = 200 # The maximum number of frames that will be fed to a socket before flushing. # This section provides configs for currency conversion api [forex_api] diff --git a/config/deployments/env_specific.toml b/config/deployments/env_specific.toml index c8c118d9827..990796c79bc 100644 --- a/config/deployments/env_specific.toml +++ b/config/deployments/env_specific.toml @@ -169,9 +169,10 @@ use_legacy_version = false # RESP p stream_read_count = 1 # Default number of entries to read from stream if not provided in stream read options auto_pipeline = true # Whether or not the client should automatically pipeline commands across tasks when possible. disable_auto_backpressure = false # Whether or not to disable the automatic backpressure features when pipelining is enabled. -max_in_flight_commands = 5000 # The maximum number of in-flight commands (per connection) before backpressure will be applied. -default_command_timeout = 0 # An optional timeout to apply to all commands. -max_feed_count = 200 # The maximum number of frames that will be fed to a socket before flushing. +max_in_flight_commands = 5000 # The maximum number of in-flight commands (per connection) before backpressure will be applied. +default_command_timeout = 30 # An optional timeout to apply to all commands. In seconds +unresponsive_timeout = 10 # An optional timeout for Unresponsive commands in seconds. This should be less than default_command_timeout. +max_feed_count = 200 # The maximum number of frames that will be fed to a socket before flushing. cluster_enabled = true # boolean cluster_urls = ["redis.cluster.uri-1:8080", "redis.cluster.uri-2:4115"] # List of redis cluster urls diff --git a/config/development.toml b/config/development.toml index d69719bd419..2fab7deeb3e 100644 --- a/config/development.toml +++ b/config/development.toml @@ -44,7 +44,8 @@ stream_read_count = 1 auto_pipeline = true disable_auto_backpressure = false max_in_flight_commands = 5000 -default_command_timeout = 0 +default_command_timeout = 30 +unresponsive_timeout = 10 max_feed_count = 200 diff --git a/config/docker_compose.toml b/config/docker_compose.toml index 8170132bb85..e0de31dfbb7 100644 --- a/config/docker_compose.toml +++ b/config/docker_compose.toml @@ -78,7 +78,8 @@ stream_read_count = 1 auto_pipeline = true disable_auto_backpressure = false max_in_flight_commands = 5000 -default_command_timeout = 0 +default_command_timeout = 30 +unresponsive_timeout = 10 max_feed_count = 200 [cors] diff --git a/crates/redis_interface/Cargo.toml b/crates/redis_interface/Cargo.toml index 32e850a073f..85cfef3df54 100644 --- a/crates/redis_interface/Cargo.toml +++ b/crates/redis_interface/Cargo.toml @@ -9,7 +9,7 @@ license.workspace = true [dependencies] error-stack = "0.3.1" -fred = { version = "7.0.0", features = ["metrics", "partial-tracing", "subscriber-client"] } +fred = { version = "7.1.2", features = ["metrics", "partial-tracing", "subscriber-client", "check-unresponsive"] } futures = "0.3" serde = { version = "1.0.193", features = ["derive"] } thiserror = "1.0.40" diff --git a/crates/redis_interface/src/lib.rs b/crates/redis_interface/src/lib.rs index 33d40ebe155..b46e4aec191 100644 --- a/crates/redis_interface/src/lib.rs +++ b/crates/redis_interface/src/lib.rs @@ -132,6 +132,11 @@ impl RedisConnectionPool { }, }; + let connection_config = fred::types::ConnectionConfig { + unresponsive_timeout: std::time::Duration::from_secs(conf.unresponsive_timeout), + ..fred::types::ConnectionConfig::default() + }; + if !conf.use_legacy_version { config.version = fred::types::RespVersion::RESP3; } @@ -151,7 +156,7 @@ impl RedisConnectionPool { let pool = fred::prelude::RedisPool::new( config, Some(perf), - None, + Some(connection_config), Some(reconnect_policy), conf.pool_size, ) @@ -201,6 +206,15 @@ impl RedisConnectionPool { } } } + + pub async fn on_unresponsive(&self) { + let _ = self.pool.clients().iter().map(|client| { + client.on_unresponsive(|server| { + logger::warn!(redis_server =?server.host, "Redis server is unresponsive"); + Ok(()) + }) + }); + } } struct RedisConfig { diff --git a/crates/redis_interface/src/types.rs b/crates/redis_interface/src/types.rs index 4ebb620c36a..cb883fc1693 100644 --- a/crates/redis_interface/src/types.rs +++ b/crates/redis_interface/src/types.rs @@ -57,6 +57,7 @@ pub struct RedisSettings { pub max_in_flight_commands: u64, pub default_command_timeout: u64, pub max_feed_count: u64, + pub unresponsive_timeout: u64, } impl RedisSettings { @@ -76,7 +77,17 @@ impl RedisSettings { "Redis `cluster_urls` must be specified if `cluster_enabled` is `true`".into(), )) .into_report() - }) + })?; + + when( + self.default_command_timeout < self.unresponsive_timeout, + || { + Err(errors::RedisError::InvalidConfiguration( + "Unresponsive timeout cannot be greater than the command timeout".into(), + )) + .into_report() + }, + ) } } @@ -97,8 +108,9 @@ impl Default for RedisSettings { auto_pipeline: true, disable_auto_backpressure: false, max_in_flight_commands: 5000, - default_command_timeout: 0, + default_command_timeout: 30, max_feed_count: 200, + unresponsive_timeout: 10, } } }
2024-01-17T08:43:10Z
## Type of Change <!-- Put an `x` in the boxes that apply --> - [x] Enhancement ## Description <!-- Describe your changes in detail --> Enable `check-unresponsive` in fred and update the version to `7.1.2` ## 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 retry the command automatically every second(ref: https://github.com/aembke/fred.rs/blob/52bff989263b8bb27030be4e20fd313e65608b44/examples/globals.rs#L22) until `unresponsive_timeout` is exhausted. For retry it tries if one succeeds other will be discarded(ref: https://github.com/aembke/fred.rs/blob/52bff989263b8bb27030be4e20fd313e65608b44/src/router/utils.rs#L566) . ## 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)? --> - Sanity Test with Payments and Refunds. **This change cannot be tested since we cannot reproduce the situation in sandbox** ## 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
15b367eb792448fb3f3312484ab13dd8241d4a14
- Sanity Test with Payments and Refunds. **This change cannot be tested since we cannot reproduce the situation in sandbox**
juspay/hyperswitch
juspay__hyperswitch-3717
Bug: feat: change role apis to support custom roles
diff --git a/crates/api_models/src/user_role.rs b/crates/api_models/src/user_role.rs index 215227b91a3..1c4c28aa993 100644 --- a/crates/api_models/src/user_role.rs +++ b/crates/api_models/src/user_role.rs @@ -1,3 +1,4 @@ +use common_enums::RoleScope; use common_utils::pii; use crate::user::DashboardEntryResponse; @@ -7,9 +8,10 @@ pub struct ListRolesResponse(pub Vec<RoleInfoResponse>); #[derive(Debug, serde::Serialize)] pub struct RoleInfoResponse { - pub role_id: &'static str, + pub role_id: String, pub permissions: Vec<Permission>, - pub role_name: &'static str, + pub role_name: String, + pub role_scope: RoleScope, } #[derive(Debug, serde::Deserialize, serde::Serialize)] diff --git a/crates/router/src/analytics.rs b/crates/router/src/analytics.rs index d126d23c8ae..51fb6ff822b 100644 --- a/crates/router/src/analytics.rs +++ b/crates/router/src/analytics.rs @@ -497,7 +497,7 @@ pub mod routes { .await .map(ApplicationResponse::Json) }, - &auth::JWTAuth(Permission::Analytics), + &auth::JWTAuth(Permission::PaymentWrite), api_locking::LockAction::NotApplicable, )) .await diff --git a/crates/router/src/core/user.rs b/crates/router/src/core/user.rs index e7639af3918..5b634920cf6 100644 --- a/crates/router/src/core/user.rs +++ b/crates/router/src/core/user.rs @@ -18,10 +18,8 @@ use crate::services::email::types as email_types; use crate::{ consts, routes::AppState, - services::{ - authentication as auth, authorization::predefined_permissions, ApplicationResponse, - }, - types::domain, + services::{authentication as auth, authorization::roles, ApplicationResponse}, + types::{domain, transformers::ForeignInto}, utils, }; pub mod dashboard_metadata; @@ -444,7 +442,16 @@ pub async fn invite_user( .into()); } - if !predefined_permissions::is_role_invitable(request.role_id.as_str())? { + let role_info = roles::get_role_info_from_role_id( + &state, + &request.role_id, + &user_from_token.merchant_id, + &user_from_token.org_id, + ) + .await + .to_not_found_response(UserErrors::InvalidRoleId)?; + + if !role_info.is_invitable() { return Err(UserErrors::InvalidRoleId.into()) .attach_printable(format!("role_id = {} is not invitable", request.role_id)); } @@ -626,7 +633,16 @@ async fn handle_invitation( .into()); } - if !predefined_permissions::is_role_invitable(request.role_id.as_str())? { + let role_info = roles::get_role_info_from_role_id( + state, + &request.role_id, + &user_from_token.merchant_id, + &user_from_token.org_id, + ) + .await + .to_not_found_response(UserErrors::InvalidRoleId)?; + + if !role_info.is_invitable() { return Err(UserErrors::InvalidRoleId.into()) .attach_printable(format!("role_id = {} is not invitable", request.role_id)); } @@ -915,20 +931,18 @@ pub async fn switch_merchant_id( .into()); } - let user_roles = state - .store - .list_user_roles_by_user_id(&user_from_token.user_id) - .await - .change_context(UserErrors::InternalServerError)?; - - let active_user_roles = user_roles - .into_iter() - .filter(|role| role.status == UserStatus::Active) - .collect::<Vec<_>>(); - let user = user_from_token.get_user_from_db(&state).await?; - let (token, role_id) = if utils::user_role::is_internal_role(&user_from_token.role_id) { + let role_info = roles::get_role_info_from_role_id( + &state, + &user_from_token.role_id, + &user_from_token.merchant_id, + &user_from_token.org_id, + ) + .await + .to_not_found_response(UserErrors::InternalServerError)?; + + let (token, role_id) = if role_info.is_internal() { let key_store = state .store .get_merchant_key_store_by_merchant_id( @@ -967,6 +981,17 @@ pub async fn switch_merchant_id( .await?; (token, user_from_token.role_id) } else { + let user_roles = state + .store + .list_user_roles_by_user_id(&user_from_token.user_id) + .await + .change_context(UserErrors::InternalServerError)?; + + let active_user_roles = user_roles + .into_iter() + .filter(|role| role.status == UserStatus::Active) + .collect::<Vec<_>>(); + let user_role = active_user_roles .iter() .find(|role| role.merchant_id == request.merchant_id) @@ -1051,17 +1076,47 @@ pub async fn get_users_for_merchant_account( state: AppState, user_from_token: auth::UserFromToken, ) -> UserResponse<user_api::GetUsersResponse> { - let users = state + let users_and_user_roles = state .store .find_users_and_roles_by_merchant_id(user_from_token.merchant_id.as_str()) .await .change_context(UserErrors::InternalServerError) - .attach_printable("No users for given merchant id")? + .attach_printable("No users for given merchant id")?; + + let users_user_roles_and_roles = + futures::future::try_join_all(users_and_user_roles.into_iter().map( + |(user, user_role)| async { + roles::get_role_info_from_role_id( + &state, + &user_role.role_id, + &user_role.merchant_id, + &user_role.org_id, + ) + .await + .map(|role_info| (user, user_role, role_info)) + .to_not_found_response(UserErrors::InternalServerError) + }, + )) + .await?; + + let user_details_vec = users_user_roles_and_roles .into_iter() - .filter_map(|(user, role)| domain::UserAndRoleJoined(user, role).try_into().ok()) + .map(|(user, user_role, role_info)| { + let user = domain::UserFromStorage::from(user); + user_api::UserDetails { + email: user.get_email(), + name: user.get_name(), + role_id: user_role.role_id, + role_name: role_info.get_role_name().to_string(), + status: user_role.status.foreign_into(), + last_modified_at: user_role.last_modified, + } + }) .collect(); - Ok(ApplicationResponse::Json(user_api::GetUsersResponse(users))) + Ok(ApplicationResponse::Json(user_api::GetUsersResponse( + user_details_vec, + ))) } #[cfg(feature = "email")] diff --git a/crates/router/src/core/user_role.rs b/crates/router/src/core/user_role.rs index 16047bc3eb7..c2dfd34322c 100644 --- a/crates/router/src/core/user_role.rs +++ b/crates/router/src/core/user_role.rs @@ -10,7 +10,7 @@ use crate::{ routes::AppState, services::{ authentication::{self as auth}, - authorization::{info, predefined_permissions}, + authorization::{info, roles}, ApplicationResponse, }, types::domain, @@ -30,58 +30,96 @@ pub async fn get_authorization_info( )) } -pub async fn list_roles(_state: AppState) -> UserResponse<user_role_api::ListRolesResponse> { +pub async fn list_invitable_roles( + state: AppState, + user_from_token: auth::UserFromToken, +) -> UserResponse<user_role_api::ListRolesResponse> { + let predefined_roles_map = roles::predefined_roles::PREDEFINED_ROLES + .iter() + .filter(|(_, role_info)| role_info.is_invitable()) + .map(|(role_id, role_info)| user_role_api::RoleInfoResponse { + 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() + .map(roles::RoleInfo::from) + .filter(|role_info| role_info.is_invitable()) + .map(|role_info| user_role_api::RoleInfoResponse { + 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(user_role_api::ListRolesResponse( - predefined_permissions::PREDEFINED_PERMISSIONS - .iter() - .filter(|(_, role_info)| role_info.is_invitable()) - .filter_map(|(role_id, role_info)| { - utils::user_role::get_role_name_and_permission_response(role_info).map( - |(permissions, role_name)| user_role_api::RoleInfoResponse { - permissions, - role_id, - role_name, - }, - ) - }) - .collect(), + predefined_roles_map.chain(custom_roles_map).collect(), ))) } pub async fn get_role( - _state: AppState, + state: AppState, + user_from_token: auth::UserFromToken, role: user_role_api::GetRoleRequest, ) -> UserResponse<user_role_api::RoleInfoResponse> { - let info = predefined_permissions::PREDEFINED_PERMISSIONS - .get_key_value(role.role_id.as_str()) - .and_then(|(role_id, role_info)| { - utils::user_role::get_role_name_and_permission_response(role_info).map( - |(permissions, role_name)| user_role_api::RoleInfoResponse { - permissions, - role_id, - role_name, - }, - ) - }) - .ok_or(UserErrors::InvalidRoleId)?; + let role_info = roles::get_role_info_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()); + } - Ok(ApplicationResponse::Json(info)) + let permissions = role_info + .get_permissions_set() + .into_iter() + .map(Into::into) + .collect(); + + Ok(ApplicationResponse::Json(user_role_api::RoleInfoResponse { + 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_from_token( - _state: AppState, - user: auth::UserFromToken, + state: AppState, + user_from_token: auth::UserFromToken, ) -> UserResponse<Vec<user_role_api::Permission>> { - Ok(ApplicationResponse::Json( - predefined_permissions::PREDEFINED_PERMISSIONS - .get(user.role_id.as_str()) - .ok_or(UserErrors::InternalServerError.into()) - .attach_printable("Invalid Role Id in JWT")? - .get_permissions() - .iter() - .map(|&per| per.into()) - .collect(), - )) + 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(permissions)) } pub async fn update_user_role( @@ -89,7 +127,16 @@ pub async fn update_user_role( user_from_token: auth::UserFromToken, req: user_role_api::UpdateUserRoleRequest, ) -> UserResponse<()> { - if !predefined_permissions::is_role_updatable(&req.role_id)? { + let role_info = roles::get_role_info_from_role_id( + &state, + &req.role_id, + &user_from_token.merchant_id, + &user_from_token.org_id, + ) + .await + .to_not_found_response(UserErrors::InvalidRoleId)?; + + if !role_info.is_updatable() { return Err(UserErrors::InvalidRoleOperation.into()) .attach_printable(format!("User role cannot be updated to {}", req.role_id)); } @@ -110,10 +157,19 @@ pub async fn update_user_role( .await .to_not_found_response(UserErrors::InvalidRoleOperation)?; - if !predefined_permissions::is_role_updatable(&user_role_to_be_updated.role_id)? { + let role_to_be_updated = roles::get_role_info_from_role_id( + &state, + &user_role_to_be_updated.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(UserErrors::InvalidRoleOperation.into()).attach_printable(format!( "User role cannot be updated from {}", - user_role_to_be_updated.role_id + role_to_be_updated.get_role_id() )); } @@ -270,7 +326,15 @@ pub async fn delete_user_role( .find(|&role| role.merchant_id == user_from_token.merchant_id.as_str()) { Some(user_role) => { - if !predefined_permissions::is_role_deletable(&user_role.role_id)? { + let role_info = roles::get_role_info_from_role_id( + &state, + &user_role.role_id, + &user_from_token.merchant_id, + &user_from_token.org_id, + ) + .await + .change_context(UserErrors::InternalServerError)?; + if !role_info.is_deletable() { return Err(UserErrors::InvalidDeleteOperation.into()) .attach_printable(format!("role_id = {} is not deletable", user_role.role_id)); } diff --git a/crates/router/src/routes/user.rs b/crates/router/src/routes/user.rs index a863bc2b662..ea51383c94b 100644 --- a/crates/router/src/routes/user.rs +++ b/crates/router/src/routes/user.rs @@ -291,7 +291,7 @@ pub async fn delete_sample_data( &http_req, payload.into_inner(), sample_data::delete_sample_data_for_user, - &auth::JWTAuth(Permission::PaymentWrite), + &auth::JWTAuth(Permission::MerchantAccountWrite), api_locking::LockAction::NotApplicable, )) .await diff --git a/crates/router/src/routes/user_role.rs b/crates/router/src/routes/user_role.rs index f84c158332b..63e2ce37269 100644 --- a/crates/router/src/routes/user_role.rs +++ b/crates/router/src/routes/user_role.rs @@ -36,7 +36,7 @@ pub async fn list_all_roles(state: web::Data<AppState>, req: HttpRequest) -> Htt state.clone(), &req, (), - |state, _: (), _| user_role_core::list_roles(state), + |state, user, _| user_role_core::list_invitable_roles(state, user), &auth::JWTAuth(Permission::UsersRead), api_locking::LockAction::NotApplicable, )) @@ -57,7 +57,7 @@ pub async fn get_role( state.clone(), &req, request_payload, - |state, _: (), req| user_role_core::get_role(state, req), + user_role_core::get_role, &auth::JWTAuth(Permission::UsersRead), api_locking::LockAction::NotApplicable, )) diff --git a/crates/router/src/services/authentication.rs b/crates/router/src/services/authentication.rs index 1004982d292..34153ef6e8f 100644 --- a/crates/router/src/services/authentication.rs +++ b/crates/router/src/services/authentication.rs @@ -503,8 +503,8 @@ where return Err(errors::ApiErrorResponse::InvalidJwtToken.into()); } - let permissions = authorization::get_permissions(&payload.role_id)?; - authorization::check_authorization(&self.0, permissions)?; + let permissions = authorization::get_permissions(state, &payload).await?; + authorization::check_authorization(&self.0, &permissions)?; Ok(( (), @@ -532,8 +532,8 @@ where return Err(errors::ApiErrorResponse::InvalidJwtToken.into()); } - let permissions = authorization::get_permissions(&payload.role_id)?; - authorization::check_authorization(&self.0, permissions)?; + let permissions = authorization::get_permissions(state, &payload).await?; + authorization::check_authorization(&self.0, &permissions)?; Ok(( UserFromToken { @@ -570,8 +570,8 @@ where return Err(errors::ApiErrorResponse::InvalidJwtToken.into()); } - let permissions = authorization::get_permissions(&payload.role_id)?; - authorization::check_authorization(&self.required_permission, permissions)?; + let permissions = authorization::get_permissions(state, &payload).await?; + authorization::check_authorization(&self.required_permission, &permissions)?; // Check if token has access to MerchantId that has been requested through query param if payload.merchant_id != self.merchant_id { @@ -613,8 +613,8 @@ where return Err(errors::ApiErrorResponse::InvalidJwtToken.into()); } - let permissions = authorization::get_permissions(&payload.role_id)?; - authorization::check_authorization(&self.0, permissions)?; + let permissions = authorization::get_permissions(state, &payload).await?; + authorization::check_authorization(&self.0, &permissions)?; let key_store = state .store() @@ -663,8 +663,8 @@ where return Err(errors::ApiErrorResponse::InvalidJwtToken.into()); } - let permissions = authorization::get_permissions(&payload.role_id)?; - authorization::check_authorization(&self.0, permissions)?; + let permissions = authorization::get_permissions(state, &payload).await?; + authorization::check_authorization(&self.0, &permissions)?; let key_store = state .store() diff --git a/crates/router/src/services/authorization.rs b/crates/router/src/services/authorization.rs index cad9b1ece62..034773a07ea 100644 --- a/crates/router/src/services/authorization.rs +++ b/crates/router/src/services/authorization.rs @@ -1,14 +1,50 @@ -use crate::core::errors::{ApiErrorResponse, RouterResult}; +use common_enums::PermissionGroup; + +use super::authentication::AuthToken; +use crate::{ + core::errors::{ApiErrorResponse, RouterResult, StorageErrorExt}, + routes::app::AppStateInfo, +}; pub mod info; +pub mod permission_groups; pub mod permissions; -pub mod predefined_permissions; +pub mod roles; + +pub async fn get_permissions<A>( + state: &A, + token: &AuthToken, +) -> RouterResult<Vec<permissions::Permission>> +where + A: AppStateInfo + Sync, +{ + if let Some(role_info) = roles::predefined_roles::PREDEFINED_ROLES.get(token.role_id.as_str()) { + Ok(get_permissions_from_groups( + role_info.get_permission_groups(), + )) + } else { + state + .store() + .find_role_by_role_id_in_merchant_scope( + &token.role_id, + &token.merchant_id, + &token.org_id, + ) + .await + .map(|role| get_permissions_from_groups(&role.groups)) + .to_not_found_response(ApiErrorResponse::InvalidJwtToken) + } +} -pub fn get_permissions(role: &str) -> RouterResult<&Vec<permissions::Permission>> { - predefined_permissions::PREDEFINED_PERMISSIONS - .get(role) - .map(|role_info| role_info.get_permissions()) - .ok_or(ApiErrorResponse::InvalidJwtToken.into()) +pub fn get_permissions_from_groups(groups: &[PermissionGroup]) -> Vec<permissions::Permission> { + groups + .iter() + .flat_map(|group| { + permission_groups::get_permissions_vec(group) + .iter() + .cloned() + }) + .collect() } pub fn check_authorization( diff --git a/crates/router/src/services/authorization/permission_groups.rs b/crates/router/src/services/authorization/permission_groups.rs new file mode 100644 index 00000000000..246a4ce91dc --- /dev/null +++ b/crates/router/src/services/authorization/permission_groups.rs @@ -0,0 +1,86 @@ +use common_enums::PermissionGroup; + +use super::permissions::Permission; + +pub fn get_permissions_vec(permission_group: &PermissionGroup) -> &[Permission] { + match permission_group { + PermissionGroup::OperationsView => &OPERATIONS_VIEW, + PermissionGroup::OperationsManage => &OPERATIONS_MANAGE, + PermissionGroup::ConnectorsView => &CONNECTORS_VIEW, + PermissionGroup::ConnectorsManage => &CONNECTORS_MANAGE, + PermissionGroup::WorkflowsView => &WORKFLOWS_VIEW, + PermissionGroup::WorkflowsManage => &WORKFLOWS_MANAGE, + PermissionGroup::AnalyticsView => &ANALYTICS_VIEW, + PermissionGroup::UsersView => &USERS_VIEW, + PermissionGroup::UsersManage => &USERS_MANAGE, + PermissionGroup::MerchantDetailsView => &MERCHANT_DETAILS_VIEW, + PermissionGroup::MerchantDetailsManage => &MERCHANT_DETAILS_MANAGE, + PermissionGroup::OrganizationManage => &ORGANIZATION_MANAGE, + } +} + +pub static OPERATIONS_VIEW: [Permission; 6] = [ + Permission::PaymentRead, + Permission::RefundRead, + Permission::MandateRead, + Permission::DisputeRead, + Permission::CustomerRead, + Permission::MerchantAccountRead, +]; + +pub static OPERATIONS_MANAGE: [Permission; 6] = [ + Permission::PaymentWrite, + Permission::RefundWrite, + Permission::MandateWrite, + Permission::DisputeWrite, + Permission::CustomerWrite, + Permission::MerchantAccountRead, +]; + +pub static CONNECTORS_VIEW: [Permission; 2] = [ + Permission::MerchantConnectorAccountRead, + Permission::MerchantAccountRead, +]; + +pub static CONNECTORS_MANAGE: [Permission; 2] = [ + Permission::MerchantConnectorAccountWrite, + Permission::MerchantAccountRead, +]; + +pub static WORKFLOWS_VIEW: [Permission; 5] = [ + Permission::RoutingRead, + Permission::ThreeDsDecisionManagerRead, + Permission::SurchargeDecisionManagerRead, + Permission::MerchantConnectorAccountRead, + Permission::MerchantAccountRead, +]; + +pub static WORKFLOWS_MANAGE: [Permission; 5] = [ + Permission::RoutingWrite, + Permission::ThreeDsDecisionManagerWrite, + Permission::SurchargeDecisionManagerWrite, + Permission::MerchantConnectorAccountRead, + Permission::MerchantAccountRead, +]; + +pub static ANALYTICS_VIEW: [Permission; 2] = + [Permission::Analytics, Permission::MerchantAccountRead]; + +pub static USERS_VIEW: [Permission; 2] = [Permission::UsersRead, Permission::MerchantAccountRead]; + +pub static USERS_MANAGE: [Permission; 2] = + [Permission::UsersWrite, Permission::MerchantAccountRead]; + +pub static MERCHANT_DETAILS_VIEW: [Permission; 1] = [Permission::MerchantAccountRead]; + +pub static MERCHANT_DETAILS_MANAGE: [Permission; 4] = [ + Permission::MerchantAccountWrite, + Permission::ApiKeyRead, + Permission::ApiKeyWrite, + Permission::MerchantAccountRead, +]; + +pub static ORGANIZATION_MANAGE: [Permission; 2] = [ + Permission::MerchantAccountCreate, + Permission::MerchantAccountRead, +]; diff --git a/crates/router/src/services/authorization/permissions.rs b/crates/router/src/services/authorization/permissions.rs index 3e022e8f666..8d436618b32 100644 --- a/crates/router/src/services/authorization/permissions.rs +++ b/crates/router/src/services/authorization/permissions.rs @@ -1,6 +1,6 @@ use strum::Display; -#[derive(PartialEq, Display, Clone, Debug, Copy)] +#[derive(PartialEq, Display, Clone, Debug, Copy, Eq, Hash)] pub enum Permission { PaymentRead, PaymentWrite, diff --git a/crates/router/src/services/authorization/roles.rs b/crates/router/src/services/authorization/roles.rs new file mode 100644 index 00000000000..6372799f98c --- /dev/null +++ b/crates/router/src/services/authorization/roles.rs @@ -0,0 +1,100 @@ +use std::collections::HashSet; + +use common_enums::{PermissionGroup, RoleScope}; +use common_utils::errors::CustomResult; + +use super::{permission_groups::get_permissions_vec, permissions::Permission}; +use crate::{core::errors, routes::AppState}; + +pub mod predefined_roles; + +#[derive(Clone)] +pub struct RoleInfo { + role_id: String, + role_name: String, + groups: Vec<PermissionGroup>, + scope: RoleScope, + is_invitable: bool, + is_deletable: bool, + is_updatable: bool, + is_internal: bool, +} + +impl RoleInfo { + pub fn get_role_id(&self) -> &str { + &self.role_id + } + + pub fn get_role_name(&self) -> &str { + &self.role_name + } + + pub fn get_permission_groups(&self) -> &Vec<PermissionGroup> { + &self.groups + } + + pub fn get_scope(&self) -> RoleScope { + self.scope + } + + pub fn is_invitable(&self) -> bool { + self.is_invitable + } + + pub fn is_deletable(&self) -> bool { + self.is_deletable + } + + pub fn is_internal(&self) -> bool { + self.is_internal + } + + pub fn is_updatable(&self) -> bool { + self.is_updatable + } + + pub fn get_permissions_set(&self) -> HashSet<Permission> { + self.groups + .iter() + .flat_map(|group| get_permissions_vec(group).iter().copied()) + .collect() + } + + pub fn check_permission_exists(&self, required_permission: &Permission) -> bool { + self.groups + .iter() + .any(|group| get_permissions_vec(group).contains(required_permission)) + } +} + +pub async fn get_role_info_from_role_id( + state: &AppState, + role_id: &str, + merchant_id: &str, + org_id: &str, +) -> CustomResult<RoleInfo, errors::StorageError> { + if let Some(role) = predefined_roles::PREDEFINED_ROLES.get(role_id) { + Ok(role.clone()) + } else { + state + .store + .find_role_by_role_id_in_merchant_scope(role_id, merchant_id, org_id) + .await + .map(RoleInfo::from) + } +} + +impl From<diesel_models::role::Role> for RoleInfo { + fn from(role: diesel_models::role::Role) -> Self { + Self { + role_id: role.role_id, + role_name: role.role_name, + groups: role.groups.into_iter().map(Into::into).collect(), + scope: role.scope, + is_invitable: true, + is_deletable: true, + is_updatable: true, + is_internal: false, + } + } +} diff --git a/crates/router/src/services/authorization/roles/predefined_roles.rs b/crates/router/src/services/authorization/roles/predefined_roles.rs new file mode 100644 index 00000000000..9accf094ea4 --- /dev/null +++ b/crates/router/src/services/authorization/roles/predefined_roles.rs @@ -0,0 +1,210 @@ +use std::collections::HashMap; + +use common_enums::{PermissionGroup, RoleScope}; +use once_cell::sync::Lazy; + +use super::RoleInfo; +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, + RoleInfo { + groups: vec![ + PermissionGroup::OperationsView, + PermissionGroup::OperationsManage, + PermissionGroup::ConnectorsView, + PermissionGroup::ConnectorsManage, + PermissionGroup::WorkflowsView, + PermissionGroup::WorkflowsManage, + PermissionGroup::AnalyticsView, + PermissionGroup::UsersView, + PermissionGroup::UsersManage, + PermissionGroup::MerchantDetailsView, + PermissionGroup::MerchantDetailsManage, + PermissionGroup::OrganizationManage, + ], + role_id: consts::user_role::ROLE_ID_INTERNAL_ADMIN.to_string(), + role_name: "Internal Admin".to_string(), + scope: RoleScope::Organization, + is_invitable: false, + is_deletable: false, + is_updatable: false, + is_internal: true, + }, + ); + roles.insert( + consts::user_role::ROLE_ID_INTERNAL_VIEW_ONLY_USER, + RoleInfo { + groups: vec![ + PermissionGroup::OperationsView, + PermissionGroup::ConnectorsView, + PermissionGroup::WorkflowsView, + PermissionGroup::AnalyticsView, + PermissionGroup::UsersView, + PermissionGroup::MerchantDetailsView, + ], + role_id: consts::user_role::ROLE_ID_INTERNAL_VIEW_ONLY_USER.to_string(), + role_name: "Internal View Only".to_string(), + scope: RoleScope::Organization, + is_invitable: false, + is_deletable: false, + is_updatable: false, + is_internal: true, + }, + ); + + roles.insert( + consts::user_role::ROLE_ID_ORGANIZATION_ADMIN, + RoleInfo { + groups: vec![ + PermissionGroup::OperationsView, + PermissionGroup::OperationsManage, + PermissionGroup::ConnectorsView, + PermissionGroup::ConnectorsManage, + PermissionGroup::WorkflowsView, + PermissionGroup::WorkflowsManage, + PermissionGroup::AnalyticsView, + PermissionGroup::UsersView, + PermissionGroup::UsersManage, + PermissionGroup::MerchantDetailsView, + PermissionGroup::MerchantDetailsManage, + PermissionGroup::OrganizationManage, + ], + role_id: consts::user_role::ROLE_ID_ORGANIZATION_ADMIN.to_string(), + role_name: "Organization Admin".to_string(), + scope: RoleScope::Organization, + is_invitable: false, + is_deletable: false, + is_updatable: false, + is_internal: false, + }, + ); + + // MERCHANT ROLES + roles.insert( + consts::user_role::ROLE_ID_MERCHANT_ADMIN, + RoleInfo { + groups: vec![ + PermissionGroup::OperationsView, + PermissionGroup::OperationsManage, + PermissionGroup::ConnectorsView, + PermissionGroup::ConnectorsManage, + PermissionGroup::WorkflowsView, + PermissionGroup::WorkflowsManage, + PermissionGroup::AnalyticsView, + PermissionGroup::UsersView, + PermissionGroup::UsersManage, + PermissionGroup::MerchantDetailsView, + PermissionGroup::MerchantDetailsManage, + ], + role_id: consts::user_role::ROLE_ID_MERCHANT_ADMIN.to_string(), + role_name: "Admin".to_string(), + scope: RoleScope::Organization, + is_invitable: true, + is_deletable: true, + is_updatable: true, + is_internal: false, + }, + ); + roles.insert( + consts::user_role::ROLE_ID_MERCHANT_VIEW_ONLY, + RoleInfo { + groups: vec![ + PermissionGroup::OperationsView, + PermissionGroup::ConnectorsView, + PermissionGroup::WorkflowsView, + PermissionGroup::AnalyticsView, + PermissionGroup::UsersView, + PermissionGroup::MerchantDetailsView, + ], + role_id: consts::user_role::ROLE_ID_MERCHANT_VIEW_ONLY.to_string(), + role_name: "View Only".to_string(), + scope: RoleScope::Organization, + is_invitable: true, + is_deletable: true, + is_updatable: true, + is_internal: false, + }, + ); + roles.insert( + consts::user_role::ROLE_ID_MERCHANT_IAM_ADMIN, + RoleInfo { + groups: vec![ + PermissionGroup::OperationsView, + PermissionGroup::AnalyticsView, + PermissionGroup::UsersView, + PermissionGroup::UsersManage, + PermissionGroup::MerchantDetailsView, + ], + role_id: consts::user_role::ROLE_ID_MERCHANT_IAM_ADMIN.to_string(), + role_name: "IAM".to_string(), + scope: RoleScope::Organization, + is_invitable: true, + is_deletable: true, + is_updatable: true, + is_internal: false, + }, + ); + roles.insert( + consts::user_role::ROLE_ID_MERCHANT_DEVELOPER, + RoleInfo { + groups: vec![ + PermissionGroup::OperationsView, + PermissionGroup::ConnectorsView, + PermissionGroup::AnalyticsView, + PermissionGroup::UsersView, + PermissionGroup::MerchantDetailsView, + PermissionGroup::MerchantDetailsManage, + ], + role_id: consts::user_role::ROLE_ID_MERCHANT_DEVELOPER.to_string(), + role_name: "Developer".to_string(), + scope: RoleScope::Organization, + is_invitable: true, + is_deletable: true, + is_updatable: true, + is_internal: false, + }, + ); + roles.insert( + consts::user_role::ROLE_ID_MERCHANT_OPERATOR, + RoleInfo { + groups: vec![ + PermissionGroup::OperationsView, + PermissionGroup::OperationsManage, + PermissionGroup::ConnectorsView, + PermissionGroup::WorkflowsView, + PermissionGroup::AnalyticsView, + PermissionGroup::UsersView, + PermissionGroup::MerchantDetailsView, + ], + role_id: consts::user_role::ROLE_ID_MERCHANT_OPERATOR.to_string(), + role_name: "Operator".to_string(), + scope: RoleScope::Organization, + is_invitable: true, + is_deletable: true, + is_updatable: true, + is_internal: false, + }, + ); + roles.insert( + consts::user_role::ROLE_ID_MERCHANT_CUSTOMER_SUPPORT, + RoleInfo { + groups: vec![ + PermissionGroup::OperationsView, + PermissionGroup::AnalyticsView, + PermissionGroup::UsersView, + PermissionGroup::MerchantDetailsView, + ], + role_id: consts::user_role::ROLE_ID_MERCHANT_CUSTOMER_SUPPORT.to_string(), + role_name: "Customer Support".to_string(), + scope: RoleScope::Organization, + is_invitable: true, + is_deletable: true, + is_updatable: true, + is_internal: false, + }, + ); + roles +}); diff --git a/crates/router/src/types/domain/user.rs b/crates/router/src/types/domain/user.rs index ab32febf9b4..263b0e52b8a 100644 --- a/crates/router/src/types/domain/user.rs +++ b/crates/router/src/types/domain/user.rs @@ -25,11 +25,7 @@ use crate::{ }, db::StorageInterface, routes::AppState, - services::{ - authentication as auth, - authentication::UserFromToken, - authorization::{info, predefined_permissions}, - }, + services::{authentication as auth, authentication::UserFromToken, authorization::info}, types::transformers::ForeignFrom, utils::{self, user::password}, }; @@ -824,32 +820,6 @@ impl From<info::PermissionInfo> for user_role_api::PermissionInfo { } } -pub struct UserAndRoleJoined(pub storage_user::User, pub UserRole); - -impl TryFrom<UserAndRoleJoined> for user_api::UserDetails { - type Error = (); - fn try_from(user_and_role: UserAndRoleJoined) -> Result<Self, Self::Error> { - let status = match user_and_role.1.status { - UserStatus::Active => user_role_api::UserStatus::Active, - UserStatus::InvitationSent => user_role_api::UserStatus::InvitationSent, - }; - - let role_id = user_and_role.1.role_id; - let role_name = predefined_permissions::get_role_name_from_id(role_id.as_str()) - .ok_or(())? - .to_string(); - - Ok(Self { - email: user_and_role.0.email, - name: user_and_role.0.name, - role_id, - status, - role_name, - last_modified_at: user_and_role.0.last_modified_at, - }) - } -} - pub enum SignInWithRoleStrategyType { SingleRole(SignInWithSingleRoleStrategy), MultipleRoles(SignInWithMultipleRolesStrategy), @@ -947,3 +917,12 @@ impl SignInWithMultipleRolesStrategy { )) } } + +impl ForeignFrom<UserStatus> for user_role_api::UserStatus { + fn foreign_from(value: UserStatus) -> Self { + match value { + UserStatus::Active => Self::Active, + UserStatus::InvitationSent => Self::InvitationSent, + } + } +} diff --git a/crates/router/src/utils/user.rs b/crates/router/src/utils/user.rs index 86b298822ac..e9b7143a26e 100644 --- a/crates/router/src/utils/user.rs +++ b/crates/router/src/utils/user.rs @@ -9,7 +9,10 @@ use masking::{ExposeInterface, Secret}; use crate::{ core::errors::{StorageError, UserErrors, UserResult}, routes::AppState, - services::authentication::{AuthToken, UserFromToken}, + services::{ + authentication::{AuthToken, UserFromToken}, + authorization::roles::{self, RoleInfo}, + }, types::domain::{self, MerchantAccount, UserFromStorage}, }; @@ -19,7 +22,10 @@ pub mod password; pub mod sample_data; impl UserFromToken { - pub async fn get_merchant_account(&self, state: AppState) -> UserResult<MerchantAccount> { + pub async fn get_merchant_account_from_db( + &self, + state: AppState, + ) -> UserResult<MerchantAccount> { let key_store = state .store .get_merchant_key_store_by_merchant_id( @@ -56,6 +62,12 @@ impl UserFromToken { .change_context(UserErrors::InternalServerError)?; Ok(user.into()) } + + pub async fn get_role_info_from_db(&self, state: &AppState) -> UserResult<RoleInfo> { + roles::get_role_info_from_role_id(state, &self.role_id, &self.merchant_id, &self.org_id) + .await + .change_context(UserErrors::InternalServerError) + } } pub async fn generate_jwt_auth_token( diff --git a/crates/router/src/utils/user_role.rs b/crates/router/src/utils/user_role.rs index b677e89269e..ef69219b4c9 100644 --- a/crates/router/src/utils/user_role.rs +++ b/crates/router/src/utils/user_role.rs @@ -1,29 +1,6 @@ use api_models::user_role as user_role_api; -use crate::{ - consts, - services::authorization::{permissions::Permission, predefined_permissions::RoleInfo}, -}; - -pub fn is_internal_role(role_id: &str) -> bool { - role_id == consts::user_role::ROLE_ID_INTERNAL_ADMIN - || role_id == consts::user_role::ROLE_ID_INTERNAL_VIEW_ONLY_USER -} - -pub fn get_role_name_and_permission_response( - role_info: &RoleInfo, -) -> Option<(Vec<user_role_api::Permission>, &'static str)> { - role_info.get_name().map(|name| { - ( - role_info - .get_permissions() - .iter() - .map(|&per| per.into()) - .collect::<Vec<user_role_api::Permission>>(), - name, - ) - }) -} +use crate::services::authorization::permissions::Permission; impl From<Permission> for user_role_api::Permission { fn from(value: Permission) -> Self {
2024-02-20T08:57:15Z
## 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 will add checks in authorization to check for custom roles. This PR also add custom roles functionality to apis which were dealing with roles. ### 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). --> To support custom roles. Closes #3717 Closes #3718 ## 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)? --> ### Roles | Group | Org Admin | Merchant Admin | Merchant View Only | Merchant IAM Admin | Merchant Developer | Merchant Operator | Merchant Customer Support | | ---- | ---- | ---- | ---- | ---- | ---- | ---- | ---- | | Operations View | &check; | &check; | &check; | &check; | &check; | &check; | &check; | | Operations Manage | &check; | &check; | | | | &check; | | | Connectors View | &check; | &check; | &check; | | &check; | &check; | | | Connectors Manage | &check; | &check; | | | | | | | Workflows View | &check; | &check; | &check; | | | &check; | | | Workflows Manage | &check; | &check; | | | | | | | Analytics View | &check; | &check; | &check; | &check; | &check; | &check; | &check; | | Users View | &check; | &check; | &check; | &check; | &check; | &check; | &check; | | Users Manage | &check; | &check; | | &check; | | | | | Merchant Details View | &check; | &check; | &check; | &check; | &check; | &check; | &check; | | MerchantDetails Manage | &check; | &check; | | | &check; | | | | Organization Manage | &check; | | | | | | | ### Groups | Permission | 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 | | ---- | ---- | ---- | ---- | ---- | ---- | ---- | ---- | ---- | ---- | ---- | ---- | ---- | | Payment Read | &check; | | | | | | | | | | | | | Payment Write | | &check; | | | | | | | | | | | | Refund Read | &check; | | | | | | | | | | | | | Refund Write | | &check; | | | | | | | | | | | | Dispute Read | &check; | | | | | | | | | | | | | Dispute Write | | &check; | | | | | | | | | | | | Mandate Read | &check; | | | | | | | | | | | | | Mandate Write | | &check; | | | | | | | | | | | | Customer Read | &check; | | | | | | | | | | | | | Customer Write | | &check; | | | | | | | | | | | | Api Key Read | | | | | | | | | | | &check; | | | Api Key Write | | | | | | | | | | | &check; | | | Merchant Account Read | &check; | &check; | &check; | &check; | &check; | &check; | &check; | &check; | &check; | &check; | &check; | &check; | | Merchant Account Write | | | | | | | | | | | &check; | | | Merchant Connector Account Read | | | &check; | | &check; | &check; | | | | | | | | Merchant Connector Account Write | | | | &check; | | | | | | | | | | Routing Read | | | | | &check; | | | | | | | | | Routing Write | | | | | | &check; | | | | | | | | Analytics | | | | | | | &check; | | | | | | | 3DS Manager Read | | | | | &check; | | | | | | | | | 3DS Manger Write | | | | | | &check; | | | | | | | | Surcharge Decision Manager Read | | | | | &check; | | | | | | | | | Surcharge Decision Manager Write | | | | | | &check; | | | | | | | | Users Read | | | | | | | | &check; | | | | | | Users Write | | | | | | | | | &check; | | | | | Merchant Account Create | | | | | | | | | | | | &check; | All the APIs will perform according to these roles from now on. ---- ``` curl --location 'http://localhost:8080/user/role/list' \ --header 'Authorization: Bearer JWT' ``` ``` [ { "role_id": "merchant_developer", "permissions": [ "CustomerRead", "MerchantAccountRead", "Analytics", "UsersRead", "PaymentRead", "MerchantAccountWrite", "MerchantConnectorAccountRead", "ApiKeyRead", "MandateRead", "RefundRead", "DisputeRead", "ApiKeyWrite" ], "role_name": "Developer", "role_scope": "organization" }, { "role_id": "merchant_operator", "permissions": [ "DisputeWrite", "RefundWrite", "SurchargeDecisionManagerRead", "CustomerWrite", "DisputeRead", "MandateWrite", "MerchantConnectorAccountRead", "MerchantAccountRead", "PaymentWrite", "MandateRead", "RefundRead", "PaymentRead", "RoutingRead", "ThreeDsDecisionManagerRead", "Analytics", "UsersRead", "CustomerRead" ], "role_name": "Operator", "role_scope": "organization" }, { "role_id": "merchant_iam_admin", "permissions": [ "PaymentRead", "MerchantAccountRead", "Analytics", "DisputeRead", "UsersRead", "MandateRead", "UsersWrite", "RefundRead", "CustomerRead" ], "role_name": "IAM", "role_scope": "organization" }, { "role_id": "merchant_view_only", "permissions": [ "MerchantConnectorAccountRead", "SurchargeDecisionManagerRead", "UsersRead", "Analytics", "ThreeDsDecisionManagerRead", "MandateRead", "DisputeRead", "MerchantAccountRead", "RoutingRead", "CustomerRead", "RefundRead", "PaymentRead" ], "role_name": "View Only", "role_scope": "organization" }, { "role_id": "merchant_customer_support", "permissions": [ "RefundRead", "UsersRead", "Analytics", "CustomerRead", "MandateRead", "DisputeRead", "MerchantAccountRead", "PaymentRead" ], "role_name": "Customer Support", "role_scope": "organization" }, { "role_id": "merchant_admin", "permissions": [ "Analytics", "RoutingRead", "ApiKeyRead", "MerchantAccountRead", "MandateWrite", "RefundWrite", "SurchargeDecisionManagerRead", "ThreeDsDecisionManagerWrite", "CustomerRead", "MerchantAccountWrite", "ApiKeyWrite", "ThreeDsDecisionManagerRead", "PaymentWrite", "MerchantConnectorAccountRead", "PaymentRead", "MerchantConnectorAccountWrite", "UsersRead", "UsersWrite", "DisputeRead", "MandateRead", "DisputeWrite", "CustomerWrite", "RoutingWrite", "RefundRead", "SurchargeDecisionManagerWrite" ], "role_name": "Admin", "role_scope": "organization" } ] ``` --- ``` curl --location 'http://localhost:8080/user/role/role_id' \ --header 'Authorization: Bearer JWT' ``` ``` { "role_id": "rold_id", "permissions": [ permissions as mentioned above ], "role_name": "name", "role_scope": "organization" } ``` ## 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 - [ ] I added a [CHANGELOG](/CHANGELOG.md) entry if applicable
4ae28e48cd73a9f96b6ae24babf167824fd182a0
### Roles | Group | Org Admin | Merchant Admin | Merchant View Only | Merchant IAM Admin | Merchant Developer | Merchant Operator | Merchant Customer Support | | ---- | ---- | ---- | ---- | ---- | ---- | ---- | ---- | | Operations View | &check; | &check; | &check; | &check; | &check; | &check; | &check; | | Operations Manage | &check; | &check; | | | | &check; | | | Connectors View | &check; | &check; | &check; | | &check; | &check; | | | Connectors Manage | &check; | &check; | | | | | | | Workflows View | &check; | &check; | &check; | | | &check; | | | Workflows Manage | &check; | &check; | | | | | | | Analytics View | &check; | &check; | &check; | &check; | &check; | &check; | &check; | | Users View | &check; | &check; | &check; | &check; | &check; | &check; | &check; | | Users Manage | &check; | &check; | | &check; | | | | | Merchant Details View | &check; | &check; | &check; | &check; | &check; | &check; | &check; | | MerchantDetails Manage | &check; | &check; | | | &check; | | | | Organization Manage | &check; | | | | | | | ### Groups | Permission | 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 | | ---- | ---- | ---- | ---- | ---- | ---- | ---- | ---- | ---- | ---- | ---- | ---- | ---- | | Payment Read | &check; | | | | | | | | | | | | | Payment Write | | &check; | | | | | | | | | | | | Refund Read | &check; | | | | | | | | | | | | | Refund Write | | &check; | | | | | | | | | | | | Dispute Read | &check; | | | | | | | | | | | | | Dispute Write | | &check; | | | | | | | | | | | | Mandate Read | &check; | | | | | | | | | | | | | Mandate Write | | &check; | | | | | | | | | | | | Customer Read | &check; | | | | | | | | | | | | | Customer Write | | &check; | | | | | | | | | | | | Api Key Read | | | | | | | | | | | &check; | | | Api Key Write | | | | | | | | | | | &check; | | | Merchant Account Read | &check; | &check; | &check; | &check; | &check; | &check; | &check; | &check; | &check; | &check; | &check; | &check; | | Merchant Account Write | | | | | | | | | | | &check; | | | Merchant Connector Account Read | | | &check; | | &check; | &check; | | | | | | | | Merchant Connector Account Write | | | | &check; | | | | | | | | | | Routing Read | | | | | &check; | | | | | | | | | Routing Write | | | | | | &check; | | | | | | | | Analytics | | | | | | | &check; | | | | | | | 3DS Manager Read | | | | | &check; | | | | | | | | | 3DS Manger Write | | | | | | &check; | | | | | | | | Surcharge Decision Manager Read | | | | | &check; | | | | | | | | | Surcharge Decision Manager Write | | | | | | &check; | | | | | | | | Users Read | | | | | | | | &check; | | | | | | Users Write | | | | | | | | | &check; | | | | | Merchant Account Create | | | | | | | | | | | | &check; | All the APIs will perform according to these roles from now on. ---- ``` curl --location 'http://localhost:8080/user/role/list' \ --header 'Authorization: Bearer JWT' ``` ``` [ { "role_id": "merchant_developer", "permissions": [ "CustomerRead", "MerchantAccountRead", "Analytics", "UsersRead", "PaymentRead", "MerchantAccountWrite", "MerchantConnectorAccountRead", "ApiKeyRead", "MandateRead", "RefundRead", "DisputeRead", "ApiKeyWrite" ], "role_name": "Developer", "role_scope": "organization" }, { "role_id": "merchant_operator", "permissions": [ "DisputeWrite", "RefundWrite", "SurchargeDecisionManagerRead", "CustomerWrite", "DisputeRead", "MandateWrite", "MerchantConnectorAccountRead", "MerchantAccountRead", "PaymentWrite", "MandateRead", "RefundRead", "PaymentRead", "RoutingRead", "ThreeDsDecisionManagerRead", "Analytics", "UsersRead", "CustomerRead" ], "role_name": "Operator", "role_scope": "organization" }, { "role_id": "merchant_iam_admin", "permissions": [ "PaymentRead", "MerchantAccountRead", "Analytics", "DisputeRead", "UsersRead", "MandateRead", "UsersWrite", "RefundRead", "CustomerRead" ], "role_name": "IAM", "role_scope": "organization" }, { "role_id": "merchant_view_only", "permissions": [ "MerchantConnectorAccountRead", "SurchargeDecisionManagerRead", "UsersRead", "Analytics", "ThreeDsDecisionManagerRead", "MandateRead", "DisputeRead", "MerchantAccountRead", "RoutingRead", "CustomerRead", "RefundRead", "PaymentRead" ], "role_name": "View Only", "role_scope": "organization" }, { "role_id": "merchant_customer_support", "permissions": [ "RefundRead", "UsersRead", "Analytics", "CustomerRead", "MandateRead", "DisputeRead", "MerchantAccountRead", "PaymentRead" ], "role_name": "Customer Support", "role_scope": "organization" }, { "role_id": "merchant_admin", "permissions": [ "Analytics", "RoutingRead", "ApiKeyRead", "MerchantAccountRead", "MandateWrite", "RefundWrite", "SurchargeDecisionManagerRead", "ThreeDsDecisionManagerWrite", "CustomerRead", "MerchantAccountWrite", "ApiKeyWrite", "ThreeDsDecisionManagerRead", "PaymentWrite", "MerchantConnectorAccountRead", "PaymentRead", "MerchantConnectorAccountWrite", "UsersRead", "UsersWrite", "DisputeRead", "MandateRead", "DisputeWrite", "CustomerWrite", "RoutingWrite", "RefundRead", "SurchargeDecisionManagerWrite" ], "role_name": "Admin", "role_scope": "organization" } ] ``` --- ``` curl --location 'http://localhost:8080/user/role/role_id' \ --header 'Authorization: Bearer JWT' ``` ``` { "role_id": "rold_id", "permissions": [ permissions as mentioned above ], "role_name": "name", "role_scope": "organization" } ```
juspay/hyperswitch
juspay__hyperswitch-3718
Bug: feat: integrate custom roles with authz
diff --git a/crates/api_models/src/user_role.rs b/crates/api_models/src/user_role.rs index 215227b91a3..1c4c28aa993 100644 --- a/crates/api_models/src/user_role.rs +++ b/crates/api_models/src/user_role.rs @@ -1,3 +1,4 @@ +use common_enums::RoleScope; use common_utils::pii; use crate::user::DashboardEntryResponse; @@ -7,9 +8,10 @@ pub struct ListRolesResponse(pub Vec<RoleInfoResponse>); #[derive(Debug, serde::Serialize)] pub struct RoleInfoResponse { - pub role_id: &'static str, + pub role_id: String, pub permissions: Vec<Permission>, - pub role_name: &'static str, + pub role_name: String, + pub role_scope: RoleScope, } #[derive(Debug, serde::Deserialize, serde::Serialize)] diff --git a/crates/router/src/analytics.rs b/crates/router/src/analytics.rs index d126d23c8ae..51fb6ff822b 100644 --- a/crates/router/src/analytics.rs +++ b/crates/router/src/analytics.rs @@ -497,7 +497,7 @@ pub mod routes { .await .map(ApplicationResponse::Json) }, - &auth::JWTAuth(Permission::Analytics), + &auth::JWTAuth(Permission::PaymentWrite), api_locking::LockAction::NotApplicable, )) .await diff --git a/crates/router/src/core/user.rs b/crates/router/src/core/user.rs index e7639af3918..5b634920cf6 100644 --- a/crates/router/src/core/user.rs +++ b/crates/router/src/core/user.rs @@ -18,10 +18,8 @@ use crate::services::email::types as email_types; use crate::{ consts, routes::AppState, - services::{ - authentication as auth, authorization::predefined_permissions, ApplicationResponse, - }, - types::domain, + services::{authentication as auth, authorization::roles, ApplicationResponse}, + types::{domain, transformers::ForeignInto}, utils, }; pub mod dashboard_metadata; @@ -444,7 +442,16 @@ pub async fn invite_user( .into()); } - if !predefined_permissions::is_role_invitable(request.role_id.as_str())? { + let role_info = roles::get_role_info_from_role_id( + &state, + &request.role_id, + &user_from_token.merchant_id, + &user_from_token.org_id, + ) + .await + .to_not_found_response(UserErrors::InvalidRoleId)?; + + if !role_info.is_invitable() { return Err(UserErrors::InvalidRoleId.into()) .attach_printable(format!("role_id = {} is not invitable", request.role_id)); } @@ -626,7 +633,16 @@ async fn handle_invitation( .into()); } - if !predefined_permissions::is_role_invitable(request.role_id.as_str())? { + let role_info = roles::get_role_info_from_role_id( + state, + &request.role_id, + &user_from_token.merchant_id, + &user_from_token.org_id, + ) + .await + .to_not_found_response(UserErrors::InvalidRoleId)?; + + if !role_info.is_invitable() { return Err(UserErrors::InvalidRoleId.into()) .attach_printable(format!("role_id = {} is not invitable", request.role_id)); } @@ -915,20 +931,18 @@ pub async fn switch_merchant_id( .into()); } - let user_roles = state - .store - .list_user_roles_by_user_id(&user_from_token.user_id) - .await - .change_context(UserErrors::InternalServerError)?; - - let active_user_roles = user_roles - .into_iter() - .filter(|role| role.status == UserStatus::Active) - .collect::<Vec<_>>(); - let user = user_from_token.get_user_from_db(&state).await?; - let (token, role_id) = if utils::user_role::is_internal_role(&user_from_token.role_id) { + let role_info = roles::get_role_info_from_role_id( + &state, + &user_from_token.role_id, + &user_from_token.merchant_id, + &user_from_token.org_id, + ) + .await + .to_not_found_response(UserErrors::InternalServerError)?; + + let (token, role_id) = if role_info.is_internal() { let key_store = state .store .get_merchant_key_store_by_merchant_id( @@ -967,6 +981,17 @@ pub async fn switch_merchant_id( .await?; (token, user_from_token.role_id) } else { + let user_roles = state + .store + .list_user_roles_by_user_id(&user_from_token.user_id) + .await + .change_context(UserErrors::InternalServerError)?; + + let active_user_roles = user_roles + .into_iter() + .filter(|role| role.status == UserStatus::Active) + .collect::<Vec<_>>(); + let user_role = active_user_roles .iter() .find(|role| role.merchant_id == request.merchant_id) @@ -1051,17 +1076,47 @@ pub async fn get_users_for_merchant_account( state: AppState, user_from_token: auth::UserFromToken, ) -> UserResponse<user_api::GetUsersResponse> { - let users = state + let users_and_user_roles = state .store .find_users_and_roles_by_merchant_id(user_from_token.merchant_id.as_str()) .await .change_context(UserErrors::InternalServerError) - .attach_printable("No users for given merchant id")? + .attach_printable("No users for given merchant id")?; + + let users_user_roles_and_roles = + futures::future::try_join_all(users_and_user_roles.into_iter().map( + |(user, user_role)| async { + roles::get_role_info_from_role_id( + &state, + &user_role.role_id, + &user_role.merchant_id, + &user_role.org_id, + ) + .await + .map(|role_info| (user, user_role, role_info)) + .to_not_found_response(UserErrors::InternalServerError) + }, + )) + .await?; + + let user_details_vec = users_user_roles_and_roles .into_iter() - .filter_map(|(user, role)| domain::UserAndRoleJoined(user, role).try_into().ok()) + .map(|(user, user_role, role_info)| { + let user = domain::UserFromStorage::from(user); + user_api::UserDetails { + email: user.get_email(), + name: user.get_name(), + role_id: user_role.role_id, + role_name: role_info.get_role_name().to_string(), + status: user_role.status.foreign_into(), + last_modified_at: user_role.last_modified, + } + }) .collect(); - Ok(ApplicationResponse::Json(user_api::GetUsersResponse(users))) + Ok(ApplicationResponse::Json(user_api::GetUsersResponse( + user_details_vec, + ))) } #[cfg(feature = "email")] diff --git a/crates/router/src/core/user_role.rs b/crates/router/src/core/user_role.rs index 16047bc3eb7..c2dfd34322c 100644 --- a/crates/router/src/core/user_role.rs +++ b/crates/router/src/core/user_role.rs @@ -10,7 +10,7 @@ use crate::{ routes::AppState, services::{ authentication::{self as auth}, - authorization::{info, predefined_permissions}, + authorization::{info, roles}, ApplicationResponse, }, types::domain, @@ -30,58 +30,96 @@ pub async fn get_authorization_info( )) } -pub async fn list_roles(_state: AppState) -> UserResponse<user_role_api::ListRolesResponse> { +pub async fn list_invitable_roles( + state: AppState, + user_from_token: auth::UserFromToken, +) -> UserResponse<user_role_api::ListRolesResponse> { + let predefined_roles_map = roles::predefined_roles::PREDEFINED_ROLES + .iter() + .filter(|(_, role_info)| role_info.is_invitable()) + .map(|(role_id, role_info)| user_role_api::RoleInfoResponse { + 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() + .map(roles::RoleInfo::from) + .filter(|role_info| role_info.is_invitable()) + .map(|role_info| user_role_api::RoleInfoResponse { + 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(user_role_api::ListRolesResponse( - predefined_permissions::PREDEFINED_PERMISSIONS - .iter() - .filter(|(_, role_info)| role_info.is_invitable()) - .filter_map(|(role_id, role_info)| { - utils::user_role::get_role_name_and_permission_response(role_info).map( - |(permissions, role_name)| user_role_api::RoleInfoResponse { - permissions, - role_id, - role_name, - }, - ) - }) - .collect(), + predefined_roles_map.chain(custom_roles_map).collect(), ))) } pub async fn get_role( - _state: AppState, + state: AppState, + user_from_token: auth::UserFromToken, role: user_role_api::GetRoleRequest, ) -> UserResponse<user_role_api::RoleInfoResponse> { - let info = predefined_permissions::PREDEFINED_PERMISSIONS - .get_key_value(role.role_id.as_str()) - .and_then(|(role_id, role_info)| { - utils::user_role::get_role_name_and_permission_response(role_info).map( - |(permissions, role_name)| user_role_api::RoleInfoResponse { - permissions, - role_id, - role_name, - }, - ) - }) - .ok_or(UserErrors::InvalidRoleId)?; + let role_info = roles::get_role_info_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()); + } - Ok(ApplicationResponse::Json(info)) + let permissions = role_info + .get_permissions_set() + .into_iter() + .map(Into::into) + .collect(); + + Ok(ApplicationResponse::Json(user_role_api::RoleInfoResponse { + 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_from_token( - _state: AppState, - user: auth::UserFromToken, + state: AppState, + user_from_token: auth::UserFromToken, ) -> UserResponse<Vec<user_role_api::Permission>> { - Ok(ApplicationResponse::Json( - predefined_permissions::PREDEFINED_PERMISSIONS - .get(user.role_id.as_str()) - .ok_or(UserErrors::InternalServerError.into()) - .attach_printable("Invalid Role Id in JWT")? - .get_permissions() - .iter() - .map(|&per| per.into()) - .collect(), - )) + 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(permissions)) } pub async fn update_user_role( @@ -89,7 +127,16 @@ pub async fn update_user_role( user_from_token: auth::UserFromToken, req: user_role_api::UpdateUserRoleRequest, ) -> UserResponse<()> { - if !predefined_permissions::is_role_updatable(&req.role_id)? { + let role_info = roles::get_role_info_from_role_id( + &state, + &req.role_id, + &user_from_token.merchant_id, + &user_from_token.org_id, + ) + .await + .to_not_found_response(UserErrors::InvalidRoleId)?; + + if !role_info.is_updatable() { return Err(UserErrors::InvalidRoleOperation.into()) .attach_printable(format!("User role cannot be updated to {}", req.role_id)); } @@ -110,10 +157,19 @@ pub async fn update_user_role( .await .to_not_found_response(UserErrors::InvalidRoleOperation)?; - if !predefined_permissions::is_role_updatable(&user_role_to_be_updated.role_id)? { + let role_to_be_updated = roles::get_role_info_from_role_id( + &state, + &user_role_to_be_updated.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(UserErrors::InvalidRoleOperation.into()).attach_printable(format!( "User role cannot be updated from {}", - user_role_to_be_updated.role_id + role_to_be_updated.get_role_id() )); } @@ -270,7 +326,15 @@ pub async fn delete_user_role( .find(|&role| role.merchant_id == user_from_token.merchant_id.as_str()) { Some(user_role) => { - if !predefined_permissions::is_role_deletable(&user_role.role_id)? { + let role_info = roles::get_role_info_from_role_id( + &state, + &user_role.role_id, + &user_from_token.merchant_id, + &user_from_token.org_id, + ) + .await + .change_context(UserErrors::InternalServerError)?; + if !role_info.is_deletable() { return Err(UserErrors::InvalidDeleteOperation.into()) .attach_printable(format!("role_id = {} is not deletable", user_role.role_id)); } diff --git a/crates/router/src/routes/user.rs b/crates/router/src/routes/user.rs index a863bc2b662..ea51383c94b 100644 --- a/crates/router/src/routes/user.rs +++ b/crates/router/src/routes/user.rs @@ -291,7 +291,7 @@ pub async fn delete_sample_data( &http_req, payload.into_inner(), sample_data::delete_sample_data_for_user, - &auth::JWTAuth(Permission::PaymentWrite), + &auth::JWTAuth(Permission::MerchantAccountWrite), api_locking::LockAction::NotApplicable, )) .await diff --git a/crates/router/src/routes/user_role.rs b/crates/router/src/routes/user_role.rs index f84c158332b..63e2ce37269 100644 --- a/crates/router/src/routes/user_role.rs +++ b/crates/router/src/routes/user_role.rs @@ -36,7 +36,7 @@ pub async fn list_all_roles(state: web::Data<AppState>, req: HttpRequest) -> Htt state.clone(), &req, (), - |state, _: (), _| user_role_core::list_roles(state), + |state, user, _| user_role_core::list_invitable_roles(state, user), &auth::JWTAuth(Permission::UsersRead), api_locking::LockAction::NotApplicable, )) @@ -57,7 +57,7 @@ pub async fn get_role( state.clone(), &req, request_payload, - |state, _: (), req| user_role_core::get_role(state, req), + user_role_core::get_role, &auth::JWTAuth(Permission::UsersRead), api_locking::LockAction::NotApplicable, )) diff --git a/crates/router/src/services/authentication.rs b/crates/router/src/services/authentication.rs index 1004982d292..34153ef6e8f 100644 --- a/crates/router/src/services/authentication.rs +++ b/crates/router/src/services/authentication.rs @@ -503,8 +503,8 @@ where return Err(errors::ApiErrorResponse::InvalidJwtToken.into()); } - let permissions = authorization::get_permissions(&payload.role_id)?; - authorization::check_authorization(&self.0, permissions)?; + let permissions = authorization::get_permissions(state, &payload).await?; + authorization::check_authorization(&self.0, &permissions)?; Ok(( (), @@ -532,8 +532,8 @@ where return Err(errors::ApiErrorResponse::InvalidJwtToken.into()); } - let permissions = authorization::get_permissions(&payload.role_id)?; - authorization::check_authorization(&self.0, permissions)?; + let permissions = authorization::get_permissions(state, &payload).await?; + authorization::check_authorization(&self.0, &permissions)?; Ok(( UserFromToken { @@ -570,8 +570,8 @@ where return Err(errors::ApiErrorResponse::InvalidJwtToken.into()); } - let permissions = authorization::get_permissions(&payload.role_id)?; - authorization::check_authorization(&self.required_permission, permissions)?; + let permissions = authorization::get_permissions(state, &payload).await?; + authorization::check_authorization(&self.required_permission, &permissions)?; // Check if token has access to MerchantId that has been requested through query param if payload.merchant_id != self.merchant_id { @@ -613,8 +613,8 @@ where return Err(errors::ApiErrorResponse::InvalidJwtToken.into()); } - let permissions = authorization::get_permissions(&payload.role_id)?; - authorization::check_authorization(&self.0, permissions)?; + let permissions = authorization::get_permissions(state, &payload).await?; + authorization::check_authorization(&self.0, &permissions)?; let key_store = state .store() @@ -663,8 +663,8 @@ where return Err(errors::ApiErrorResponse::InvalidJwtToken.into()); } - let permissions = authorization::get_permissions(&payload.role_id)?; - authorization::check_authorization(&self.0, permissions)?; + let permissions = authorization::get_permissions(state, &payload).await?; + authorization::check_authorization(&self.0, &permissions)?; let key_store = state .store() diff --git a/crates/router/src/services/authorization.rs b/crates/router/src/services/authorization.rs index cad9b1ece62..034773a07ea 100644 --- a/crates/router/src/services/authorization.rs +++ b/crates/router/src/services/authorization.rs @@ -1,14 +1,50 @@ -use crate::core::errors::{ApiErrorResponse, RouterResult}; +use common_enums::PermissionGroup; + +use super::authentication::AuthToken; +use crate::{ + core::errors::{ApiErrorResponse, RouterResult, StorageErrorExt}, + routes::app::AppStateInfo, +}; pub mod info; +pub mod permission_groups; pub mod permissions; -pub mod predefined_permissions; +pub mod roles; + +pub async fn get_permissions<A>( + state: &A, + token: &AuthToken, +) -> RouterResult<Vec<permissions::Permission>> +where + A: AppStateInfo + Sync, +{ + if let Some(role_info) = roles::predefined_roles::PREDEFINED_ROLES.get(token.role_id.as_str()) { + Ok(get_permissions_from_groups( + role_info.get_permission_groups(), + )) + } else { + state + .store() + .find_role_by_role_id_in_merchant_scope( + &token.role_id, + &token.merchant_id, + &token.org_id, + ) + .await + .map(|role| get_permissions_from_groups(&role.groups)) + .to_not_found_response(ApiErrorResponse::InvalidJwtToken) + } +} -pub fn get_permissions(role: &str) -> RouterResult<&Vec<permissions::Permission>> { - predefined_permissions::PREDEFINED_PERMISSIONS - .get(role) - .map(|role_info| role_info.get_permissions()) - .ok_or(ApiErrorResponse::InvalidJwtToken.into()) +pub fn get_permissions_from_groups(groups: &[PermissionGroup]) -> Vec<permissions::Permission> { + groups + .iter() + .flat_map(|group| { + permission_groups::get_permissions_vec(group) + .iter() + .cloned() + }) + .collect() } pub fn check_authorization( diff --git a/crates/router/src/services/authorization/permission_groups.rs b/crates/router/src/services/authorization/permission_groups.rs new file mode 100644 index 00000000000..246a4ce91dc --- /dev/null +++ b/crates/router/src/services/authorization/permission_groups.rs @@ -0,0 +1,86 @@ +use common_enums::PermissionGroup; + +use super::permissions::Permission; + +pub fn get_permissions_vec(permission_group: &PermissionGroup) -> &[Permission] { + match permission_group { + PermissionGroup::OperationsView => &OPERATIONS_VIEW, + PermissionGroup::OperationsManage => &OPERATIONS_MANAGE, + PermissionGroup::ConnectorsView => &CONNECTORS_VIEW, + PermissionGroup::ConnectorsManage => &CONNECTORS_MANAGE, + PermissionGroup::WorkflowsView => &WORKFLOWS_VIEW, + PermissionGroup::WorkflowsManage => &WORKFLOWS_MANAGE, + PermissionGroup::AnalyticsView => &ANALYTICS_VIEW, + PermissionGroup::UsersView => &USERS_VIEW, + PermissionGroup::UsersManage => &USERS_MANAGE, + PermissionGroup::MerchantDetailsView => &MERCHANT_DETAILS_VIEW, + PermissionGroup::MerchantDetailsManage => &MERCHANT_DETAILS_MANAGE, + PermissionGroup::OrganizationManage => &ORGANIZATION_MANAGE, + } +} + +pub static OPERATIONS_VIEW: [Permission; 6] = [ + Permission::PaymentRead, + Permission::RefundRead, + Permission::MandateRead, + Permission::DisputeRead, + Permission::CustomerRead, + Permission::MerchantAccountRead, +]; + +pub static OPERATIONS_MANAGE: [Permission; 6] = [ + Permission::PaymentWrite, + Permission::RefundWrite, + Permission::MandateWrite, + Permission::DisputeWrite, + Permission::CustomerWrite, + Permission::MerchantAccountRead, +]; + +pub static CONNECTORS_VIEW: [Permission; 2] = [ + Permission::MerchantConnectorAccountRead, + Permission::MerchantAccountRead, +]; + +pub static CONNECTORS_MANAGE: [Permission; 2] = [ + Permission::MerchantConnectorAccountWrite, + Permission::MerchantAccountRead, +]; + +pub static WORKFLOWS_VIEW: [Permission; 5] = [ + Permission::RoutingRead, + Permission::ThreeDsDecisionManagerRead, + Permission::SurchargeDecisionManagerRead, + Permission::MerchantConnectorAccountRead, + Permission::MerchantAccountRead, +]; + +pub static WORKFLOWS_MANAGE: [Permission; 5] = [ + Permission::RoutingWrite, + Permission::ThreeDsDecisionManagerWrite, + Permission::SurchargeDecisionManagerWrite, + Permission::MerchantConnectorAccountRead, + Permission::MerchantAccountRead, +]; + +pub static ANALYTICS_VIEW: [Permission; 2] = + [Permission::Analytics, Permission::MerchantAccountRead]; + +pub static USERS_VIEW: [Permission; 2] = [Permission::UsersRead, Permission::MerchantAccountRead]; + +pub static USERS_MANAGE: [Permission; 2] = + [Permission::UsersWrite, Permission::MerchantAccountRead]; + +pub static MERCHANT_DETAILS_VIEW: [Permission; 1] = [Permission::MerchantAccountRead]; + +pub static MERCHANT_DETAILS_MANAGE: [Permission; 4] = [ + Permission::MerchantAccountWrite, + Permission::ApiKeyRead, + Permission::ApiKeyWrite, + Permission::MerchantAccountRead, +]; + +pub static ORGANIZATION_MANAGE: [Permission; 2] = [ + Permission::MerchantAccountCreate, + Permission::MerchantAccountRead, +]; diff --git a/crates/router/src/services/authorization/permissions.rs b/crates/router/src/services/authorization/permissions.rs index 3e022e8f666..8d436618b32 100644 --- a/crates/router/src/services/authorization/permissions.rs +++ b/crates/router/src/services/authorization/permissions.rs @@ -1,6 +1,6 @@ use strum::Display; -#[derive(PartialEq, Display, Clone, Debug, Copy)] +#[derive(PartialEq, Display, Clone, Debug, Copy, Eq, Hash)] pub enum Permission { PaymentRead, PaymentWrite, diff --git a/crates/router/src/services/authorization/roles.rs b/crates/router/src/services/authorization/roles.rs new file mode 100644 index 00000000000..6372799f98c --- /dev/null +++ b/crates/router/src/services/authorization/roles.rs @@ -0,0 +1,100 @@ +use std::collections::HashSet; + +use common_enums::{PermissionGroup, RoleScope}; +use common_utils::errors::CustomResult; + +use super::{permission_groups::get_permissions_vec, permissions::Permission}; +use crate::{core::errors, routes::AppState}; + +pub mod predefined_roles; + +#[derive(Clone)] +pub struct RoleInfo { + role_id: String, + role_name: String, + groups: Vec<PermissionGroup>, + scope: RoleScope, + is_invitable: bool, + is_deletable: bool, + is_updatable: bool, + is_internal: bool, +} + +impl RoleInfo { + pub fn get_role_id(&self) -> &str { + &self.role_id + } + + pub fn get_role_name(&self) -> &str { + &self.role_name + } + + pub fn get_permission_groups(&self) -> &Vec<PermissionGroup> { + &self.groups + } + + pub fn get_scope(&self) -> RoleScope { + self.scope + } + + pub fn is_invitable(&self) -> bool { + self.is_invitable + } + + pub fn is_deletable(&self) -> bool { + self.is_deletable + } + + pub fn is_internal(&self) -> bool { + self.is_internal + } + + pub fn is_updatable(&self) -> bool { + self.is_updatable + } + + pub fn get_permissions_set(&self) -> HashSet<Permission> { + self.groups + .iter() + .flat_map(|group| get_permissions_vec(group).iter().copied()) + .collect() + } + + pub fn check_permission_exists(&self, required_permission: &Permission) -> bool { + self.groups + .iter() + .any(|group| get_permissions_vec(group).contains(required_permission)) + } +} + +pub async fn get_role_info_from_role_id( + state: &AppState, + role_id: &str, + merchant_id: &str, + org_id: &str, +) -> CustomResult<RoleInfo, errors::StorageError> { + if let Some(role) = predefined_roles::PREDEFINED_ROLES.get(role_id) { + Ok(role.clone()) + } else { + state + .store + .find_role_by_role_id_in_merchant_scope(role_id, merchant_id, org_id) + .await + .map(RoleInfo::from) + } +} + +impl From<diesel_models::role::Role> for RoleInfo { + fn from(role: diesel_models::role::Role) -> Self { + Self { + role_id: role.role_id, + role_name: role.role_name, + groups: role.groups.into_iter().map(Into::into).collect(), + scope: role.scope, + is_invitable: true, + is_deletable: true, + is_updatable: true, + is_internal: false, + } + } +} diff --git a/crates/router/src/services/authorization/roles/predefined_roles.rs b/crates/router/src/services/authorization/roles/predefined_roles.rs new file mode 100644 index 00000000000..9accf094ea4 --- /dev/null +++ b/crates/router/src/services/authorization/roles/predefined_roles.rs @@ -0,0 +1,210 @@ +use std::collections::HashMap; + +use common_enums::{PermissionGroup, RoleScope}; +use once_cell::sync::Lazy; + +use super::RoleInfo; +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, + RoleInfo { + groups: vec![ + PermissionGroup::OperationsView, + PermissionGroup::OperationsManage, + PermissionGroup::ConnectorsView, + PermissionGroup::ConnectorsManage, + PermissionGroup::WorkflowsView, + PermissionGroup::WorkflowsManage, + PermissionGroup::AnalyticsView, + PermissionGroup::UsersView, + PermissionGroup::UsersManage, + PermissionGroup::MerchantDetailsView, + PermissionGroup::MerchantDetailsManage, + PermissionGroup::OrganizationManage, + ], + role_id: consts::user_role::ROLE_ID_INTERNAL_ADMIN.to_string(), + role_name: "Internal Admin".to_string(), + scope: RoleScope::Organization, + is_invitable: false, + is_deletable: false, + is_updatable: false, + is_internal: true, + }, + ); + roles.insert( + consts::user_role::ROLE_ID_INTERNAL_VIEW_ONLY_USER, + RoleInfo { + groups: vec![ + PermissionGroup::OperationsView, + PermissionGroup::ConnectorsView, + PermissionGroup::WorkflowsView, + PermissionGroup::AnalyticsView, + PermissionGroup::UsersView, + PermissionGroup::MerchantDetailsView, + ], + role_id: consts::user_role::ROLE_ID_INTERNAL_VIEW_ONLY_USER.to_string(), + role_name: "Internal View Only".to_string(), + scope: RoleScope::Organization, + is_invitable: false, + is_deletable: false, + is_updatable: false, + is_internal: true, + }, + ); + + roles.insert( + consts::user_role::ROLE_ID_ORGANIZATION_ADMIN, + RoleInfo { + groups: vec![ + PermissionGroup::OperationsView, + PermissionGroup::OperationsManage, + PermissionGroup::ConnectorsView, + PermissionGroup::ConnectorsManage, + PermissionGroup::WorkflowsView, + PermissionGroup::WorkflowsManage, + PermissionGroup::AnalyticsView, + PermissionGroup::UsersView, + PermissionGroup::UsersManage, + PermissionGroup::MerchantDetailsView, + PermissionGroup::MerchantDetailsManage, + PermissionGroup::OrganizationManage, + ], + role_id: consts::user_role::ROLE_ID_ORGANIZATION_ADMIN.to_string(), + role_name: "Organization Admin".to_string(), + scope: RoleScope::Organization, + is_invitable: false, + is_deletable: false, + is_updatable: false, + is_internal: false, + }, + ); + + // MERCHANT ROLES + roles.insert( + consts::user_role::ROLE_ID_MERCHANT_ADMIN, + RoleInfo { + groups: vec![ + PermissionGroup::OperationsView, + PermissionGroup::OperationsManage, + PermissionGroup::ConnectorsView, + PermissionGroup::ConnectorsManage, + PermissionGroup::WorkflowsView, + PermissionGroup::WorkflowsManage, + PermissionGroup::AnalyticsView, + PermissionGroup::UsersView, + PermissionGroup::UsersManage, + PermissionGroup::MerchantDetailsView, + PermissionGroup::MerchantDetailsManage, + ], + role_id: consts::user_role::ROLE_ID_MERCHANT_ADMIN.to_string(), + role_name: "Admin".to_string(), + scope: RoleScope::Organization, + is_invitable: true, + is_deletable: true, + is_updatable: true, + is_internal: false, + }, + ); + roles.insert( + consts::user_role::ROLE_ID_MERCHANT_VIEW_ONLY, + RoleInfo { + groups: vec![ + PermissionGroup::OperationsView, + PermissionGroup::ConnectorsView, + PermissionGroup::WorkflowsView, + PermissionGroup::AnalyticsView, + PermissionGroup::UsersView, + PermissionGroup::MerchantDetailsView, + ], + role_id: consts::user_role::ROLE_ID_MERCHANT_VIEW_ONLY.to_string(), + role_name: "View Only".to_string(), + scope: RoleScope::Organization, + is_invitable: true, + is_deletable: true, + is_updatable: true, + is_internal: false, + }, + ); + roles.insert( + consts::user_role::ROLE_ID_MERCHANT_IAM_ADMIN, + RoleInfo { + groups: vec![ + PermissionGroup::OperationsView, + PermissionGroup::AnalyticsView, + PermissionGroup::UsersView, + PermissionGroup::UsersManage, + PermissionGroup::MerchantDetailsView, + ], + role_id: consts::user_role::ROLE_ID_MERCHANT_IAM_ADMIN.to_string(), + role_name: "IAM".to_string(), + scope: RoleScope::Organization, + is_invitable: true, + is_deletable: true, + is_updatable: true, + is_internal: false, + }, + ); + roles.insert( + consts::user_role::ROLE_ID_MERCHANT_DEVELOPER, + RoleInfo { + groups: vec![ + PermissionGroup::OperationsView, + PermissionGroup::ConnectorsView, + PermissionGroup::AnalyticsView, + PermissionGroup::UsersView, + PermissionGroup::MerchantDetailsView, + PermissionGroup::MerchantDetailsManage, + ], + role_id: consts::user_role::ROLE_ID_MERCHANT_DEVELOPER.to_string(), + role_name: "Developer".to_string(), + scope: RoleScope::Organization, + is_invitable: true, + is_deletable: true, + is_updatable: true, + is_internal: false, + }, + ); + roles.insert( + consts::user_role::ROLE_ID_MERCHANT_OPERATOR, + RoleInfo { + groups: vec![ + PermissionGroup::OperationsView, + PermissionGroup::OperationsManage, + PermissionGroup::ConnectorsView, + PermissionGroup::WorkflowsView, + PermissionGroup::AnalyticsView, + PermissionGroup::UsersView, + PermissionGroup::MerchantDetailsView, + ], + role_id: consts::user_role::ROLE_ID_MERCHANT_OPERATOR.to_string(), + role_name: "Operator".to_string(), + scope: RoleScope::Organization, + is_invitable: true, + is_deletable: true, + is_updatable: true, + is_internal: false, + }, + ); + roles.insert( + consts::user_role::ROLE_ID_MERCHANT_CUSTOMER_SUPPORT, + RoleInfo { + groups: vec![ + PermissionGroup::OperationsView, + PermissionGroup::AnalyticsView, + PermissionGroup::UsersView, + PermissionGroup::MerchantDetailsView, + ], + role_id: consts::user_role::ROLE_ID_MERCHANT_CUSTOMER_SUPPORT.to_string(), + role_name: "Customer Support".to_string(), + scope: RoleScope::Organization, + is_invitable: true, + is_deletable: true, + is_updatable: true, + is_internal: false, + }, + ); + roles +}); diff --git a/crates/router/src/types/domain/user.rs b/crates/router/src/types/domain/user.rs index ab32febf9b4..263b0e52b8a 100644 --- a/crates/router/src/types/domain/user.rs +++ b/crates/router/src/types/domain/user.rs @@ -25,11 +25,7 @@ use crate::{ }, db::StorageInterface, routes::AppState, - services::{ - authentication as auth, - authentication::UserFromToken, - authorization::{info, predefined_permissions}, - }, + services::{authentication as auth, authentication::UserFromToken, authorization::info}, types::transformers::ForeignFrom, utils::{self, user::password}, }; @@ -824,32 +820,6 @@ impl From<info::PermissionInfo> for user_role_api::PermissionInfo { } } -pub struct UserAndRoleJoined(pub storage_user::User, pub UserRole); - -impl TryFrom<UserAndRoleJoined> for user_api::UserDetails { - type Error = (); - fn try_from(user_and_role: UserAndRoleJoined) -> Result<Self, Self::Error> { - let status = match user_and_role.1.status { - UserStatus::Active => user_role_api::UserStatus::Active, - UserStatus::InvitationSent => user_role_api::UserStatus::InvitationSent, - }; - - let role_id = user_and_role.1.role_id; - let role_name = predefined_permissions::get_role_name_from_id(role_id.as_str()) - .ok_or(())? - .to_string(); - - Ok(Self { - email: user_and_role.0.email, - name: user_and_role.0.name, - role_id, - status, - role_name, - last_modified_at: user_and_role.0.last_modified_at, - }) - } -} - pub enum SignInWithRoleStrategyType { SingleRole(SignInWithSingleRoleStrategy), MultipleRoles(SignInWithMultipleRolesStrategy), @@ -947,3 +917,12 @@ impl SignInWithMultipleRolesStrategy { )) } } + +impl ForeignFrom<UserStatus> for user_role_api::UserStatus { + fn foreign_from(value: UserStatus) -> Self { + match value { + UserStatus::Active => Self::Active, + UserStatus::InvitationSent => Self::InvitationSent, + } + } +} diff --git a/crates/router/src/utils/user.rs b/crates/router/src/utils/user.rs index 86b298822ac..e9b7143a26e 100644 --- a/crates/router/src/utils/user.rs +++ b/crates/router/src/utils/user.rs @@ -9,7 +9,10 @@ use masking::{ExposeInterface, Secret}; use crate::{ core::errors::{StorageError, UserErrors, UserResult}, routes::AppState, - services::authentication::{AuthToken, UserFromToken}, + services::{ + authentication::{AuthToken, UserFromToken}, + authorization::roles::{self, RoleInfo}, + }, types::domain::{self, MerchantAccount, UserFromStorage}, }; @@ -19,7 +22,10 @@ pub mod password; pub mod sample_data; impl UserFromToken { - pub async fn get_merchant_account(&self, state: AppState) -> UserResult<MerchantAccount> { + pub async fn get_merchant_account_from_db( + &self, + state: AppState, + ) -> UserResult<MerchantAccount> { let key_store = state .store .get_merchant_key_store_by_merchant_id( @@ -56,6 +62,12 @@ impl UserFromToken { .change_context(UserErrors::InternalServerError)?; Ok(user.into()) } + + pub async fn get_role_info_from_db(&self, state: &AppState) -> UserResult<RoleInfo> { + roles::get_role_info_from_role_id(state, &self.role_id, &self.merchant_id, &self.org_id) + .await + .change_context(UserErrors::InternalServerError) + } } pub async fn generate_jwt_auth_token( diff --git a/crates/router/src/utils/user_role.rs b/crates/router/src/utils/user_role.rs index b677e89269e..ef69219b4c9 100644 --- a/crates/router/src/utils/user_role.rs +++ b/crates/router/src/utils/user_role.rs @@ -1,29 +1,6 @@ use api_models::user_role as user_role_api; -use crate::{ - consts, - services::authorization::{permissions::Permission, predefined_permissions::RoleInfo}, -}; - -pub fn is_internal_role(role_id: &str) -> bool { - role_id == consts::user_role::ROLE_ID_INTERNAL_ADMIN - || role_id == consts::user_role::ROLE_ID_INTERNAL_VIEW_ONLY_USER -} - -pub fn get_role_name_and_permission_response( - role_info: &RoleInfo, -) -> Option<(Vec<user_role_api::Permission>, &'static str)> { - role_info.get_name().map(|name| { - ( - role_info - .get_permissions() - .iter() - .map(|&per| per.into()) - .collect::<Vec<user_role_api::Permission>>(), - name, - ) - }) -} +use crate::services::authorization::permissions::Permission; impl From<Permission> for user_role_api::Permission { fn from(value: Permission) -> Self {
2024-02-20T08:57:15Z
## 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 will add checks in authorization to check for custom roles. This PR also add custom roles functionality to apis which were dealing with roles. ### 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). --> To support custom roles. Closes #3717 Closes #3718 ## 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)? --> ### Roles | Group | Org Admin | Merchant Admin | Merchant View Only | Merchant IAM Admin | Merchant Developer | Merchant Operator | Merchant Customer Support | | ---- | ---- | ---- | ---- | ---- | ---- | ---- | ---- | | Operations View | &check; | &check; | &check; | &check; | &check; | &check; | &check; | | Operations Manage | &check; | &check; | | | | &check; | | | Connectors View | &check; | &check; | &check; | | &check; | &check; | | | Connectors Manage | &check; | &check; | | | | | | | Workflows View | &check; | &check; | &check; | | | &check; | | | Workflows Manage | &check; | &check; | | | | | | | Analytics View | &check; | &check; | &check; | &check; | &check; | &check; | &check; | | Users View | &check; | &check; | &check; | &check; | &check; | &check; | &check; | | Users Manage | &check; | &check; | | &check; | | | | | Merchant Details View | &check; | &check; | &check; | &check; | &check; | &check; | &check; | | MerchantDetails Manage | &check; | &check; | | | &check; | | | | Organization Manage | &check; | | | | | | | ### Groups | Permission | 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 | | ---- | ---- | ---- | ---- | ---- | ---- | ---- | ---- | ---- | ---- | ---- | ---- | ---- | | Payment Read | &check; | | | | | | | | | | | | | Payment Write | | &check; | | | | | | | | | | | | Refund Read | &check; | | | | | | | | | | | | | Refund Write | | &check; | | | | | | | | | | | | Dispute Read | &check; | | | | | | | | | | | | | Dispute Write | | &check; | | | | | | | | | | | | Mandate Read | &check; | | | | | | | | | | | | | Mandate Write | | &check; | | | | | | | | | | | | Customer Read | &check; | | | | | | | | | | | | | Customer Write | | &check; | | | | | | | | | | | | Api Key Read | | | | | | | | | | | &check; | | | Api Key Write | | | | | | | | | | | &check; | | | Merchant Account Read | &check; | &check; | &check; | &check; | &check; | &check; | &check; | &check; | &check; | &check; | &check; | &check; | | Merchant Account Write | | | | | | | | | | | &check; | | | Merchant Connector Account Read | | | &check; | | &check; | &check; | | | | | | | | Merchant Connector Account Write | | | | &check; | | | | | | | | | | Routing Read | | | | | &check; | | | | | | | | | Routing Write | | | | | | &check; | | | | | | | | Analytics | | | | | | | &check; | | | | | | | 3DS Manager Read | | | | | &check; | | | | | | | | | 3DS Manger Write | | | | | | &check; | | | | | | | | Surcharge Decision Manager Read | | | | | &check; | | | | | | | | | Surcharge Decision Manager Write | | | | | | &check; | | | | | | | | Users Read | | | | | | | | &check; | | | | | | Users Write | | | | | | | | | &check; | | | | | Merchant Account Create | | | | | | | | | | | | &check; | All the APIs will perform according to these roles from now on. ---- ``` curl --location 'http://localhost:8080/user/role/list' \ --header 'Authorization: Bearer JWT' ``` ``` [ { "role_id": "merchant_developer", "permissions": [ "CustomerRead", "MerchantAccountRead", "Analytics", "UsersRead", "PaymentRead", "MerchantAccountWrite", "MerchantConnectorAccountRead", "ApiKeyRead", "MandateRead", "RefundRead", "DisputeRead", "ApiKeyWrite" ], "role_name": "Developer", "role_scope": "organization" }, { "role_id": "merchant_operator", "permissions": [ "DisputeWrite", "RefundWrite", "SurchargeDecisionManagerRead", "CustomerWrite", "DisputeRead", "MandateWrite", "MerchantConnectorAccountRead", "MerchantAccountRead", "PaymentWrite", "MandateRead", "RefundRead", "PaymentRead", "RoutingRead", "ThreeDsDecisionManagerRead", "Analytics", "UsersRead", "CustomerRead" ], "role_name": "Operator", "role_scope": "organization" }, { "role_id": "merchant_iam_admin", "permissions": [ "PaymentRead", "MerchantAccountRead", "Analytics", "DisputeRead", "UsersRead", "MandateRead", "UsersWrite", "RefundRead", "CustomerRead" ], "role_name": "IAM", "role_scope": "organization" }, { "role_id": "merchant_view_only", "permissions": [ "MerchantConnectorAccountRead", "SurchargeDecisionManagerRead", "UsersRead", "Analytics", "ThreeDsDecisionManagerRead", "MandateRead", "DisputeRead", "MerchantAccountRead", "RoutingRead", "CustomerRead", "RefundRead", "PaymentRead" ], "role_name": "View Only", "role_scope": "organization" }, { "role_id": "merchant_customer_support", "permissions": [ "RefundRead", "UsersRead", "Analytics", "CustomerRead", "MandateRead", "DisputeRead", "MerchantAccountRead", "PaymentRead" ], "role_name": "Customer Support", "role_scope": "organization" }, { "role_id": "merchant_admin", "permissions": [ "Analytics", "RoutingRead", "ApiKeyRead", "MerchantAccountRead", "MandateWrite", "RefundWrite", "SurchargeDecisionManagerRead", "ThreeDsDecisionManagerWrite", "CustomerRead", "MerchantAccountWrite", "ApiKeyWrite", "ThreeDsDecisionManagerRead", "PaymentWrite", "MerchantConnectorAccountRead", "PaymentRead", "MerchantConnectorAccountWrite", "UsersRead", "UsersWrite", "DisputeRead", "MandateRead", "DisputeWrite", "CustomerWrite", "RoutingWrite", "RefundRead", "SurchargeDecisionManagerWrite" ], "role_name": "Admin", "role_scope": "organization" } ] ``` --- ``` curl --location 'http://localhost:8080/user/role/role_id' \ --header 'Authorization: Bearer JWT' ``` ``` { "role_id": "rold_id", "permissions": [ permissions as mentioned above ], "role_name": "name", "role_scope": "organization" } ``` ## 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 - [ ] I added a [CHANGELOG](/CHANGELOG.md) entry if applicable
4ae28e48cd73a9f96b6ae24babf167824fd182a0
### Roles | Group | Org Admin | Merchant Admin | Merchant View Only | Merchant IAM Admin | Merchant Developer | Merchant Operator | Merchant Customer Support | | ---- | ---- | ---- | ---- | ---- | ---- | ---- | ---- | | Operations View | &check; | &check; | &check; | &check; | &check; | &check; | &check; | | Operations Manage | &check; | &check; | | | | &check; | | | Connectors View | &check; | &check; | &check; | | &check; | &check; | | | Connectors Manage | &check; | &check; | | | | | | | Workflows View | &check; | &check; | &check; | | | &check; | | | Workflows Manage | &check; | &check; | | | | | | | Analytics View | &check; | &check; | &check; | &check; | &check; | &check; | &check; | | Users View | &check; | &check; | &check; | &check; | &check; | &check; | &check; | | Users Manage | &check; | &check; | | &check; | | | | | Merchant Details View | &check; | &check; | &check; | &check; | &check; | &check; | &check; | | MerchantDetails Manage | &check; | &check; | | | &check; | | | | Organization Manage | &check; | | | | | | | ### Groups | Permission | 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 | | ---- | ---- | ---- | ---- | ---- | ---- | ---- | ---- | ---- | ---- | ---- | ---- | ---- | | Payment Read | &check; | | | | | | | | | | | | | Payment Write | | &check; | | | | | | | | | | | | Refund Read | &check; | | | | | | | | | | | | | Refund Write | | &check; | | | | | | | | | | | | Dispute Read | &check; | | | | | | | | | | | | | Dispute Write | | &check; | | | | | | | | | | | | Mandate Read | &check; | | | | | | | | | | | | | Mandate Write | | &check; | | | | | | | | | | | | Customer Read | &check; | | | | | | | | | | | | | Customer Write | | &check; | | | | | | | | | | | | Api Key Read | | | | | | | | | | | &check; | | | Api Key Write | | | | | | | | | | | &check; | | | Merchant Account Read | &check; | &check; | &check; | &check; | &check; | &check; | &check; | &check; | &check; | &check; | &check; | &check; | | Merchant Account Write | | | | | | | | | | | &check; | | | Merchant Connector Account Read | | | &check; | | &check; | &check; | | | | | | | | Merchant Connector Account Write | | | | &check; | | | | | | | | | | Routing Read | | | | | &check; | | | | | | | | | Routing Write | | | | | | &check; | | | | | | | | Analytics | | | | | | | &check; | | | | | | | 3DS Manager Read | | | | | &check; | | | | | | | | | 3DS Manger Write | | | | | | &check; | | | | | | | | Surcharge Decision Manager Read | | | | | &check; | | | | | | | | | Surcharge Decision Manager Write | | | | | | &check; | | | | | | | | Users Read | | | | | | | | &check; | | | | | | Users Write | | | | | | | | | &check; | | | | | Merchant Account Create | | | | | | | | | | | | &check; | All the APIs will perform according to these roles from now on. ---- ``` curl --location 'http://localhost:8080/user/role/list' \ --header 'Authorization: Bearer JWT' ``` ``` [ { "role_id": "merchant_developer", "permissions": [ "CustomerRead", "MerchantAccountRead", "Analytics", "UsersRead", "PaymentRead", "MerchantAccountWrite", "MerchantConnectorAccountRead", "ApiKeyRead", "MandateRead", "RefundRead", "DisputeRead", "ApiKeyWrite" ], "role_name": "Developer", "role_scope": "organization" }, { "role_id": "merchant_operator", "permissions": [ "DisputeWrite", "RefundWrite", "SurchargeDecisionManagerRead", "CustomerWrite", "DisputeRead", "MandateWrite", "MerchantConnectorAccountRead", "MerchantAccountRead", "PaymentWrite", "MandateRead", "RefundRead", "PaymentRead", "RoutingRead", "ThreeDsDecisionManagerRead", "Analytics", "UsersRead", "CustomerRead" ], "role_name": "Operator", "role_scope": "organization" }, { "role_id": "merchant_iam_admin", "permissions": [ "PaymentRead", "MerchantAccountRead", "Analytics", "DisputeRead", "UsersRead", "MandateRead", "UsersWrite", "RefundRead", "CustomerRead" ], "role_name": "IAM", "role_scope": "organization" }, { "role_id": "merchant_view_only", "permissions": [ "MerchantConnectorAccountRead", "SurchargeDecisionManagerRead", "UsersRead", "Analytics", "ThreeDsDecisionManagerRead", "MandateRead", "DisputeRead", "MerchantAccountRead", "RoutingRead", "CustomerRead", "RefundRead", "PaymentRead" ], "role_name": "View Only", "role_scope": "organization" }, { "role_id": "merchant_customer_support", "permissions": [ "RefundRead", "UsersRead", "Analytics", "CustomerRead", "MandateRead", "DisputeRead", "MerchantAccountRead", "PaymentRead" ], "role_name": "Customer Support", "role_scope": "organization" }, { "role_id": "merchant_admin", "permissions": [ "Analytics", "RoutingRead", "ApiKeyRead", "MerchantAccountRead", "MandateWrite", "RefundWrite", "SurchargeDecisionManagerRead", "ThreeDsDecisionManagerWrite", "CustomerRead", "MerchantAccountWrite", "ApiKeyWrite", "ThreeDsDecisionManagerRead", "PaymentWrite", "MerchantConnectorAccountRead", "PaymentRead", "MerchantConnectorAccountWrite", "UsersRead", "UsersWrite", "DisputeRead", "MandateRead", "DisputeWrite", "CustomerWrite", "RoutingWrite", "RefundRead", "SurchargeDecisionManagerWrite" ], "role_name": "Admin", "role_scope": "organization" } ] ``` --- ``` curl --location 'http://localhost:8080/user/role/role_id' \ --header 'Authorization: Bearer JWT' ``` ``` { "role_id": "rold_id", "permissions": [ permissions as mentioned above ], "role_name": "name", "role_scope": "organization" } ```
juspay/hyperswitch
juspay__hyperswitch-3694
Bug: feat(analytics): adding dispute as uri param to analytics info api
diff --git a/crates/analytics/src/clickhouse.rs b/crates/analytics/src/clickhouse.rs index 27d42350509..ead3b1699ec 100644 --- a/crates/analytics/src/clickhouse.rs +++ b/crates/analytics/src/clickhouse.rs @@ -130,7 +130,8 @@ impl AnalyticsDataSource for ClickhouseClient { match table { AnalyticsCollection::Payment | AnalyticsCollection::Refund - | AnalyticsCollection::PaymentIntent => { + | AnalyticsCollection::PaymentIntent + | AnalyticsCollection::Dispute => { TableEngine::CollapsingMergeTree { sign: "sign_flag" } } AnalyticsCollection::SdkEvents => TableEngine::BasicTree, @@ -374,6 +375,7 @@ impl ToSql<ClickhouseClient> for AnalyticsCollection { Self::PaymentIntent => Ok("payment_intents".to_string()), Self::ConnectorEvents => Ok("connector_events_audit".to_string()), Self::OutgoingWebhookEvent => Ok("outgoing_webhook_events_audit".to_string()), + Self::Dispute => Ok("dispute".to_string()), } } } diff --git a/crates/analytics/src/core.rs b/crates/analytics/src/core.rs index 354e1e2f176..6ccf2858e22 100644 --- a/crates/analytics/src/core.rs +++ b/crates/analytics/src/core.rs @@ -26,6 +26,11 @@ pub async fn get_domain_info( download_dimensions: None, dimensions: utils::get_api_event_dimensions(), }, + AnalyticsDomain::Dispute => GetInfoResponse { + metrics: utils::get_dispute_metrics_info(), + download_dimensions: None, + dimensions: utils::get_dispute_dimensions(), + }, }; Ok(info) } diff --git a/crates/analytics/src/sqlx.rs b/crates/analytics/src/sqlx.rs index 562a3a1f64d..1fb7a9b4509 100644 --- a/crates/analytics/src/sqlx.rs +++ b/crates/analytics/src/sqlx.rs @@ -445,6 +445,7 @@ impl ToSql<SqlxClient> for AnalyticsCollection { .attach_printable("ConnectorEvents table is not implemented for Sqlx"))?, Self::OutgoingWebhookEvent => Err(error_stack::report!(ParsingError::UnknownError) .attach_printable("OutgoingWebhookEvents table is not implemented for Sqlx"))?, + Self::Dispute => Ok("dispute".to_string()), } } } diff --git a/crates/analytics/src/types.rs b/crates/analytics/src/types.rs index 18e9e9f4334..356d11bb77d 100644 --- a/crates/analytics/src/types.rs +++ b/crates/analytics/src/types.rs @@ -17,6 +17,7 @@ pub enum AnalyticsDomain { Refunds, SdkEvents, ApiEvents, + Dispute, } #[derive(Debug, strum::AsRefStr, strum::Display, Clone, Copy)] @@ -28,6 +29,7 @@ pub enum AnalyticsCollection { PaymentIntent, ConnectorEvents, OutgoingWebhookEvent, + Dispute, } #[allow(dead_code)] diff --git a/crates/analytics/src/utils.rs b/crates/analytics/src/utils.rs index 6a0aa973a1e..7bff5c87da6 100644 --- a/crates/analytics/src/utils.rs +++ b/crates/analytics/src/utils.rs @@ -1,5 +1,6 @@ use api_models::analytics::{ api_event::{ApiEventDimensions, ApiEventMetrics}, + disputes::{DisputeDimensions, DisputeMetrics}, payments::{PaymentDimensions, PaymentMetrics}, refunds::{RefundDimensions, RefundMetrics}, sdk_events::{SdkEventDimensions, SdkEventMetrics}, @@ -38,3 +39,11 @@ pub fn get_sdk_event_metrics_info() -> Vec<NameDescription> { pub fn get_api_event_metrics_info() -> Vec<NameDescription> { ApiEventMetrics::iter().map(Into::into).collect() } + +pub fn get_dispute_metrics_info() -> Vec<NameDescription> { + DisputeMetrics::iter().map(Into::into).collect() +} + +pub fn get_dispute_dimensions() -> Vec<NameDescription> { + DisputeDimensions::iter().map(Into::into).collect() +} diff --git a/crates/api_models/src/analytics.rs b/crates/api_models/src/analytics.rs index c6ca215f9f7..1115d40b19d 100644 --- a/crates/api_models/src/analytics.rs +++ b/crates/api_models/src/analytics.rs @@ -13,6 +13,7 @@ pub use crate::payments::TimeRange; pub mod api_event; pub mod connector_events; +pub mod disputes; pub mod outgoing_webhook_event; pub mod payments; pub mod refunds; diff --git a/crates/api_models/src/analytics/disputes.rs b/crates/api_models/src/analytics/disputes.rs new file mode 100644 index 00000000000..19d552d45d4 --- /dev/null +++ b/crates/api_models/src/analytics/disputes.rs @@ -0,0 +1,65 @@ +use super::NameDescription; + +#[derive( + Clone, + Debug, + Hash, + PartialEq, + Eq, + serde::Serialize, + serde::Deserialize, + strum::Display, + strum::EnumIter, + strum::AsRefStr, +)] +#[strum(serialize_all = "snake_case")] +#[serde(rename_all = "snake_case")] +pub enum DisputeMetrics { + DisputesChallenged, + DisputesWon, + DisputesLost, + TotalAmountDisputed, + TotalDisputeLostAmount, +} + +#[derive( + Debug, + serde::Serialize, + serde::Deserialize, + strum::AsRefStr, + PartialEq, + PartialOrd, + Eq, + Ord, + strum::Display, + strum::EnumIter, + Clone, + Copy, +)] +#[serde(rename_all = "snake_case")] +#[strum(serialize_all = "snake_case")] +pub enum DisputeDimensions { + // Do not change the order of these enums + // Consult the Dashboard FE folks since these also affects the order of metrics on FE + Connector, + DisputeStatus, + ConnectorStatus, +} + +impl From<DisputeDimensions> for NameDescription { + fn from(value: DisputeDimensions) -> Self { + Self { + name: value.to_string(), + desc: String::new(), + } + } +} + +impl From<DisputeMetrics> for NameDescription { + fn from(value: DisputeMetrics) -> Self { + Self { + name: value.to_string(), + desc: String::new(), + } + } +}
2024-02-19T07:15:26Z
## Type of Change <!-- Put an `x` in the boxes that apply --> - [ ] Bugfix - [x] New feature - [ ] Enhancement - [ ] Refactoring - [ ] Dependency updates - [ ] Documentation - [ ] CI/CD ## Description added dispute as URI PARAM to info api of analytics ### 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? Hit the curl mentioned below and expected response has posted below ## 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 - [ ] I added a [CHANGELOG](/CHANGELOG.md) entry if applicable
df739a302b062277647afe5c3888015272fdc2cf
Hit the curl mentioned below and expected response has posted below
juspay/hyperswitch
juspay__hyperswitch-3721
Bug: [Refactor]: Make use of Locker for generating/storing fingerprints # Description Previously we were generating the fingerprints on our application end itself after this change we will have the fingerprints generated by our locker. Fingerprint is generated for each and every card payment. Moreover we are storing fingerprint in all the attempt tables. Now vouching for the scenarios were there are more than one attempt associated with one intent in that case we are adding the successful attempt's fingerprint in intent. So how does the whole flow works: 1. Before confirmation of payment the payment instrument's fingerprint is cross-checked with the blocklist. 2. If it is present in blocklist the payment will be blocked (status as false). 3. This payment can be retried with another instrument and in case if succeeds the fingerprint will be added in intent. **Note**: All successful attempts will have a fingerprint but intent's fingerprint will always be the successful attempt's fingerprint. Other checkpoints under same hood:- - [x] Instead of generating the fingerprint in application add support for `/cards/fingerprint` API call with `hash_key` (Also ensure to whitelist this endpoint in proxy). - [x] Storing the fingerprint in payment attempt and payment intent table. - [x] Refactoring Block List checking using the fingerprint API # Testing ### Generating fingerprints -> Toggle the blocklist guard from merchant account being used using `/blocklist/toggle?status=true`. More about toggling guard [here](https://github.com/juspay/hyperswitch/issues/3467). -> We need to create a payment. -> While trying to confirm the payment it will have the `fingerprint_id` in the response. This can be used to block the instrument. If the payment was able to be captured the fingerprint will be stored in the intent table as well ### Blocking fingerprints Refer to the attached postman collection for the API contracts for the blocklist APIs([Description](https://github.com/juspay/hyperswitch/issues/3439)). Currently we support blocking three types of resources i.e. card numbers (payment intrument), card bin, and extended card bin. [blocklist_api_postman.zip](https://github.com/juspay/hyperswitch/files/13893696/blocklist_api_postman.zip) ``` For Card Bin and Extended Card Bin :- 1. Setup a Merchant Account and any Connector account 2. Make a payment with a certain card (ensure it succeeds) 3. Block the card's card bin or extended card bin 4. Try the payment again (should fail this time with an API response saying that the payment was blocked) For Payment Instrument :- 1. Repeat steps 1 and 2 of previous section 2. In the payment confirm response, there will be an additional field called "fingerprint". This is the fingerprint id that can be used to block a particular payment method. Use this to block the card. 3. Try the payment again (should fail) ``` # Curls for testing out the complete flow ### Toggle Blocklist Guard for merchant ``` Req curl --location --request POST 'https://sandbox.hyperswitch.io/blocklist/toggle?status=true' \ --header 'api-key: snd_key' Response { "blocklist_guard_status": "enabled" } ``` ### Blocklisting fingerprint for merchant ``` Req curl --location 'https://sandbox.hyperswitch.io/blocklist' \ --header 'x-feature: router-custom' \ --header 'Content-Type: application/json' \ --header 'api-key:snd_key' \ --data '{ "type": "fingerprint", "data": "**fingerprint got in intent**" } ' Response { "fingerprint_id": "**fingerprint got in intent**", "data_kind": "payment_method", "created_at": "2024-02-21T07:47:01.939Z" } ``` ### Listing Blocked fingerprints of merchant ``` Req curl --location 'https://sandbox.hyperswitch.io/blocklist?data_kind=payment_method' \ --header 'x-feature: router-custom' \ --header 'api-key: snd_key' ' Response [ { "fingerprint_id": "**fingerprint got in intent**", "data_kind": "payment_method", "created_at": "2024-02-21T07:47:01.939Z" } ] ``` ### Unblocking Blocked fingerprints for merchant ``` Req curl --location --request DELETE 'https://sandbox.hyperswitch.io/blocklist' \ --header 'x-feature: router-custom' \ --header 'Content-Type: application/json' \ --header 'api-key: snd_key' \ --data '{ "type": "fingerprint", "data": "**fingerprint got in list blocklist**" }' Response [ { "fingerprint_id": "**fingerprint got in list blocklist**", "data_kind": "payment_method", "created_at": "2024-02-21T07:47:01.939Z" } ] ```
diff --git a/crates/api_models/src/blocklist.rs b/crates/api_models/src/blocklist.rs index 9672b6de6ee..2afeb2db4f6 100644 --- a/crates/api_models/src/blocklist.rs +++ b/crates/api_models/src/blocklist.rs @@ -1,5 +1,6 @@ use common_enums::enums; use common_utils::events::ApiEventMetric; +use masking::StrongSecret; use utoipa::ToSchema; #[derive(Debug, Clone, serde::Serialize, serde::Deserialize, ToSchema)] @@ -10,6 +11,15 @@ pub enum BlocklistRequest { ExtendedCardBin(String), } +#[derive(Debug, Clone, serde::Serialize, serde::Deserialize, ToSchema)] +pub struct GenerateFingerprintRequest { + pub card: Card, + pub hash_key: StrongSecret<String>, +} +#[derive(Debug, Clone, serde::Deserialize, serde::Serialize)] +pub struct Card { + pub card_number: StrongSecret<String>, +} pub type AddToBlocklistRequest = BlocklistRequest; pub type DeleteFromBlocklistRequest = BlocklistRequest; @@ -22,6 +32,11 @@ pub struct BlocklistResponse { pub created_at: time::PrimitiveDateTime, } +#[derive(Clone, Debug, serde::Deserialize, serde::Serialize)] +#[serde(rename_all = "snake_case")] +pub struct GenerateFingerprintResponsePayload { + pub card_fingerprint: String, +} #[derive(Debug, Clone, serde::Serialize, serde::Deserialize, ToSchema)] pub struct ToggleBlocklistResponse { pub blocklist_guard_status: String, @@ -54,4 +69,7 @@ impl ApiEventMetric for BlocklistRequest {} impl ApiEventMetric for BlocklistResponse {} impl ApiEventMetric for ToggleBlocklistResponse {} impl ApiEventMetric for ListBlocklistQuery {} +impl ApiEventMetric for GenerateFingerprintRequest {} impl ApiEventMetric for ToggleBlocklistQuery {} +impl ApiEventMetric for GenerateFingerprintResponsePayload {} +impl ApiEventMetric for Card {} diff --git a/crates/data_models/src/payments/payment_attempt.rs b/crates/data_models/src/payments/payment_attempt.rs index 084b0ef251e..3e187e25bc5 100644 --- a/crates/data_models/src/payments/payment_attempt.rs +++ b/crates/data_models/src/payments/payment_attempt.rs @@ -160,6 +160,7 @@ pub struct PaymentAttempt { pub unified_code: Option<String>, pub unified_message: Option<String>, pub mandate_data: Option<MandateDetails>, + pub fingerprint_id: Option<String>, } impl PaymentAttempt { @@ -238,6 +239,7 @@ pub struct PaymentAttemptNew { pub unified_code: Option<String>, pub unified_message: Option<String>, pub mandate_data: Option<MandateDetails>, + pub fingerprint_id: Option<String>, } impl PaymentAttemptNew { @@ -270,6 +272,7 @@ pub enum PaymentAttemptUpdate { capture_method: Option<storage_enums::CaptureMethod>, surcharge_amount: Option<i64>, tax_amount: Option<i64>, + fingerprint_id: Option<String>, updated_by: String, }, UpdateTrackers { @@ -307,6 +310,7 @@ pub enum PaymentAttemptUpdate { surcharge_amount: Option<i64>, tax_amount: Option<i64>, merchant_connector_id: Option<String>, + fingerprint_id: Option<String>, }, RejectUpdate { status: storage_enums::AttemptStatus, diff --git a/crates/data_models/src/payments/payment_intent.rs b/crates/data_models/src/payments/payment_intent.rs index 7470b5f8502..b2fafeb92a0 100644 --- a/crates/data_models/src/payments/payment_intent.rs +++ b/crates/data_models/src/payments/payment_intent.rs @@ -121,6 +121,7 @@ pub enum PaymentIntentUpdate { amount_captured: Option<i64>, return_url: Option<String>, updated_by: String, + fingerprint_id: Option<String>, incremental_authorization_allowed: Option<bool>, }, MetadataUpdate { @@ -335,6 +336,7 @@ impl From<PaymentIntentUpdate> for PaymentIntentUpdateInternal { // currency, status, amount_captured, + fingerprint_id, // customer_id, return_url, updated_by, @@ -344,6 +346,7 @@ impl From<PaymentIntentUpdate> for PaymentIntentUpdateInternal { // currency: Some(currency), status: Some(status), amount_captured, + fingerprint_id, // customer_id, return_url, modified_at: Some(common_utils::date_time::now()), diff --git a/crates/diesel_models/src/payment_attempt.rs b/crates/diesel_models/src/payment_attempt.rs index 9af4595c9f4..927a05bfa56 100644 --- a/crates/diesel_models/src/payment_attempt.rs +++ b/crates/diesel_models/src/payment_attempt.rs @@ -65,6 +65,7 @@ pub struct PaymentAttempt { pub unified_message: Option<String>, pub net_amount: Option<i64>, pub mandate_data: Option<storage_enums::MandateDetails>, + pub fingerprint_id: Option<String>, } impl PaymentAttempt { @@ -140,6 +141,7 @@ pub struct PaymentAttemptNew { pub unified_message: Option<String>, pub net_amount: Option<i64>, pub mandate_data: Option<storage_enums::MandateDetails>, + pub fingerprint_id: Option<String>, } impl PaymentAttemptNew { @@ -177,6 +179,7 @@ pub enum PaymentAttemptUpdate { capture_method: Option<storage_enums::CaptureMethod>, surcharge_amount: Option<i64>, tax_amount: Option<i64>, + fingerprint_id: Option<String>, updated_by: String, }, UpdateTrackers { @@ -212,6 +215,7 @@ pub enum PaymentAttemptUpdate { amount_capturable: Option<i64>, surcharge_amount: Option<i64>, tax_amount: Option<i64>, + fingerprint_id: Option<String>, updated_by: String, merchant_connector_id: Option<String>, }, @@ -351,6 +355,7 @@ pub struct PaymentAttemptUpdateInternal { encoded_data: Option<String>, unified_code: Option<Option<String>>, unified_message: Option<Option<String>>, + fingerprint_id: Option<String>, } impl PaymentAttemptUpdateInternal { @@ -411,6 +416,7 @@ impl PaymentAttemptUpdate { encoded_data, unified_code, unified_message, + fingerprint_id, } = PaymentAttemptUpdateInternal::from(self).populate_derived_fields(&source); PaymentAttempt { amount: amount.unwrap_or(source.amount), @@ -452,6 +458,7 @@ impl PaymentAttemptUpdate { encoded_data: encoded_data.or(source.encoded_data), unified_code: unified_code.unwrap_or(source.unified_code), unified_message: unified_message.unwrap_or(source.unified_message), + fingerprint_id: fingerprint_id.or(source.fingerprint_id), ..source } } @@ -476,6 +483,7 @@ impl From<PaymentAttemptUpdate> for PaymentAttemptUpdateInternal { capture_method, surcharge_amount, tax_amount, + fingerprint_id, updated_by, } => Self { amount: Some(amount), @@ -494,6 +502,7 @@ impl From<PaymentAttemptUpdate> for PaymentAttemptUpdateInternal { capture_method, surcharge_amount, tax_amount, + fingerprint_id, updated_by, ..Default::default() }, @@ -527,6 +536,7 @@ impl From<PaymentAttemptUpdate> for PaymentAttemptUpdateInternal { merchant_connector_id, surcharge_amount, tax_amount, + fingerprint_id, } => Self { amount: Some(amount), currency: Some(currency), @@ -549,6 +559,7 @@ impl From<PaymentAttemptUpdate> for PaymentAttemptUpdateInternal { merchant_connector_id: merchant_connector_id.map(Some), surcharge_amount, tax_amount, + fingerprint_id, ..Default::default() }, PaymentAttemptUpdate::VoidUpdate { diff --git a/crates/diesel_models/src/payment_intent.rs b/crates/diesel_models/src/payment_intent.rs index 31bc0c06c51..69fb61a8d42 100644 --- a/crates/diesel_models/src/payment_intent.rs +++ b/crates/diesel_models/src/payment_intent.rs @@ -116,6 +116,7 @@ pub enum PaymentIntentUpdate { ResponseUpdate { status: storage_enums::IntentStatus, amount_captured: Option<i64>, + fingerprint_id: Option<String>, return_url: Option<String>, updated_by: String, incremental_authorization_allowed: Option<bool>, @@ -405,6 +406,7 @@ impl From<PaymentIntentUpdate> for PaymentIntentUpdateInternal { // currency, status, amount_captured, + fingerprint_id, // customer_id, return_url, updated_by, @@ -414,6 +416,7 @@ impl From<PaymentIntentUpdate> for PaymentIntentUpdateInternal { // currency: Some(currency), status: Some(status), amount_captured, + fingerprint_id, // customer_id, return_url, modified_at: Some(common_utils::date_time::now()), diff --git a/crates/diesel_models/src/schema.rs b/crates/diesel_models/src/schema.rs index 2cbcb52fb44..5093f0df7d0 100644 --- a/crates/diesel_models/src/schema.rs +++ b/crates/diesel_models/src/schema.rs @@ -689,6 +689,8 @@ diesel::table! { unified_message -> Nullable<Varchar>, net_amount -> Nullable<Int8>, mandate_data -> Nullable<Jsonb>, + #[max_length = 64] + fingerprint_id -> Nullable<Varchar>, } } diff --git a/crates/diesel_models/src/user/sample_data.rs b/crates/diesel_models/src/user/sample_data.rs index 6a6d4c52c97..beac5b0733e 100644 --- a/crates/diesel_models/src/user/sample_data.rs +++ b/crates/diesel_models/src/user/sample_data.rs @@ -68,6 +68,7 @@ pub struct PaymentAttemptBatchNew { pub unified_message: Option<String>, pub net_amount: Option<i64>, pub mandate_data: Option<MandateDetails>, + pub fingerprint_id: Option<String>, } #[allow(dead_code)] @@ -122,6 +123,7 @@ impl PaymentAttemptBatchNew { unified_message: self.unified_message, net_amount: self.net_amount, mandate_data: self.mandate_data, + fingerprint_id: self.fingerprint_id, } } } diff --git a/crates/router/src/core/blocklist/transformers.rs b/crates/router/src/core/blocklist/transformers.rs index 2cb5f86a264..f4122a6a651 100644 --- a/crates/router/src/core/blocklist/transformers.rs +++ b/crates/router/src/core/blocklist/transformers.rs @@ -1,6 +1,28 @@ -use api_models::blocklist; +use api_models::{blocklist, enums as api_enums}; +use common_utils::{ + ext_traits::{Encode, StringExt}, + request::RequestContent, +}; +use error_stack::ResultExt; +use josekit::jwe; +#[cfg(feature = "aws_kms")] +use masking::PeekInterface; +use masking::StrongSecret; +use router_env::{instrument, tracing}; -use crate::types::{storage, transformers::ForeignFrom}; +use crate::{ + configs::settings, + core::{ + errors::{self, CustomResult}, + payment_methods::transformers as payment_methods, + }, + headers, routes, + services::{api as services, encryption}, + types::{storage, transformers::ForeignFrom}, + utils::ConnectorResponseExt, +}; + +const LOCKER_FINGERPRINT_PATH: &str = "/cards/fingerprint"; impl ForeignFrom<storage::Blocklist> for blocklist::AddToBlocklistResponse { fn foreign_from(from: storage::Blocklist) -> Self { @@ -11,3 +33,192 @@ impl ForeignFrom<storage::Blocklist> for blocklist::AddToBlocklistResponse { } } } + +async fn generate_fingerprint_request<'a>( + #[cfg(not(feature = "aws_kms"))] jwekey: &settings::Jwekey, + #[cfg(feature = "aws_kms")] jwekey: &settings::ActiveKmsSecrets, + locker: &settings::Locker, + payload: &blocklist::GenerateFingerprintRequest, + locker_choice: api_enums::LockerChoice, +) -> CustomResult<services::Request, errors::VaultError> { + let payload = payload + .encode_to_vec() + .change_context(errors::VaultError::RequestEncodingFailed)?; + + #[cfg(feature = "aws_kms")] + let private_key = jwekey.jwekey.peek().vault_private_key.as_bytes(); + + #[cfg(not(feature = "aws_kms"))] + let private_key = jwekey.vault_private_key.as_bytes(); + + let jws = encryption::jws_sign_payload(&payload, &locker.locker_signing_key_id, private_key) + .await + .change_context(errors::VaultError::RequestEncodingFailed)?; + + let jwe_payload = generate_jwe_payload_for_request(jwekey, &jws, locker_choice).await?; + let mut url = match locker_choice { + api_enums::LockerChoice::HyperswitchCardVault => locker.host.to_owned(), + }; + url.push_str(LOCKER_FINGERPRINT_PATH); + let mut request = services::Request::new(services::Method::Post, &url); + request.add_header(headers::CONTENT_TYPE, "application/json".into()); + request.set_body(RequestContent::Json(Box::new(jwe_payload))); + Ok(request) +} + +async fn generate_jwe_payload_for_request( + #[cfg(feature = "aws_kms")] jwekey: &settings::ActiveKmsSecrets, + #[cfg(not(feature = "aws_kms"))] jwekey: &settings::Jwekey, + jws: &str, + locker_choice: api_enums::LockerChoice, +) -> CustomResult<encryption::JweBody, errors::VaultError> { + let jws_payload: Vec<&str> = jws.split('.').collect(); + + let generate_jws_body = |payload: Vec<&str>| -> Option<encryption::JwsBody> { + Some(encryption::JwsBody { + header: payload.first()?.to_string(), + payload: payload.get(1)?.to_string(), + signature: payload.get(2)?.to_string(), + }) + }; + + let jws_body = + generate_jws_body(jws_payload).ok_or(errors::VaultError::GenerateFingerprintFailed)?; + + let payload = jws_body + .encode_to_vec() + .change_context(errors::VaultError::GenerateFingerprintFailed)?; + + #[cfg(feature = "aws_kms")] + let public_key = match locker_choice { + api_enums::LockerChoice::HyperswitchCardVault => { + jwekey.jwekey.peek().vault_encryption_key.as_bytes() + } + }; + + #[cfg(not(feature = "aws_kms"))] + let public_key = match locker_choice { + api_enums::LockerChoice::HyperswitchCardVault => jwekey.vault_encryption_key.as_bytes(), + }; + + let jwe_encrypted = encryption::encrypt_jwe(&payload, public_key) + .await + .change_context(errors::VaultError::SaveCardFailed) + .attach_printable("Error on jwe encrypt")?; + let jwe_payload: Vec<&str> = jwe_encrypted.split('.').collect(); + + let generate_jwe_body = |payload: Vec<&str>| -> Option<encryption::JweBody> { + Some(encryption::JweBody { + header: payload.first()?.to_string(), + iv: payload.get(2)?.to_string(), + encrypted_payload: payload.get(3)?.to_string(), + tag: payload.get(4)?.to_string(), + encrypted_key: payload.get(1)?.to_string(), + }) + }; + + let jwe_body = + generate_jwe_body(jwe_payload).ok_or(errors::VaultError::GenerateFingerprintFailed)?; + + Ok(jwe_body) +} + +#[instrument(skip_all)] +pub async fn generate_fingerprint( + state: &routes::AppState, + card_number: StrongSecret<String>, + hash_key: StrongSecret<String>, + locker_choice: api_enums::LockerChoice, +) -> CustomResult<blocklist::GenerateFingerprintResponsePayload, errors::VaultError> { + let payload = blocklist::GenerateFingerprintRequest { + card: blocklist::Card { card_number }, + hash_key, + }; + + let generate_fingerprint_resp = + call_to_locker_for_fingerprint(state, &payload, locker_choice).await?; + + Ok(generate_fingerprint_resp) +} + +#[instrument(skip_all)] +async fn call_to_locker_for_fingerprint( + state: &routes::AppState, + payload: &blocklist::GenerateFingerprintRequest, + locker_choice: api_enums::LockerChoice, +) -> CustomResult<blocklist::GenerateFingerprintResponsePayload, errors::VaultError> { + let locker = &state.conf.locker; + #[cfg(not(feature = "aws_kms"))] + let jwekey = &state.conf.jwekey; + #[cfg(feature = "aws_kms")] + let jwekey = &state.kms_secrets; + + let request = generate_fingerprint_request(jwekey, locker, payload, locker_choice).await?; + let response = services::call_connector_api(state, request) + .await + .change_context(errors::VaultError::GenerateFingerprintFailed); + let jwe_body: encryption::JweBody = response + .get_response_inner("JweBody") + .change_context(errors::VaultError::GenerateFingerprintFailed)?; + + let decrypted_payload = + decrypt_generate_fingerprint_response_payload(jwekey, jwe_body, Some(locker_choice)) + .await + .change_context(errors::VaultError::GenerateFingerprintFailed) + .attach_printable("Error getting decrypted fingerprint response payload")?; + let generate_fingerprint_response: blocklist::GenerateFingerprintResponsePayload = + decrypted_payload + .parse_struct("GenerateFingerprintResponse") + .change_context(errors::VaultError::ResponseDeserializationFailed)?; + + Ok(generate_fingerprint_response) +} + +async fn decrypt_generate_fingerprint_response_payload( + #[cfg(not(feature = "aws_kms"))] jwekey: &settings::Jwekey, + #[cfg(feature = "aws_kms")] jwekey: &settings::ActiveKmsSecrets, + jwe_body: encryption::JweBody, + locker_choice: Option<api_enums::LockerChoice>, +) -> CustomResult<String, errors::VaultError> { + let target_locker = locker_choice.unwrap_or(api_enums::LockerChoice::HyperswitchCardVault); + + #[cfg(feature = "aws_kms")] + let public_key = match target_locker { + api_enums::LockerChoice::HyperswitchCardVault => { + jwekey.jwekey.peek().vault_encryption_key.as_bytes() + } + }; + + #[cfg(feature = "aws_kms")] + let private_key = jwekey.jwekey.peek().vault_private_key.as_bytes(); + + #[cfg(not(feature = "aws_kms"))] + let public_key = match target_locker { + api_enums::LockerChoice::HyperswitchCardVault => jwekey.vault_encryption_key.as_bytes(), + }; + + #[cfg(not(feature = "aws_kms"))] + let private_key = jwekey.vault_private_key.as_bytes(); + + let jwt = payment_methods::get_dotted_jwe(jwe_body); + let alg = jwe::RSA_OAEP; + + let jwe_decrypted = encryption::decrypt_jwe( + &jwt, + encryption::KeyIdCheck::SkipKeyIdCheck, + private_key, + alg, + ) + .await + .change_context(errors::VaultError::SaveCardFailed) + .attach_printable("Jwe Decryption failed for JweBody for vault")?; + + let jws = jwe_decrypted + .parse_struct("JwsBody") + .change_context(errors::VaultError::ResponseDeserializationFailed)?; + let jws_body = payment_methods::get_dotted_jws(jws); + + encryption::verify_sign(jws_body, public_key) + .change_context(errors::VaultError::SaveCardFailed) + .attach_printable("Jws Decryption failed for JwsBody for vault") +} diff --git a/crates/router/src/core/blocklist/utils.rs b/crates/router/src/core/blocklist/utils.rs index 733b565beed..68cdb2690b7 100644 --- a/crates/router/src/core/blocklist/utils.rs +++ b/crates/router/src/core/blocklist/utils.rs @@ -1,15 +1,11 @@ use api_models::blocklist as api_blocklist; use common_enums::MerchantDecision; -use common_utils::{ - crypto::{self, SignMessage}, - errors::CustomResult, -}; +use common_utils::errors::CustomResult; use diesel_models::configs; use error_stack::{IntoReport, ResultExt}; -#[cfg(feature = "aws_kms")] -use external_services::aws_kms; +use masking::StrongSecret; -use super::{errors, AppState}; +use super::{errors, transformers::generate_fingerprint, AppState}; use crate::{ consts, core::{ @@ -35,52 +31,13 @@ pub async fn delete_entry_from_blocklist( delete_card_bin_blocklist_entry(state, &xbin, &merchant_id).await? } - api_blocklist::DeleteFromBlocklistRequest::Fingerprint(fingerprint_id) => { - let blocklist_fingerprint = state - .store - .find_blocklist_fingerprint_by_merchant_id_fingerprint_id( - &merchant_id, - &fingerprint_id, - ) - .await - .to_not_found_response(errors::ApiErrorResponse::GenericNotFoundError { - message: "blocklist record with given fingerprint id not found".to_string(), - })?; - - #[cfg(feature = "aws_kms")] - let decrypted_fingerprint = aws_kms::core::get_aws_kms_client(&state.conf.kms) - .await - .decrypt(blocklist_fingerprint.encrypted_fingerprint) - .await - .change_context(errors::ApiErrorResponse::InternalServerError) - .attach_printable("failed to kms decrypt fingerprint")?; - - #[cfg(not(feature = "aws_kms"))] - let decrypted_fingerprint = blocklist_fingerprint.encrypted_fingerprint; - - let blocklist_entry = state - .store - .delete_blocklist_entry_by_merchant_id_fingerprint_id(&merchant_id, &fingerprint_id) - .await - .to_not_found_response(errors::ApiErrorResponse::GenericNotFoundError { - message: "no blocklist record for the given fingerprint id was found" - .to_string(), - })?; - - state - .store - .delete_blocklist_lookup_entry_by_merchant_id_fingerprint( - &merchant_id, - &decrypted_fingerprint, - ) - .await - .to_not_found_response(errors::ApiErrorResponse::GenericNotFoundError { - message: "no blocklist record for the given fingerprint id was found" - .to_string(), - })?; - - blocklist_entry - } + api_blocklist::DeleteFromBlocklistRequest::Fingerprint(fingerprint_id) => state + .store + .delete_blocklist_entry_by_merchant_id_fingerprint_id(&merchant_id, &fingerprint_id) + .await + .to_not_found_response(errors::ApiErrorResponse::GenericNotFoundError { + message: "no blocklist record for the given fingerprint id was found".to_string(), + })?, }; Ok(blocklist_entry.foreign_into()) @@ -232,57 +189,20 @@ pub async fn insert_entry_into_blocklist( } } - let blocklist_fingerprint = state - .store - .find_blocklist_fingerprint_by_merchant_id_fingerprint_id( - &merchant_id, - fingerprint_id, - ) - .await - .to_not_found_response(errors::ApiErrorResponse::GenericNotFoundError { - message: "fingerprint not found".to_string(), - })?; - - #[cfg(feature = "aws_kms")] - let decrypted_fingerprint = aws_kms::core::get_aws_kms_client(&state.conf.kms) - .await - .decrypt(blocklist_fingerprint.encrypted_fingerprint) - .await - .change_context(errors::ApiErrorResponse::InternalServerError) - .attach_printable("failed to kms decrypt encrypted fingerprint")?; - - #[cfg(not(feature = "aws_kms"))] - let decrypted_fingerprint = blocklist_fingerprint.encrypted_fingerprint; - - state - .store - .insert_blocklist_lookup_entry( - diesel_models::blocklist_lookup::BlocklistLookupNew { - merchant_id: merchant_id.clone(), - fingerprint: decrypted_fingerprint, - }, - ) - .await - .to_duplicate_response(errors::ApiErrorResponse::PreconditionFailed { - message: "the payment instrument associated with the given fingerprint is already in the blocklist".to_string(), - }) - .attach_printable("failed to add fingerprint to blocklist lookup")?; - state .store .insert_blocklist_entry(storage::BlocklistNew { merchant_id: merchant_id.clone(), fingerprint_id: fingerprint_id.clone(), - data_kind: blocklist_fingerprint.data_kind, + data_kind: api_models::enums::enums::BlocklistDataKind::PaymentMethod, metadata: None, created_at: common_utils::date_time::now(), }) .await .change_context(errors::ApiErrorResponse::InternalServerError) - .attach_printable("failed to add fingerprint to pm blocklist")? + .attach_printable("failed to add fingerprint to blocklist")? } }; - Ok(blocklist_entry.foreign_into()) } @@ -330,17 +250,6 @@ async fn duplicate_check_insert_bin( merchant_id: &str, data_kind: common_enums::BlocklistDataKind, ) -> RouterResult<storage::Blocklist> { - let merchant_secret = get_merchant_fingerprint_secret(state, merchant_id).await?; - let bin_fingerprint = crypto::HmacSha512::sign_message( - &crypto::HmacSha512, - merchant_secret.clone().as_bytes(), - bin.as_bytes(), - ) - .change_context(errors::ApiErrorResponse::InternalServerError) - .attach_printable("error in bin hash creation")?; - - let encoded_fingerprint = hex::encode(bin_fingerprint.clone()); - let blocklist_entry_result = state .store .find_blocklist_entry_by_merchant_id_fingerprint_id(merchant_id, bin) @@ -363,17 +272,6 @@ async fn duplicate_check_insert_bin( } } - // Checking for duplicacy - state - .store - .insert_blocklist_lookup_entry(diesel_models::blocklist_lookup::BlocklistLookupNew { - merchant_id: merchant_id.to_string(), - fingerprint: encoded_fingerprint.clone(), - }) - .await - .change_context(errors::ApiErrorResponse::InternalServerError) - .attach_printable("error inserting blocklist lookup entry")?; - state .store .insert_blocklist_entry(storage::BlocklistNew { @@ -393,21 +291,6 @@ async fn delete_card_bin_blocklist_entry( bin: &str, merchant_id: &str, ) -> RouterResult<storage::Blocklist> { - let merchant_secret = get_merchant_fingerprint_secret(state, merchant_id).await?; - let bin_fingerprint = crypto::HmacSha512 - .sign_message(merchant_secret.as_bytes(), bin.as_bytes()) - .change_context(errors::ApiErrorResponse::InternalServerError) - .attach_printable("error when hashing card bin")?; - let encoded_fingerprint = hex::encode(bin_fingerprint); - - state - .store - .delete_blocklist_lookup_entry_by_merchant_id_fingerprint(merchant_id, &encoded_fingerprint) - .await - .to_not_found_response(errors::ApiErrorResponse::GenericNotFoundError { - message: "could not find a blocklist entry for the given bin".to_string(), - })?; - state .store .delete_blocklist_entry_by_merchant_id_fingerprint_id(merchant_id, bin) @@ -431,28 +314,28 @@ where get_merchant_fingerprint_secret(state, merchant_id.as_str()).await?; // Hashed Fingerprint to check whether or not this payment should be blocked. - let card_number_fingerprint = payment_data - .payment_method_data - .as_ref() - .and_then(|pm_data| match pm_data { - api_models::payments::PaymentMethodData::Card(card) => { - crypto::HmacSha512::sign_message( - &crypto::HmacSha512, - merchant_fingerprint_secret.as_bytes(), - card.card_number.clone().get_card_no().as_bytes(), - ) - .attach_printable("error in pm fingerprint creation") - .map_or_else( - |err| { - logger::error!(error=?err); - None - }, - Some, - ) - } - _ => None, - }) - .map(hex::encode); + let card_number_fingerprint = if let Some(api_models::payments::PaymentMethodData::Card(card)) = + payment_data.payment_method_data.as_ref() + { + generate_fingerprint( + state, + StrongSecret::new(card.card_number.clone().get_card_no()), + StrongSecret::new(merchant_fingerprint_secret.clone()), + api_models::enums::LockerChoice::HyperswitchCardVault, + ) + .await + .attach_printable("error in pm fingerprint creation") + .map_or_else( + |err| { + logger::error!(error=?err); + None + }, + Some, + ) + .map(|payload| payload.card_fingerprint) + } else { + None + }; // Hashed Cardbin to check whether or not this payment should be blocked. let card_bin_fingerprint = payment_data @@ -460,66 +343,43 @@ where .as_ref() .and_then(|pm_data| match pm_data { api_models::payments::PaymentMethodData::Card(card) => { - crypto::HmacSha512::sign_message( - &crypto::HmacSha512, - merchant_fingerprint_secret.as_bytes(), - card.card_number.clone().get_card_isin().as_bytes(), - ) - .attach_printable("error in card bin hash creation") - .map_or_else( - |err| { - logger::error!(error=?err); - None - }, - Some, - ) + Some(card.card_number.clone().get_card_isin()) } _ => None, - }) - .map(hex::encode); + }); // Hashed Extended Cardbin to check whether or not this payment should be blocked. - let extended_card_bin_fingerprint = payment_data - .payment_method_data - .as_ref() - .and_then(|pm_data| match pm_data { - api_models::payments::PaymentMethodData::Card(card) => { - crypto::HmacSha512::sign_message( - &crypto::HmacSha512, - merchant_fingerprint_secret.as_bytes(), - card.card_number.clone().get_extended_card_bin().as_bytes(), - ) - .attach_printable("error in extended card bin hash creation") - .map_or_else( - |err| { - logger::error!(error=?err); - None - }, - Some, - ) - } - _ => None, - }) - .map(hex::encode); + let extended_card_bin_fingerprint = + payment_data + .payment_method_data + .as_ref() + .and_then(|pm_data| match pm_data { + api_models::payments::PaymentMethodData::Card(card) => { + Some(card.card_number.clone().get_extended_card_bin()) + } + _ => None, + }); //validating the payment method. let mut blocklist_futures = Vec::new(); if let Some(card_number_fingerprint) = card_number_fingerprint.as_ref() { - blocklist_futures.push(db.find_blocklist_lookup_entry_by_merchant_id_fingerprint( + blocklist_futures.push(db.find_blocklist_entry_by_merchant_id_fingerprint_id( merchant_id, card_number_fingerprint, )); } if let Some(card_bin_fingerprint) = card_bin_fingerprint.as_ref() { - blocklist_futures.push(db.find_blocklist_lookup_entry_by_merchant_id_fingerprint( - merchant_id, - card_bin_fingerprint, - )); + blocklist_futures.push( + db.find_blocklist_entry_by_merchant_id_fingerprint_id( + merchant_id, + card_bin_fingerprint, + ), + ); } if let Some(extended_card_bin_fingerprint) = extended_card_bin_fingerprint.as_ref() { - blocklist_futures.push(db.find_blocklist_lookup_entry_by_merchant_id_fingerprint( + blocklist_futures.push(db.find_blocklist_entry_by_merchant_id_fingerprint_id( merchant_id, extended_card_bin_fingerprint, )); @@ -538,7 +398,6 @@ where } } } - if should_payment_be_blocked { // Update db for attempt and intent status. db.update_payment_intent( @@ -582,13 +441,12 @@ where } .into()) } else { - payment_data.payment_intent.fingerprint_id = generate_payment_fingerprint( + payment_data.payment_attempt.fingerprint_id = generate_payment_fingerprint( state, payment_data.payment_attempt.merchant_id.clone(), payment_data.payment_method_data.clone(), ) .await?; - Ok(false) } } @@ -598,68 +456,31 @@ pub async fn generate_payment_fingerprint( merchant_id: String, payment_method_data: Option<crate::types::api::PaymentMethodData>, ) -> CustomResult<Option<String>, errors::ApiErrorResponse> { - let db = &state.store; let merchant_fingerprint_secret = get_merchant_fingerprint_secret(state, &merchant_id).await?; - let card_number_fingerprint = payment_method_data - .as_ref() - .and_then(|pm_data| match pm_data { - api_models::payments::PaymentMethodData::Card(card) => { - crypto::HmacSha512::sign_message( - &crypto::HmacSha512, - merchant_fingerprint_secret.as_bytes(), - card.card_number.clone().get_card_no().as_bytes(), - ) - .attach_printable("error in pm fingerprint creation") - .map_or_else( - |err| { - logger::error!(error=?err); - None - }, - Some, - ) - } - _ => None, - }) - .map(hex::encode); - let mut fingerprint_id = None; - if let Some(encoded_hash) = card_number_fingerprint { - #[cfg(feature = "kms")] - let encrypted_fingerprint = kms::get_kms_client(&state.conf.kms) - .await - .encrypt(encoded_hash) + Ok( + if let Some(api_models::payments::PaymentMethodData::Card(card)) = + payment_method_data.as_ref() + { + generate_fingerprint( + state, + StrongSecret::new(card.card_number.clone().get_card_no()), + StrongSecret::new(merchant_fingerprint_secret), + api_models::enums::LockerChoice::HyperswitchCardVault, + ) .await + .attach_printable("error in pm fingerprint creation") .map_or_else( - |e| { - logger::error!(error=?e, "failed kms encryption of card fingerprint"); + |err| { + logger::error!(error=?err); None }, Some, - ); - - #[cfg(not(feature = "kms"))] - let encrypted_fingerprint = Some(encoded_hash); - - if let Some(encrypted_fingerprint) = encrypted_fingerprint { - fingerprint_id = db - .insert_blocklist_fingerprint_entry( - diesel_models::blocklist_fingerprint::BlocklistFingerprintNew { - merchant_id, - fingerprint_id: utils::generate_id(consts::ID_LENGTH, "fingerprint"), - encrypted_fingerprint, - data_kind: common_enums::BlocklistDataKind::PaymentMethod, - created_at: common_utils::date_time::now(), - }, - ) - .await - .map_or_else( - |e| { - logger::error!(error=?e, "failed storing card fingerprint in db"); - None - }, - |fp| Some(fp.fingerprint_id), - ); - } - } - Ok(fingerprint_id) + ) + .map(|payload| payload.card_fingerprint) + } else { + logger::error!("failed to retrieve card fingerprint"); + None + }, + ) } diff --git a/crates/router/src/core/errors.rs b/crates/router/src/core/errors.rs index d1814f7ee82..cec563b9631 100644 --- a/crates/router/src/core/errors.rs +++ b/crates/router/src/core/errors.rs @@ -236,6 +236,8 @@ pub enum VaultError { FetchPaymentMethodFailed, #[error("Failed to save payment method in vault")] SavePaymentMethodFailed, + #[error("Failed to generate fingerprint")] + GenerateFingerprintFailed, } #[derive(Debug, thiserror::Error)] diff --git a/crates/router/src/core/payments/helpers.rs b/crates/router/src/core/payments/helpers.rs index 635ba917168..764752ba903 100644 --- a/crates/router/src/core/payments/helpers.rs +++ b/crates/router/src/core/payments/helpers.rs @@ -3202,6 +3202,7 @@ impl AttemptType { unified_message: None, net_amount: old_payment_attempt.amount, mandate_data: old_payment_attempt.mandate_data, + fingerprint_id: None, } } diff --git a/crates/router/src/core/payments/operations/payment_confirm.rs b/crates/router/src/core/payments/operations/payment_confirm.rs index 734839c9b6d..2d2ee0e8728 100644 --- a/crates/router/src/core/payments/operations/payment_confirm.rs +++ b/crates/router/src/core/payments/operations/payment_confirm.rs @@ -739,6 +739,7 @@ impl<F: Clone, Ctx: PaymentMethodRetrieve> let m_straight_through_algorithm = straight_through_algorithm.clone(); let m_error_code = error_code.clone(); let m_error_message = error_message.clone(); + let m_fingerprint_id = payment_data.payment_attempt.fingerprint_id.clone(); let m_db = state.clone().store; let surcharge_amount = payment_data .surcharge_details @@ -774,6 +775,7 @@ impl<F: Clone, Ctx: PaymentMethodRetrieve> merchant_connector_id, surcharge_amount, tax_amount, + fingerprint_id: m_fingerprint_id, }, storage_scheme, ) @@ -784,7 +786,6 @@ impl<F: Clone, Ctx: PaymentMethodRetrieve> ); let m_payment_data_payment_intent = payment_data.payment_intent.clone(); - let m_fingerprint_id = payment_data.payment_intent.fingerprint_id.clone(); let m_customer_id = customer_id.clone(); let m_shipping_address_id = shipping_address.clone(); let m_billing_address_id = billing_address.clone(); @@ -821,7 +822,7 @@ impl<F: Clone, Ctx: PaymentMethodRetrieve> metadata: m_metadata, payment_confirm_source: header_payload.payment_confirm_source, updated_by: m_storage_scheme, - fingerprint_id: m_fingerprint_id, + fingerprint_id: None, session_expiry, }, storage_scheme, diff --git a/crates/router/src/core/payments/operations/payment_response.rs b/crates/router/src/core/payments/operations/payment_response.rs index 6bd6ca91100..099eae71800 100644 --- a/crates/router/src/core/payments/operations/payment_response.rs +++ b/crates/router/src/core/payments/operations/payment_response.rs @@ -604,6 +604,8 @@ async fn payment_response_update_tracker<F: Clone, T: types::Capturable>( }; if router_data.status == enums::AttemptStatus::Charged { + payment_data.payment_intent.fingerprint_id = + payment_data.payment_attempt.fingerprint_id.clone(); metrics::SUCCESSFUL_PAYMENT.add(&metrics::CONTEXT, 1, &[]); } @@ -798,6 +800,7 @@ async fn payment_response_update_tracker<F: Clone, T: types::Capturable>( return_url: router_data.return_url.clone(), amount_captured, updated_by: storage_scheme.to_string(), + fingerprint_id: payment_data.payment_attempt.fingerprint_id.clone(), incremental_authorization_allowed: payment_data .payment_intent .incremental_authorization_allowed, diff --git a/crates/router/src/core/payments/operations/payment_update.rs b/crates/router/src/core/payments/operations/payment_update.rs index 0ec11e39f62..071d919eb19 100644 --- a/crates/router/src/core/payments/operations/payment_update.rs +++ b/crates/router/src/core/payments/operations/payment_update.rs @@ -559,6 +559,7 @@ impl<F: Clone, Ctx: PaymentMethodRetrieve> capture_method, surcharge_amount, tax_amount, + fingerprint_id: None, updated_by: storage_scheme.to_string(), }, storage_scheme, diff --git a/crates/router/src/services/api/client.rs b/crates/router/src/services/api/client.rs index f4d74c4f81b..a2cf65ce66b 100644 --- a/crates/router/src/services/api/client.rs +++ b/crates/router/src/services/api/client.rs @@ -114,6 +114,7 @@ pub fn proxy_bypass_urls(locker: &Locker) -> Vec<String> { let locker_host_rs = locker.host_rs.to_owned(); vec![ format!("{locker_host}/cards/add"), + format!("{locker_host}/cards/fingerprint"), format!("{locker_host}/cards/retrieve"), format!("{locker_host}/cards/delete"), format!("{locker_host_rs}/cards/add"), diff --git a/crates/storage_impl/src/mock_db/payment_attempt.rs b/crates/storage_impl/src/mock_db/payment_attempt.rs index e60e32227d3..5add5036f08 100644 --- a/crates/storage_impl/src/mock_db/payment_attempt.rs +++ b/crates/storage_impl/src/mock_db/payment_attempt.rs @@ -148,6 +148,7 @@ impl PaymentAttemptInterface for MockDb { unified_code: payment_attempt.unified_code, unified_message: payment_attempt.unified_message, mandate_data: payment_attempt.mandate_data, + fingerprint_id: payment_attempt.fingerprint_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 ec19e30c0ec..a51f95e1e74 100644 --- a/crates/storage_impl/src/payments/payment_attempt.rs +++ b/crates/storage_impl/src/payments/payment_attempt.rs @@ -391,6 +391,7 @@ impl<T: DatabaseStore> PaymentAttemptInterface for KVRouterStore<T> { unified_code: payment_attempt.unified_code.clone(), unified_message: payment_attempt.unified_message.clone(), mandate_data: payment_attempt.mandate_data.clone(), + fingerprint_id: payment_attempt.fingerprint_id.clone(), }; let field = format!("pa_{}", created_attempt.attempt_id); @@ -1105,6 +1106,7 @@ impl DataModelExt for PaymentAttempt { unified_code: self.unified_code, unified_message: self.unified_message, mandate_data: self.mandate_data.map(|d| d.to_storage_model()), + fingerprint_id: self.fingerprint_id, } } @@ -1163,6 +1165,7 @@ impl DataModelExt for PaymentAttempt { mandate_data: storage_model .mandate_data .map(MandateDetails::from_storage_model), + fingerprint_id: storage_model.fingerprint_id, } } } @@ -1219,6 +1222,7 @@ impl DataModelExt for PaymentAttemptNew { unified_code: self.unified_code, unified_message: self.unified_message, mandate_data: self.mandate_data.map(|d| d.to_storage_model()), + fingerprint_id: self.fingerprint_id, } } @@ -1275,6 +1279,7 @@ impl DataModelExt for PaymentAttemptNew { mandate_data: storage_model .mandate_data .map(MandateDetails::from_storage_model), + fingerprint_id: storage_model.fingerprint_id, } } } @@ -1299,6 +1304,7 @@ impl DataModelExt for PaymentAttemptUpdate { capture_method, surcharge_amount, tax_amount, + fingerprint_id, updated_by, } => DieselPaymentAttemptUpdate::Update { amount, @@ -1315,6 +1321,7 @@ impl DataModelExt for PaymentAttemptUpdate { capture_method, surcharge_amount, tax_amount, + fingerprint_id, updated_by, }, Self::UpdateTrackers { @@ -1373,6 +1380,7 @@ impl DataModelExt for PaymentAttemptUpdate { amount_capturable, surcharge_amount, tax_amount, + fingerprint_id, updated_by, merchant_connector_id: connector_id, } => DieselPaymentAttemptUpdate::ConfirmUpdate { @@ -1394,6 +1402,7 @@ impl DataModelExt for PaymentAttemptUpdate { amount_capturable, surcharge_amount, tax_amount, + fingerprint_id, updated_by, merchant_connector_id: connector_id, }, @@ -1578,6 +1587,7 @@ impl DataModelExt for PaymentAttemptUpdate { capture_method, surcharge_amount, tax_amount, + fingerprint_id, updated_by, } => Self::Update { amount, @@ -1594,6 +1604,7 @@ impl DataModelExt for PaymentAttemptUpdate { capture_method, surcharge_amount, tax_amount, + fingerprint_id, updated_by, }, DieselPaymentAttemptUpdate::UpdateTrackers { @@ -1641,6 +1652,7 @@ impl DataModelExt for PaymentAttemptUpdate { amount_capturable, surcharge_amount, tax_amount, + fingerprint_id, updated_by, merchant_connector_id: connector_id, } => Self::ConfirmUpdate { @@ -1662,6 +1674,7 @@ impl DataModelExt for PaymentAttemptUpdate { amount_capturable, surcharge_amount, tax_amount, + fingerprint_id, updated_by, merchant_connector_id: connector_id, }, diff --git a/crates/storage_impl/src/payments/payment_intent.rs b/crates/storage_impl/src/payments/payment_intent.rs index 7efbafb662d..d201d2a053a 100644 --- a/crates/storage_impl/src/payments/payment_intent.rs +++ b/crates/storage_impl/src/payments/payment_intent.rs @@ -925,12 +925,14 @@ impl DataModelExt for PaymentIntentUpdate { Self::ResponseUpdate { status, amount_captured, + fingerprint_id, return_url, updated_by, incremental_authorization_allowed, } => DieselPaymentIntentUpdate::ResponseUpdate { status, amount_captured, + fingerprint_id, return_url, updated_by, incremental_authorization_allowed, diff --git a/migrations/2024-02-12-135546_add_fingerprint_id_in_payment_attempt/down.sql b/migrations/2024-02-12-135546_add_fingerprint_id_in_payment_attempt/down.sql new file mode 100644 index 00000000000..c6647bd3ab0 --- /dev/null +++ b/migrations/2024-02-12-135546_add_fingerprint_id_in_payment_attempt/down.sql @@ -0,0 +1,2 @@ +-- This file should undo anything in `up.sql` +ALTER TABLE payment_attempt DROP COLUMN IF EXISTS fingerprint_id; diff --git a/migrations/2024-02-12-135546_add_fingerprint_id_in_payment_attempt/up.sql b/migrations/2024-02-12-135546_add_fingerprint_id_in_payment_attempt/up.sql new file mode 100644 index 00000000000..8d219935234 --- /dev/null +++ b/migrations/2024-02-12-135546_add_fingerprint_id_in_payment_attempt/up.sql @@ -0,0 +1,2 @@ +-- Your SQL goes here +ALTER TABLE payment_attempt ADD COLUMN IF NOT EXISTS fingerprint_id VARCHAR(64);
2024-02-12T11:07:58Z
## Type of Change <!-- Put an `x` in the boxes that apply --> Refactoring the present blocklist flow and storing the fingerprint on our locker end for more security and efficiency. More details are here in this [issue](https://github.com/juspay/hyperswitch/issues/3344). - [ ] Bugfix - [ ] New feature - [ ] Enhancement - [x] Refactoring - [ ] Dependency updates - [ ] Documentation - [ ] CI/CD ## Description <!-- Describe your changes in detail --> After this change we will store the fingerprints on our locker in fingerprints table. No more storing anything related to fingerprints in our DB. There will be only one table usable left for blocklsit which will be `blocklist` (stores all the fingerprints blocked by a merchant with their type and metadata). Previously we were generating the fingerprints on our application end itself after this change we will have the fingerprints generated by our locker. Fingerprint is generated for each and every card payment. Moreover we are storing fingerprint in all the attempt tables. Now vouching for the scenarios were there are more than one attempt associated with one intent in that case we are adding the successful attempt's fingerprint in intent. ## Required DB changes purpose: support for addition of fingerprint_id in payment_attempt table Query: `ALTER TABLE payment_attempt ADD COLUMN IF NOT EXISTS fingerprint_id VARCHAR(64);` So how does the whole flow works: 1. Before confirmation of payment the payment instrument's fingerprint is cross-checked with the blocklist. 2. If it is present in blocklist the payment will be blocked (status as false). 3. This payment can be retried with another instrument and in case if succeeds the fingerprint will be added in intent. **Note**: All successful attempts will have a fingerprint but intent's fingerprint will always be the successful attempt's fingerprint. ### Other checkpoints under same hood - [x] Instead of generating the fingerprint in application add support for `/cards/fingerprint` API call with `hash_key`. - [x] whitelisting mentioned endpoint in proxy. - [x] Storing the fingerprint in payment attempt and payment intent table. - [x] Refactoring Block List checking using the fingerprint API. ### 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? ### Generating fingerprints -> Toggle the blocklist guard from merchant account being used using `/blocklist/toggle?status=true`. More about toggling guard [here](https://github.com/juspay/hyperswitch/issues/3467). -> We need to create a payment. -> While trying to confirm the payment it will have the `fingerprint_id` in the response. This can be used to block the instrument. If the payment was able to be captured the fingerprint will be stored in the intent table as well ### Blocking fingerprints Refer to the attached postman collection for the API contracts for the blocklist APIs([Description](https://github.com/juspay/hyperswitch/issues/3439)). Currently we support blocking three types of resources i.e. card numbers (payment intrument), card bin, and extended card bin. [blocklist_api_postman.zip](https://github.com/juspay/hyperswitch/files/13893696/blocklist_api_postman.zip) ``` For Card Bin and Extended Card Bin :- 1. Setup a Merchant Account and any Connector account 2. Make a payment with a certain card (ensure it succeeds) 3. Block the card's card bin or extended card bin 4. Try the payment again (should fail this time with an API response saying that the payment was blocked) For Payment Instrument :- 1. Repeat steps 1 and 2 of previous section 2. In the payment confirm response, there will be an additional field called "fingerprint". This is the fingerprint id that can be used to block a particular payment method. Use this to block the card. 3. Try the payment again (should fail) ``` The respected curls are mentioned in the issue. ## 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 - [ ] I added a [CHANGELOG](/CHANGELOG.md) entry if applicable
e5e44857d21af9db8dee580e276028de76c7d278
### Generating fingerprints -> Toggle the blocklist guard from merchant account being used using `/blocklist/toggle?status=true`. More about toggling guard [here](https://github.com/juspay/hyperswitch/issues/3467). -> We need to create a payment. -> While trying to confirm the payment it will have the `fingerprint_id` in the response. This can be used to block the instrument. If the payment was able to be captured the fingerprint will be stored in the intent table as well ### Blocking fingerprints Refer to the attached postman collection for the API contracts for the blocklist APIs([Description](https://github.com/juspay/hyperswitch/issues/3439)). Currently we support blocking three types of resources i.e. card numbers (payment intrument), card bin, and extended card bin. [blocklist_api_postman.zip](https://github.com/juspay/hyperswitch/files/13893696/blocklist_api_postman.zip) ``` For Card Bin and Extended Card Bin :- 1. Setup a Merchant Account and any Connector account 2. Make a payment with a certain card (ensure it succeeds) 3. Block the card's card bin or extended card bin 4. Try the payment again (should fail this time with an API response saying that the payment was blocked) For Payment Instrument :- 1. Repeat steps 1 and 2 of previous section 2. In the payment confirm response, there will be an additional field called "fingerprint". This is the fingerprint id that can be used to block a particular payment method. Use this to block the card. 3. Try the payment again (should fail) ``` The respected curls are mentioned in the issue.
juspay/hyperswitch
juspay__hyperswitch-3698
Bug: setup roles table Setup `roles` table along with db functions to support custom roles.
diff --git a/crates/diesel_models/src/enums.rs b/crates/diesel_models/src/enums.rs index 7ca65ac4b76..4ca5b4c986c 100644 --- a/crates/diesel_models/src/enums.rs +++ b/crates/diesel_models/src/enums.rs @@ -17,7 +17,8 @@ pub mod diesel_exports { DbProcessTrackerStatus as ProcessTrackerStatus, DbReconStatus as ReconStatus, DbRefundStatus as RefundStatus, DbRefundType as RefundType, DbRequestIncrementalAuthorization as RequestIncrementalAuthorization, - DbRoutingAlgorithmKind as RoutingAlgorithmKind, DbUserStatus as UserStatus, + DbRoleScope as RoleScope, DbRoutingAlgorithmKind as RoutingAlgorithmKind, + DbUserStatus as UserStatus, }; } pub use common_enums::*; @@ -500,3 +501,53 @@ pub enum DashboardMetadata { IsMultipleConfiguration, IsChangePasswordRequired, } + +#[derive( + Clone, + Copy, + Debug, + Eq, + PartialEq, + serde::Deserialize, + serde::Serialize, + strum::Display, + strum::EnumString, + frunk::LabelledGeneric, +)] +#[diesel_enum(storage_type = "db_enum")] +#[serde(rename_all = "snake_case")] +#[strum(serialize_all = "snake_case")] +pub enum RoleScope { + Merchant, + Organization, +} + +#[derive( + Clone, + Copy, + Debug, + Eq, + PartialEq, + serde::Serialize, + serde::Deserialize, + strum::Display, + strum::EnumString, + frunk::LabelledGeneric, +)] +#[diesel_enum(storage_type = "text")] +#[serde(rename_all = "snake_case")] +#[strum(serialize_all = "snake_case")] +pub enum PermissionGroup { + OperationsView, + OperationsManage, + ConnectorsView, + ConnectorsManage, + WorkflowsView, + WorkflowsManage, + AnalyticsView, + UsersView, + UsersManage, + MerchantDetailsView, + MerchantDetailsManage, + OrganizationManage, +} diff --git a/crates/diesel_models/src/lib.rs b/crates/diesel_models/src/lib.rs index 82b1e29ee83..f7678793bc2 100644 --- a/crates/diesel_models/src/lib.rs +++ b/crates/diesel_models/src/lib.rs @@ -39,6 +39,7 @@ pub mod process_tracker; pub mod query; pub mod refund; pub mod reverse_lookup; +pub mod role; pub mod routing_algorithm; #[allow(unused_qualifications)] pub mod schema; diff --git a/crates/diesel_models/src/query.rs b/crates/diesel_models/src/query.rs index 3a0a008b76b..c395ae3df92 100644 --- a/crates/diesel_models/src/query.rs +++ b/crates/diesel_models/src/query.rs @@ -32,6 +32,7 @@ pub mod payouts; pub mod process_tracker; pub mod refund; pub mod reverse_lookup; +pub mod role; pub mod routing_algorithm; pub mod user; pub mod user_role; diff --git a/crates/diesel_models/src/query/role.rs b/crates/diesel_models/src/query/role.rs new file mode 100644 index 00000000000..b8704aebbd0 --- /dev/null +++ b/crates/diesel_models/src/query/role.rs @@ -0,0 +1,68 @@ +use diesel::{associations::HasTable, BoolExpressionMethods, ExpressionMethods}; +use router_env::tracing::{self, instrument}; + +use crate::{ + enums::RoleScope, query::generics, role::*, schema::roles::dsl, PgPooledConn, StorageResult, +}; + +impl RoleNew { + #[instrument(skip(conn))] + pub async fn insert(self, conn: &PgPooledConn) -> StorageResult<Role> { + generics::generic_insert(conn, self).await + } +} + +impl Role { + pub async fn find_by_role_id(conn: &PgPooledConn, role_id: &str) -> StorageResult<Self> { + generics::generic_find_one::<<Self as HasTable>::Table, _, _>( + conn, + dsl::role_id.eq(role_id.to_owned()), + ) + .await + } + + pub async fn update_by_role_id( + conn: &PgPooledConn, + role_id: &str, + role_update: RoleUpdate, + ) -> StorageResult<Self> { + generics::generic_update_with_unique_predicate_get_result::< + <Self as HasTable>::Table, + _, + _, + _, + >( + conn, + dsl::role_id.eq(role_id.to_owned()), + RoleUpdateInternal::from(role_update), + ) + .await + } + + pub async fn delete_by_role_id(conn: &PgPooledConn, role_id: &str) -> StorageResult<Self> { + generics::generic_delete_one_with_result::<<Self as HasTable>::Table, _, _>( + conn, + dsl::role_id.eq(role_id.to_owned()), + ) + .await + } + + pub async fn list_roles( + conn: &PgPooledConn, + merchant_id: &str, + org_id: &str, + ) -> StorageResult<Vec<Self>> { + let predicate = dsl::merchant_id.eq(merchant_id.to_owned()).or(dsl::org_id + .eq(org_id.to_owned()) + .and(dsl::scope.eq(RoleScope::Organization))); + + generics::generic_filter::<<Self as HasTable>::Table, _, _, _>( + conn, + predicate, + None, + None, + Some(dsl::last_modified_at.asc()), + ) + .await + } +} diff --git a/crates/diesel_models/src/role.rs b/crates/diesel_models/src/role.rs new file mode 100644 index 00000000000..6b21b1461cd --- /dev/null +++ b/crates/diesel_models/src/role.rs @@ -0,0 +1,83 @@ +use diesel::{AsChangeset, Identifiable, Insertable, Queryable}; +use time::PrimitiveDateTime; + +use crate::{enums, schema::roles}; + +#[derive(Clone, Debug, Identifiable, Queryable)] +#[diesel(table_name = roles)] +pub struct Role { + pub id: i32, + pub role_name: String, + pub role_id: String, + pub merchant_id: String, + pub org_id: String, + #[diesel(deserialize_as = super::DieselArray<enums::PermissionGroup>)] + pub groups: Vec<enums::PermissionGroup>, + pub scope: enums::RoleScope, + pub created_at: PrimitiveDateTime, + pub created_by: String, + pub last_modified_at: PrimitiveDateTime, + pub last_modified_by: String, +} + +#[derive(router_derive::Setter, Clone, Debug, Insertable, router_derive::DebugAsDisplay)] +#[diesel(table_name = roles)] +pub struct RoleNew { + pub role_name: String, + pub role_id: String, + pub merchant_id: String, + pub org_id: String, + #[diesel(deserialize_as = super::DieselArray<enums::PermissionGroup>)] + pub groups: Vec<enums::PermissionGroup>, + pub scope: enums::RoleScope, + pub created_at: PrimitiveDateTime, + pub created_by: String, + pub last_modified_at: PrimitiveDateTime, + pub last_modified_by: String, +} + +#[derive(Clone, Debug, AsChangeset, router_derive::DebugAsDisplay)] +#[diesel(table_name = roles)] +pub struct RoleUpdateInternal { + groups: Option<Vec<enums::PermissionGroup>>, + role_name: Option<String>, + last_modified_by: String, + last_modified_at: PrimitiveDateTime, +} + +pub enum RoleUpdate { + UpdateGroup { + groups: Vec<enums::PermissionGroup>, + last_modified_by: String, + }, + UpdateRoleName { + role_name: String, + last_modified_by: String, + }, +} + +impl From<RoleUpdate> for RoleUpdateInternal { + fn from(value: RoleUpdate) -> Self { + let last_modified_at = common_utils::date_time::now(); + match value { + RoleUpdate::UpdateGroup { + groups, + last_modified_by, + } => Self { + groups: Some(groups), + role_name: None, + last_modified_at, + last_modified_by, + }, + RoleUpdate::UpdateRoleName { + role_name, + last_modified_by, + } => Self { + groups: None, + role_name: Some(role_name), + last_modified_at, + last_modified_by, + }, + } + } +} diff --git a/crates/diesel_models/src/schema.rs b/crates/diesel_models/src/schema.rs index 6c28677432b..2cbcb52fb44 100644 --- a/crates/diesel_models/src/schema.rs +++ b/crates/diesel_models/src/schema.rs @@ -994,6 +994,31 @@ diesel::table! { } } +diesel::table! { + use diesel::sql_types::*; + use crate::enums::diesel_exports::*; + + roles (id) { + id -> Int4, + #[max_length = 64] + role_name -> Varchar, + #[max_length = 64] + role_id -> Varchar, + #[max_length = 64] + merchant_id -> Varchar, + #[max_length = 64] + org_id -> Varchar, + groups -> Array<Nullable<Text>>, + scope -> RoleScope, + created_at -> Timestamp, + #[max_length = 64] + created_by -> Varchar, + last_modified_at -> Timestamp, + #[max_length = 64] + last_modified_by -> Varchar, + } +} + diesel::table! { use diesel::sql_types::*; use crate::enums::diesel_exports::*; @@ -1095,6 +1120,7 @@ diesel::allow_tables_to_appear_in_same_query!( process_tracker, refund, reverse_lookup, + roles, routing_algorithm, user_roles, users, diff --git a/crates/router/src/db.rs b/crates/router/src/db.rs index 54900177246..d385d94a5de 100644 --- a/crates/router/src/db.rs +++ b/crates/router/src/db.rs @@ -31,6 +31,7 @@ pub mod payout_attempt; pub mod payouts; pub mod refund; pub mod reverse_lookup; +pub mod role; pub mod routing_algorithm; pub mod user; pub mod user_role; @@ -111,6 +112,7 @@ pub trait StorageInterface: + authorization::AuthorizationInterface + user::sample_data::BatchSampleDataInterface + health_check::HealthCheckDbInterface + + role::RoleInterface + 'static { fn get_scheduler_db(&self) -> Box<dyn scheduler::SchedulerInterface>; diff --git a/crates/router/src/db/kafka_store.rs b/crates/router/src/db/kafka_store.rs index 0078f030c5a..0897deb87e5 100644 --- a/crates/router/src/db/kafka_store.rs +++ b/crates/router/src/db/kafka_store.rs @@ -24,6 +24,7 @@ use time::PrimitiveDateTime; use super::{ dashboard_metadata::DashboardMetadataInterface, + role::RoleInterface, user::{sample_data::BatchSampleDataInterface, UserInterface}, user_role::UserRoleInterface, }; @@ -2256,3 +2257,45 @@ impl HealthCheckDbInterface for KafkaStore { self.diesel_store.health_check_db().await } } + +#[async_trait::async_trait] +impl RoleInterface for KafkaStore { + async fn insert_role( + &self, + role: storage::RoleNew, + ) -> CustomResult<storage::Role, errors::StorageError> { + self.diesel_store.insert_role(role).await + } + + async fn find_role_by_role_id( + &self, + role_id: &str, + ) -> CustomResult<storage::Role, errors::StorageError> { + self.diesel_store.find_role_by_role_id(role_id).await + } + + async fn update_role_by_role_id( + &self, + role_id: &str, + role_update: storage::RoleUpdate, + ) -> CustomResult<storage::Role, errors::StorageError> { + self.diesel_store + .update_role_by_role_id(role_id, role_update) + .await + } + + async fn delete_role_by_role_id( + &self, + role_id: &str, + ) -> CustomResult<storage::Role, errors::StorageError> { + self.diesel_store.delete_role_by_role_id(role_id).await + } + + async fn list_all_roles( + &self, + merchant_id: &str, + org_id: &str, + ) -> CustomResult<Vec<storage::Role>, errors::StorageError> { + self.diesel_store.list_all_roles(merchant_id, org_id).await + } +} diff --git a/crates/router/src/db/role.rs b/crates/router/src/db/role.rs new file mode 100644 index 00000000000..da2abf15ff7 --- /dev/null +++ b/crates/router/src/db/role.rs @@ -0,0 +1,236 @@ +use diesel_models::role as storage; +use error_stack::{IntoReport, ResultExt}; + +use super::MockDb; +use crate::{ + connection, + core::errors::{self, CustomResult}, + services::Store, +}; + +#[async_trait::async_trait] +pub trait RoleInterface { + async fn insert_role( + &self, + role: storage::RoleNew, + ) -> CustomResult<storage::Role, errors::StorageError>; + + async fn find_role_by_role_id( + &self, + role_id: &str, + ) -> CustomResult<storage::Role, errors::StorageError>; + + async fn update_role_by_role_id( + &self, + role_id: &str, + role_update: storage::RoleUpdate, + ) -> CustomResult<storage::Role, errors::StorageError>; + + async fn delete_role_by_role_id( + &self, + role_id: &str, + ) -> CustomResult<storage::Role, errors::StorageError>; + + async fn list_all_roles( + &self, + merchant_id: &str, + org_id: &str, + ) -> CustomResult<Vec<storage::Role>, errors::StorageError>; +} + +#[async_trait::async_trait] +impl RoleInterface for Store { + async fn insert_role( + &self, + role: storage::RoleNew, + ) -> CustomResult<storage::Role, errors::StorageError> { + let conn = connection::pg_connection_write(self).await?; + role.insert(&conn).await.map_err(Into::into).into_report() + } + + async fn find_role_by_role_id( + &self, + role_id: &str, + ) -> CustomResult<storage::Role, errors::StorageError> { + let conn = connection::pg_connection_write(self).await?; + storage::Role::find_by_role_id(&conn, role_id) + .await + .map_err(Into::into) + .into_report() + } + + async fn update_role_by_role_id( + &self, + role_id: &str, + role_update: storage::RoleUpdate, + ) -> CustomResult<storage::Role, errors::StorageError> { + let conn = connection::pg_connection_write(self).await?; + storage::Role::update_by_role_id(&conn, role_id, role_update) + .await + .map_err(Into::into) + .into_report() + } + + async fn delete_role_by_role_id( + &self, + role_id: &str, + ) -> CustomResult<storage::Role, errors::StorageError> { + let conn = connection::pg_connection_write(self).await?; + storage::Role::delete_by_role_id(&conn, role_id) + .await + .map_err(Into::into) + .into_report() + } + + async fn list_all_roles( + &self, + merchant_id: &str, + org_id: &str, + ) -> CustomResult<Vec<storage::Role>, errors::StorageError> { + let conn = connection::pg_connection_write(self).await?; + storage::Role::list_roles(&conn, merchant_id, org_id) + .await + .map_err(Into::into) + .into_report() + } +} + +#[async_trait::async_trait] +impl RoleInterface for MockDb { + async fn insert_role( + &self, + role: storage::RoleNew, + ) -> CustomResult<storage::Role, errors::StorageError> { + let mut roles = self.roles.lock().await; + if roles + .iter() + .any(|role_inner| role_inner.role_id == role.role_id) + { + Err(errors::StorageError::DuplicateValue { + entity: "role_id", + key: None, + })? + } + let role = storage::Role { + id: roles + .len() + .try_into() + .into_report() + .change_context(errors::StorageError::MockDbError)?, + role_name: role.role_name, + role_id: role.role_id, + merchant_id: role.merchant_id, + org_id: role.org_id, + groups: role.groups, + scope: role.scope, + created_by: role.created_by, + created_at: role.created_at, + last_modified_at: role.last_modified_at, + last_modified_by: role.last_modified_by, + }; + roles.push(role.clone()); + Ok(role) + } + + async fn find_role_by_role_id( + &self, + role_id: &str, + ) -> CustomResult<storage::Role, errors::StorageError> { + let roles = self.roles.lock().await; + roles + .iter() + .find(|role| role.role_id == role_id) + .cloned() + .ok_or( + errors::StorageError::ValueNotFound(format!( + "No role available role_id = {role_id}" + )) + .into(), + ) + } + + async fn update_role_by_role_id( + &self, + role_id: &str, + role_update: storage::RoleUpdate, + ) -> CustomResult<storage::Role, errors::StorageError> { + let mut roles = self.roles.lock().await; + let last_modified_at = common_utils::date_time::now(); + + roles + .iter_mut() + .find(|role| role.role_id == role_id) + .map(|role| { + *role = match role_update { + storage::RoleUpdate::UpdateGroup { + groups, + last_modified_by, + } => storage::Role { + groups, + last_modified_by, + last_modified_at, + ..role.to_owned() + }, + storage::RoleUpdate::UpdateRoleName { + role_name, + last_modified_by, + } => storage::Role { + role_name, + last_modified_at, + last_modified_by, + ..role.to_owned() + }, + }; + role.to_owned() + }) + .ok_or( + errors::StorageError::ValueNotFound(format!( + "No role available for role_id = {role_id}" + )) + .into(), + ) + } + + async fn delete_role_by_role_id( + &self, + role_id: &str, + ) -> CustomResult<storage::Role, errors::StorageError> { + let mut roles = self.roles.lock().await; + let role_index = roles + .iter() + .position(|role| role.role_id == role_id) + .ok_or(errors::StorageError::ValueNotFound(format!( + "No role available for role_id = {role_id}" + )))?; + + Ok(roles.remove(role_index)) + } + + async fn list_all_roles( + &self, + merchant_id: &str, + org_id: &str, + ) -> CustomResult<Vec<storage::Role>, errors::StorageError> { + let roles = self.roles.lock().await; + + let roles_list: Vec<_> = roles + .iter() + .filter(|role| { + role.merchant_id == merchant_id + || (role.org_id == org_id + && role.scope == diesel_models::enums::RoleScope::Organization) + }) + .cloned() + .collect(); + + if roles_list.is_empty() { + return Err(errors::StorageError::ValueNotFound(format!( + "No role found for merchant id = {} and org_id = {}", + merchant_id, org_id + )) + .into()); + } + + Ok(roles_list) + } +} diff --git a/crates/router/src/types/storage.rs b/crates/router/src/types/storage.rs index b93cbbbbba9..01decc89c4c 100644 --- a/crates/router/src/types/storage.rs +++ b/crates/router/src/types/storage.rs @@ -31,6 +31,7 @@ pub mod payout_attempt; pub mod payouts; pub mod refund; pub mod reverse_lookup; +pub mod role; pub mod routing_algorithm; pub mod user; pub mod user_role; @@ -51,7 +52,8 @@ pub use self::{ dashboard_metadata::*, dispute::*, ephemeral_key::*, events::*, file::*, fraud_check::*, gsm::*, locker_mock_up::*, mandate::*, merchant_account::*, merchant_connector_account::*, merchant_key_store::*, payment_link::*, payment_method::*, payout_attempt::*, payouts::*, - process_tracker::*, refund::*, reverse_lookup::*, routing_algorithm::*, user::*, user_role::*, + process_tracker::*, refund::*, reverse_lookup::*, role::*, routing_algorithm::*, user::*, + user_role::*, }; use crate::types::api::routing; diff --git a/crates/router/src/types/storage/role.rs b/crates/router/src/types/storage/role.rs new file mode 100644 index 00000000000..4a831762a4e --- /dev/null +++ b/crates/router/src/types/storage/role.rs @@ -0,0 +1 @@ +pub use diesel_models::role::*; diff --git a/crates/storage_impl/src/mock_db.rs b/crates/storage_impl/src/mock_db.rs index a6ba763bd91..a1518cea431 100644 --- a/crates/storage_impl/src/mock_db.rs +++ b/crates/storage_impl/src/mock_db.rs @@ -45,6 +45,7 @@ pub struct MockDb { pub user_roles: Arc<Mutex<Vec<store::user_role::UserRole>>>, pub authorizations: Arc<Mutex<Vec<store::authorization::Authorization>>>, pub dashboard_metadata: Arc<Mutex<Vec<store::user::dashboard_metadata::DashboardMetadata>>>, + pub roles: Arc<Mutex<Vec<store::role::Role>>>, } impl MockDb { @@ -82,6 +83,7 @@ impl MockDb { user_roles: Default::default(), authorizations: Default::default(), dashboard_metadata: Default::default(), + roles: Default::default(), }) } } diff --git a/migrations/2024-02-14-092225_create_roles_table/down.sql b/migrations/2024-02-14-092225_create_roles_table/down.sql new file mode 100644 index 00000000000..c8b1c055f7d --- /dev/null +++ b/migrations/2024-02-14-092225_create_roles_table/down.sql @@ -0,0 +1,6 @@ +-- This file should undo anything in `up.sql` +DROP INDEX IF EXISTS role_id_index; +DROP INDEX IF EXISTS roles_merchant_org_index; + +DROP TABLE IF EXISTS roles; +DROP TYPE "RoleScope"; \ No newline at end of file diff --git a/migrations/2024-02-14-092225_create_roles_table/up.sql b/migrations/2024-02-14-092225_create_roles_table/up.sql new file mode 100644 index 00000000000..c33c133a078 --- /dev/null +++ b/migrations/2024-02-14-092225_create_roles_table/up.sql @@ -0,0 +1,19 @@ +-- Your SQL goes here +CREATE TYPE "RoleScope" AS ENUM ('merchant','organization'); + +CREATE TABLE IF NOT EXISTS roles ( + id SERIAL PRIMARY KEY, + role_name VARCHAR(64) NOT NULL, + role_id VARCHAR(64) NOT NULL UNIQUE, + merchant_id VARCHAR(64) NOT NULL, + org_id VARCHAR(64) NOT NULL, + groups TEXT[] NOT NULL, + scope "RoleScope" NOT NULL, + created_at TIMESTAMP NOT NULL DEFAULT now(), + created_by VARCHAR(64) NOT NULL, + last_modified_at TIMESTAMP NOT NULL DEFAULT now(), + last_modified_by VARCHAR(64) NOT NULL +); + +CREATE UNIQUE INDEX IF NOT EXISTS role_id_index ON roles (role_id); +CREATE INDEX roles_merchant_org_index ON roles (merchant_id, org_id); \ No newline at end of file
2024-02-18T21:15:04Z
## Type of Change <!-- Put an `x` in the boxes that apply --> - [ ] Bugfix - [x] New feature - [ ] Enhancement - [ ] Refactoring - [ ] Dependency updates - [ ] Documentation - [ ] CI/CD ## Description Setup roles table to support custom 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 ## How did you test it? Will be dependent on one core PR; checked table schema locally by running the migrations. After core functions micro PR containing Apis to interact with DB this can be tested in other environments as well. ## 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 - [ ] I added a [CHANGELOG](/CHANGELOG.md) entry if applicable
8038b48a54c937b3fe72b36cec5f20ee87309be4
Will be dependent on one core PR; checked table schema locally by running the migrations. After core functions micro PR containing Apis to interact with DB this can be tested in other environments as well.
juspay/hyperswitch
juspay__hyperswitch-3686
Bug: [FEATURE]: [Adyen] Use connector_response_reference_id as reference to merchant ### :memo: Feature Description - Reference id are used to map transactions in the connector’s dashboard. - Hyperswitch manages several reference ids, such as `payment_id`, `attempt_id`, and `connector_transaction_id` for a single transaction. - However, merchants may encounter uncertainty when determining which ID to utilize in the connector dashboard to identify the payment. ### :package: Have you spent some time checking if this feature request has been raised before? - [X] I checked and didn't find a similar issue ### :package: Have you read the Contributing Guidelines? - [X] I have read the [Contributing Guidelines](https://github.com/juspay/hyperswitch/blob/main/docs/CONTRIBUTING.md) ### :sparkles: Are you willing to submit a PR? - yes
diff --git a/crates/router/src/connector/adyen/transformers.rs b/crates/router/src/connector/adyen/transformers.rs index 072b542eee0..00c6ecbd6ab 100644 --- a/crates/router/src/connector/adyen/transformers.rs +++ b/crates/router/src/connector/adyen/transformers.rs @@ -338,6 +338,7 @@ pub struct RedirectionResponse { refusal_reason: Option<String>, refusal_reason_code: Option<String>, psp_reference: Option<String>, + merchant_reference: Option<String>, } #[derive(Debug, Clone, Deserialize, Serialize)] @@ -348,6 +349,7 @@ pub struct PresentToShopperResponse { action: AdyenPtsAction, refusal_reason: Option<String>, refusal_reason_code: Option<String>, + merchant_reference: Option<String>, } #[derive(Debug, Clone, Deserialize, Serialize)] @@ -359,6 +361,7 @@ pub struct QrCodeResponseResponse { refusal_reason_code: Option<String>, additional_data: Option<QrCodeAdditionalData>, psp_reference: Option<String>, + merchant_reference: Option<String>, } #[derive(Debug, Clone, Serialize, Deserialize)] @@ -3166,7 +3169,10 @@ pub fn get_redirection_response( mandate_reference: None, connector_metadata, network_txn_id: None, - connector_response_reference_id: None, + connector_response_reference_id: response + .merchant_reference + .clone() + .or(response.psp_reference), incremental_authorization_allowed: None, }; Ok((status, error, payments_response_data)) @@ -3220,7 +3226,10 @@ pub fn get_present_to_shopper_response( mandate_reference: None, connector_metadata, network_txn_id: None, - connector_response_reference_id: None, + connector_response_reference_id: response + .merchant_reference + .clone() + .or(response.psp_reference), incremental_authorization_allowed: None, }; Ok((status, error, payments_response_data)) @@ -3271,7 +3280,10 @@ pub fn get_qr_code_response( mandate_reference: None, connector_metadata, network_txn_id: None, - connector_response_reference_id: None, + connector_response_reference_id: response + .merchant_reference + .clone() + .or(response.psp_reference), incremental_authorization_allowed: None, }; Ok((status, error, payments_response_data)) @@ -3645,6 +3657,7 @@ pub struct AdyenCaptureResponse { reference: String, status: String, amount: Amount, + merchant_reference: Option<String>, } impl TryFrom<types::PaymentsCaptureResponseRouterData<AdyenCaptureResponse>> @@ -3655,7 +3668,7 @@ impl TryFrom<types::PaymentsCaptureResponseRouterData<AdyenCaptureResponse>> item: types::PaymentsCaptureResponseRouterData<AdyenCaptureResponse>, ) -> Result<Self, Self::Error> { let connector_transaction_id = if item.data.request.multiple_capture_data.is_some() { - item.response.psp_reference + item.response.psp_reference.clone() } else { item.response.payment_psp_reference }; @@ -3670,7 +3683,11 @@ impl TryFrom<types::PaymentsCaptureResponseRouterData<AdyenCaptureResponse>> mandate_reference: None, connector_metadata: None, network_txn_id: None, - connector_response_reference_id: None, + connector_response_reference_id: item + .response + .merchant_reference + .clone() + .or(Some(item.response.psp_reference)), incremental_authorization_allowed: None, }), amount_captured: Some(item.response.amount.value),
2024-02-16T13:05:53Z
## 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 --> ### 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? Payment Request for Cards ``` { "amount": 6540, "currency": "USD", "confirm": true, "capture_method": "automatic", "capture_on": "2022-09-10T10:11:12Z", "amount_to_capture": 6540, "customer_id": "StripeCustomer", "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": "371449635398431", "card_exp_month": "03", "card_exp_year": "2030", "card_holder_name": "joseph Doe", "card_cvc": "7373" } }, "routing": { "type": "single", "data": "adyen" }, "billing": { "address": { "line1": "1467", "line2": "Harrison Street", "line3": "Harrison Street", "city": "San Fransico", "state": "California", "zip": "94122", "country": "US", "first_name": "PiX" } }, "shipping": { "address": { "line1": "1467", "line2": "Harrison Street", "line3": "Harrison Street", "city": "San Fransico", "state": "California", "zip": "94122", "country": "US", "first_name": "PiX" } }, "statement_descriptor_name": "joseph", "statement_descriptor_suffix": "JS", "metadata": { "udf1": "value1", "new_customer": "true", "login_date": "2019-09-10T10:11:12Z" } } ``` In Response we should get `"reference_id": "some value",` ``` { "payment_id": "pay_q9uYD8e8lUUsO8BX1OBN", "merchant_id": "merchant_1708428346", "status": "succeeded", "amount": 6540, "net_amount": 6540, "amount_capturable": 0, "amount_received": 6540, "connector": "adyen", "client_secret": "pay_q9uYD8e8lUUsO8BX1OBN_secret_OAZ7LeGk4bwipgEyl7fT", "created": "2024-02-21T06:56:37.030Z", "currency": "USD", "customer_id": "StripeCustomer", "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": "8431", "card_type": null, "card_network": null, "card_issuer": null, "card_issuing_country": null, "card_isin": "371449", "card_extended_bin": "37144963", "card_exp_month": "03", "card_exp_year": "2030", "card_holder_name": "joseph Doe" } }, "payment_token": null, "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": { "number": null, "country_code": 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": null }, "phone": { "number": null, "country_code": 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": "StripeCustomer", "created_at": 1708498596, "expires": 1708502196, "secret": "epk_ed9cc758e8484b5fb018382c33097f4b" }, "manual_retry_allowed": false, "connector_transaction_id": "ZK5M8KH2HV8DCG65", "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_q9uYD8e8lUUsO8BX1OBN_1", (should not be null) "payment_link": null, "profile_id": "pro_qisu2wRsK4dq0H3hKKpM", "surcharge_details": null, "attempt_count": 1, "merchant_decision": null, "merchant_connector_id": "mca_wkHJMOOIYr9gbxJRXn5g", "incremental_authorization_allowed": null, "authorization_count": null, "incremental_authorizations": null, "expires_on": "2024-02-21T07:11:37.030Z", "fingerprint": null } ``` <img width="1728" alt="Screenshot 2024-02-20 at 1 39 43 PM" src="https://github.com/juspay/hyperswitch/assets/85639103/ad497234-2799-4aa9-84af-11aeef3d71d8"> Payment Request for Blik ``` { "amount": 16000, "currency": "PLN", "confirm": true, "capture_method": "automatic", "capture_on": "2022-09-10T10:11:12Z", "amount_to_capture": 16000, "customer_id": "StripeCustomer", "email": "abcdef123@gmail.com", "name": "John Doe", "phone": "999999999", "phone_country_code": "+65", "profile_id": "pro_sx78reJN0zgRzB5UGicx", "description": "Its my first payment request", "authentication_type": "three_ds", "return_url": "https://duck.com", "payment_method": "bank_redirect", "payment_method_type": "blik", "payment_method_data": { "bank_redirect": { "blik": { "blik_code":"777987" } } }, "billing": { "address": { "first_name": "John", "last_name": "Doe", "line1": "1467", "line2": "Harrison Street", "line3": "Harrison Street", "city": "San Fransico", "state": "California", "zip": "94122", "country": "PL" } }, "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": "PL", "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" } } ``` In Response we should get `"reference_id": "some value",` ``` { "payment_id": "pay_brzqtt6cdm5rL3HAYPxk", "merchant_id": "merchant_1708428346", "status": "processing", "amount": 10000, "net_amount": 10000, "amount_capturable": 0, "amount_received": null, "connector": "adyen", "client_secret": "pay_brzqtt6cdm5rL3HAYPxk_secret_eY8ZA1UonKsrJnmGRVC3", "created": "2024-02-20T13:30:26.642Z", "currency": "PLN", "customer_id": "StripeCustomer", "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": "bank_redirect", "payment_method_data": "bank_redirect", "payment_token": null, "shipping": { "address": { "city": "San Fransico", "country": "PL", "line1": "1467", "line2": "Harrison Street", "line3": "Harrison Street", "zip": "94122", "state": "California", "first_name": "John", "last_name": "Doe" }, "phone": { "number": null, "country_code": null } }, "billing": { "address": { "city": "San Fransico", "country": "PL", "line1": "1467", "line2": "Harrison Street", "line3": "Harrison Street", "zip": "94122", "state": "California", "first_name": "John", "last_name": "Doe" }, "phone": { "number": null, "country_code": null } }, "order_details": null, "email": "abcdef123@gmail.com", "name": "John Doe", "phone": "999999999", "return_url": "https://duck.com/", "authentication_type": "three_ds", "statement_descriptor_name": "joseph", "statement_descriptor_suffix": "JS", "next_action": { "type": "wait_screen_information", "display_from_timestamp": 1708435828625707000, "display_to_timestamp": 1708435888625707000 }, "cancellation_reason": null, "error_code": null, "error_message": null, "unified_code": null, "unified_message": null, "payment_experience": null, "payment_method_type": "blik", "connector_label": null, "business_country": null, "business_label": "default", "business_sub_label": null, "allowed_payment_method_types": null, "ephemeral_key": { "customer_id": "StripeCustomer", "created_at": 1708435826, "expires": 1708439426, "secret": "epk_940c1cecdd6b49928d2047f91ff5659c" }, "manual_retry_allowed": false, "connector_transaction_id": "DQ7M74SBGTGLNK82", "frm_message": null, "metadata": { "udf1": "value1", "login_date": "2019-09-10T10:11:12Z", "new_customer": "true" }, "connector_metadata": null, "feature_metadata": null, "reference_id": "some value, (it should not be null) "payment_link": null, "profile_id": "pro_qisu2wRsK4dq0H3hKKpM", "surcharge_details": null, "attempt_count": 1, "merchant_decision": null, "merchant_connector_id": "mca_wkHJMOOIYr9gbxJRXn5g", "incremental_authorization_allowed": null, "authorization_count": null, "incremental_authorizations": null, "expires_on": "2024-02-20T13:45:26.642Z", "fingerprint": null } ``` <img width="1579" alt="Screenshot 2024-02-20 at 3 09 28 PM" src="https://github.com/juspay/hyperswitch/assets/85639103/0db938b9-8c2a-4e8f-9f42-0cbb414274e3"> Payment Request for PIX ``` { "amount": 5000, "currency": "BRL", "confirm": true, "capture_method": "automatic", "capture_on": "2022-09-10T10:11:12Z", "amount_to_capture": 5000, "customer_id": "StripeCustomer", "email": "abcdef123@gmail.com", "name": "John Doe", "phone": "999999999", "phone_country_code": "+65", "profile_id": "pro_sx78reJN0zgRzB5UGicx", "description": "Its my first payment request", "authentication_type": "three_ds", "return_url": "https://duck.com", "payment_method": "bank_transfer", "payment_method_type": "pix", "payment_method_data": { "bank_transfer": { "pix": {} } }, "billing": { "address": { "first_name": "John", "last_name": "Doe", "line1": "1467", "line2": "Harrison Street", "line3": "Harrison Street", "city": "San Fransico", "state": "California", "zip": "94122", "country": "BR" } }, "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": "BR", "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" } } ``` Resoonse of PIx ``` { "payment_id": "pay_jIHarDTbWEuaOXjb7gAa", "merchant_id": "merchant_1708428346", "status": "requires_customer_action", "amount": 5000, "net_amount": 5000, "amount_capturable": 5000, "amount_received": null, "connector": "adyen", "client_secret": "pay_jIHarDTbWEuaOXjb7gAa_secret_Snqq6qd95TFXjk6AlvBN", "created": "2024-02-21T06:58:43.312Z", "currency": "BRL", "customer_id": "StripeCustomer", "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": "bank_transfer", "payment_method_data": "bank_transfer", "payment_token": null, "shipping": { "address": { "city": "San Fransico", "country": "BR", "line1": "1467", "line2": "Harrison Street", "line3": "Harrison Street", "zip": "94122", "state": "California", "first_name": "John", "last_name": "Doe" }, "phone": { "number": null, "country_code": null } }, "billing": { "address": { "city": "San Fransico", "country": "BR", "line1": "1467", "line2": "Harrison Street", "line3": "Harrison Street", "zip": "94122", "state": "California", "first_name": "John", "last_name": "Doe" }, "phone": { "number": null, "country_code": null } }, "order_details": null, "email": "abcdef123@gmail.com", "name": "John Doe", "phone": "999999999", "return_url": "https://duck.com/", "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": "pix", "connector_label": null, "business_country": null, "business_label": "default", "business_sub_label": null, "allowed_payment_method_types": null, "ephemeral_key": { "customer_id": "StripeCustomer", "created_at": 1708498723, "expires": 1708502323, "secret": "epk_735c0ab3ea1847d7add23e9c402f217b" }, "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": "some value", (should not be null) "payment_link": null, "profile_id": "pro_qisu2wRsK4dq0H3hKKpM", "surcharge_details": null, "attempt_count": 1, "merchant_decision": null, "merchant_connector_id": "mca_wkHJMOOIYr9gbxJRXn5g", "incremental_authorization_allowed": null, "authorization_count": null, "incremental_authorizations": null, "expires_on": "2024-02-21T07:13:43.312Z", "fingerprint": null } ``` In Response we should get `"reference_id": "some value",` <img width="1543" alt="Screenshot 2024-02-20 at 3 10 45 PM" src="https://github.com/juspay/hyperswitch/assets/85639103/c4d6a287-c04e-4bab-8dac-d9ba3d3f9c11"> ## 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 - [ ] I added a [CHANGELOG](/CHANGELOG.md) entry if applicable
cf3c66636ffee30cdd4353b276a89a8f9fc2d9d0
Payment Request for Cards ``` { "amount": 6540, "currency": "USD", "confirm": true, "capture_method": "automatic", "capture_on": "2022-09-10T10:11:12Z", "amount_to_capture": 6540, "customer_id": "StripeCustomer", "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": "371449635398431", "card_exp_month": "03", "card_exp_year": "2030", "card_holder_name": "joseph Doe", "card_cvc": "7373" } }, "routing": { "type": "single", "data": "adyen" }, "billing": { "address": { "line1": "1467", "line2": "Harrison Street", "line3": "Harrison Street", "city": "San Fransico", "state": "California", "zip": "94122", "country": "US", "first_name": "PiX" } }, "shipping": { "address": { "line1": "1467", "line2": "Harrison Street", "line3": "Harrison Street", "city": "San Fransico", "state": "California", "zip": "94122", "country": "US", "first_name": "PiX" } }, "statement_descriptor_name": "joseph", "statement_descriptor_suffix": "JS", "metadata": { "udf1": "value1", "new_customer": "true", "login_date": "2019-09-10T10:11:12Z" } } ``` In Response we should get `"reference_id": "some value",` ``` { "payment_id": "pay_q9uYD8e8lUUsO8BX1OBN", "merchant_id": "merchant_1708428346", "status": "succeeded", "amount": 6540, "net_amount": 6540, "amount_capturable": 0, "amount_received": 6540, "connector": "adyen", "client_secret": "pay_q9uYD8e8lUUsO8BX1OBN_secret_OAZ7LeGk4bwipgEyl7fT", "created": "2024-02-21T06:56:37.030Z", "currency": "USD", "customer_id": "StripeCustomer", "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": "8431", "card_type": null, "card_network": null, "card_issuer": null, "card_issuing_country": null, "card_isin": "371449", "card_extended_bin": "37144963", "card_exp_month": "03", "card_exp_year": "2030", "card_holder_name": "joseph Doe" } }, "payment_token": null, "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": { "number": null, "country_code": 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": null }, "phone": { "number": null, "country_code": 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": "StripeCustomer", "created_at": 1708498596, "expires": 1708502196, "secret": "epk_ed9cc758e8484b5fb018382c33097f4b" }, "manual_retry_allowed": false, "connector_transaction_id": "ZK5M8KH2HV8DCG65", "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_q9uYD8e8lUUsO8BX1OBN_1", (should not be null) "payment_link": null, "profile_id": "pro_qisu2wRsK4dq0H3hKKpM", "surcharge_details": null, "attempt_count": 1, "merchant_decision": null, "merchant_connector_id": "mca_wkHJMOOIYr9gbxJRXn5g", "incremental_authorization_allowed": null, "authorization_count": null, "incremental_authorizations": null, "expires_on": "2024-02-21T07:11:37.030Z", "fingerprint": null } ``` <img width="1728" alt="Screenshot 2024-02-20 at 1 39 43 PM" src="https://github.com/juspay/hyperswitch/assets/85639103/ad497234-2799-4aa9-84af-11aeef3d71d8"> Payment Request for Blik ``` { "amount": 16000, "currency": "PLN", "confirm": true, "capture_method": "automatic", "capture_on": "2022-09-10T10:11:12Z", "amount_to_capture": 16000, "customer_id": "StripeCustomer", "email": "abcdef123@gmail.com", "name": "John Doe", "phone": "999999999", "phone_country_code": "+65", "profile_id": "pro_sx78reJN0zgRzB5UGicx", "description": "Its my first payment request", "authentication_type": "three_ds", "return_url": "https://duck.com", "payment_method": "bank_redirect", "payment_method_type": "blik", "payment_method_data": { "bank_redirect": { "blik": { "blik_code":"777987" } } }, "billing": { "address": { "first_name": "John", "last_name": "Doe", "line1": "1467", "line2": "Harrison Street", "line3": "Harrison Street", "city": "San Fransico", "state": "California", "zip": "94122", "country": "PL" } }, "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": "PL", "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" } } ``` In Response we should get `"reference_id": "some value",` ``` { "payment_id": "pay_brzqtt6cdm5rL3HAYPxk", "merchant_id": "merchant_1708428346", "status": "processing", "amount": 10000, "net_amount": 10000, "amount_capturable": 0, "amount_received": null, "connector": "adyen", "client_secret": "pay_brzqtt6cdm5rL3HAYPxk_secret_eY8ZA1UonKsrJnmGRVC3", "created": "2024-02-20T13:30:26.642Z", "currency": "PLN", "customer_id": "StripeCustomer", "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": "bank_redirect", "payment_method_data": "bank_redirect", "payment_token": null, "shipping": { "address": { "city": "San Fransico", "country": "PL", "line1": "1467", "line2": "Harrison Street", "line3": "Harrison Street", "zip": "94122", "state": "California", "first_name": "John", "last_name": "Doe" }, "phone": { "number": null, "country_code": null } }, "billing": { "address": { "city": "San Fransico", "country": "PL", "line1": "1467", "line2": "Harrison Street", "line3": "Harrison Street", "zip": "94122", "state": "California", "first_name": "John", "last_name": "Doe" }, "phone": { "number": null, "country_code": null } }, "order_details": null, "email": "abcdef123@gmail.com", "name": "John Doe", "phone": "999999999", "return_url": "https://duck.com/", "authentication_type": "three_ds", "statement_descriptor_name": "joseph", "statement_descriptor_suffix": "JS", "next_action": { "type": "wait_screen_information", "display_from_timestamp": 1708435828625707000, "display_to_timestamp": 1708435888625707000 }, "cancellation_reason": null, "error_code": null, "error_message": null, "unified_code": null, "unified_message": null, "payment_experience": null, "payment_method_type": "blik", "connector_label": null, "business_country": null, "business_label": "default", "business_sub_label": null, "allowed_payment_method_types": null, "ephemeral_key": { "customer_id": "StripeCustomer", "created_at": 1708435826, "expires": 1708439426, "secret": "epk_940c1cecdd6b49928d2047f91ff5659c" }, "manual_retry_allowed": false, "connector_transaction_id": "DQ7M74SBGTGLNK82", "frm_message": null, "metadata": { "udf1": "value1", "login_date": "2019-09-10T10:11:12Z", "new_customer": "true" }, "connector_metadata": null, "feature_metadata": null, "reference_id": "some value, (it should not be null) "payment_link": null, "profile_id": "pro_qisu2wRsK4dq0H3hKKpM", "surcharge_details": null, "attempt_count": 1, "merchant_decision": null, "merchant_connector_id": "mca_wkHJMOOIYr9gbxJRXn5g", "incremental_authorization_allowed": null, "authorization_count": null, "incremental_authorizations": null, "expires_on": "2024-02-20T13:45:26.642Z", "fingerprint": null } ``` <img width="1579" alt="Screenshot 2024-02-20 at 3 09 28 PM" src="https://github.com/juspay/hyperswitch/assets/85639103/0db938b9-8c2a-4e8f-9f42-0cbb414274e3"> Payment Request for PIX ``` { "amount": 5000, "currency": "BRL", "confirm": true, "capture_method": "automatic", "capture_on": "2022-09-10T10:11:12Z", "amount_to_capture": 5000, "customer_id": "StripeCustomer", "email": "abcdef123@gmail.com", "name": "John Doe", "phone": "999999999", "phone_country_code": "+65", "profile_id": "pro_sx78reJN0zgRzB5UGicx", "description": "Its my first payment request", "authentication_type": "three_ds", "return_url": "https://duck.com", "payment_method": "bank_transfer", "payment_method_type": "pix", "payment_method_data": { "bank_transfer": { "pix": {} } }, "billing": { "address": { "first_name": "John", "last_name": "Doe", "line1": "1467", "line2": "Harrison Street", "line3": "Harrison Street", "city": "San Fransico", "state": "California", "zip": "94122", "country": "BR" } }, "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": "BR", "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" } } ``` Resoonse of PIx ``` { "payment_id": "pay_jIHarDTbWEuaOXjb7gAa", "merchant_id": "merchant_1708428346", "status": "requires_customer_action", "amount": 5000, "net_amount": 5000, "amount_capturable": 5000, "amount_received": null, "connector": "adyen", "client_secret": "pay_jIHarDTbWEuaOXjb7gAa_secret_Snqq6qd95TFXjk6AlvBN", "created": "2024-02-21T06:58:43.312Z", "currency": "BRL", "customer_id": "StripeCustomer", "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": "bank_transfer", "payment_method_data": "bank_transfer", "payment_token": null, "shipping": { "address": { "city": "San Fransico", "country": "BR", "line1": "1467", "line2": "Harrison Street", "line3": "Harrison Street", "zip": "94122", "state": "California", "first_name": "John", "last_name": "Doe" }, "phone": { "number": null, "country_code": null } }, "billing": { "address": { "city": "San Fransico", "country": "BR", "line1": "1467", "line2": "Harrison Street", "line3": "Harrison Street", "zip": "94122", "state": "California", "first_name": "John", "last_name": "Doe" }, "phone": { "number": null, "country_code": null } }, "order_details": null, "email": "abcdef123@gmail.com", "name": "John Doe", "phone": "999999999", "return_url": "https://duck.com/", "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": "pix", "connector_label": null, "business_country": null, "business_label": "default", "business_sub_label": null, "allowed_payment_method_types": null, "ephemeral_key": { "customer_id": "StripeCustomer", "created_at": 1708498723, "expires": 1708502323, "secret": "epk_735c0ab3ea1847d7add23e9c402f217b" }, "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": "some value", (should not be null) "payment_link": null, "profile_id": "pro_qisu2wRsK4dq0H3hKKpM", "surcharge_details": null, "attempt_count": 1, "merchant_decision": null, "merchant_connector_id": "mca_wkHJMOOIYr9gbxJRXn5g", "incremental_authorization_allowed": null, "authorization_count": null, "incremental_authorizations": null, "expires_on": "2024-02-21T07:13:43.312Z", "fingerprint": null } ``` In Response we should get `"reference_id": "some value",` <img width="1543" alt="Screenshot 2024-02-20 at 3 10 45 PM" src="https://github.com/juspay/hyperswitch/assets/85639103/c4d6a287-c04e-4bab-8dac-d9ba3d3f9c11">
juspay/hyperswitch
juspay__hyperswitch-3711
Bug: [REFACTOR] Refactor process tracker (scheduler) code to increase code reusability and improve logging ### Description 1. The process tracker (scheduler) code includes some amount of repetitive code, which can be extracted out to functions with suitable parameters to accommodate all usages. One such instance is the construction of the `ProcessTrackerNew` type, which is being done manually in multiple places, one of which is: https://github.com/juspay/hyperswitch/blob/fff780218ac356bb9b599896e766dd45266ac34a/crates/router/src/core/payment_methods/vault.rs#L1013-L1027 There exists the `ProcessTrackerExt::make_process_tracker_new()` method which can be used for the purpose, with suitable modifications. https://github.com/juspay/hyperswitch/blob/fff780218ac356bb9b599896e766dd45266ac34a/crates/scheduler/src/db/process_tracker.rs#L276-L303 2. The methods from the `ProcessTrackerExt` trait can be moved as methods on `diesel_models::ProcessTracker` and `diesel_models::ProcessTrackerNew` types, and the remaining ones (`reset()`, `retry()` and `finish_with_status()`) can be moved to the `ProcessTrackerInterface` trait. 3. The `business_status` column in the `process_tracker` database table contains high cardinality data due to the business status containing the process tracker ID itself, making it difficult for filtering based on business status. This can be improved by removing the process tracker ID from the business status, thus restricting the number of possible values for the column to a reasonably fixed number and reducing cardinality. (Attaching a screenshot of `business_status` column from a testing environment as of now.) ![Screenshot of business status column in process tracker table](https://github.com/juspay/hyperswitch/assets/22217505/c87d0e93-f5f0-42f1-9686-58092d98a87f) 4. The logging setup within the scheduler can be improved to better indicate about errors occurring when things fail within the scheduler.
diff --git a/crates/diesel_models/src/process_tracker.rs b/crates/diesel_models/src/process_tracker.rs index 9e649279f24..76e280d6bc0 100644 --- a/crates/diesel_models/src/process_tracker.rs +++ b/crates/diesel_models/src/process_tracker.rs @@ -1,8 +1,10 @@ +use common_utils::ext_traits::Encode; use diesel::{AsChangeset, Identifiable, Insertable, Queryable}; +use error_stack::ResultExt; use serde::{Deserialize, Serialize}; use time::PrimitiveDateTime; -use crate::{enums as storage_enums, schema::process_tracker}; +use crate::{enums as storage_enums, errors, schema::process_tracker, StorageResult}; #[derive( Clone, @@ -37,6 +39,13 @@ pub struct ProcessTracker { pub updated_at: PrimitiveDateTime, } +impl ProcessTracker { + #[inline(always)] + pub fn is_valid_business_status(&self, valid_statuses: &[&str]) -> bool { + valid_statuses.iter().any(|&x| x == self.business_status) + } +} + #[derive(Clone, Debug, Insertable, router_derive::DebugAsDisplay)] #[diesel(table_name = process_tracker)] pub struct ProcessTrackerNew { @@ -55,6 +64,42 @@ pub struct ProcessTrackerNew { pub updated_at: PrimitiveDateTime, } +impl ProcessTrackerNew { + pub fn new<T>( + process_tracker_id: impl Into<String>, + task: impl Into<String>, + runner: ProcessTrackerRunner, + tag: impl IntoIterator<Item = impl Into<String>>, + tracking_data: T, + schedule_time: PrimitiveDateTime, + ) -> StorageResult<Self> + where + T: Serialize + std::fmt::Debug, + { + const BUSINESS_STATUS_PENDING: &str = "Pending"; + + let current_time = common_utils::date_time::now(); + Ok(Self { + id: process_tracker_id.into(), + name: Some(task.into()), + tag: tag.into_iter().map(Into::into).collect(), + runner: Some(runner.to_string()), + retry_count: 0, + schedule_time: Some(schedule_time), + rule: String::new(), + tracking_data: tracking_data + .encode_to_value() + .change_context(errors::DatabaseError::Others) + .attach_printable("Failed to serialize process tracker tracking data")?, + business_status: String::from(BUSINESS_STATUS_PENDING), + status: storage_enums::ProcessTrackerStatus::New, + event: vec![], + created_at: current_time, + updated_at: current_time, + }) + } +} + #[derive(Debug)] pub enum ProcessTrackerUpdate { Update { @@ -165,3 +210,39 @@ pub struct ProcessData { cache_name: String, process_tracker: ProcessTracker, } + +#[derive( + serde::Serialize, + serde::Deserialize, + Clone, + Copy, + Debug, + PartialEq, + Eq, + strum::EnumString, + strum::Display, +)] +#[serde(rename_all = "SCREAMING_SNAKE_CASE")] +#[strum(serialize_all = "SCREAMING_SNAKE_CASE")] +pub enum ProcessTrackerRunner { + PaymentsSyncWorkflow, + RefundWorkflowRouter, + DeleteTokenizeDataWorkflow, + ApiKeyExpiryWorkflow, +} + +#[cfg(test)] +mod tests { + #![allow(clippy::unwrap_used)] + use common_utils::ext_traits::StringExt; + + use super::ProcessTrackerRunner; + + #[test] + fn test_enum_to_string() { + let string_format = "PAYMENTS_SYNC_WORKFLOW".to_string(); + let enum_format: ProcessTrackerRunner = + string_format.parse_enum("ProcessTrackerRunner").unwrap(); + assert_eq!(enum_format, ProcessTrackerRunner::PaymentsSyncWorkflow); + } +} diff --git a/crates/redis_interface/src/commands.rs b/crates/redis_interface/src/commands.rs index 5d376a4d7b1..70d24f0493c 100644 --- a/crates/redis_interface/src/commands.rs +++ b/crates/redis_interface/src/commands.rs @@ -596,7 +596,12 @@ impl super::RedisConnectionPool { None => self.pool.xread_map(count, block, streams, ids).await, } .into_report() - .change_context(errors::RedisError::StreamReadFailed) + .map_err(|err| match err.current_context().kind() { + RedisErrorKind::NotFound | RedisErrorKind::Parse => { + err.change_context(errors::RedisError::StreamEmptyOrNotAvailable) + } + _ => err.change_context(errors::RedisError::StreamReadFailed), + }) } // Consumer Group API diff --git a/crates/router/src/bin/scheduler.rs b/crates/router/src/bin/scheduler.rs index caa69ea1394..c2877535daa 100644 --- a/crates/router/src/bin/scheduler.rs +++ b/crates/router/src/bin/scheduler.rs @@ -14,7 +14,6 @@ use router::{ }, logger, routes, services::{self, api}, - types::storage::ProcessTrackerExt, workflows, }; use router_env::{instrument, tracing}; @@ -22,9 +21,7 @@ use scheduler::{ consumer::workflows::ProcessTrackerWorkflow, errors::ProcessTrackerError, workflows::ProcessTrackerWorkflows, SchedulerAppState, }; -use serde::{Deserialize, Serialize}; use storage_impl::errors::ApplicationError; -use strum::EnumString; use tokio::sync::{mpsc, oneshot}; const SCHEDULER_FLOW: &str = "SCHEDULER_FLOW"; @@ -209,17 +206,6 @@ pub async fn deep_health_check_func( Ok(response) } -#[derive(Serialize, Deserialize, Clone, Debug, PartialEq, Eq, EnumString)] -#[serde(rename_all = "SCREAMING_SNAKE_CASE")] -#[strum(serialize_all = "SCREAMING_SNAKE_CASE")] -pub enum PTRunner { - PaymentsSyncWorkflow, - RefundWorkflowRouter, - DeleteTokenizeDataWorkflow, - #[cfg(feature = "email")] - ApiKeyExpiryWorkflow, -} - #[derive(Debug, Copy, Clone)] pub struct WorkflowRunner; @@ -229,25 +215,51 @@ impl ProcessTrackerWorkflows<routes::AppState> for WorkflowRunner { &'a self, state: &'a routes::AppState, process: storage::ProcessTracker, - ) -> Result<(), ProcessTrackerError> { - let runner = process.runner.clone().get_required_value("runner")?; - let runner: Option<PTRunner> = runner.parse_enum("PTRunner").ok(); - let operation: Box<dyn ProcessTrackerWorkflow<routes::AppState>> = match runner { - Some(PTRunner::PaymentsSyncWorkflow) => { - Box::new(workflows::payment_sync::PaymentsSyncWorkflow) - } - Some(PTRunner::RefundWorkflowRouter) => { - Box::new(workflows::refund_router::RefundWorkflowRouter) - } - Some(PTRunner::DeleteTokenizeDataWorkflow) => { - Box::new(workflows::tokenized_data::DeleteTokenizeDataWorkflow) - } - #[cfg(feature = "email")] - Some(PTRunner::ApiKeyExpiryWorkflow) => { - Box::new(workflows::api_key_expiry::ApiKeyExpiryWorkflow) + ) -> CustomResult<(), ProcessTrackerError> { + let runner = process + .runner + .clone() + .get_required_value("runner") + .change_context(ProcessTrackerError::MissingRequiredField) + .attach_printable("Missing runner field in process information")?; + let runner: storage::ProcessTrackerRunner = runner + .parse_enum("ProcessTrackerRunner") + .change_context(ProcessTrackerError::UnexpectedFlow) + .attach_printable("Failed to parse workflow runner name")?; + + let get_operation = |runner: storage::ProcessTrackerRunner| -> CustomResult< + Box<dyn ProcessTrackerWorkflow<routes::AppState>>, + ProcessTrackerError, + > { + match runner { + storage::ProcessTrackerRunner::PaymentsSyncWorkflow => { + Ok(Box::new(workflows::payment_sync::PaymentsSyncWorkflow)) + } + storage::ProcessTrackerRunner::RefundWorkflowRouter => { + Ok(Box::new(workflows::refund_router::RefundWorkflowRouter)) + } + storage::ProcessTrackerRunner::DeleteTokenizeDataWorkflow => Ok(Box::new( + workflows::tokenized_data::DeleteTokenizeDataWorkflow, + )), + storage::ProcessTrackerRunner::ApiKeyExpiryWorkflow => { + #[cfg(feature = "email")] + { + Ok(Box::new(workflows::api_key_expiry::ApiKeyExpiryWorkflow)) + } + + #[cfg(not(feature = "email"))] + { + Err(error_stack::report!(ProcessTrackerError::UnexpectedFlow)) + .attach_printable( + "Cannot run API key expiry workflow when email feature is disabled", + ) + } + } } - _ => Err(ProcessTrackerError::UnexpectedFlow)?, }; + + let operation = get_operation(runner)?; + let app_state = &state.clone(); let output = operation.execute_workflow(app_state, process.clone()).await; match output { @@ -259,11 +271,10 @@ impl ProcessTrackerWorkflows<routes::AppState> for WorkflowRunner { Ok(_) => (), Err(error) => { logger::error!(%error, "Failed while handling error"); - let status = process - .finish_with_status( - state.get_db().as_scheduler(), - "GLOBAL_FAILURE".to_string(), - ) + let status = state + .get_db() + .as_scheduler() + .finish_process_with_business_status(process, "GLOBAL_FAILURE".to_string()) .await; if let Err(err) = status { logger::error!(%err, "Failed while performing database operation: GLOBAL_FAILURE"); @@ -294,18 +305,3 @@ async fn start_scheduler( ) .await } - -#[cfg(test)] -mod workflow_tests { - #![allow(clippy::unwrap_used)] - use common_utils::ext_traits::StringExt; - - use super::PTRunner; - - #[test] - fn test_enum_to_string() { - let string_format = "PAYMENTS_SYNC_WORKFLOW".to_string(); - let enum_format: PTRunner = string_format.parse_enum("PTRunner").unwrap(); - assert_eq!(enum_format, PTRunner::PaymentsSyncWorkflow) - } -} diff --git a/crates/router/src/configs/validations.rs b/crates/router/src/configs/validations.rs index 21ef4037d81..851b7ba7571 100644 --- a/crates/router/src/configs/validations.rs +++ b/crates/router/src/configs/validations.rs @@ -156,18 +156,27 @@ impl super::settings::ApiKeys { use common_utils::fp_utils::when; #[cfg(feature = "aws_kms")] - return when(self.kms_encrypted_hash_key.is_default_or_empty(), || { + when(self.kms_encrypted_hash_key.is_default_or_empty(), || { Err(ApplicationError::InvalidConfigurationValueError( "API key hashing key must not be empty when KMS feature is enabled".into(), )) - }); + })?; #[cfg(not(feature = "aws_kms"))] when(self.hash_key.is_empty(), || { Err(ApplicationError::InvalidConfigurationValueError( "API key hashing key must not be empty".into(), )) - }) + })?; + + #[cfg(feature = "email")] + when(self.expiry_reminder_days.is_empty(), || { + Err(ApplicationError::InvalidConfigurationValueError( + "API key expiry reminder days must not be empty".into(), + )) + })?; + + Ok(()) } } diff --git a/crates/router/src/core/api_keys.rs b/crates/router/src/core/api_keys.rs index 39212ab3814..b3f8931cde5 100644 --- a/crates/router/src/core/api_keys.rs +++ b/crates/router/src/core/api_keys.rs @@ -11,8 +11,6 @@ use masking::ExposeInterface; use masking::{PeekInterface, StrongSecret}; use router_env::{instrument, tracing}; -#[cfg(feature = "email")] -use crate::types::storage::enums; use crate::{ configs::settings, consts, @@ -28,7 +26,8 @@ const API_KEY_EXPIRY_TAG: &str = "API_KEY"; #[cfg(feature = "email")] const API_KEY_EXPIRY_NAME: &str = "API_KEY_EXPIRY"; #[cfg(feature = "email")] -const API_KEY_EXPIRY_RUNNER: &str = "API_KEY_EXPIRY_WORKFLOW"; +const API_KEY_EXPIRY_RUNNER: diesel_models::ProcessTrackerRunner = + diesel_models::ProcessTrackerRunner::ApiKeyExpiryWorkflow; #[cfg(feature = "aws_kms")] use external_services::aws_kms::decrypt::AwsKmsDecrypt; @@ -245,15 +244,16 @@ pub async fn add_api_key_expiry_task( api_key.expires_at.map(|expires_at| { expires_at.saturating_sub(time::Duration::days(i64::from(*expiry_reminder_day))) }) - }); + }) + .ok_or(errors::ApiErrorResponse::InternalServerError) + .into_report() + .attach_printable("Failed to obtain initial process tracker schedule time")?; - if let Some(schedule_time) = schedule_time { - if schedule_time <= current_time { - return Ok(()); - } + if schedule_time <= current_time { + return Ok(()); } - let api_key_expiry_tracker = &storage::ApiKeyExpiryTrackingData { + let api_key_expiry_tracker = storage::ApiKeyExpiryTrackingData { key_id: api_key.key_id.clone(), merchant_id: api_key.merchant_id.clone(), // We need API key expiry too, because we need to decide on the schedule_time in @@ -261,30 +261,18 @@ pub async fn add_api_key_expiry_task( api_key_expiry: api_key.expires_at, expiry_reminder_days: expiry_reminder_days.clone(), }; - let api_key_expiry_workflow_model = serde_json::to_value(api_key_expiry_tracker) - .into_report() - .change_context(errors::ApiErrorResponse::InternalServerError) - .attach_printable_lazy(|| { - format!("unable to serialize API key expiry tracker: {api_key_expiry_tracker:?}") - })?; - let process_tracker_entry = storage::ProcessTrackerNew { - id: generate_task_id_for_api_key_expiry_workflow(api_key.key_id.as_str()), - name: Some(String::from(API_KEY_EXPIRY_NAME)), - tag: vec![String::from(API_KEY_EXPIRY_TAG)], - runner: Some(String::from(API_KEY_EXPIRY_RUNNER)), - // Retry count specifies, number of times the current process (email) has been retried. - // It also acts as an index of expiry_reminder_days vector - retry_count: 0, + let process_tracker_id = generate_task_id_for_api_key_expiry_workflow(api_key.key_id.as_str()); + let process_tracker_entry = storage::ProcessTrackerNew::new( + process_tracker_id, + API_KEY_EXPIRY_NAME, + API_KEY_EXPIRY_RUNNER, + [API_KEY_EXPIRY_TAG], + api_key_expiry_tracker, schedule_time, - rule: String::new(), - tracking_data: api_key_expiry_workflow_model, - business_status: String::from("Pending"), - status: enums::ProcessTrackerStatus::New, - event: vec![], - created_at: current_time, - updated_at: current_time, - }; + ) + .change_context(errors::ApiErrorResponse::InternalServerError) + .attach_printable("Failed to construct API key expiry process tracker task")?; store .insert_process(process_tracker_entry) @@ -293,7 +281,7 @@ pub async fn add_api_key_expiry_task( .attach_printable_lazy(|| { format!( "Failed while inserting API key expiry reminder to process_tracker: api_key_id: {}", - api_key_expiry_tracker.key_id + api_key.key_id ) })?; metrics::TASKS_ADDED_COUNT.add( diff --git a/crates/router/src/core/payment_methods/vault.rs b/crates/router/src/core/payment_methods/vault.rs index b547027a1c7..622fed0738a 100644 --- a/crates/router/src/core/payment_methods/vault.rs +++ b/crates/router/src/core/payment_methods/vault.rs @@ -17,7 +17,7 @@ use crate::{ routes::metrics, types::{ api, domain, - storage::{self, enums, ProcessTrackerExt}, + storage::{self, enums}, }, utils::StringExt, }; @@ -998,33 +998,31 @@ pub async fn add_delete_tokenized_data_task( lookup_key: &str, pm: enums::PaymentMethod, ) -> RouterResult<()> { - let runner = "DELETE_TOKENIZE_DATA_WORKFLOW"; - let current_time = common_utils::date_time::now(); - let tracking_data = serde_json::to_value(storage::TokenizeCoreWorkflow { + let runner = storage::ProcessTrackerRunner::DeleteTokenizeDataWorkflow; + let process_tracker_id = format!("{runner}_{lookup_key}"); + let task = runner.to_string(); + let tag = ["BASILISK-V3"]; + let tracking_data = storage::TokenizeCoreWorkflow { lookup_key: lookup_key.to_owned(), pm, - }) - .into_report() + }; + let schedule_time = get_delete_tokenize_schedule_time(db, &pm, 0) + .await + .ok_or(errors::ApiErrorResponse::InternalServerError) + .into_report() + .attach_printable("Failed to obtain initial process tracker schedule time")?; + + let process_tracker_entry = storage::ProcessTrackerNew::new( + process_tracker_id, + &task, + runner, + tag, + tracking_data, + schedule_time, + ) .change_context(errors::ApiErrorResponse::InternalServerError) - .attach_printable_lazy(|| format!("unable to convert into value {lookup_key:?}"))?; - - let schedule_time = get_delete_tokenize_schedule_time(db, &pm, 0).await; + .attach_printable("Failed to construct delete tokenized data process tracker task")?; - let process_tracker_entry = storage::ProcessTrackerNew { - id: format!("{runner}_{lookup_key}"), - name: Some(String::from(runner)), - tag: vec![String::from("BASILISK-V3")], - runner: Some(String::from(runner)), - retry_count: 0, - schedule_time, - rule: String::new(), - tracking_data, - business_status: String::from("Pending"), - status: enums::ProcessTrackerStatus::New, - event: vec![], - created_at: current_time, - updated_at: current_time, - }; let response = db.insert_process(process_tracker_entry).await; response.map(|_| ()).or_else(|err| { if err.current_context().is_db_unique_violation() { @@ -1056,10 +1054,11 @@ pub async fn start_tokenize_data_workflow( Ok(()) => { logger::info!("Card From locker deleted Successfully"); //mark task as finished - let id = tokenize_tracker.id.clone(); - tokenize_tracker - .clone() - .finish_with_status(db.as_scheduler(), format!("COMPLETED_BY_PT_{id}")) + db.as_scheduler() + .finish_process_with_business_status( + tokenize_tracker.clone(), + "COMPLETED_BY_PT".to_string(), + ) .await?; } Err(err) => { @@ -1104,7 +1103,11 @@ pub async fn retry_delete_tokenize( match schedule_time { Some(s_time) => { - let retry_schedule = pt.retry(db.as_scheduler(), s_time).await; + let retry_schedule = db + .as_scheduler() + .retry_process(pt, s_time) + .await + .map_err(Into::into); metrics::TASKS_RESET_COUNT.add( &metrics::CONTEXT, 1, @@ -1115,10 +1118,11 @@ pub async fn retry_delete_tokenize( ); retry_schedule } - None => { - pt.finish_with_status(db.as_scheduler(), "RETRIES_EXCEEDED".to_string()) - .await - } + None => db + .as_scheduler() + .finish_process_with_business_status(pt, "RETRIES_EXCEEDED".to_string()) + .await + .map_err(Into::into), } } diff --git a/crates/router/src/core/payments.rs b/crates/router/src/core/payments.rs index 7348a2b8f0c..050b0dd4b7b 100644 --- a/crates/router/src/core/payments.rs +++ b/crates/router/src/core/payments.rs @@ -25,7 +25,7 @@ use redis_interface::errors::RedisError; use router_env::{instrument, tracing}; #[cfg(feature = "olap")] use router_types::transformers::ForeignFrom; -use scheduler::{db::process_tracker::ProcessTrackerExt, errors as sch_errors, utils as pt_utils}; +use scheduler::utils as pt_utils; use time; pub use self::operations::{ @@ -2356,28 +2356,32 @@ pub async fn add_process_sync_task( db: &dyn StorageInterface, payment_attempt: &storage::PaymentAttempt, schedule_time: time::PrimitiveDateTime, -) -> Result<(), sch_errors::ProcessTrackerError> { +) -> CustomResult<(), errors::StorageError> { let tracking_data = api::PaymentsRetrieveRequest { force_sync: true, merchant_id: Some(payment_attempt.merchant_id.clone()), resource_id: api::PaymentIdType::PaymentAttemptId(payment_attempt.attempt_id.clone()), ..Default::default() }; - let runner = "PAYMENTS_SYNC_WORKFLOW"; + let runner = storage::ProcessTrackerRunner::PaymentsSyncWorkflow; let task = "PAYMENTS_SYNC"; + let tag = ["SYNC", "PAYMENT"]; let process_tracker_id = pt_utils::get_process_tracker_id( runner, task, &payment_attempt.attempt_id, &payment_attempt.merchant_id, ); - let process_tracker_entry = <storage::ProcessTracker>::make_process_tracker_new( + let process_tracker_entry = storage::ProcessTrackerNew::new( process_tracker_id, task, runner, + tag, tracking_data, schedule_time, - )?; + ) + .map_err(errors::StorageError::from) + .into_report()?; db.insert_process(process_tracker_entry).await?; Ok(()) @@ -2388,7 +2392,7 @@ pub async fn reset_process_sync_task( payment_attempt: &storage::PaymentAttempt, schedule_time: time::PrimitiveDateTime, ) -> Result<(), errors::ProcessTrackerError> { - let runner = "PAYMENTS_SYNC_WORKFLOW"; + let runner = storage::ProcessTrackerRunner::PaymentsSyncWorkflow; let task = "PAYMENTS_SYNC"; let process_tracker_id = pt_utils::get_process_tracker_id( runner, @@ -2400,8 +2404,8 @@ pub async fn reset_process_sync_task( .find_process_by_id(&process_tracker_id) .await? .ok_or(errors::ProcessTrackerError::ProcessFetchingFailed)?; - psync_process - .reset(db.as_scheduler(), schedule_time) + db.as_scheduler() + .reset_process(psync_process, schedule_time) .await?; Ok(()) } diff --git a/crates/router/src/core/payments/helpers.rs b/crates/router/src/core/payments/helpers.rs index 74a382e63de..31671f2862c 100644 --- a/crates/router/src/core/payments/helpers.rs +++ b/crates/router/src/core/payments/helpers.rs @@ -1032,7 +1032,6 @@ where ); super::add_process_sync_task(&*state.store, payment_attempt, stime) .await - .into_report() .change_context(errors::ApiErrorResponse::InternalServerError) .attach_printable("Failed while adding task to process tracker") } else { diff --git a/crates/router/src/core/refunds.rs b/crates/router/src/core/refunds.rs index 4b1c33296e6..06030262fbc 100644 --- a/crates/router/src/core/refunds.rs +++ b/crates/router/src/core/refunds.rs @@ -19,7 +19,7 @@ use crate::{ self, api::{self, refunds}, domain, - storage::{self, enums, ProcessTrackerExt}, + storage::{self, enums}, transformers::{ForeignFrom, ForeignInto}, }, utils::{self, OptionExt}, @@ -798,9 +798,9 @@ pub async fn schedule_refund_execution( ) -> RouterResult<storage::Refund> { // refunds::RefundResponse> { let db = &*state.store; - let runner = "REFUND_WORKFLOW_ROUTER"; + let runner = storage::ProcessTrackerRunner::RefundWorkflowRouter; let task = "EXECUTE_REFUND"; - let task_id = format!("{}_{}_{}", runner, task, refund.internal_reference_id); + let task_id = format!("{runner}_{task}_{}", refund.internal_reference_id); let refund_process = db .find_process_by_id(&task_id) @@ -909,10 +909,13 @@ pub async fn sync_refund_with_gateway_workflow( ]; match response.refund_status { status if terminal_status.contains(&status) => { - let id = refund_tracker.id.clone(); - refund_tracker - .clone() - .finish_with_status(state.store.as_scheduler(), format!("COMPLETED_BY_PT_{id}")) + state + .store + .as_scheduler() + .finish_process_with_business_status( + refund_tracker.clone(), + "COMPLETED_BY_PT".to_string(), + ) .await? } _ => { @@ -1020,18 +1023,29 @@ pub async fn trigger_refund_execute_workflow( None, ) .await?; - add_refund_sync_task(db, &updated_refund, "REFUND_WORKFLOW_ROUTER").await?; + add_refund_sync_task( + db, + &updated_refund, + storage::ProcessTrackerRunner::RefundWorkflowRouter, + ) + .await?; } (true, enums::RefundStatus::Pending) => { // create sync task - add_refund_sync_task(db, &refund, "REFUND_WORKFLOW_ROUTER").await?; + add_refund_sync_task( + db, + &refund, + storage::ProcessTrackerRunner::RefundWorkflowRouter, + ) + .await?; } (_, _) => { //mark task as finished - let id = refund_tracker.id.clone(); - refund_tracker - .clone() - .finish_with_status(db.as_scheduler(), format!("COMPLETED_BY_PT_{id}")) + db.as_scheduler() + .finish_process_with_business_status( + refund_tracker.clone(), + "COMPLETED_BY_PT".to_string(), + ) .await?; } }; @@ -1054,29 +1068,23 @@ pub fn refund_to_refund_core_workflow_model( pub async fn add_refund_sync_task( db: &dyn db::StorageInterface, refund: &storage::Refund, - runner: &str, + runner: storage::ProcessTrackerRunner, ) -> RouterResult<storage::ProcessTracker> { - let current_time = common_utils::date_time::now(); - let refund_workflow_model = serde_json::to_value(refund_to_refund_core_workflow_model(refund)) - .into_report() - .change_context(errors::ApiErrorResponse::InternalServerError) - .attach_printable_lazy(|| format!("unable to convert into value {:?}", &refund))?; let task = "SYNC_REFUND"; - let process_tracker_entry = storage::ProcessTrackerNew { - id: format!("{}_{}_{}", runner, task, refund.internal_reference_id), - name: Some(String::from(task)), - tag: vec![String::from("REFUND")], - runner: Some(String::from(runner)), - retry_count: 0, - schedule_time: Some(common_utils::date_time::now()), - rule: String::new(), - tracking_data: refund_workflow_model, - business_status: String::from("Pending"), - status: enums::ProcessTrackerStatus::New, - event: vec![], - created_at: current_time, - updated_at: current_time, - }; + let process_tracker_id = format!("{runner}_{task}_{}", refund.internal_reference_id); + let schedule_time = common_utils::date_time::now(); + let refund_workflow_tracking_data = refund_to_refund_core_workflow_model(refund); + let tag = ["REFUND"]; + let process_tracker_entry = storage::ProcessTrackerNew::new( + process_tracker_id, + task, + runner, + tag, + refund_workflow_tracking_data, + schedule_time, + ) + .change_context(errors::ApiErrorResponse::InternalServerError) + .attach_printable("Failed to construct refund sync process tracker task")?; let response = db .insert_process(process_tracker_entry) @@ -1101,29 +1109,23 @@ pub async fn add_refund_sync_task( pub async fn add_refund_execute_task( db: &dyn db::StorageInterface, refund: &storage::Refund, - runner: &str, + runner: storage::ProcessTrackerRunner, ) -> RouterResult<storage::ProcessTracker> { let task = "EXECUTE_REFUND"; - let current_time = common_utils::date_time::now(); - let refund_workflow_model = serde_json::to_value(refund_to_refund_core_workflow_model(refund)) - .into_report() - .change_context(errors::ApiErrorResponse::InternalServerError) - .attach_printable_lazy(|| format!("unable to convert into value {:?}", &refund))?; - let process_tracker_entry = storage::ProcessTrackerNew { - id: format!("{}_{}_{}", runner, task, refund.internal_reference_id), - name: Some(String::from(task)), - tag: vec![String::from("REFUND")], - runner: Some(String::from(runner)), - retry_count: 0, - schedule_time: Some(common_utils::date_time::now()), - rule: String::new(), - tracking_data: refund_workflow_model, - business_status: String::from("Pending"), - status: enums::ProcessTrackerStatus::New, - event: vec![], - created_at: current_time, - updated_at: current_time, - }; + let process_tracker_id = format!("{runner}_{task}_{}", refund.internal_reference_id); + let tag = ["REFUND"]; + let schedule_time = common_utils::date_time::now(); + let refund_workflow_tracking_data = refund_to_refund_core_workflow_model(refund); + let process_tracker_entry = storage::ProcessTrackerNew::new( + process_tracker_id, + task, + runner, + tag, + refund_workflow_tracking_data, + schedule_time, + ) + .change_context(errors::ApiErrorResponse::InternalServerError) + .attach_printable("Failed to construct refund execute process tracker task")?; let response = db .insert_process(process_tracker_entry) @@ -1177,7 +1179,11 @@ pub async fn retry_refund_sync_task( match schedule_time { Some(s_time) => { - let retry_schedule = pt.retry(db.as_scheduler(), s_time).await; + let retry_schedule = db + .as_scheduler() + .retry_process(pt, s_time) + .await + .map_err(Into::into); metrics::TASKS_RESET_COUNT.add( &metrics::CONTEXT, 1, @@ -1185,9 +1191,10 @@ pub async fn retry_refund_sync_task( ); retry_schedule } - None => { - pt.finish_with_status(db.as_scheduler(), "RETRIES_EXCEEDED".to_string()) - .await - } + None => db + .as_scheduler() + .finish_process_with_business_status(pt, "RETRIES_EXCEEDED".to_string()) + .await + .map_err(Into::into), } } diff --git a/crates/router/src/db/kafka_store.rs b/crates/router/src/db/kafka_store.rs index 0897deb87e5..599c8a3492b 100644 --- a/crates/router/src/db/kafka_store.rs +++ b/crates/router/src/db/kafka_store.rs @@ -1396,15 +1396,6 @@ impl ProcessTrackerInterface for KafkaStore { .process_tracker_update_process_status_by_ids(task_ids, task_update) .await } - async fn update_process_tracker( - &self, - this: storage::ProcessTracker, - process: storage::ProcessTrackerUpdate, - ) -> CustomResult<storage::ProcessTracker, errors::StorageError> { - self.diesel_store - .update_process_tracker(this, process) - .await - } async fn insert_process( &self, @@ -1413,6 +1404,32 @@ impl ProcessTrackerInterface for KafkaStore { self.diesel_store.insert_process(new).await } + async fn reset_process( + &self, + this: storage::ProcessTracker, + schedule_time: PrimitiveDateTime, + ) -> CustomResult<(), errors::StorageError> { + self.diesel_store.reset_process(this, schedule_time).await + } + + async fn retry_process( + &self, + this: storage::ProcessTracker, + schedule_time: PrimitiveDateTime, + ) -> CustomResult<(), errors::StorageError> { + self.diesel_store.retry_process(this, schedule_time).await + } + + async fn finish_process_with_business_status( + &self, + this: storage::ProcessTracker, + business_status: String, + ) -> CustomResult<(), errors::StorageError> { + self.diesel_store + .finish_process_with_business_status(this, business_status) + .await + } + async fn find_processes_by_time_status( &self, time_lower_limit: PrimitiveDateTime, diff --git a/crates/router/src/types/storage.rs b/crates/router/src/types/storage.rs index 01decc89c4c..27fd6db8e7e 100644 --- a/crates/router/src/types/storage.rs +++ b/crates/router/src/types/storage.rs @@ -43,7 +43,9 @@ pub use data_models::payments::{ payment_intent::{PaymentIntentNew, PaymentIntentUpdate}, PaymentIntent, }; -pub use diesel_models::{ProcessTracker, ProcessTrackerNew, ProcessTrackerUpdate}; +pub use diesel_models::{ + ProcessTracker, ProcessTrackerNew, ProcessTrackerRunner, ProcessTrackerUpdate, +}; pub use scheduler::db::process_tracker; pub use self::{ diff --git a/crates/router/src/workflows/api_key_expiry.rs b/crates/router/src/workflows/api_key_expiry.rs index b9830c4ebc5..e9e1f323708 100644 --- a/crates/router/src/workflows/api_key_expiry.rs +++ b/crates/router/src/workflows/api_key_expiry.rs @@ -8,11 +8,7 @@ use crate::{ logger::error, routes::{metrics, AppState}, services::email::types::ApiKeyExpiryReminder, - types::{ - api, - domain::UserEmail, - storage::{self, ProcessTrackerExt}, - }, + types::{api, domain::UserEmail, storage}, utils::OptionExt, }; @@ -90,8 +86,10 @@ impl ProcessTrackerWorkflow<AppState> for ApiKeyExpiryWorkflow { == i32::try_from(tracking_data.expiry_reminder_days.len() - 1) .map_err(|_| errors::ProcessTrackerError::TypeConversionError)? { - process - .finish_with_status(state.get_db().as_scheduler(), "COMPLETED_BY_PT".to_string()) + state + .get_db() + .as_scheduler() + .finish_process_with_business_status(process, "COMPLETED_BY_PT".to_string()) .await? } // If tasks are remaining that has to be scheduled diff --git a/crates/router/src/workflows/payment_sync.rs b/crates/router/src/workflows/payment_sync.rs index b2296e17f70..92057b08899 100644 --- a/crates/router/src/workflows/payment_sync.rs +++ b/crates/router/src/workflows/payment_sync.rs @@ -3,7 +3,6 @@ use error_stack::ResultExt; use router_env::logger; use scheduler::{ consumer::{self, types::process_data, workflows::ProcessTrackerWorkflow}, - db::process_tracker::ProcessTrackerExt, errors as sch_errors, utils as scheduler_utils, SchedulerAppState, }; @@ -91,12 +90,10 @@ impl ProcessTrackerWorkflow<AppState> for PaymentsSyncWorkflow { ]; match &payment_data.payment_attempt.status { status if terminal_status.contains(status) => { - let id = process.id.clone(); - process - .finish_with_status( - state.get_db().as_scheduler(), - format!("COMPLETED_BY_PT_{id}"), - ) + state + .get_db() + .as_scheduler() + .finish_process_with_business_status(process, "COMPLETED_BY_PT".to_string()) .await? } _ => { @@ -274,11 +271,12 @@ pub async fn retry_sync_task( match schedule_time { Some(s_time) => { - pt.retry(db.as_scheduler(), s_time).await?; + db.as_scheduler().retry_process(pt, s_time).await?; Ok(false) } None => { - pt.finish_with_status(db.as_scheduler(), "RETRIES_EXCEEDED".to_string()) + db.as_scheduler() + .finish_process_with_business_status(pt, "RETRIES_EXCEEDED".to_string()) .await?; Ok(true) } diff --git a/crates/scheduler/src/consumer.rs b/crates/scheduler/src/consumer.rs index ccc943afba3..e069db28da7 100644 --- a/crates/scheduler/src/consumer.rs +++ b/crates/scheduler/src/consumer.rs @@ -18,9 +18,8 @@ use uuid::Uuid; use super::env::logger; pub use super::workflows::ProcessTrackerWorkflow; use crate::{ - configs::settings::SchedulerSettings, - db::process_tracker::{ProcessTrackerExt, ProcessTrackerInterface}, - errors, metrics, utils as pt_utils, SchedulerAppState, SchedulerInterface, + configs::settings::SchedulerSettings, db::process_tracker::ProcessTrackerInterface, errors, + metrics, utils as pt_utils, SchedulerAppState, SchedulerInterface, }; // Valid consumer business statuses @@ -59,7 +58,7 @@ pub async fn start_consumer<T: SchedulerAppState + 'static>( let consumer_operation_counter = sync::Arc::new(atomic::AtomicU64::new(0)); let signal = get_allowed_signals() .map_err(|error| { - logger::error!("Signal Handler Error: {:?}", error); + logger::error!(?error, "Signal Handler Error"); errors::ProcessTrackerError::ConfigurationError }) .into_report() @@ -80,8 +79,8 @@ pub async fn start_consumer<T: SchedulerAppState + 'static>( pt_utils::consumer_operation_handler( state.clone(), settings.clone(), - |err| { - logger::error!(%err); + |error| { + logger::error!(?error, "Failed to perform consumer operation"); }, sync::Arc::clone(&consumer_operation_counter), workflow_selector, @@ -94,7 +93,7 @@ pub async fn start_consumer<T: SchedulerAppState + 'static>( loop { shutdown_interval.tick().await; let active_tasks = consumer_operation_counter.load(atomic::Ordering::Acquire); - logger::error!("{}", active_tasks); + logger::info!("Active tasks: {active_tasks}"); match active_tasks { 0 => { logger::info!("Terminating consumer"); @@ -130,7 +129,7 @@ pub async fn consumer_operations<T: SchedulerAppState + 'static>( .consumer_group_create(&stream_name, &group_name, &RedisEntryId::AfterLastID) .await; if group_created.is_err() { - logger::info!("Consumer group already exists"); + logger::info!("Consumer group {group_name} already exists"); } let mut tasks = state @@ -148,7 +147,7 @@ pub async fn consumer_operations<T: SchedulerAppState + 'static>( pt_utils::add_histogram_metrics(&pickup_time, task, &stream_name); metrics::TASK_CONSUMED.add(&metrics::CONTEXT, 1, &[]); - // let runner = workflow_selector(task)?.ok_or(errors::ProcessTrackerError::UnexpectedFlow)?; + handler.push(tokio::task::spawn(start_workflow( state.clone(), task.clone(), @@ -171,6 +170,11 @@ pub async fn fetch_consumer_tasks( ) -> CustomResult<Vec<storage::ProcessTracker>, errors::ProcessTrackerError> { let batches = pt_utils::get_batches(redis_conn, stream_name, group_name, consumer_name).await?; + // Returning early to avoid execution of database queries when `batches` is empty + if batches.is_empty() { + return Ok(Vec::new()); + } + let mut tasks = batches.into_iter().fold(Vec::new(), |mut acc, batch| { acc.extend_from_slice( batch @@ -209,15 +213,20 @@ pub async fn start_workflow<T>( process: storage::ProcessTracker, _pickup_time: PrimitiveDateTime, workflow_selector: impl workflows::ProcessTrackerWorkflows<T> + 'static + std::fmt::Debug, -) -> Result<(), errors::ProcessTrackerError> +) -> CustomResult<(), errors::ProcessTrackerError> where T: SchedulerAppState, { tracing::Span::current().record("workflow_id", Uuid::new_v4().to_string()); - logger::info!("{:?}", process.name.as_ref()); + logger::info!(pt.name=?process.name, pt.id=%process.id); + let res = workflow_selector .trigger_workflow(&state.clone(), process.clone()) - .await; + .await + .map_err(|error| { + logger::error!(?error, "Failed to trigger workflow"); + error + }); metrics::TASK_PROCESSED.add(&metrics::CONTEXT, 1, &[]); res } @@ -228,7 +237,7 @@ pub async fn consumer_error_handler( process: storage::ProcessTracker, error: errors::ProcessTrackerError, ) -> CustomResult<(), errors::ProcessTrackerError> { - logger::error!(pt.name = ?process.name, pt.id = %process.id, ?error, "ERROR: Failed while executing workflow"); + logger::error!(pt.name=?process.name, pt.id=%process.id, ?error, "Failed to execute workflow"); state .process_tracker_update_process_status_by_ids( diff --git a/crates/scheduler/src/consumer/workflows.rs b/crates/scheduler/src/consumer/workflows.rs index 3b897347bed..3e8a4c8e502 100644 --- a/crates/scheduler/src/consumer/workflows.rs +++ b/crates/scheduler/src/consumer/workflows.rs @@ -1,8 +1,9 @@ use async_trait::async_trait; use common_utils::errors::CustomResult; pub use diesel_models::process_tracker as storage; +use router_env::logger; -use crate::{db::process_tracker::ProcessTrackerExt, errors, SchedulerAppState}; +use crate::{errors, SchedulerAppState}; pub type WorkflowSelectorFn = fn(&storage::ProcessTracker) -> Result<(), errors::ProcessTrackerError>; @@ -14,15 +15,16 @@ pub trait ProcessTrackerWorkflows<T>: Send + Sync { &'a self, _state: &'a T, _process: storage::ProcessTracker, - ) -> Result<(), errors::ProcessTrackerError> { + ) -> CustomResult<(), errors::ProcessTrackerError> { Err(errors::ProcessTrackerError::NotImplemented)? } + async fn execute_workflow<'a>( &'a self, operation: Box<dyn ProcessTrackerWorkflow<T>>, state: &'a T, process: storage::ProcessTracker, - ) -> Result<(), errors::ProcessTrackerError> + ) -> CustomResult<(), errors::ProcessTrackerError> where T: SchedulerAppState, { @@ -35,16 +37,18 @@ pub trait ProcessTrackerWorkflows<T>: Send + Sync { .await { Ok(_) => (), - Err(_error) => { - // logger::error!(%error, "Failed while handling error"); - let status = process - .finish_with_status( - state.get_db().as_scheduler(), - "GLOBAL_FAILURE".to_string(), - ) + Err(error) => { + logger::error!( + ?error, + "Failed to handle process tracker workflow execution error" + ); + let status = app_state + .get_db() + .as_scheduler() + .finish_process_with_business_status(process, "GLOBAL_FAILURE".to_string()) .await; - if let Err(_err) = status { - // logger::error!(%err, "Failed while performing database operation: GLOBAL_FAILURE"); + if let Err(error) = status { + logger::error!(?error, "Failed to update process business status"); } } }, @@ -55,7 +59,7 @@ pub trait ProcessTrackerWorkflows<T>: Send + Sync { #[async_trait] pub trait ProcessTrackerWorkflow<T>: Send + Sync { - // The core execution of the workflow + /// The core execution of the workflow async fn execute_workflow<'a>( &'a self, _state: &'a T, @@ -63,9 +67,11 @@ pub trait ProcessTrackerWorkflow<T>: Send + Sync { ) -> Result<(), errors::ProcessTrackerError> { Err(errors::ProcessTrackerError::NotImplemented)? } - // Callback function after successful execution of the `execute_workflow` + + /// Callback function after successful execution of the `execute_workflow` async fn success_handler<'a>(&'a self, _state: &'a T, _process: storage::ProcessTracker) {} - // Callback function after error received from `execute_workflow` + + /// Callback function after error received from `execute_workflow` async fn error_handler<'a>( &'a self, _state: &'a T, @@ -75,18 +81,3 @@ pub trait ProcessTrackerWorkflow<T>: Send + Sync { Err(errors::ProcessTrackerError::NotImplemented)? } } - -// #[cfg(test)] -// mod workflow_tests { -// #![allow(clippy::unwrap_used)] -// use common_utils::ext_traits::StringExt; - -// use super::PTRunner; - -// #[test] -// fn test_enum_to_string() { -// let string_format = "PAYMENTS_SYNC_WORKFLOW".to_string(); -// let enum_format: PTRunner = string_format.parse_enum("PTRunner").unwrap(); -// assert_eq!(enum_format, PTRunner::PaymentsSyncWorkflow) -// } -// } diff --git a/crates/scheduler/src/db/process_tracker.rs b/crates/scheduler/src/db/process_tracker.rs index 728c146a64e..ac20d4b293f 100644 --- a/crates/scheduler/src/db/process_tracker.rs +++ b/crates/scheduler/src/db/process_tracker.rs @@ -2,11 +2,10 @@ use common_utils::errors::CustomResult; pub use diesel_models as storage; use diesel_models::enums as storage_enums; use error_stack::{IntoReport, ResultExt}; -use serde::Serialize; use storage_impl::{connection, errors, mock_db::MockDb}; use time::PrimitiveDateTime; -use crate::{errors as sch_errors, metrics, scheduler::Store, SchedulerInterface}; +use crate::{metrics, scheduler::Store}; #[async_trait::async_trait] pub trait ProcessTrackerInterface: Send + Sync + 'static { @@ -32,17 +31,30 @@ pub trait ProcessTrackerInterface: Send + Sync + 'static { task_ids: Vec<String>, task_update: storage::ProcessTrackerUpdate, ) -> CustomResult<usize, errors::StorageError>; - async fn update_process_tracker( - &self, - this: storage::ProcessTracker, - process: storage::ProcessTrackerUpdate, - ) -> CustomResult<storage::ProcessTracker, errors::StorageError>; async fn insert_process( &self, new: storage::ProcessTrackerNew, ) -> CustomResult<storage::ProcessTracker, errors::StorageError>; + async fn reset_process( + &self, + this: storage::ProcessTracker, + schedule_time: PrimitiveDateTime, + ) -> CustomResult<(), errors::StorageError>; + + async fn retry_process( + &self, + this: storage::ProcessTracker, + schedule_time: PrimitiveDateTime, + ) -> CustomResult<(), errors::StorageError>; + + async fn finish_process_with_business_status( + &self, + this: storage::ProcessTracker, + business_status: String, + ) -> CustomResult<(), errors::StorageError>; + async fn find_processes_by_time_status( &self, time_lower_limit: PrimitiveDateTime, @@ -120,16 +132,58 @@ impl ProcessTrackerInterface for Store { .into_report() } - async fn update_process_tracker( + async fn reset_process( &self, this: storage::ProcessTracker, - process: storage::ProcessTrackerUpdate, - ) -> CustomResult<storage::ProcessTracker, errors::StorageError> { - let conn = connection::pg_connection_write(self).await?; - this.update(&conn, process) - .await - .map_err(Into::into) - .into_report() + schedule_time: PrimitiveDateTime, + ) -> CustomResult<(), errors::StorageError> { + self.update_process( + this, + storage::ProcessTrackerUpdate::StatusRetryUpdate { + status: storage_enums::ProcessTrackerStatus::New, + retry_count: 0, + schedule_time, + }, + ) + .await?; + Ok(()) + } + + async fn retry_process( + &self, + this: storage::ProcessTracker, + schedule_time: PrimitiveDateTime, + ) -> CustomResult<(), errors::StorageError> { + metrics::TASK_RETRIED.add(&metrics::CONTEXT, 1, &[]); + let retry_count = this.retry_count + 1; + self.update_process( + this, + storage::ProcessTrackerUpdate::StatusRetryUpdate { + status: storage_enums::ProcessTrackerStatus::Pending, + retry_count, + schedule_time, + }, + ) + .await?; + Ok(()) + } + + async fn finish_process_with_business_status( + &self, + this: storage::ProcessTracker, + business_status: String, + ) -> CustomResult<(), errors::StorageError> { + self.update_process( + this, + storage::ProcessTrackerUpdate::StatusUpdate { + status: storage_enums::ProcessTrackerStatus::Finish, + business_status: Some(business_status), + }, + ) + .await + .attach_printable("Failed to update business status of process")?; + metrics::TASK_FINISHED.add(&metrics::CONTEXT, 1, &[]); + Ok(()) } async fn process_tracker_update_process_status_by_ids( @@ -215,143 +269,39 @@ impl ProcessTrackerInterface for MockDb { Err(errors::StorageError::MockDbError)? } - async fn update_process_tracker( + async fn reset_process( &self, _this: storage::ProcessTracker, - _process: storage::ProcessTrackerUpdate, - ) -> CustomResult<storage::ProcessTracker, errors::StorageError> { + _schedule_time: PrimitiveDateTime, + ) -> CustomResult<(), errors::StorageError> { // [#172]: Implement function for `MockDb` Err(errors::StorageError::MockDbError)? } - async fn process_tracker_update_process_status_by_ids( + async fn retry_process( &self, - _task_ids: Vec<String>, - _task_update: storage::ProcessTrackerUpdate, - ) -> CustomResult<usize, errors::StorageError> { + _this: storage::ProcessTracker, + _schedule_time: PrimitiveDateTime, + ) -> CustomResult<(), errors::StorageError> { // [#172]: Implement function for `MockDb` Err(errors::StorageError::MockDbError)? } -} - -#[async_trait::async_trait] -pub trait ProcessTrackerExt { - fn is_valid_business_status(&self, valid_statuses: &[&str]) -> bool; - - fn make_process_tracker_new<'a, T>( - process_tracker_id: String, - task: &'a str, - runner: &'a str, - tracking_data: T, - schedule_time: PrimitiveDateTime, - ) -> Result<storage::ProcessTrackerNew, sch_errors::ProcessTrackerError> - where - T: Serialize; - - async fn reset( - self, - db: &dyn SchedulerInterface, - schedule_time: PrimitiveDateTime, - ) -> Result<(), sch_errors::ProcessTrackerError>; - - async fn retry( - self, - db: &dyn SchedulerInterface, - schedule_time: PrimitiveDateTime, - ) -> Result<(), sch_errors::ProcessTrackerError>; - - async fn finish_with_status( - self, - db: &dyn SchedulerInterface, - status: String, - ) -> Result<(), sch_errors::ProcessTrackerError>; -} - -#[async_trait::async_trait] -impl ProcessTrackerExt for storage::ProcessTracker { - fn is_valid_business_status(&self, valid_statuses: &[&str]) -> bool { - valid_statuses.iter().any(|x| x == &self.business_status) - } - - fn make_process_tracker_new<'a, T>( - process_tracker_id: String, - task: &'a str, - runner: &'a str, - tracking_data: T, - schedule_time: PrimitiveDateTime, - ) -> Result<storage::ProcessTrackerNew, sch_errors::ProcessTrackerError> - where - T: Serialize, - { - let current_time = common_utils::date_time::now(); - Ok(storage::ProcessTrackerNew { - id: process_tracker_id, - name: Some(String::from(task)), - tag: vec![String::from("SYNC"), String::from("PAYMENT")], - runner: Some(String::from(runner)), - retry_count: 0, - schedule_time: Some(schedule_time), - rule: String::new(), - tracking_data: serde_json::to_value(tracking_data) - .map_err(|_| sch_errors::ProcessTrackerError::SerializationFailed)?, - business_status: String::from("Pending"), - status: storage_enums::ProcessTrackerStatus::New, - event: vec![], - created_at: current_time, - updated_at: current_time, - }) - } - async fn reset( - self, - db: &dyn SchedulerInterface, - schedule_time: PrimitiveDateTime, - ) -> Result<(), sch_errors::ProcessTrackerError> { - db.update_process_tracker( - self.clone(), - storage::ProcessTrackerUpdate::StatusRetryUpdate { - status: storage_enums::ProcessTrackerStatus::New, - retry_count: 0, - schedule_time, - }, - ) - .await?; - Ok(()) - } - - async fn retry( - self, - db: &dyn SchedulerInterface, - schedule_time: PrimitiveDateTime, - ) -> Result<(), sch_errors::ProcessTrackerError> { - metrics::TASK_RETRIED.add(&metrics::CONTEXT, 1, &[]); - db.update_process_tracker( - self.clone(), - storage::ProcessTrackerUpdate::StatusRetryUpdate { - status: storage_enums::ProcessTrackerStatus::Pending, - retry_count: self.retry_count + 1, - schedule_time, - }, - ) - .await?; - Ok(()) + async fn finish_process_with_business_status( + &self, + _this: storage::ProcessTracker, + _business_status: String, + ) -> CustomResult<(), errors::StorageError> { + // [#172]: Implement function for `MockDb` + Err(errors::StorageError::MockDbError)? } - async fn finish_with_status( - self, - db: &dyn SchedulerInterface, - status: String, - ) -> Result<(), sch_errors::ProcessTrackerError> { - db.update_process( - self, - storage::ProcessTrackerUpdate::StatusUpdate { - status: storage_enums::ProcessTrackerStatus::Finish, - business_status: Some(status), - }, - ) - .await - .attach_printable("Failed while updating status of the process")?; - metrics::TASK_FINISHED.add(&metrics::CONTEXT, 1, &[]); - Ok(()) + async fn process_tracker_update_process_status_by_ids( + &self, + _task_ids: Vec<String>, + _task_update: storage::ProcessTrackerUpdate, + ) -> CustomResult<usize, errors::StorageError> { + // [#172]: Implement function for `MockDb` + Err(errors::StorageError::MockDbError)? } } diff --git a/crates/scheduler/src/utils.rs b/crates/scheduler/src/utils.rs index f6a340e9d59..174efd637e9 100644 --- a/crates/scheduler/src/utils.rs +++ b/crates/scheduler/src/utils.rs @@ -8,7 +8,7 @@ use diesel_models::enums::{self, ProcessTrackerStatus}; pub use diesel_models::process_tracker as storage; use error_stack::{report, ResultExt}; use redis_interface::{RedisConnectionPool, RedisEntryId}; -use router_env::opentelemetry; +use router_env::{instrument, opentelemetry, tracing}; use uuid::Uuid; use super::{ @@ -178,7 +178,7 @@ pub async fn get_batches( group_name: &str, consumer_name: &str, ) -> CustomResult<Vec<ProcessTrackerBatch>, errors::ProcessTrackerError> { - let response = conn + let response = match conn .stream_read_with_options( stream_name, RedisEntryId::UndeliveredEntryID, @@ -188,10 +188,20 @@ pub async fn get_batches( Some((group_name, consumer_name)), ) .await - .map_err(|error| { - logger::warn!(%error, "Warning: finding batch in stream"); - error.change_context(errors::ProcessTrackerError::BatchNotFound) - })?; + { + Ok(response) => response, + Err(error) => { + if let redis_interface::errors::RedisError::StreamEmptyOrNotAvailable = + error.current_context() + { + logger::debug!("No batches processed as stream is empty"); + return Ok(Vec::new()); + } else { + return Err(error.change_context(errors::ProcessTrackerError::BatchNotFound)); + } + } + }; + metrics::BATCHES_CONSUMED.add(&metrics::CONTEXT, 1, &[]); let (batches, entry_ids): (Vec<Vec<ProcessTrackerBatch>>, Vec<Vec<String>>) = response.into_values().map(|entries| { @@ -217,13 +227,13 @@ pub async fn get_batches( conn.stream_acknowledge_entries(stream_name, group_name, entry_ids.clone()) .await .map_err(|error| { - logger::error!(%error, "Error acknowledging batch in stream"); + logger::error!(?error, "Error acknowledging batch in stream"); error.change_context(errors::ProcessTrackerError::BatchUpdateFailed) })?; conn.stream_delete_entries(stream_name, entry_ids.clone()) .await .map_err(|error| { - logger::error!(%error, "Error deleting batch from stream"); + logger::error!(?error, "Error deleting batch from stream"); error.change_context(errors::ProcessTrackerError::BatchDeleteFailed) })?; @@ -231,7 +241,7 @@ pub async fn get_batches( } pub fn get_process_tracker_id<'a>( - runner: &'a str, + runner: storage::ProcessTrackerRunner, task_name: &'a str, txn_id: &'a str, merchant_id: &'a str, @@ -243,6 +253,7 @@ pub fn get_time_from_delta(delta: Option<i32>) -> Option<time::PrimitiveDateTime delta.map(|t| common_utils::date_time::now().saturating_add(time::Duration::seconds(t.into()))) } +#[instrument(skip_all)] pub async fn consumer_operation_handler<E, T: Send + Sync + 'static>( state: T, settings: sync::Arc<SchedulerSettings>,
2024-02-19T19:59:37Z
## 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 contains changes to address the problems listed in #3711, namely: 1. Updates `ProcessTrackerExt::make_process_tracker_new()` method to accept a `tag` parameter in order to increase reusability. 2. Moves the `PTRunner` enum to the `diesel_models::process_tracker` module and renames it as `ProcessTrackerRunner`. 3. Makes use of the `ProcessTrackerExt::make_process_tracker_new()` method to construct all instances of `ProcessTrackerNew` within the codebase. 4. Move `ProcessTrackerExt::make_process_tracker_new()` as `ProcessTrackerNew::new()` method. 5. Removes a redundant `update_process_tracker()` method from the `ProcessTrackerInterface` trait in favor of the `update_process()` method from the same trait. 6. Moves the `reset()`, `retry()` and `finish_with_status()` methods from `ProcessTrackerExt` trait to `ProcessTrackerInterface` trait. 7. Update the business status insertion/updation logic to reduce cardinality of the business status column in the resulting process tracker table. 8. Adds/updates logs that would be displayed when specific parts of the scheduler execution fails. ## 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). --> Resolves #3711. ## 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)? --> Most of the changes involve moving existing code around, which should not affect the functioning of the scheduler, which I've verified by confirming the correct functioning of the payment sync workflow: the workflow now successfully completes with a business status of `COMPLETED_BY_PT` (only) instead of also including the process tracker ID in the business status. ### Sanity testing of process tracker with payments sync workflow 1. Disable any incoming payment webhooks from the connector with which a payment will be created in the next step. 2. Create a payment with a connector such that the payment reaches the processing state. 3. Check if the process tracker performs a payments sync successfully and updates the status of the payment to either succeeded or failed: 1. Immediately after creating the payment, you should see an entry in the `process_tracker` table with status `new` and business status `Pending`. The task should be scheduled to execute in a few minutes' time from the time of creation of the payment. 2. Once the producer picks up the task, the status should be `processing` and business status remains same. 3. Once the consumer picks up the task, the status should be `process_started` and business status remains same. If the execution of the task completes quickly enough, you might not notice this status transition. 4. Once the consumer has successfully completed the execution of the task, the final status should be `finish` and business status should be `COMPLETED_BY_PT`. 5. If you perform a payments retrieve after the execution of the task has completed, the payment intent's status should now be updated to a succeeded or failed state, as reported by the connector. ### Screenshots from local manual testing - Screenshot of process tracker entry in database after successful payment sync workflow execution: <img width="1200" alt="Screenshot of process tracker entry in database" src="https://github.com/juspay/hyperswitch/assets/22217505/7be2948e-e666-4d02-9003-306512c39d5c"> As for the logs, I've verified that logs are shown when there are consumer workflow execution errors: - Screenshot of error log displayed when the process tracker entry in the database table contains a value that does not correspond to a valid `ProcessTrackerRunner` variant: <img width="800" alt="Screenshot of error indicating invalid workflow runner name" src="https://github.com/juspay/hyperswitch/assets/22217505/2057e83d-873d-4d5c-8d79-b3e349012155"> This can be used to identify if an old version of the `consumer` service is deployed with a relatively newer version of the `router` service with newer process tracker workflows. - Screenshot of error log displayed when the `email` feature is enabled on the `router` service, but disabled on the `consumer` service: <img width="800" alt="Screenshot of error indicating email feature being disabled" src="https://github.com/juspay/hyperswitch/assets/22217505/cca4ab95-9ae6-4eb0-820d-3232f0fc1f3f"> This does not typically occur in our hosted environments, since we run builds/images with most (if not all) features enabled. ## 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 - [ ] I added a [CHANGELOG](/CHANGELOG.md) entry if applicable
fff780218ac356bb9b599896e766dd45266ac34a
Most of the changes involve moving existing code around, which should not affect the functioning of the scheduler, which I've verified by confirming the correct functioning of the payment sync workflow: the workflow now successfully completes with a business status of `COMPLETED_BY_PT` (only) instead of also including the process tracker ID in the business status. ### Sanity testing of process tracker with payments sync workflow 1. Disable any incoming payment webhooks from the connector with which a payment will be created in the next step. 2. Create a payment with a connector such that the payment reaches the processing state. 3. Check if the process tracker performs a payments sync successfully and updates the status of the payment to either succeeded or failed: 1. Immediately after creating the payment, you should see an entry in the `process_tracker` table with status `new` and business status `Pending`. The task should be scheduled to execute in a few minutes' time from the time of creation of the payment. 2. Once the producer picks up the task, the status should be `processing` and business status remains same. 3. Once the consumer picks up the task, the status should be `process_started` and business status remains same. If the execution of the task completes quickly enough, you might not notice this status transition. 4. Once the consumer has successfully completed the execution of the task, the final status should be `finish` and business status should be `COMPLETED_BY_PT`. 5. If you perform a payments retrieve after the execution of the task has completed, the payment intent's status should now be updated to a succeeded or failed state, as reported by the connector. ### Screenshots from local manual testing - Screenshot of process tracker entry in database after successful payment sync workflow execution: <img width="1200" alt="Screenshot of process tracker entry in database" src="https://github.com/juspay/hyperswitch/assets/22217505/7be2948e-e666-4d02-9003-306512c39d5c"> As for the logs, I've verified that logs are shown when there are consumer workflow execution errors: - Screenshot of error log displayed when the process tracker entry in the database table contains a value that does not correspond to a valid `ProcessTrackerRunner` variant: <img width="800" alt="Screenshot of error indicating invalid workflow runner name" src="https://github.com/juspay/hyperswitch/assets/22217505/2057e83d-873d-4d5c-8d79-b3e349012155"> This can be used to identify if an old version of the `consumer` service is deployed with a relatively newer version of the `router` service with newer process tracker workflows. - Screenshot of error log displayed when the `email` feature is enabled on the `router` service, but disabled on the `consumer` service: <img width="800" alt="Screenshot of error indicating email feature being disabled" src="https://github.com/juspay/hyperswitch/assets/22217505/cca4ab95-9ae6-4eb0-820d-3232f0fc1f3f"> This does not typically occur in our hosted environments, since we run builds/images with most (if not all) features enabled.
juspay/hyperswitch
juspay__hyperswitch-3675
Bug: [BUG]: [Noon] Payment not reaching terminal state ### Bug Description If there is a timeout or some other unfortunate instance in the application the payment is put in `pending` state, when we sync the payment with Noon, in some cases it returns 4xx and we do not update the status. But for some status like `order_does_not_exist` in their system we should fail it immediately. ### Expected Behavior for some status like `order_does_not_exist` in their system we should fail it immediately. ### Actual Behavior in some cases it returns 4xx and we do not update the status. ### 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/connector/noon.rs b/crates/router/src/connector/noon.rs index 6e1959b46d0..a055c2eac59 100644 --- a/crates/router/src/connector/noon.rs +++ b/crates/router/src/connector/noon.rs @@ -132,14 +132,22 @@ impl ConnectorCommon for Noon { res.response.parse_struct("NoonErrorResponse"); match response { - Ok(noon_error_response) => Ok(ErrorResponse { - status_code: res.status_code, - code: consts::NO_ERROR_CODE.to_string(), - message: noon_error_response.class_description, - reason: Some(noon_error_response.message), - attempt_status: None, - connector_transaction_id: None, - }), + Ok(noon_error_response) => { + // Adding in case of timeouts, if psync gives 4xx with this code, fail the payment + let attempt_status = if noon_error_response.result_code == 19001 { + Some(enums::AttemptStatus::Failure) + } else { + None + }; + Ok(ErrorResponse { + status_code: res.status_code, + code: noon_error_response.result_code.to_string(), + message: noon_error_response.class_description, + reason: Some(noon_error_response.message), + attempt_status, + connector_transaction_id: None, + }) + } Err(error_message) => { logger::error!(deserialization_error =? error_message); utils::handle_json_response_deserialization_failure(res, "noon".to_owned())
2024-02-16T08:44:56Z
## 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 in Psync if 4xx or 5xx comes the payment_status is not changed for all the error_codes, for specific error_codes like order does not exist should be failed immediately. ### 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). --> #3675 ## 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 sync with noon for payment that was not registered with noon, it should fail rather than stuck in pending state. <img width="1124" alt="Screenshot 2024-02-16 at 2 02 08 PM" src="https://github.com/juspay/hyperswitch/assets/55536657/133a10ae-73bd-4fac-a73e-d00775ecad97"> <img width="1115" alt="Screenshot 2024-02-16 at 2 02 01 PM" src="https://github.com/juspay/hyperswitch/assets/55536657/bb3aff72-759b-43f4-b63c-b5b2bf298203"> ## 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 - [ ] I added a [CHANGELOG](/CHANGELOG.md) entry if applicable
682f4ede8e957021bf0c01849406d1acd6bc17bb
- Create a sync with noon for payment that was not registered with noon, it should fail rather than stuck in pending state. <img width="1124" alt="Screenshot 2024-02-16 at 2 02 08 PM" src="https://github.com/juspay/hyperswitch/assets/55536657/133a10ae-73bd-4fac-a73e-d00775ecad97"> <img width="1115" alt="Screenshot 2024-02-16 at 2 02 01 PM" src="https://github.com/juspay/hyperswitch/assets/55536657/bb3aff72-759b-43f4-b63c-b5b2bf298203">
juspay/hyperswitch
juspay__hyperswitch-3683
Bug: Handle span closures after request completion or after consolidated log... Currently some consolidated logs don't have the values propogated all the way to the top, This seems to be a result of the way we handle the consolidated log & value propogation In this case the consolidated log line is printed before the spans are closed resulting in values not being propogated at the top <img width="1445" alt="image" src="https://github.com/juspay/hyperswitch/assets/21202349/fdbd4858-e432-4347-9a28-c28046566f38">
diff --git a/crates/router/src/middleware.rs b/crates/router/src/middleware.rs index f1a3275ab21..2cab332a677 100644 --- a/crates/router/src/middleware.rs +++ b/crates/router/src/middleware.rs @@ -143,7 +143,7 @@ where Box::pin( async move { let response = response_fut.await; - logger::info!(golden_log_line = true); + router_env::tracing::Span::current().record("golden_log_line", true); response } .instrument( @@ -153,7 +153,8 @@ where merchant_id = Empty, connector_name = Empty, payment_method = Empty, - flow = "UNKNOWN" + flow = "UNKNOWN", + golden_log_line = Empty ) .or_current(), ), diff --git a/crates/router_env/src/logger/config.rs b/crates/router_env/src/logger/config.rs index 664c0d508f5..09d285a8628 100644 --- a/crates/router_env/src/logger/config.rs +++ b/crates/router_env/src/logger/config.rs @@ -107,13 +107,15 @@ pub struct LogTelemetry { /// Telemetry / tracing. #[derive(Default, Debug, Deserialize, Clone, PartialEq, Eq)] -#[serde(rename_all = "lowercase")] +#[serde(rename_all = "snake_case")] pub enum LogFormat { /// Default pretty log format Default, /// JSON based structured logging #[default] Json, + /// JSON based structured logging with pretty print + PrettyJson, } impl Config { diff --git a/crates/router_env/src/logger/formatter.rs b/crates/router_env/src/logger/formatter.rs index 4fd94c22163..472b917e746 100644 --- a/crates/router_env/src/logger/formatter.rs +++ b/crates/router_env/src/logger/formatter.rs @@ -10,7 +10,7 @@ use std::{ use once_cell::sync::Lazy; use serde::ser::{SerializeMap, Serializer}; -use serde_json::Value; +use serde_json::{ser::Formatter, Value}; // use time::format_description::well_known::Rfc3339; use time::format_description::well_known::Iso8601; use tracing::{Event, Metadata, Subscriber}; @@ -121,9 +121,10 @@ impl fmt::Display for RecordType { /// `FormattingLayer` relies on the `tracing_bunyan_formatter::JsonStorageLayer` which is storage of entries. /// #[derive(Debug)] -pub struct FormattingLayer<W> +pub struct FormattingLayer<W, F> where W: for<'a> MakeWriter<'a> + 'static, + F: Formatter + Clone, { dst_writer: W, pid: u32, @@ -135,11 +136,13 @@ where #[cfg(feature = "vergen")] build: String, default_fields: HashMap<String, Value>, + formatter: F, } -impl<W> FormattingLayer<W> +impl<W, F> FormattingLayer<W, F> where W: for<'a> MakeWriter<'a> + 'static, + F: Formatter + Clone, { /// /// Constructor of `FormattingLayer`. @@ -149,11 +152,11 @@ where /// /// ## Example /// ```rust - /// let formatting_layer = router_env::FormattingLayer::new(router_env::service_name!(),std::io::stdout); + /// let formatting_layer = router_env::FormattingLayer::new(router_env::service_name!(),std::io::stdout, CompactFormatter); /// ``` /// - pub fn new(service: &str, dst_writer: W) -> Self { - Self::new_with_implicit_entries(service, dst_writer, HashMap::new()) + pub fn new(service: &str, dst_writer: W, formatter: F) -> Self { + Self::new_with_implicit_entries(service, dst_writer, HashMap::new(), formatter) } /// Construct of `FormattingLayer with implicit default entries. @@ -161,6 +164,7 @@ where service: &str, dst_writer: W, default_fields: HashMap<String, Value>, + formatter: F, ) -> Self { let pid = std::process::id(); let hostname = gethostname::gethostname().to_string_lossy().into_owned(); @@ -182,6 +186,7 @@ where #[cfg(feature = "vergen")] build, default_fields, + formatter, } } @@ -287,7 +292,6 @@ where } /// Serialize entries of span. - #[cfg(feature = "log_active_span_json")] fn span_serialize<S>( &self, span: &SpanRef<'_, S>, @@ -297,7 +301,8 @@ where S: Subscriber + for<'a> LookupSpan<'a>, { let mut buffer = Vec::new(); - let mut serializer = serde_json::Serializer::new(&mut buffer); + let mut serializer = + serde_json::Serializer::with_formatter(&mut buffer, self.formatter.clone()); let mut map_serializer = serializer.serialize_map(None)?; let message = Self::span_message(span, ty); @@ -324,7 +329,8 @@ where S: Subscriber + for<'a> LookupSpan<'a>, { let mut buffer = Vec::new(); - let mut serializer = serde_json::Serializer::new(&mut buffer); + let mut serializer = + serde_json::Serializer::with_formatter(&mut buffer, self.formatter.clone()); let mut map_serializer = serializer.serialize_map(None)?; let mut storage = Storage::default(); @@ -398,10 +404,11 @@ where } #[allow(clippy::expect_used)] -impl<S, W> Layer<S> for FormattingLayer<W> +impl<S, W, F> Layer<S> for FormattingLayer<W, F> where S: Subscriber + for<'a> LookupSpan<'a>, W: for<'a> MakeWriter<'a> + 'static, + F: Formatter + Clone + 'static, { fn on_event(&self, event: &Event<'_>, ctx: Context<'_, S>) { // Event could have no span. @@ -421,6 +428,16 @@ where } } + #[cfg(not(feature = "log_active_span_json"))] + fn on_close(&self, id: tracing::Id, ctx: Context<'_, S>) { + let span = ctx.span(&id).expect("No span"); + if span.parent().is_none() { + if let Ok(serialized) = self.span_serialize(&span, RecordType::ExitSpan) { + let _ = self.flush(serialized); + } + } + } + #[cfg(feature = "log_active_span_json")] fn on_close(&self, id: tracing::Id, ctx: Context<'_, S>) { let span = ctx.span(&id).expect("No span"); diff --git a/crates/router_env/src/logger/setup.rs b/crates/router_env/src/logger/setup.rs index 992de3e747e..af77991e804 100644 --- a/crates/router_env/src/logger/setup.rs +++ b/crates/router_env/src/logger/setup.rs @@ -16,6 +16,7 @@ use opentelemetry::{ KeyValue, }; use opentelemetry_otlp::{TonicExporterBuilder, WithExportConfig}; +use serde_json::ser::{CompactFormatter, PrettyFormatter}; use tracing_appender::non_blocking::WorkerGuard; use tracing_subscriber::{fmt, prelude::*, util::SubscriberInitExt, EnvFilter, Layer}; @@ -69,7 +70,10 @@ pub fn setup( ); println!("Using file logging filter: {file_filter}"); - Some(FormattingLayer::new(service_name, file_writer).with_filter(file_filter)) + Some( + FormattingLayer::new(service_name, file_writer, CompactFormatter) + .with_filter(file_filter), + ) } else { None }; @@ -104,7 +108,15 @@ pub fn setup( config::LogFormat::Json => { error_stack::Report::set_color_mode(error_stack::fmt::ColorMode::None); let logging_layer = - FormattingLayer::new(service_name, console_writer).with_filter(console_filter); + FormattingLayer::new(service_name, console_writer, CompactFormatter) + .with_filter(console_filter); + subscriber.with(logging_layer).init(); + } + config::LogFormat::PrettyJson => { + error_stack::Report::set_color_mode(error_stack::fmt::ColorMode::None); + let logging_layer = + FormattingLayer::new(service_name, console_writer, PrettyFormatter::new()) + .with_filter(console_filter); subscriber.with(logging_layer).init(); } }
2024-02-16T11:10:32Z
## 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 --> - Add `pretty_json` log format for console logs - Add span end log for root span close as the default behaviour - move consolidated log from event to span close ### 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)? --> - running it locally check for the last log line after any request ``` curl --location 'http://localhost:8080/payments' \ --header 'Content-Type: application/json' \ --header 'Accept: application/json' \ --header 'api-key: dev_st84Q3ucbQSWWnUbPwQXAyefTD2w5gJsRN8GEQ0shegg1ZomnwsseEdJU3KjVoAp' \ --data-raw '{ "amount": 6540, "currency": "USD", "confirm": true, "capture_method": "automatic", "capture_on": "2022-09-10T10:11:12Z", "amount_to_capture": 6540, "customer_id": "StripeCustomer", "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://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", "metadata": { "udf1": "value1", "new_customer": "true", "login_date": "2019-09-10T10:11:12Z" } }' ``` - It should contain every field in consolidated log <img width="463" alt="image" src="https://github.com/juspay/hyperswitch/assets/21202349/dc279a45-1b16-40d4-bb88-5433b458f0f3"> [grafana](https://grafana.staging.eu.juspay.net/explore?orgId=1&left=%7B%22datasource%22:%22x5WTfCG4k%22,%22queries%22:%5B%7B%22refId%22:%22A%22,%22expr%22:%22%7Bapp%3D%5C%22bach%5C%22,%20golden_log_line%3D%5C%22true%5C%22%7D%20%7C%3D%20%60%60%22,%22queryType%22:%22range%22,%22datasource%22:%7B%22type%22:%22loki%22,%22uid%22:%22x5WTfCG4k%22%7D,%22editorMode%22:%22builder%22%7D%5D,%22range%22:%7B%22from%22:%22now-1h%22,%22to%22:%22now%22%7D%7D) ```json { "message": "[ROOT_SPAN - END]", "hostname": "sampraslopes-SERIAL.local", "pid": 3422, "env": "development", "level": "INFO", "target": "router::middleware", "service": "router", "line": 150, "file": "crates/router/src/middleware.rs", "fn": "ROOT_SPAN", "full_name": "router::middleware::ROOT_SPAN", "time": "2024-02-16T10:31:12.692105000Z", "flow": "PaymentsConfirm", "request_id": "018db178-5a8f-7a9d-ac46-218510ab655a", "merchant_id": "merchant_1707203569", "extra": { "connector_name": "stripe", "http.scheme": "http", "http.user_agent": "PostmanRuntime/7.33.0", "http.host": "localhost:8080", "http.target": "/payments/pay_tIvDNoPTya0pP7SiTJAU/confirm", "otel.name": "HTTP POST /payments/{payment_id}/confirm", "trace_id": "00000000000000000000000000000000", "payment_id": "pay_tIvDNoPTya0pP7SiTJAU", "payment_method": "card", "elapsed_milliseconds": 1443, "http.flavor": "1.1", "golden_log_line": true, "http.route": "/payments/{payment_id}/confirm", "http.method": "POST", "otel.kind": "server", "http.client_ip": "::1" } } ``` ## 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 - [ ] I added a [CHANGELOG](/CHANGELOG.md) entry if applicable
fb254b8924808e6a2b2a9a31dbed78749836e8d3
- running it locally check for the last log line after any request ``` curl --location 'http://localhost:8080/payments' \ --header 'Content-Type: application/json' \ --header 'Accept: application/json' \ --header 'api-key: dev_st84Q3ucbQSWWnUbPwQXAyefTD2w5gJsRN8GEQ0shegg1ZomnwsseEdJU3KjVoAp' \ --data-raw '{ "amount": 6540, "currency": "USD", "confirm": true, "capture_method": "automatic", "capture_on": "2022-09-10T10:11:12Z", "amount_to_capture": 6540, "customer_id": "StripeCustomer", "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://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", "metadata": { "udf1": "value1", "new_customer": "true", "login_date": "2019-09-10T10:11:12Z" } }' ``` - It should contain every field in consolidated log <img width="463" alt="image" src="https://github.com/juspay/hyperswitch/assets/21202349/dc279a45-1b16-40d4-bb88-5433b458f0f3"> [grafana](https://grafana.staging.eu.juspay.net/explore?orgId=1&left=%7B%22datasource%22:%22x5WTfCG4k%22,%22queries%22:%5B%7B%22refId%22:%22A%22,%22expr%22:%22%7Bapp%3D%5C%22bach%5C%22,%20golden_log_line%3D%5C%22true%5C%22%7D%20%7C%3D%20%60%60%22,%22queryType%22:%22range%22,%22datasource%22:%7B%22type%22:%22loki%22,%22uid%22:%22x5WTfCG4k%22%7D,%22editorMode%22:%22builder%22%7D%5D,%22range%22:%7B%22from%22:%22now-1h%22,%22to%22:%22now%22%7D%7D) ```json { "message": "[ROOT_SPAN - END]", "hostname": "sampraslopes-SERIAL.local", "pid": 3422, "env": "development", "level": "INFO", "target": "router::middleware", "service": "router", "line": 150, "file": "crates/router/src/middleware.rs", "fn": "ROOT_SPAN", "full_name": "router::middleware::ROOT_SPAN", "time": "2024-02-16T10:31:12.692105000Z", "flow": "PaymentsConfirm", "request_id": "018db178-5a8f-7a9d-ac46-218510ab655a", "merchant_id": "merchant_1707203569", "extra": { "connector_name": "stripe", "http.scheme": "http", "http.user_agent": "PostmanRuntime/7.33.0", "http.host": "localhost:8080", "http.target": "/payments/pay_tIvDNoPTya0pP7SiTJAU/confirm", "otel.name": "HTTP POST /payments/{payment_id}/confirm", "trace_id": "00000000000000000000000000000000", "payment_id": "pay_tIvDNoPTya0pP7SiTJAU", "payment_method": "card", "elapsed_milliseconds": 1443, "http.flavor": "1.1", "golden_log_line": true, "http.route": "/payments/{payment_id}/confirm", "http.method": "POST", "otel.kind": "server", "http.client_ip": "::1" } } ```
juspay/hyperswitch
juspay__hyperswitch-3667
Bug: Add migration for IsChangePasswordRequired enum Add migration for force password reset enum, `IsChangePasswordRequired`
diff --git a/migrations/2024-02-15-153757_add_dashboard_metadata_enum_is_change_password_required/down.sql b/migrations/2024-02-15-153757_add_dashboard_metadata_enum_is_change_password_required/down.sql new file mode 100644 index 00000000000..c7c9cbeb401 --- /dev/null +++ b/migrations/2024-02-15-153757_add_dashboard_metadata_enum_is_change_password_required/down.sql @@ -0,0 +1,2 @@ +-- This file should undo anything in `up.sql` +SELECT 1; \ No newline at end of file diff --git a/migrations/2024-02-15-153757_add_dashboard_metadata_enum_is_change_password_required/up.sql b/migrations/2024-02-15-153757_add_dashboard_metadata_enum_is_change_password_required/up.sql new file mode 100644 index 00000000000..6c9269ef2e1 --- /dev/null +++ b/migrations/2024-02-15-153757_add_dashboard_metadata_enum_is_change_password_required/up.sql @@ -0,0 +1,2 @@ +-- Your SQL goes here +ALTER TYPE "DashboardMetadata" ADD VALUE IF NOT EXISTS 'is_change_password_required'; \ No newline at end of file
2024-02-15T15:45:34Z
## Type of Change <!-- Put an `x` in the boxes that apply --> - [x] Bugfix - [ ] New feature - [ ] Enhancement - [ ] Refactoring - [ ] Dependency updates - [ ] Documentation - [ ] CI/CD ## Description Add migration for force password enum(`IsChangePasswordRequired`). ### 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 For force password enum `isChangePasswordRequired` migration is not present. ## How did you test it? Tested locally, for the invite flow, after migration its working fine and value of enum is getting updated correctly. ``` curl --location 'http://localhost:8080/user/user/invite' \ --header 'Authorization: Bearer JWT' \ --header 'Content-Type: application/json' \ --data-raw '{ "email": "cdc@gmail.com", "name": "test3", "role_id": "merchant_admin" } ' ``` ## 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 - [ ] I added a [CHANGELOG](/CHANGELOG.md) entry if applicable
9f385008106e1cfca8ded40009b364f97ecf69f2
Tested locally, for the invite flow, after migration its working fine and value of enum is getting updated correctly. ``` curl --location 'http://localhost:8080/user/user/invite' \ --header 'Authorization: Bearer JWT' \ --header 'Content-Type: application/json' \ --data-raw '{ "email": "cdc@gmail.com", "name": "test3", "role_id": "merchant_admin" } ' ```
juspay/hyperswitch
juspay__hyperswitch-3664
Bug: Add Toml file changes for dashboard origin
diff --git a/config/development.toml b/config/development.toml index ad5944c34c3..3a3540da5b6 100644 --- a/config/development.toml +++ b/config/development.toml @@ -235,7 +235,7 @@ workers = 1 [cors] max_age = 30 -origins = "http://localhost:8080" +origins = "http://localhost:8080,http://localhost:9000" allowed_methods = "GET,POST,PUT,DELETE" wildcard_origin = false diff --git a/config/docker_compose.toml b/config/docker_compose.toml index 4f1f34d1bed..9728497aaf6 100644 --- a/config/docker_compose.toml +++ b/config/docker_compose.toml @@ -83,7 +83,7 @@ max_feed_count = 200 [cors] max_age = 30 -origins = "http://localhost:8080" +origins = "http://localhost:8080,http://localhost:9000" allowed_methods = "GET,POST,PUT,DELETE" wildcard_origin = false
2024-02-15T13:08:31Z
## Type of Change <!-- Put an `x` in the boxes that apply --> - [x] Bugfix - [ ] New feature - [ ] Enhancement - [ ] Refactoring - [ ] Dependency updates - [ ] Documentation - [ ] CI/CD ## Description For localhost testing added Dashboard Origin in the Toml files. ### 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? Nothing to test. ## 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 - [ ] I added a [CHANGELOG](/CHANGELOG.md) entry if applicable
0666d814af93045ff23c85d8fd796da08cd5749b
Nothing to test.
juspay/hyperswitch
juspay__hyperswitch-3658
Bug: feat: Email blacklist
diff --git a/crates/router/src/core/user.rs b/crates/router/src/core/user.rs index 002452a8a35..54fbecc64f3 100644 --- a/crates/router/src/core/user.rs +++ b/crates/router/src/core/user.rs @@ -311,6 +311,10 @@ pub async fn change_password( .await .change_context(UserErrors::InternalServerError)?; + let _ = auth::blacklist::insert_user_in_blacklist(&state, user.get_user_id()) + .await + .map_err(|e| logger::error!(?e)); + #[cfg(not(feature = "email"))] { state @@ -372,10 +376,12 @@ pub async fn reset_password( state: AppState, request: user_api::ResetPasswordRequest, ) -> UserResponse<()> { - let token = - auth::decode_jwt::<email_types::EmailToken>(request.token.expose().as_str(), &state) - .await - .change_context(UserErrors::LinkInvalid)?; + 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)?; @@ -384,7 +390,7 @@ pub async fn reset_password( let user = state .store .update_user_by_email( - token.get_email(), + email_token.get_email(), storage_user::UserUpdate::AccountUpdate { name: None, password: Some(hash_password), @@ -395,7 +401,7 @@ pub async fn reset_password( .await .change_context(UserErrors::InternalServerError)?; - if let Some(inviter_merchant_id) = token.get_merchant_id() { + if let Some(inviter_merchant_id) = email_token.get_merchant_id() { let update_status_result = state .store .update_user_role_by_user_id_merchant_id( @@ -403,13 +409,20 @@ pub async fn reset_password( inviter_merchant_id, UserRoleUpdate::UpdateStatus { status: UserStatus::Active, - modified_by: user.user_id, + modified_by: user.user_id.clone(), }, ) .await; logger::info!(?update_status_result); } + let _ = auth::blacklist::insert_email_token_in_blacklist(&state, &token) + .await + .map_err(|e| logger::error!(?e)); + let _ = auth::blacklist::insert_user_in_blacklist(&state, &user.user_id) + .await + .map_err(|e| logger::error!(?e)); + Ok(ApplicationResponse::StatusOk) } @@ -454,7 +467,13 @@ pub async fn invite_user( merchant_id: user_from_token.merchant_id, role_id: request.role_id, org_id: user_from_token.org_id, - status: UserStatus::Active, + 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, created_at: now, @@ -1050,12 +1069,14 @@ pub async fn verify_email_without_invite_checks( state: AppState, req: user_api::VerifyEmailRequest, ) -> UserResponse<user_api::DashboardEntryResponse> { - let token = auth::decode_jwt::<email_types::EmailToken>(&req.token.clone().expose(), &state) + 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 .store - .find_user_by_email(token.get_email()) + .find_user_by_email(email_token.get_email()) .await .change_context(UserErrors::InternalServerError)?; let user = state @@ -1065,6 +1086,9 @@ pub async fn verify_email_without_invite_checks( .change_context(UserErrors::InternalServerError)?; let user_from_db: domain::UserFromStorage = user.into(); let user_role = user_from_db.get_role_from_db(state.clone()).await?; + let _ = auth::blacklist::insert_email_token_in_blacklist(&state, &token) + .await + .map_err(|e| logger::error!(?e)); let token = utils::user::generate_jwt_auth_token(&state, &user_from_db, &user_role).await?; Ok(ApplicationResponse::Json( @@ -1077,13 +1101,16 @@ pub async fn verify_email( state: AppState, req: user_api::VerifyEmailRequest, ) -> UserResponse<user_api::SignInResponse> { - let token = auth::decode_jwt::<email_types::EmailToken>(&req.token.clone().expose(), &state) + 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 .store - .find_user_by_email(token.get_email()) + .find_user_by_email(email_token.get_email()) .await .change_context(UserErrors::InternalServerError)?; @@ -1115,6 +1142,10 @@ pub async fn verify_email( .await? }; + let _ = auth::blacklist::insert_email_token_in_blacklist(&state, &token) + .await + .map_err(|e| logger::error!(?e)); + Ok(ApplicationResponse::Json( signin_strategy.get_signin_response(&state).await?, )) diff --git a/crates/router/src/services/authentication/blacklist.rs b/crates/router/src/services/authentication/blacklist.rs index 6fab28433b4..325ef29bad3 100644 --- a/crates/router/src/services/authentication/blacklist.rs +++ b/crates/router/src/services/authentication/blacklist.rs @@ -5,6 +5,8 @@ use common_utils::date_time; use error_stack::{IntoReport, ResultExt}; use redis_interface::RedisConnectionPool; +#[cfg(feature = "email")] +use crate::consts::{EMAIL_TOKEN_BLACKLIST_PREFIX, EMAIL_TOKEN_TIME_IN_SECS}; use crate::{ consts::{JWT_TOKEN_TIME_IN_SECS, USER_BLACKLIST_PREFIX}, core::errors::{ApiErrorResponse, RouterResult}, @@ -47,6 +49,33 @@ pub async fn check_user_in_blacklist<A: AppStateInfo>( .map(|timestamp| timestamp.map_or(false, |timestamp| timestamp > token_issued_at)) } +#[cfg(feature = "email")] +pub async fn insert_email_token_in_blacklist(state: &AppState, token: &str) -> UserResult<()> { + let redis_conn = get_redis_connection(state).change_context(UserErrors::InternalServerError)?; + let blacklist_key = format!("{}{token}", EMAIL_TOKEN_BLACKLIST_PREFIX); + let expiry = + expiry_to_i64(EMAIL_TOKEN_TIME_IN_SECS).change_context(UserErrors::InternalServerError)?; + redis_conn + .set_key_with_expiry(blacklist_key.as_str(), true, expiry) + .await + .change_context(UserErrors::InternalServerError) +} + +#[cfg(feature = "email")] +pub async fn check_email_token_in_blacklist(state: &AppState, token: &str) -> UserResult<()> { + let redis_conn = get_redis_connection(state).change_context(UserErrors::InternalServerError)?; + let blacklist_key = format!("{}{token}", EMAIL_TOKEN_BLACKLIST_PREFIX); + let key_exists = redis_conn + .exists::<()>(blacklist_key.as_str()) + .await + .change_context(UserErrors::InternalServerError)?; + + if key_exists { + return Err(UserErrors::LinkInvalid.into()); + } + Ok(()) +} + fn get_redis_connection<A: AppStateInfo>(state: &A) -> RouterResult<Arc<RedisConnectionPool>> { state .store()
2024-02-15T12:21:20Z
## Type of Change <!-- Put an `x` in the boxes that apply --> - [ ] Bugfix - [X] New feature - [ ] Enhancement - [ ] Refactoring - [ ] Dependency updates - [ ] Documentation - [ ] CI/CD ## Description - Adding blacklisting for email tokens, this will prevent use of same email token to be used twice. - Change Password & Reset Password logs out user from all open dashboard sessions. <!-- 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 Prevention of use of same email link to be used twice. Forcing Users to re-enter password if password is changed. <!-- 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? With Dashboard Frontend. Following links should not work twice: - Magic Link To generate magic link email use dashboard frontend or below curl. ```sh curl --location --request POST '<URL>/user/connect_account' \ --header 'Content-Type: application/json' \ --data-raw '{ "email": "" }' ``` - Reset Password To generate reset password email use dashboard frontend or below curl. ```sh curl --location --request POST '<URL>/user/forgot_password' \ --header 'Content-Type: application/json' \ --data-raw '{ "email": "" }' ``` All sessions should be logged out after change password or reset password. Expected error response for the use of email token twice ```json { "error": { "type": "invalid_request", "message": "Invalid or expired link", "code": "UR_04" } } ``` <!-- 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 - [ ] I added a [CHANGELOG](/CHANGELOG.md) entry if applicable
0666d814af93045ff23c85d8fd796da08cd5749b
With Dashboard Frontend. Following links should not work twice: - Magic Link To generate magic link email use dashboard frontend or below curl. ```sh curl --location --request POST '<URL>/user/connect_account' \ --header 'Content-Type: application/json' \ --data-raw '{ "email": "" }' ``` - Reset Password To generate reset password email use dashboard frontend or below curl. ```sh curl --location --request POST '<URL>/user/forgot_password' \ --header 'Content-Type: application/json' \ --data-raw '{ "email": "" }' ``` All sessions should be logged out after change password or reset password. Expected error response for the use of email token twice ```json { "error": { "type": "invalid_request", "message": "Invalid or expired link", "code": "UR_04" } } ```
juspay/hyperswitch
juspay__hyperswitch-3654
Bug: [FIX] cors throwing unallowed headers
diff --git a/crates/router/src/cors.rs b/crates/router/src/cors.rs index 9baa4484ee4..21293301b95 100644 --- a/crates/router/src/cors.rs +++ b/crates/router/src/cors.rs @@ -7,6 +7,7 @@ pub fn cors(config: settings::CorsSettings) -> actix_cors::Cors { let mut cors = actix_cors::Cors::default() .allowed_methods(allowed_methods) + .allow_any_header() .max_age(config.max_age); if config.wildcard_origin { @@ -15,6 +16,8 @@ pub fn cors(config: settings::CorsSettings) -> actix_cors::Cors { for origin in &config.origins { cors = cors.allowed_origin(origin); } + // Only allow this in case if it's not wildcard origins. ref: https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Access-Control-Allow-Credentials + cors = cors.supports_credentials(); } cors
2024-02-15T07:56:03Z
## Type of Change <!-- Put an `x` in the boxes that apply --> - [x] Bugfix ## Description <!-- Describe your changes in detail --> Allow all headers on CORS ## 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 fixes CORS error on headers not being allowed ## 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)? --> - Do a preflight request to `/user/role` ```bash curl --location --request OPTIONS 'http://localhost:8080/user/role' \ --header 'authority: sandbox.hyperswitch.io' \ --header 'accept: */*' \ --header 'accept-language: en-GB,en-US;q=0.9,en;q=0.8' \ --header 'access-control-request-headers: api-key,authorization,content-type' \ --header 'access-control-request-method: GET' \ --header 'cache-control: no-cache' \ --header 'origin: https://app.hyperswitch.io' \ --header 'pragma: no-cache' \ --header 'referer: https://app.hyperswitch.io/' \ --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/120.0.0.0 Safari/537.36' ``` Should send a 200 OK response ## 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
2d4f6b3fa004a3f03beaa604e2dbfe95fcbe22a6
- Do a preflight request to `/user/role` ```bash curl --location --request OPTIONS 'http://localhost:8080/user/role' \ --header 'authority: sandbox.hyperswitch.io' \ --header 'accept: */*' \ --header 'accept-language: en-GB,en-US;q=0.9,en;q=0.8' \ --header 'access-control-request-headers: api-key,authorization,content-type' \ --header 'access-control-request-method: GET' \ --header 'cache-control: no-cache' \ --header 'origin: https://app.hyperswitch.io' \ --header 'pragma: no-cache' \ --header 'referer: https://app.hyperswitch.io/' \ --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/120.0.0.0 Safari/537.36' ``` Should send a 200 OK response
juspay/hyperswitch
juspay__hyperswitch-3660
Bug: [REFACTOR]: include api key expiry workflow into process tracker Currently, `ApiKeyExpiryWorkflow` is not part of the workflows being run in scheduler. Refactor to include it, as well as update the email sending section to the latest email refactor logic
diff --git a/crates/diesel_models/src/api_keys.rs b/crates/diesel_models/src/api_keys.rs index 6608d4ed2fd..1875fc4dc51 100644 --- a/crates/diesel_models/src/api_keys.rs +++ b/crates/diesel_models/src/api_keys.rs @@ -138,7 +138,7 @@ mod diesel_impl { // Tracking data by process_tracker #[derive(Default, Debug, Deserialize, Serialize, Clone)] -pub struct ApiKeyExpiryWorkflow { +pub struct ApiKeyExpiryTrackingData { pub key_id: String, pub merchant_id: String, pub api_key_expiry: Option<PrimitiveDateTime>, diff --git a/crates/router/Cargo.toml b/crates/router/Cargo.toml index 2f3dfa82831..88e9c88b4fc 100644 --- a/crates/router/Cargo.toml +++ b/crates/router/Cargo.toml @@ -13,7 +13,7 @@ default = ["kv_store", "stripe", "oltp", "olap", "backwards_compatibility", "acc aws_s3 = ["external_services/aws_s3"] aws_kms = ["external_services/aws_kms"] hashicorp-vault = ["external_services/hashicorp-vault"] -email = ["external_services/email", "olap"] +email = ["external_services/email", "scheduler/email", "olap"] frm = [] stripe = ["dep:serde_qs"] release = ["aws_kms", "stripe", "aws_s3", "email", "backwards_compatibility", "business_profile_routing", "accounts_cache", "kv_store", "connector_choice_mca_id", "profile_specific_fallback_routing", "vergen", "recon"] diff --git a/crates/router/src/bin/scheduler.rs b/crates/router/src/bin/scheduler.rs index 59a108ef5e6..caa69ea1394 100644 --- a/crates/router/src/bin/scheduler.rs +++ b/crates/router/src/bin/scheduler.rs @@ -216,6 +216,8 @@ pub enum PTRunner { PaymentsSyncWorkflow, RefundWorkflowRouter, DeleteTokenizeDataWorkflow, + #[cfg(feature = "email")] + ApiKeyExpiryWorkflow, } #[derive(Debug, Copy, Clone)] @@ -240,6 +242,10 @@ impl ProcessTrackerWorkflows<routes::AppState> for WorkflowRunner { Some(PTRunner::DeleteTokenizeDataWorkflow) => { Box::new(workflows::tokenized_data::DeleteTokenizeDataWorkflow) } + #[cfg(feature = "email")] + Some(PTRunner::ApiKeyExpiryWorkflow) => { + Box::new(workflows::api_key_expiry::ApiKeyExpiryWorkflow) + } _ => Err(ProcessTrackerError::UnexpectedFlow)?, }; let app_state = &state.clone(); diff --git a/crates/router/src/core/api_keys.rs b/crates/router/src/core/api_keys.rs index b694d1291a8..39212ab3814 100644 --- a/crates/router/src/core/api_keys.rs +++ b/crates/router/src/core/api_keys.rs @@ -253,7 +253,7 @@ pub async fn add_api_key_expiry_task( } } - let api_key_expiry_tracker = &storage::ApiKeyExpiryWorkflow { + let api_key_expiry_tracker = &storage::ApiKeyExpiryTrackingData { key_id: api_key.key_id.clone(), merchant_id: api_key.merchant_id.clone(), // We need API key expiry too, because we need to decide on the schedule_time in @@ -427,7 +427,7 @@ pub async fn update_api_key_expiry_task( let task_ids = vec![task_id.clone()]; - let updated_tracking_data = &storage::ApiKeyExpiryWorkflow { + let updated_tracking_data = &storage::ApiKeyExpiryTrackingData { key_id: api_key.key_id.clone(), merchant_id: api_key.merchant_id.clone(), api_key_expiry: api_key.expires_at, 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 new file mode 100644 index 00000000000..1865ae38141 --- /dev/null +++ b/crates/router/src/services/email/assets/api_key_expiry_reminder.html @@ -0,0 +1,203 @@ +<meta content="text/html; charset=UTF-8" http-equiv="Content-Type" /> +<title>API Key Expiry Notice</title> +<body style="background-color: #ececec"> + <style> + .apple-footer a {{ + text-decoration: none !important; + color: #999 !important; + border: none !important; + }} + .apple-email a {{ + text-decoration: none !important; + color: #448bff !important; + border: none !important; + }} + </style> + <div + id="wrapper" + style=" + background-color: none; + margin: 0 auto; + text-align: center; + width: 60%; + -premailer-height: 200; + " + > + <table + align="center" + class="main-table" + style=" + -premailer-cellpadding: 0; + -premailer-cellspacing: 0; + background-color: #fff; + border: 0; + border-top: 5px solid #0165ef; + margin: 0 auto; + mso-table-lspace: 0; + mso-table-rspace: 0; + padding: 0 40; + text-align: center; + width: 100%; + " + bgcolor="#ffffff" + cellpadding="0" + cellspacing="0" + > + <tr> + <td + class="spacer-lg" + style=" + -premailer-height: 75; + -premailer-width: 100%; + line-height: 30px; + margin: 0 auto; + padding: 0; + " + height="75" + width="100%" + ></td> + </tr> + <tr> + <td + class="spacer-lg" + style=" + -premailer-height: 75; + -premailer-width: 100%; + line-height: 30px; + margin: 0 auto; + padding: 0; + " + height="25" + width="100%" + ></td> + </tr> + <tr> + <td + class="spacer-lg" + style=" + -premailer-height: 75; + -premailer-width: 100%; + line-height: 30px; + margin: 0 auto; + padding: 0; + " + height="50" + width="100%" + ></td> + </tr> + <tr> + <td + class="headline" + style=" + color: #444; + font-family: Roboto, Helvetica, Arial, san-serif; + font-size: 30px; + font-weight: 100; + line-height: 36px; + margin: 0 auto; + padding: 0; + text-align: center; + " + align="center" + > + <p style="font-size: 18px">Dear Merchant,</p> + <span style="font-size: 18px"> + It has come to our attention that your API key will expire in {expires_in} days. To ensure uninterrupted + access to our platform and continued smooth operation of your services, we kindly request that you take the + necessary actions as soon as possible. + </span> + </td> + </tr> + <tr> + <td + class="spacer-sm" + style=" + -premailer-height: 20; + -premailer-width: 80%; + line-height: 10px; + margin: 0 auto; + padding: 0; + " + width="100%" + ></td> + </tr> + + <tr> + <td + class="spacer-sm" + style=" + -premailer-height: 20; + -premailer-width: 100%; + line-height: 10px; + margin: 0 auto; + padding: 0; + " + height="20" + width="100%" + ></td> + </tr> + + <tr> + <td + class="spacer-lg" + style=" + -premailer-height: 75; + -premailer-width: 100%; + line-height: 30px; + margin: 0 auto; + padding: 0; + " + height="75" + width="100%" + ></td> + </tr> + <tr> + <td + class="headline" + style=" + color: #444; + font-family: Roboto, Helvetica, Arial, san-serif; + font-size: 18px; + font-weight: 100; + line-height: 36px; + margin: 0 auto; + padding: 0; + text-align: center; + " + align="center" + > + Thanks,<br /> + Team Hyperswitch + </td> + </tr> + <tr> + <td + class="spacer-lg" + style=" + -premailer-height: 75; + -premailer-width: 100%; + line-height: 30px; + margin: 0 auto; + padding: 0; + " + height="75" + width="100%" + ></td> + </tr> + <tr> + <td + class="spacer-lg" + style=" + -premailer-height: 75; + -premailer-width: 100%; + line-height: 30px; + margin: 0 auto; + padding: 0; + " + height="75" + width="100%" + ></td> + </tr> + </table> + </div> +</body> diff --git a/crates/router/src/services/email/types.rs b/crates/router/src/services/email/types.rs index 6ad1a0eb99a..389979d5723 100644 --- a/crates/router/src/services/email/types.rs +++ b/crates/router/src/services/email/types.rs @@ -44,6 +44,9 @@ pub enum EmailBody { user_name: String, user_email: String, }, + ApiKeyExpiryReminder { + expires_in: u8, + }, } pub mod html { @@ -113,6 +116,10 @@ Email : {user_email} (note: This is an auto generated email. Use merchant email for any further communications)", ), + EmailBody::ApiKeyExpiryReminder { expires_in } => format!( + include_str!("assets/api_key_expiry_reminder.html"), + expires_in = expires_in, + ), } } } @@ -381,3 +388,26 @@ impl EmailData for ProFeatureRequest { }) } } + +pub struct ApiKeyExpiryReminder { + pub recipient_email: domain::UserEmail, + pub subject: &'static str, + pub expires_in: u8, +} + +#[async_trait::async_trait] +impl EmailData for ApiKeyExpiryReminder { + async fn get_email_data(&self) -> CustomResult<EmailContents, EmailError> { + let recipient = self.recipient_email.clone().into_inner(); + + let body = html::get_html_body(EmailBody::ApiKeyExpiryReminder { + expires_in: self.expires_in, + }); + + Ok(EmailContents { + subject: self.subject.to_string(), + body: external_services::email::IntermediateString::new(body), + recipient, + }) + } +} diff --git a/crates/router/src/types/storage/api_keys.rs b/crates/router/src/types/storage/api_keys.rs index 74c503d3c76..b1051c3d19c 100644 --- a/crates/router/src/types/storage/api_keys.rs +++ b/crates/router/src/types/storage/api_keys.rs @@ -1,3 +1,3 @@ #[cfg(feature = "email")] -pub use diesel_models::api_keys::ApiKeyExpiryWorkflow; +pub use diesel_models::api_keys::ApiKeyExpiryTrackingData; pub use diesel_models::api_keys::{ApiKey, ApiKeyNew, ApiKeyUpdate, HashedApiKey}; diff --git a/crates/router/src/workflows.rs b/crates/router/src/workflows.rs index b036193bb27..deb5bf785fa 100644 --- a/crates/router/src/workflows.rs +++ b/crates/router/src/workflows.rs @@ -1,3 +1,5 @@ +#[cfg(feature = "email")] +pub mod api_key_expiry; pub mod payment_sync; pub mod refund_router; pub mod tokenized_data; diff --git a/crates/router/src/workflows/api_key_expiry.rs b/crates/router/src/workflows/api_key_expiry.rs index eb3c1d9c1ce..b9830c4ebc5 100644 --- a/crates/router/src/workflows/api_key_expiry.rs +++ b/crates/router/src/workflows/api_key_expiry.rs @@ -1,30 +1,35 @@ -use common_utils::ext_traits::ValueExt; -use diesel_models::enums::{self as storage_enums}; +use common_utils::{errors::ValidationError, ext_traits::ValueExt}; +use diesel_models::{enums as storage_enums, ApiKeyExpiryTrackingData}; +use router_env::logger; +use scheduler::{workflows::ProcessTrackerWorkflow, SchedulerAppState}; -use super::{ApiKeyExpiryWorkflow, ProcessTrackerWorkflow}; use crate::{ errors, logger::error, - routes::AppState, + routes::{metrics, AppState}, + services::email::types::ApiKeyExpiryReminder, types::{ api, + domain::UserEmail, storage::{self, ProcessTrackerExt}, }, utils::OptionExt, }; +pub struct ApiKeyExpiryWorkflow; + #[async_trait::async_trait] -impl ProcessTrackerWorkflow for ApiKeyExpiryWorkflow { +impl ProcessTrackerWorkflow<AppState> for ApiKeyExpiryWorkflow { async fn execute_workflow<'a>( &'a self, state: &'a AppState, process: storage::ProcessTracker, ) -> Result<(), errors::ProcessTrackerError> { let db = &*state.store; - let tracking_data: storage::ApiKeyExpiryWorkflow = process + let tracking_data: ApiKeyExpiryTrackingData = process .tracking_data .clone() - .parse_value("ApiKeyExpiryWorkflow")?; + .parse_value("ApiKeyExpiryTrackingData")?; let key_store = state .store @@ -41,7 +46,13 @@ impl ProcessTrackerWorkflow for ApiKeyExpiryWorkflow { let email_id = merchant_account .merchant_details .parse_value::<api::MerchantDetails>("MerchantDetails")? - .primary_email; + .primary_email + .ok_or(errors::ProcessTrackerError::EValidationError( + ValidationError::MissingRequiredField { + field_name: "email".to_string(), + } + .into(), + ))?; let task_id = process.id.clone(); @@ -53,28 +64,26 @@ impl ProcessTrackerWorkflow for ApiKeyExpiryWorkflow { usize::try_from(retry_count) .map_err(|_| errors::ProcessTrackerError::TypeConversionError)?, ) - .ok_or(errors::ProcessTrackerError::EApiErrorResponse( - errors::ApiErrorResponse::InvalidDataValue { - field_name: "index", - } - .into(), - ))?; + .ok_or(errors::ProcessTrackerError::EApiErrorResponse)?; + + let email_contents = ApiKeyExpiryReminder { + recipient_email: UserEmail::from_pii_email(email_id).map_err(|err| { + logger::error!(%err,"Failed to convert recipient's email to UserEmail from pii::Email"); + errors::ProcessTrackerError::EApiErrorResponse + })?, + subject: "API Key Expiry Notice", + expires_in: *expires_in, + }; state .email_client .clone() - .send_email( - email_id.ok_or_else(|| errors::ProcessTrackerError::MissingRequiredField)?, - "API Key Expiry Notice".to_string(), - format!("Dear Merchant,\n -It has come to our attention that your API key will expire in {expires_in} days. To ensure uninterrupted access to our platform and continued smooth operation of your services, we kindly request that you take the necessary actions as soon as possible.\n\n -Thanks,\n -Team Hyperswitch"), + .compose_and_send_email( + Box::new(email_contents), + state.conf.proxy.https_url.as_ref(), ) .await - .map_err(|_| errors::ProcessTrackerError::FlowExecutionError { - flow: "ApiKeyExpiryWorkflow", - })?; + .map_err(errors::ProcessTrackerError::EEmailError)?; // If all the mails have been sent, then retry_count would be equal to length of the expiry_reminder_days vector if retry_count @@ -82,7 +91,7 @@ Team Hyperswitch"), .map_err(|_| errors::ProcessTrackerError::TypeConversionError)? { process - .finish_with_status(db, format!("COMPLETED_BY_PT_{task_id}")) + .finish_with_status(state.get_db().as_scheduler(), "COMPLETED_BY_PT".to_string()) .await? } // If tasks are remaining that has to be scheduled @@ -93,12 +102,7 @@ Team Hyperswitch"), usize::try_from(retry_count + 1) .map_err(|_| errors::ProcessTrackerError::TypeConversionError)?, ) - .ok_or(errors::ProcessTrackerError::EApiErrorResponse( - errors::ApiErrorResponse::InvalidDataValue { - field_name: "index", - } - .into(), - ))?; + .ok_or(errors::ProcessTrackerError::EApiErrorResponse)?; let updated_schedule_time = tracking_data.api_key_expiry.map(|api_key_expiry| { api_key_expiry.saturating_sub(time::Duration::days(i64::from(*expiry_reminder_day))) diff --git a/crates/scheduler/Cargo.toml b/crates/scheduler/Cargo.toml index b281bc862a2..72eaea3be06 100644 --- a/crates/scheduler/Cargo.toml +++ b/crates/scheduler/Cargo.toml @@ -7,6 +7,7 @@ edition = "2021" default = ["kv_store", "olap"] olap = ["storage_impl/olap"] kv_store = [] +email = ["external_services/email"] [dependencies] # Third party crates diff --git a/crates/scheduler/src/errors.rs b/crates/scheduler/src/errors.rs index 481fae07937..78a0bdee624 100644 --- a/crates/scheduler/src/errors.rs +++ b/crates/scheduler/src/errors.rs @@ -1,4 +1,6 @@ pub use common_utils::errors::{ParsingError, ValidationError}; +#[cfg(feature = "email")] +use external_services::email::EmailError; pub use redis_interface::errors::RedisError; pub use storage_impl::errors::ApplicationError; use storage_impl::errors::StorageError; @@ -51,6 +53,9 @@ pub enum ProcessTrackerError { EParsingError(error_stack::Report<ParsingError>), #[error("Validation Error Received: {0}")] EValidationError(error_stack::Report<ValidationError>), + #[cfg(feature = "email")] + #[error("Received Error EmailError: {0}")] + EEmailError(error_stack::Report<EmailError>), #[error("Type Conversion error")] TypeConversionError, } @@ -111,3 +116,9 @@ error_to_process_tracker_error!( error_stack::Report<ValidationError>, ProcessTrackerError::EValidationError(error_stack::Report<ValidationError>) ); + +#[cfg(feature = "email")] +error_to_process_tracker_error!( + error_stack::Report<EmailError>, + ProcessTrackerError::EEmailError(error_stack::Report<EmailError>) +);
2024-02-15T12:37:59Z
## 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, `ApiKeyExpiryWorkflow` is not part of the workflows being run in scheduler. This PR refactors that workflow to be included in the existing workflow list, as well as update the email sending section to the latest email refactor logic. Includes changes for sending an html page in email as opposed to plain text ### 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). --> Re-enables api key expiry reminder workflow ## 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. Locally set up email config 2. Created a merchant 3. Created an api key with some expiry (Locally changed the schedule time to be 3 minutes before the expiry) ![image](https://github.com/juspay/hyperswitch/assets/70657455/f93cb042-383d-45e9-b111-19c4381f7fe6) Since the email is triggered 7 days before expiry, complete flow cannot be tested in sandbox. However, api_key can be created with expiry set, then check the process tracker table whether an entry has been created in the table for this api_key with schedule time being 7 days prior to expiry. Query - ``` select * from process_tracker where runner = 'API_KEY_EXPIRY_WORKFLOW' order by created_at desc; ``` Check the `id` field of the latest entry in the table which has to be something like `API_KEY_EXPIRY_WORKFLOW_API_KEY_EXPIRY_{YOUR_KEY_ID}` and `schedule_time` being 7 days prior to expiry ## 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 - [ ] I added a [CHANGELOG](/CHANGELOG.md) entry if applicable
0666d814af93045ff23c85d8fd796da08cd5749b
1. Locally set up email config 2. Created a merchant 3. Created an api key with some expiry (Locally changed the schedule time to be 3 minutes before the expiry) ![image](https://github.com/juspay/hyperswitch/assets/70657455/f93cb042-383d-45e9-b111-19c4381f7fe6) Since the email is triggered 7 days before expiry, complete flow cannot be tested in sandbox. However, api_key can be created with expiry set, then check the process tracker table whether an entry has been created in the table for this api_key with schedule time being 7 days prior to expiry. Query - ``` select * from process_tracker where runner = 'API_KEY_EXPIRY_WORKFLOW' order by created_at desc; ``` Check the `id` field of the latest entry in the table which has to be something like `API_KEY_EXPIRY_WORKFLOW_API_KEY_EXPIRY_{YOUR_KEY_ID}` and `schedule_time` being 7 days prior to expiry
juspay/hyperswitch
juspay__hyperswitch-3647
Bug: [FIX] create a CORS rule for hyperswitch
diff --git a/config/config.example.toml b/config/config.example.toml index 9551fe4f7a2..2b189ea4022 100644 --- a/config/config.example.toml +++ b/config/config.example.toml @@ -327,6 +327,12 @@ paypal = { currency = "USD,INR", country = "US" } key_id = "" # The AWS key ID used by the KMS SDK for decrypting data. region = "" # The AWS region used by the KMS SDK for decrypting data. +[cors] +max_age = 30 # Maximum time (in seconds) for which this CORS request may be cached. +origins = "http://localhost:8080" # List of origins that are allowed to make requests. +allowed_methods = "GET,POST,PUT,DELETE" # List of methods that are allowed +wildcard_origin = false # If true, allows any origin to make requests + # EmailClient configuration. Only applicable when the `email` feature flag is enabled. [email] sender_email = "example@example.com" # Sender email diff --git a/config/deployments/env_specific.toml b/config/deployments/env_specific.toml index 04831376050..39bf7060b66 100644 --- a/config/deployments/env_specific.toml +++ b/config/deployments/env_specific.toml @@ -45,6 +45,12 @@ partner_id = "paypal_partner_id" [connector_request_reference_id_config] merchant_ids_send_payment_id_as_connector_request_id = ["merchant_id_1", "merchant_id_2", "etc.,"] +[cors] +max_age = 30 # Maximum time (in seconds) for which this CORS request may be cached. +origins = "http://localhost:8080" # List of origins that are allowed to make requests. +allowed_methods = "GET,POST,PUT,DELETE" # List of methods that are allowed +wildcard_origin = false # If true, allows any origin to make requests + # EmailClient configuration. Only applicable when the `email` feature flag is enabled. [email] sender_email = "example@example.com" # Sender email diff --git a/config/development.toml b/config/development.toml index 1bff54d8f43..d3b94f1e7e6 100644 --- a/config/development.toml +++ b/config/development.toml @@ -233,6 +233,12 @@ port = 3000 host = "127.0.0.1" workers = 1 +[cors] +max_age = 30 +origins = "http://localhost:8080" +allowed_methods = "GET,POST,PUT,DELETE" +wildcard_origin = false + [email] sender_email = "example@example.com" aws_region = "" diff --git a/config/docker_compose.toml b/config/docker_compose.toml index 7aabf3bb56e..90c9aa94fb7 100644 --- a/config/docker_compose.toml +++ b/config/docker_compose.toml @@ -81,6 +81,11 @@ max_in_flight_commands = 5000 default_command_timeout = 0 max_feed_count = 200 +[cors] +max_age = 30 +origins = "http://localhost:8080" +allowed_methods = "GET,POST,PUT,DELETE" +wildcard_origin = false [refund] max_attempts = 10 diff --git a/crates/router/src/configs/defaults.rs b/crates/router/src/configs/defaults.rs index e9b4de40d27..a7e36921961 100644 --- a/crates/router/src/configs/defaults.rs +++ b/crates/router/src/configs/defaults.rs @@ -19,6 +19,20 @@ impl Default for super::settings::Server { } } +impl Default for super::settings::CorsSettings { + fn default() -> Self { + Self { + origins: HashSet::from_iter(["http://localhost:8080".to_string()]), + allowed_methods: HashSet::from_iter( + ["GET", "PUT", "POST", "DELETE"] + .into_iter() + .map(ToString::to_string), + ), + wildcard_origin: false, + max_age: 30, + } + } +} impl Default for super::settings::Database { fn default() -> Self { Self { diff --git a/crates/router/src/configs/settings.rs b/crates/router/src/configs/settings.rs index 13c3ba23e1d..8ed2daef5f3 100644 --- a/crates/router/src/configs/settings.rs +++ b/crates/router/src/configs/settings.rs @@ -107,6 +107,7 @@ pub struct Settings { pub dummy_connector: DummyConnector, #[cfg(feature = "email")] pub email: EmailSettings, + pub cors: CorsSettings, pub mandates: Mandates, pub required_fields: RequiredFields, pub delayed_session_response: DelayedSessionConfig, @@ -242,6 +243,17 @@ pub struct DummyConnector { pub discord_invite_url: String, } +#[derive(Debug, Deserialize, Clone)] +pub struct CorsSettings { + #[serde(default, deserialize_with = "deserialize_hashset")] + pub origins: HashSet<String>, + #[serde(default)] + pub wildcard_origin: bool, + pub max_age: usize, + #[serde(deserialize_with = "deserialize_hashset")] + pub allowed_methods: HashSet<String>, +} + #[derive(Debug, Deserialize, Clone)] pub struct Mandates { pub supported_payment_methods: SupportedPaymentMethodsForMandate, @@ -714,6 +726,8 @@ impl Settings { self.locker.validate()?; self.connectors.validate("connectors")?; + self.cors.validate()?; + self.scheduler .as_ref() .map(|scheduler_settings| scheduler_settings.validate()) diff --git a/crates/router/src/configs/validations.rs b/crates/router/src/configs/validations.rs index 655dca33384..21ef4037d81 100644 --- a/crates/router/src/configs/validations.rs +++ b/crates/router/src/configs/validations.rs @@ -124,6 +124,22 @@ impl super::settings::SupportedConnectors { } } +impl super::settings::CorsSettings { + pub fn validate(&self) -> Result<(), ApplicationError> { + common_utils::fp_utils::when(self.wildcard_origin && !self.origins.is_empty(), || { + Err(ApplicationError::InvalidConfigurationValueError( + "Allowed Origins must be empty when wildcard origin is true".to_string(), + )) + })?; + + common_utils::fp_utils::when(!self.wildcard_origin && self.origins.is_empty(), || { + Err(ApplicationError::InvalidConfigurationValueError( + "Allowed origins must not be empty. Please either enable wildcard origin or provide Allowed Origin".to_string(), + )) + }) + } +} + #[cfg(feature = "kv_store")] impl super::settings::DrainerSettings { pub fn validate(&self) -> Result<(), ApplicationError> { diff --git a/crates/router/src/cors.rs b/crates/router/src/cors.rs index 07e12b0d3fd..9baa4484ee4 100644 --- a/crates/router/src/cors.rs +++ b/crates/router/src/cors.rs @@ -1,19 +1,21 @@ // use actix_web::http::header; -pub fn cors() -> actix_cors::Cors { - actix_cors::Cors::permissive() // FIXME : Never use in production +use crate::configs::settings; - /* - .allowed_methods(vec!["GET", "POST", "PUT", "DELETE"]) - .allowed_headers(vec![header::AUTHORIZATION, header::CONTENT_TYPE]); - if CONFIG.profile == "debug" { // --------->>> FIXME: It should be conditional - cors.allowed_origin_fn(|origin, _req_head| { - origin.as_bytes().starts_with(b"http://localhost") - }) - } else { +pub fn cors(config: settings::CorsSettings) -> actix_cors::Cors { + let allowed_methods = config.allowed_methods.iter().map(|s| s.as_str()); + + let mut cors = actix_cors::Cors::default() + .allowed_methods(allowed_methods) + .max_age(config.max_age); - FIXME : I don't know what to put here - .allowed_origin_fn(|origin, _req_head| origin.as_bytes().starts_with(b"http://localhost")) + if config.wildcard_origin { + cors = cors.allow_any_origin() + } else { + for origin in &config.origins { + cors = cors.allowed_origin(origin); + } } - */ + + cors } diff --git a/crates/router/src/lib.rs b/crates/router/src/lib.rs index ed443c9e418..19bd28b8dbc 100644 --- a/crates/router/src/lib.rs +++ b/crates/router/src/lib.rs @@ -91,7 +91,7 @@ pub fn mk_app( InitError = (), >, > { - let mut server_app = get_application_builder(request_body_limit); + let mut server_app = get_application_builder(request_body_limit, state.conf.cors.clone()); #[cfg(feature = "dummy_connector")] { @@ -231,6 +231,7 @@ impl Stop for mpsc::Sender<()> { pub fn get_application_builder( request_body_limit: usize, + cors: settings::CorsSettings, ) -> actix_web::App< impl ServiceFactory< ServiceRequest, @@ -257,7 +258,7 @@ pub fn get_application_builder( )) .wrap(middleware::default_response_headers()) .wrap(middleware::RequestId) - .wrap(cors::cors()) + .wrap(cors::cors(cors)) // this middleware works only for Http1.1 requests .wrap(middleware::Http400RequestDetailsLogger) .wrap(middleware::LogSpanInitializer) diff --git a/loadtest/config/development.toml b/loadtest/config/development.toml index 85dfec5232e..85cf404ed2e 100644 --- a/loadtest/config/development.toml +++ b/loadtest/config/development.toml @@ -254,6 +254,12 @@ bank_redirect.sofort = {connector_list = "stripe,adyen,globalpay"} bank_redirect.giropay = {connector_list = "adyen,globalpay"} +[cors] +max_age = 30 +origins = "http://localhost:8080" +allowed_methods = "GET,POST,PUT,DELETE" +wildcard_origin = false + [mandates.update_mandate_supported] card.credit ={connector_list ="cybersource"} card.debit = {connector_list ="cybersource"}
2024-02-13T19:42:10Z
## Type of Change <!-- Put an `x` in the boxes that apply --> - [x] Enhancement ## Description <!-- Describe your changes in detail --> Adds cors rules to actix ### Additional Changes - [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` --> - Added `CorsSettings` 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). --> NA ## 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)? --> - Configure allowed origins in `ROUTER__CORS__ORIGINS`. - Add `Origin` header to that configured to your config and the request should return 200 ```bash curl --location 'http://localhost:8080/health' \ --header 'Origin: http://localhost:8080' ``` - And configure origin header to something else like `google.com`. It should return `Bad Request` with Response `Origin is not allowed to make this request` ```bash curl --location 'http://localhost:8080/health' \ --header 'Origin: https://google.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
774a0322aa4b36d87b122e47cd893383e262de12
- Configure allowed origins in `ROUTER__CORS__ORIGINS`. - Add `Origin` header to that configured to your config and the request should return 200 ```bash curl --location 'http://localhost:8080/health' \ --header 'Origin: http://localhost:8080' ``` - And configure origin header to something else like `google.com`. It should return `Bad Request` with Response `Origin is not allowed to make this request` ```bash curl --location 'http://localhost:8080/health' \ --header 'Origin: https://google.com' ```
juspay/hyperswitch
juspay__hyperswitch-3643
Bug: [BUG] Update Iatapay config URL to use sandbox URl instead of production URL ### Bug Description It bugs out when you try to do a payment with Iatapay and it throws Unauthorized error in Sandbox environment ### Expected Behavior It should do the payment. ### Actual Behavior Throws an error ### Steps To Reproduce 1. Do a Payment through Iatapay ### Context For The Bug Error. Unauthorized error. ### Environment Are you using hyperswitch hosted version? Yes Sandbox ### 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/config/deployments/sandbox.toml b/config/deployments/sandbox.toml index 42588cb7345..564a2d9e984 100644 --- a/config/deployments/sandbox.toml +++ b/config/deployments/sandbox.toml @@ -43,7 +43,7 @@ globalpay.base_url = "https://apis.sandbox.globalpay.com/ucp/" globepay.base_url = "https://pay.globepay.co/" gocardless.base_url = "https://api-sandbox.gocardless.com" helcim.base_url = "https://api.helcim.com/" -iatapay.base_url = "https://iata-pay.iata.org/api/v1" +iatapay.base_url = "https://sandbox.iata-pay.iata.org/api/v1" klarna.base_url = "https://api-na.playground.klarna.com/" mollie.base_url = "https://api.mollie.com/v2/" mollie.secondary_base_url = "https://api.cc.mollie.com/v1/" @@ -121,7 +121,6 @@ bank_redirect.ideal.connector_list = "stripe,adyen,globalpay" bank_redirect.sofort.connector_list = "stripe,adyen,globalpay" bank_redirect.giropay.connector_list = "adyen,globalpay" - [mandates.update_mandate_supported] card.credit ={connector_list ="cybersource"} card.debit = {connector_list ="cybersource"}
2024-02-13T09:39:17Z
## 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 updates Iatapay to use Sandbox URL instead of Production URL in Sandbox environment. Closes #3643 ### 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` --> `config/deployment/sandbox.toml` ## 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). --> Everytime, we need to manually do another deployment manually to see whether the connector is working as expected. With this PR, if they want to test, we'll do manual deployment with production URL going forward. ## 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)? --> Iataoay payments in Sandbox environments should work now: #### Create - Payment ```curl curl --location 'https://sandbox.hyperswitch.io/payments' \ --header 'Content-Type: application/json' \ --header 'Accept: application/json' \ --header 'api-key: snd_oJVcvSxV6aBs3qzsG8en6nVUOMYcczuNBSCaIRToSiHhreVNNOYVmCj9gccgXuhR' \ --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": "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://pixincreate.dev", "payment_method": "upi", "payment_method_type": "upi_collect", "payment_method_data": { "upi": { "vpa_id": "successtest@iata" } }, "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" }, "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": "IN", "first_name": "joseph", "last_name": "Doe" } }, "statement_descriptor_name": "joseph", "statement_descriptor_suffix": "JS", "metadata": { "udf1": "value1", "new_customer": "true", "login_date": "2019-09-10T10:11:12Z" } }' ``` ```json { "payment_id": "pay_4vM0FY3dKVl0yTKS2dJJ", "merchant_id": "postman_merchant_GHAction_329d9d3f-e66f-4b01-a085-da6baa0d7896", "status": "requires_customer_action", "amount": 6540, "net_amount": 6540, "amount_capturable": 6540, "amount_received": null, "connector": "iatapay", "client_secret": "pay_4vM0FY3dKVl0yTKS2dJJ_secret_OEMfrIA3fJuUi8R67p6Q", "created": "2024-02-13T09:33:44.649Z", "currency": "INR", "customer_id": "StripeCustomer", "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": "upi", "payment_method_data": "upi", "payment_token": null, "shipping": { "address": { "city": "San Fransico", "country": "IN", "line1": "1467", "line2": "Harrison Street", "line3": "Harrison Street", "zip": "94122", "state": "California", "first_name": "joseph", "last_name": "Doe" }, "phone": { "number": null, "country_code": 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": "8056594427", "country_code": "+91" } }, "order_details": null, "email": "guest@example.com", "name": "John Doe", "phone": "999999999", "return_url": "https://pixincreate.dev/", "authentication_type": "no_three_ds", "statement_descriptor_name": "joseph", "statement_descriptor_suffix": "JS", "next_action": { "type": "redirect_to_url", "redirect_to_url": "https://sandbox.hyperswitch.io/payments/redirect/pay_4vM0FY3dKVl0yTKS2dJJ/postman_merchant_GHAction_329d9d3f-e66f-4b01-a085-da6baa0d7896/pay_4vM0FY3dKVl0yTKS2dJJ_1" }, "cancellation_reason": null, "error_code": null, "error_message": null, "unified_code": null, "unified_message": null, "payment_experience": null, "payment_method_type": "upi_collect", "connector_label": null, "business_country": null, "business_label": null, "business_sub_label": null, "allowed_payment_method_types": null, "ephemeral_key": { "customer_id": "StripeCustomer", "created_at": 1707816824, "expires": 1707820424, "secret": "epk_124b752c19a14485ae02906c800475a1" }, "manual_retry_allowed": null, "connector_transaction_id": "PHK6FODTMD0IO", "frm_message": null, "metadata": { "udf1": "value1", "new_customer": "true", "login_date": "2019-09-10T10:11:12Z" }, "connector_metadata": null, "feature_metadata": null, "reference_id": "pay_4vM0FY3dKVl0yTKS2dJJ_1", "payment_link": null, "profile_id": "pro_uKrcYw3NgIA71P3M1DAW", "surcharge_details": null, "attempt_count": 1, "merchant_decision": null, "merchant_connector_id": "mca_3Q8AZBbrkmL6x0Mxfko3", "incremental_authorization_allowed": null, "authorization_count": null, "incremental_authorizations": null, "expires_on": "2024-02-13T09:48:44.649Z", "fingerprint": null } ``` #### Retrieve - Payment ```curl curl --location 'https://sandbox.hyperswitch.io/payments/pay_4vM0FY3dKVl0yTKS2dJJ' \ --header 'Accept: application/json' \ --header 'api-key: snd_oJVcvSxV6aBs3qzsG8en6nVUOMYcczuNBSCaIRToSiHhreVNNOYVmCj9gccgXuhR' ``` ```json { "payment_id": "pay_4vM0FY3dKVl0yTKS2dJJ", "merchant_id": "postman_merchant_GHAction_329d9d3f-e66f-4b01-a085-da6baa0d7896", "status": "succeeded", "amount": 6540, "net_amount": 6540, "amount_capturable": 0, "amount_received": 6540, "connector": "iatapay", "client_secret": "pay_4vM0FY3dKVl0yTKS2dJJ_secret_OEMfrIA3fJuUi8R67p6Q", "created": "2024-02-13T09:33:44.649Z", "currency": "INR", "customer_id": "StripeCustomer", "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": "upi", "payment_method_data": "upi", "payment_token": null, "shipping": { "address": { "city": "San Fransico", "country": "IN", "line1": "1467", "line2": "Harrison Street", "line3": "Harrison Street", "zip": "94122", "state": "California", "first_name": "joseph", "last_name": "Doe" }, "phone": { "number": null, "country_code": 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": "8056594427", "country_code": "+91" } }, "order_details": null, "email": "guest@example.com", "name": "John Doe", "phone": "999999999", "return_url": "https://pixincreate.dev/", "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": "upi_collect", "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": "PHK6FODTMD0IO", "frm_message": null, "metadata": { "udf1": "value1", "new_customer": "true", "login_date": "2019-09-10T10:11:12Z" }, "connector_metadata": null, "feature_metadata": null, "reference_id": "pay_4vM0FY3dKVl0yTKS2dJJ_1", "payment_link": null, "profile_id": "pro_uKrcYw3NgIA71P3M1DAW", "surcharge_details": null, "attempt_count": 1, "merchant_decision": null, "merchant_connector_id": "mca_3Q8AZBbrkmL6x0Mxfko3", "incremental_authorization_allowed": null, "authorization_count": null, "incremental_authorizations": null, "expires_on": "2024-02-13T09:48:44.649Z", "fingerprint": 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` - [x] I reviewed the submitted code - [ ] I added unit tests for my changes where possible - [ ] I added a [CHANGELOG](/CHANGELOG.md) entry if applicable
6e103cef50fea31d2508880985f80f0fd65cd536
Iataoay payments in Sandbox environments should work now: #### Create - Payment ```curl curl --location 'https://sandbox.hyperswitch.io/payments' \ --header 'Content-Type: application/json' \ --header 'Accept: application/json' \ --header 'api-key: snd_oJVcvSxV6aBs3qzsG8en6nVUOMYcczuNBSCaIRToSiHhreVNNOYVmCj9gccgXuhR' \ --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": "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://pixincreate.dev", "payment_method": "upi", "payment_method_type": "upi_collect", "payment_method_data": { "upi": { "vpa_id": "successtest@iata" } }, "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" }, "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": "IN", "first_name": "joseph", "last_name": "Doe" } }, "statement_descriptor_name": "joseph", "statement_descriptor_suffix": "JS", "metadata": { "udf1": "value1", "new_customer": "true", "login_date": "2019-09-10T10:11:12Z" } }' ``` ```json { "payment_id": "pay_4vM0FY3dKVl0yTKS2dJJ", "merchant_id": "postman_merchant_GHAction_329d9d3f-e66f-4b01-a085-da6baa0d7896", "status": "requires_customer_action", "amount": 6540, "net_amount": 6540, "amount_capturable": 6540, "amount_received": null, "connector": "iatapay", "client_secret": "pay_4vM0FY3dKVl0yTKS2dJJ_secret_OEMfrIA3fJuUi8R67p6Q", "created": "2024-02-13T09:33:44.649Z", "currency": "INR", "customer_id": "StripeCustomer", "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": "upi", "payment_method_data": "upi", "payment_token": null, "shipping": { "address": { "city": "San Fransico", "country": "IN", "line1": "1467", "line2": "Harrison Street", "line3": "Harrison Street", "zip": "94122", "state": "California", "first_name": "joseph", "last_name": "Doe" }, "phone": { "number": null, "country_code": 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": "8056594427", "country_code": "+91" } }, "order_details": null, "email": "guest@example.com", "name": "John Doe", "phone": "999999999", "return_url": "https://pixincreate.dev/", "authentication_type": "no_three_ds", "statement_descriptor_name": "joseph", "statement_descriptor_suffix": "JS", "next_action": { "type": "redirect_to_url", "redirect_to_url": "https://sandbox.hyperswitch.io/payments/redirect/pay_4vM0FY3dKVl0yTKS2dJJ/postman_merchant_GHAction_329d9d3f-e66f-4b01-a085-da6baa0d7896/pay_4vM0FY3dKVl0yTKS2dJJ_1" }, "cancellation_reason": null, "error_code": null, "error_message": null, "unified_code": null, "unified_message": null, "payment_experience": null, "payment_method_type": "upi_collect", "connector_label": null, "business_country": null, "business_label": null, "business_sub_label": null, "allowed_payment_method_types": null, "ephemeral_key": { "customer_id": "StripeCustomer", "created_at": 1707816824, "expires": 1707820424, "secret": "epk_124b752c19a14485ae02906c800475a1" }, "manual_retry_allowed": null, "connector_transaction_id": "PHK6FODTMD0IO", "frm_message": null, "metadata": { "udf1": "value1", "new_customer": "true", "login_date": "2019-09-10T10:11:12Z" }, "connector_metadata": null, "feature_metadata": null, "reference_id": "pay_4vM0FY3dKVl0yTKS2dJJ_1", "payment_link": null, "profile_id": "pro_uKrcYw3NgIA71P3M1DAW", "surcharge_details": null, "attempt_count": 1, "merchant_decision": null, "merchant_connector_id": "mca_3Q8AZBbrkmL6x0Mxfko3", "incremental_authorization_allowed": null, "authorization_count": null, "incremental_authorizations": null, "expires_on": "2024-02-13T09:48:44.649Z", "fingerprint": null } ``` #### Retrieve - Payment ```curl curl --location 'https://sandbox.hyperswitch.io/payments/pay_4vM0FY3dKVl0yTKS2dJJ' \ --header 'Accept: application/json' \ --header 'api-key: snd_oJVcvSxV6aBs3qzsG8en6nVUOMYcczuNBSCaIRToSiHhreVNNOYVmCj9gccgXuhR' ``` ```json { "payment_id": "pay_4vM0FY3dKVl0yTKS2dJJ", "merchant_id": "postman_merchant_GHAction_329d9d3f-e66f-4b01-a085-da6baa0d7896", "status": "succeeded", "amount": 6540, "net_amount": 6540, "amount_capturable": 0, "amount_received": 6540, "connector": "iatapay", "client_secret": "pay_4vM0FY3dKVl0yTKS2dJJ_secret_OEMfrIA3fJuUi8R67p6Q", "created": "2024-02-13T09:33:44.649Z", "currency": "INR", "customer_id": "StripeCustomer", "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": "upi", "payment_method_data": "upi", "payment_token": null, "shipping": { "address": { "city": "San Fransico", "country": "IN", "line1": "1467", "line2": "Harrison Street", "line3": "Harrison Street", "zip": "94122", "state": "California", "first_name": "joseph", "last_name": "Doe" }, "phone": { "number": null, "country_code": 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": "8056594427", "country_code": "+91" } }, "order_details": null, "email": "guest@example.com", "name": "John Doe", "phone": "999999999", "return_url": "https://pixincreate.dev/", "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": "upi_collect", "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": "PHK6FODTMD0IO", "frm_message": null, "metadata": { "udf1": "value1", "new_customer": "true", "login_date": "2019-09-10T10:11:12Z" }, "connector_metadata": null, "feature_metadata": null, "reference_id": "pay_4vM0FY3dKVl0yTKS2dJJ_1", "payment_link": null, "profile_id": "pro_uKrcYw3NgIA71P3M1DAW", "surcharge_details": null, "attempt_count": 1, "merchant_decision": null, "merchant_connector_id": "mca_3Q8AZBbrkmL6x0Mxfko3", "incremental_authorization_allowed": null, "authorization_count": null, "incremental_authorizations": null, "expires_on": "2024-02-13T09:48:44.649Z", "fingerprint": null } ```
juspay/hyperswitch
juspay__hyperswitch-3685
Bug: [REFACTOR] Simplify the method signatures of some methods in the `Encode` extension trait ### Description The definition of the [`common_utils::ext_traits::Encode`](https://github.com/juspay/hyperswitch/blob/fb254b8924808e6a2b2a9a31dbed78749836e8d3/crates/common_utils/src/ext_traits.rs#L21) trait has a generic type parameter `P`, which is used in only a subset of the trait methods. This causes the type having to be specified when calling methods which don't use that generic type parameter, such as the [`encode_to_value()`](https://github.com/juspay/hyperswitch/blob/fb254b8924808e6a2b2a9a31dbed78749836e8d3/crates/common_utils/src/ext_traits.rs#L78) method, used to convert a type which implements `serde::Serialize` to a `serde_json::Value`. One such usage is: https://github.com/juspay/hyperswitch/blob/fb254b8924808e6a2b2a9a31dbed78749836e8d3/crates/router/src/routes/payments/helpers.rs#L76-L80 Ignoring the error handling and propagation bolierplate code, it looks like so: ```rust use common_utils::ext_traits::Encode; // Include trait in scope let encoded = Encode::<types::BrowserInformation>::encode_to_value(&browser_info)?; ``` This can be simplified to something like this (since the compiler is able to infer types in most cases): ```rust use common_utils::ext_traits::Encode; // Include trait in scope let encoded = browser_info.encode_to_value()?; ``` ### Possible Implementation Remove the generic type parameter `P` on the trait, and add it in the trait methods which use that type parameter.
diff --git a/add_connector.md b/add_connector.md index 57fb6fdfff4..ac9d3f8d847 100644 --- a/add_connector.md +++ b/add_connector.md @@ -531,7 +531,7 @@ Within the `ConnectorIntegration` trait, you'll find the following methods imple let connector_req = checkout::PaymentsRequest::try_from(&connector_router_data)?; let checkout_req = types::RequestBody::log_and_get_request_body( &connector_req, - utils::Encode::<checkout::PaymentsRequest>::encode_to_string_of_json, + utils::Encode::encode_to_string_of_json, ) .change_context(errors::ConnectorError::RequestEncodingFailed)?; Ok(Some(checkout_req)) diff --git a/crates/api_models/src/payments.rs b/crates/api_models/src/payments.rs index 1be9762c76c..b95b74b329f 100644 --- a/crates/api_models/src/payments.rs +++ b/crates/api_models/src/payments.rs @@ -625,7 +625,7 @@ impl PaymentsRequest { > { self.feature_metadata .as_ref() - .map(Encode::<FeatureMetadata>::encode_to_value) + .map(Encode::encode_to_value) .transpose() } @@ -637,7 +637,7 @@ impl PaymentsRequest { > { self.connector_metadata .as_ref() - .map(Encode::<ConnectorMetadata>::encode_to_value) + .map(Encode::encode_to_value) .transpose() } @@ -649,7 +649,7 @@ impl PaymentsRequest { > { self.allowed_payment_method_types .as_ref() - .map(Encode::<Vec<api_enums::PaymentMethodType>>::encode_to_value) + .map(Encode::encode_to_value) .transpose() } @@ -663,10 +663,7 @@ impl PaymentsRequest { .as_ref() .map(|od| { od.iter() - .map(|order| { - Encode::<OrderDetailsWithAmount>::encode_to_value(order) - .map(masking::Secret::new) - }) + .map(|order| order.encode_to_value().map(masking::Secret::new)) .collect::<Result<Vec<_>, _>>() }) .transpose() diff --git a/crates/common_utils/src/ext_traits.rs b/crates/common_utils/src/ext_traits.rs index d3296f98953..8f97dd75534 100644 --- a/crates/common_utils/src/ext_traits.rs +++ b/crates/common_utils/src/ext_traits.rs @@ -18,7 +18,7 @@ use crate::{ /// Encode interface /// An interface for performing type conversions and serialization /// -pub trait Encode<'e, P> +pub trait Encode<'e> where Self: 'e + std::fmt::Debug, { @@ -28,7 +28,7 @@ where /// and then performing encoding operation using the `Serialize` trait from `serde` /// Specifically to convert into json, by using `serde_json` /// - fn convert_and_encode(&'e self) -> CustomResult<String, errors::ParsingError> + fn convert_and_encode<P>(&'e self) -> CustomResult<String, errors::ParsingError> where P: TryFrom<&'e Self> + Serialize, Result<P, <P as TryFrom<&'e Self>>::Error>: ResultExt, @@ -39,7 +39,7 @@ where /// and then performing encoding operation using the `Serialize` trait from `serde` /// Specifically, to convert into urlencoded, by using `serde_urlencoded` /// - fn convert_and_url_encode(&'e self) -> CustomResult<String, errors::ParsingError> + fn convert_and_url_encode<P>(&'e self) -> CustomResult<String, errors::ParsingError> where P: TryFrom<&'e Self> + Serialize, Result<P, <P as TryFrom<&'e Self>>::Error>: ResultExt, @@ -88,11 +88,11 @@ where Self: Serialize; } -impl<'e, P, A> Encode<'e, P> for A +impl<'e, A> Encode<'e> for A where Self: 'e + std::fmt::Debug, { - fn convert_and_encode(&'e self) -> CustomResult<String, errors::ParsingError> + fn convert_and_encode<P>(&'e self) -> CustomResult<String, errors::ParsingError> where P: TryFrom<&'e Self> + Serialize, Result<P, <P as TryFrom<&'e Self>>::Error>: ResultExt, @@ -106,7 +106,7 @@ where .attach_printable_lazy(|| format!("Unable to convert {self:?} to a request")) } - fn convert_and_url_encode(&'e self) -> CustomResult<String, errors::ParsingError> + fn convert_and_url_encode<P>(&'e self) -> CustomResult<String, errors::ParsingError> where P: TryFrom<&'e Self> + Serialize, Result<P, <P as TryFrom<&'e Self>>::Error>: ResultExt, diff --git a/crates/redis_interface/src/commands.rs b/crates/redis_interface/src/commands.rs index ce2b138d923..5d376a4d7b1 100644 --- a/crates/redis_interface/src/commands.rs +++ b/crates/redis_interface/src/commands.rs @@ -75,7 +75,8 @@ impl super::RedisConnectionPool { where V: serde::Serialize + Debug, { - let serialized = Encode::<V>::encode_to_vec(&value) + let serialized = value + .encode_to_vec() .change_context(errors::RedisError::JsonSerializationFailed)?; self.set_key_if_not_exists_with_expiry(key, serialized.as_slice(), ttl) .await @@ -90,7 +91,8 @@ impl super::RedisConnectionPool { where V: serde::Serialize + Debug, { - let serialized = Encode::<V>::encode_to_vec(&value) + let serialized = value + .encode_to_vec() .change_context(errors::RedisError::JsonSerializationFailed)?; self.set_key(key, serialized.as_slice()).await @@ -106,7 +108,8 @@ impl super::RedisConnectionPool { where V: serde::Serialize + Debug, { - let serialized = Encode::<V>::encode_to_vec(&value) + let serialized = value + .encode_to_vec() .change_context(errors::RedisError::JsonSerializationFailed)?; self.pool @@ -307,7 +310,8 @@ impl super::RedisConnectionPool { where V: serde::Serialize + Debug, { - let serialized = Encode::<V>::encode_to_vec(&value) + let serialized = value + .encode_to_vec() .change_context(errors::RedisError::JsonSerializationFailed)?; self.set_hash_field_if_not_exist(key, field, serialized.as_slice(), ttl) diff --git a/crates/router/src/compatibility/stripe/webhooks.rs b/crates/router/src/compatibility/stripe/webhooks.rs index 807278e0aff..0cbd89bdd3e 100644 --- a/crates/router/src/compatibility/stripe/webhooks.rs +++ b/crates/router/src/compatibility/stripe/webhooks.rs @@ -2,7 +2,7 @@ use api_models::{ enums::{DisputeStatus, MandateStatus}, webhooks::{self as api}, }; -use common_utils::{crypto::SignMessage, date_time, ext_traits}; +use common_utils::{crypto::SignMessage, date_time, ext_traits::Encode}; use error_stack::{IntoReport, ResultExt}; use router_env::logger; use serde::Serialize; @@ -39,10 +39,10 @@ impl OutgoingWebhookType for StripeOutgoingWebhook { .into_report() .attach_printable("For stripe compatibility payment_response_hash_key is mandatory")?; - let webhook_signature_payload = - ext_traits::Encode::<serde_json::Value>::encode_to_string_of_json(self) - .change_context(errors::WebhooksFlowError::OutgoingWebhookEncodingFailed) - .attach_printable("failed encoding outgoing webhook payload")?; + let webhook_signature_payload = self + .encode_to_string_of_json() + .change_context(errors::WebhooksFlowError::OutgoingWebhookEncodingFailed) + .attach_printable("failed encoding outgoing webhook payload")?; let new_signature_payload = format!("{timestamp}.{webhook_signature_payload}"); let v1 = hex::encode( diff --git a/crates/router/src/connector/adyen/transformers.rs b/crates/router/src/connector/adyen/transformers.rs index a79826e2f19..05c1a0ede97 100644 --- a/crates/router/src/connector/adyen/transformers.rs +++ b/crates/router/src/connector/adyen/transformers.rs @@ -2,6 +2,7 @@ use api_models::payouts::PayoutMethodData; use api_models::{enums, payments, webhooks}; use cards::CardNumber; +use common_utils::ext_traits::Encode; use error_stack::ResultExt; use masking::PeekInterface; use reqwest::Url; @@ -3331,32 +3332,26 @@ pub fn get_qr_metadata( qr_code_url, display_to_timestamp, }; - Some(common_utils::ext_traits::Encode::< - payments::QrCodeInformation, - >::encode_to_value(&qr_code_info)) - .transpose() - .change_context(errors::ConnectorError::ResponseHandlingFailed) + Some(qr_code_info.encode_to_value()) + .transpose() + .change_context(errors::ConnectorError::ResponseHandlingFailed) } else if let (None, Some(qr_code_url)) = (image_data_url.clone(), qr_code_url.clone()) { let qr_code_info = payments::QrCodeInformation::QrCodeImageUrl { qr_code_url, display_to_timestamp, }; - Some(common_utils::ext_traits::Encode::< - payments::QrCodeInformation, - >::encode_to_value(&qr_code_info)) - .transpose() - .change_context(errors::ConnectorError::ResponseHandlingFailed) + Some(qr_code_info.encode_to_value()) + .transpose() + .change_context(errors::ConnectorError::ResponseHandlingFailed) } else if let (Some(image_data_url), None) = (image_data_url, qr_code_url) { let qr_code_info = payments::QrCodeInformation::QrDataUrl { image_data_url, display_to_timestamp, }; - Some(common_utils::ext_traits::Encode::< - payments::QrCodeInformation, - >::encode_to_value(&qr_code_info)) - .transpose() - .change_context(errors::ConnectorError::ResponseHandlingFailed) + Some(qr_code_info.encode_to_value()) + .transpose() + .change_context(errors::ConnectorError::ResponseHandlingFailed) } else { Ok(None) } @@ -3481,11 +3476,9 @@ pub fn get_present_to_shopper_metadata( instructions_url: response.action.instructions_url.clone(), }; - Some(common_utils::ext_traits::Encode::< - payments::VoucherNextStepData, - >::encode_to_value(&voucher_data)) - .transpose() - .change_context(errors::ConnectorError::ResponseHandlingFailed) + Some(voucher_data.encode_to_value()) + .transpose() + .change_context(errors::ConnectorError::ResponseHandlingFailed) } PaymentType::PermataBankTransfer | PaymentType::BcaBankTransfer @@ -3503,11 +3496,9 @@ pub fn get_present_to_shopper_metadata( }), ); - Some(common_utils::ext_traits::Encode::< - payments::DokuBankTransferInstructions, - >::encode_to_value(&voucher_data)) - .transpose() - .change_context(errors::ConnectorError::ResponseHandlingFailed) + Some(voucher_data.encode_to_value()) + .transpose() + .change_context(errors::ConnectorError::ResponseHandlingFailed) } PaymentType::Affirm | PaymentType::Afterpaytouch diff --git a/crates/router/src/connector/authorizedotnet/transformers.rs b/crates/router/src/connector/authorizedotnet/transformers.rs index 3377457f38a..bc5bfe86ca1 100644 --- a/crates/router/src/connector/authorizedotnet/transformers.rs +++ b/crates/router/src/connector/authorizedotnet/transformers.rs @@ -581,9 +581,7 @@ impl<F, T> .account_number .as_ref() .map(|acc_no| { - Encode::<'_, PaymentDetails>::encode_to_value( - &construct_refund_payment_details(acc_no.clone()), - ) + construct_refund_payment_details(acc_no.clone()).encode_to_value() }) .transpose() .change_context(errors::ConnectorError::MissingRequiredField { @@ -658,9 +656,7 @@ impl<F, T> .account_number .as_ref() .map(|acc_no| { - Encode::<'_, PaymentDetails>::encode_to_value( - &construct_refund_payment_details(acc_no.clone()), - ) + construct_refund_payment_details(acc_no.clone()).encode_to_value() }) .transpose() .change_context(errors::ConnectorError::MissingRequiredField { diff --git a/crates/router/src/connector/bluesnap/transformers.rs b/crates/router/src/connector/bluesnap/transformers.rs index f1c27d72749..63ca7750303 100644 --- a/crates/router/src/connector/bluesnap/transformers.rs +++ b/crates/router/src/connector/bluesnap/transformers.rs @@ -294,13 +294,10 @@ impl TryFrom<&BluesnapRouterData<&types::PaymentsAuthorizeRouterData>> for Blues )), api::PaymentMethodData::Wallet(wallet_data) => match wallet_data { api_models::payments::WalletData::GooglePay(payment_method_data) => { - let gpay_object = Encode::<BluesnapGooglePayObject>::encode_to_string_of_json( - &BluesnapGooglePayObject { - payment_method_data: utils::GooglePayWalletData::from( - payment_method_data, - ), - }, - ) + let gpay_object = BluesnapGooglePayObject { + payment_method_data: utils::GooglePayWalletData::from(payment_method_data), + } + .encode_to_string_of_json() .change_context(errors::ConnectorError::RequestEncodingFailed)?; Ok(( PaymentMethodDetails::Wallet(BluesnapWallet { @@ -350,25 +347,21 @@ impl TryFrom<&BluesnapRouterData<&types::PaymentsAuthorizeRouterData>> for Blues address.push(add) } - let apple_pay_object = Encode::<EncodedPaymentToken>::encode_to_string_of_json( - &EncodedPaymentToken { - token: ApplepayPaymentData { - payment_data: apple_pay_payment_data, - payment_method: payment_method_data - .payment_method - .to_owned() - .into(), - transaction_identifier: payment_method_data.transaction_identifier, - }, - billing_contact: BillingDetails { - country_code: billing_address.country, - address_lines: Some(address), - family_name: billing_address.last_name.to_owned(), - given_name: billing_address.first_name.to_owned(), - postal_code: billing_address.zip, - }, + let apple_pay_object = EncodedPaymentToken { + token: ApplepayPaymentData { + payment_data: apple_pay_payment_data, + payment_method: payment_method_data.payment_method.to_owned().into(), + transaction_identifier: payment_method_data.transaction_identifier, }, - ) + billing_contact: BillingDetails { + country_code: billing_address.country, + address_lines: Some(address), + family_name: billing_address.last_name.to_owned(), + given_name: billing_address.first_name.to_owned(), + postal_code: billing_address.zip, + }, + } + .encode_to_string_of_json() .change_context(errors::ConnectorError::RequestEncodingFailed)?; Ok(( diff --git a/crates/router/src/connector/checkout.rs b/crates/router/src/connector/checkout.rs index cf1b5a1498d..0d26584c43b 100644 --- a/crates/router/src/connector/checkout.rs +++ b/crates/router/src/connector/checkout.rs @@ -2,7 +2,11 @@ pub mod transformers; use std::fmt::Debug; -use common_utils::{crypto, ext_traits::ByteSliceExt, request::RequestContent}; +use common_utils::{ + crypto, + ext_traits::{ByteSliceExt, Encode}, + request::RequestContent, +}; use diesel_models::enums; use error_stack::{IntoReport, ResultExt}; use masking::PeekInterface; @@ -30,7 +34,6 @@ use crate::{ self, api::{self, ConnectorCommon, ConnectorCommonExt}, }, - utils, utils::BytesExt, }; @@ -1297,7 +1300,8 @@ impl api::IncomingWebhook for Checkout { } else { // if payment_event, construct PaymentResponse and then serialize it to json and return. let payment_response = checkout::PaymentsResponse::try_from(request)?; - utils::Encode::<checkout::PaymentsResponse>::encode_to_value(&payment_response) + payment_response + .encode_to_value() .change_context(errors::ConnectorError::WebhookResourceObjectNotFound)? }; // Ideally this should be a strict type that has type information diff --git a/crates/router/src/connector/globepay/transformers.rs b/crates/router/src/connector/globepay/transformers.rs index 5cb22890b7c..c988bff52ea 100644 --- a/crates/router/src/connector/globepay/transformers.rs +++ b/crates/router/src/connector/globepay/transformers.rs @@ -1,3 +1,4 @@ +use common_utils::ext_traits::Encode; use error_stack::ResultExt; use masking::Secret; use serde::{Deserialize, Serialize}; @@ -169,11 +170,9 @@ impl<F, T> .qrcode_img .ok_or(errors::ConnectorError::ResponseHandlingFailed)?, }; - let connector_metadata = Some(common_utils::ext_traits::Encode::< - GlobepayConnectorMetadata, - >::encode_to_value(&globepay_metadata)) - .transpose() - .change_context(errors::ConnectorError::ResponseHandlingFailed)?; + let connector_metadata = Some(globepay_metadata.encode_to_value()) + .transpose() + .change_context(errors::ConnectorError::ResponseHandlingFailed)?; let globepay_status = item .response .result_code diff --git a/crates/router/src/connector/noon/transformers.rs b/crates/router/src/connector/noon/transformers.rs index bbd7da234b6..fff99109b28 100644 --- a/crates/router/src/connector/noon/transformers.rs +++ b/crates/router/src/connector/noon/transformers.rs @@ -1,4 +1,4 @@ -use common_utils::pii; +use common_utils::{ext_traits::Encode, pii}; use error_stack::{IntoReport, ResultExt}; use masking::{PeekInterface, Secret}; use serde::{Deserialize, Serialize}; @@ -11,7 +11,6 @@ use crate::{ core::{errors, mandate::MandateBehaviour}, services, types::{self, api, storage::enums, transformers::ForeignFrom, ErrorResponse}, - utils, }; // These needs to be accepted from SDK, need to be done after 1.0.0 stability as API contract will change @@ -271,10 +270,8 @@ impl TryFrom<&types::PaymentsAuthorizeRouterData> for NoonPaymentsRequest { ), }, }; - let payment_token = - utils::Encode::<NoonApplePayTokenData>::encode_to_string_of_json( - &payment_token_data, - ) + let payment_token = payment_token_data + .encode_to_string_of_json() .change_context(errors::ConnectorError::RequestEncodingFailed)?; Ok(NoonPaymentData::ApplePay(NoonApplePay { diff --git a/crates/router/src/connector/nuvei/transformers.rs b/crates/router/src/connector/nuvei/transformers.rs index 4ed6b25b136..d5dd6e813ae 100644 --- a/crates/router/src/connector/nuvei/transformers.rs +++ b/crates/router/src/connector/nuvei/transformers.rs @@ -1,7 +1,9 @@ use api_models::payments; use common_utils::{ crypto::{self, GenerateDigest}, - date_time, fp_utils, pii, + date_time, + ext_traits::Encode, + fp_utils, pii, pii::Email, }; use data_models::mandates::MandateDataType; @@ -433,23 +435,14 @@ impl TryFrom<payments::GooglePayWalletData> for NuveiPaymentsRequest { Ok(Self { payment_option: PaymentOption { card: Some(Card { - external_token: - Some( - ExternalToken { - external_token_provider: ExternalTokenProvider::GooglePay, - mobile_token: - Secret::new( - common_utils::ext_traits::Encode::< - payments::GooglePayWalletData, - >::encode_to_string_of_json( - &utils::GooglePayWalletData::from(gpay_data), - ) - .change_context( - errors::ConnectorError::RequestEncodingFailed, - )?, - ), - }, + external_token: Some(ExternalToken { + external_token_provider: ExternalTokenProvider::GooglePay, + mobile_token: Secret::new( + utils::GooglePayWalletData::from(gpay_data) + .encode_to_string_of_json() + .change_context(errors::ConnectorError::RequestEncodingFailed)?, ), + }), ..Default::default() }), ..Default::default() diff --git a/crates/router/src/connector/payeezy/transformers.rs b/crates/router/src/connector/payeezy/transformers.rs index e8801e3222b..90b4b0b0bba 100644 --- a/crates/router/src/connector/payeezy/transformers.rs +++ b/crates/router/src/connector/payeezy/transformers.rs @@ -407,11 +407,7 @@ impl<F, T> let metadata = item .response .transaction_tag - .map(|txn_tag| { - Encode::<'_, PayeezyPaymentsMetadata>::encode_to_value( - &construct_payeezy_payments_metadata(txn_tag), - ) - }) + .map(|txn_tag| construct_payeezy_payments_metadata(txn_tag).encode_to_value()) .transpose() .change_context(errors::ConnectorError::ResponseHandlingFailed)?; diff --git a/crates/router/src/connector/rapyd.rs b/crates/router/src/connector/rapyd.rs index 9bf5101e8b8..b487740d07d 100644 --- a/crates/router/src/connector/rapyd.rs +++ b/crates/router/src/connector/rapyd.rs @@ -2,7 +2,11 @@ pub mod transformers; use std::fmt::Debug; use base64::Engine; -use common_utils::{date_time, ext_traits::StringExt, request::RequestContent}; +use common_utils::{ + date_time, + ext_traits::{Encode, StringExt}, + request::RequestContent, +}; use diesel_models::enums; use error_stack::{IntoReport, Report, ResultExt}; use masking::{ExposeInterface, PeekInterface}; @@ -938,19 +942,16 @@ impl api::IncomingWebhook for Rapyd { transformers::WebhookData::Payment(payment_data) => { let rapyd_response: transformers::RapydPaymentsResponse = payment_data.into(); - utils::Encode::<transformers::RapydPaymentsResponse>::encode_to_value( - &rapyd_response, - ) - .change_context(errors::ConnectorError::WebhookResourceObjectNotFound)? - } - transformers::WebhookData::Refund(refund_data) => { - utils::Encode::<transformers::RefundResponseData>::encode_to_value(&refund_data) - .change_context(errors::ConnectorError::WebhookResourceObjectNotFound)? - } - transformers::WebhookData::Dispute(dispute_data) => { - utils::Encode::<transformers::DisputeResponseData>::encode_to_value(&dispute_data) + rapyd_response + .encode_to_value() .change_context(errors::ConnectorError::WebhookResourceObjectNotFound)? } + transformers::WebhookData::Refund(refund_data) => refund_data + .encode_to_value() + .change_context(errors::ConnectorError::WebhookResourceObjectNotFound)?, + transformers::WebhookData::Dispute(dispute_data) => dispute_data + .encode_to_value() + .change_context(errors::ConnectorError::WebhookResourceObjectNotFound)?, }; Ok(Box::new(res_json)) } diff --git a/crates/router/src/connector/stripe/transformers.rs b/crates/router/src/connector/stripe/transformers.rs index 6a89232d4e8..8c370317c62 100644 --- a/crates/router/src/connector/stripe/transformers.rs +++ b/crates/router/src/connector/stripe/transformers.rs @@ -3,7 +3,7 @@ use std::{collections::HashMap, ops::Deref}; use api_models::{self, enums as api_enums, payments}; use common_utils::{ errors::CustomResult, - ext_traits::ByteSliceExt, + ext_traits::{ByteSliceExt, Encode}, pii::{self, Email}, request::RequestContent, }; @@ -2437,11 +2437,7 @@ pub fn get_connector_metadata( }, }; - Some(common_utils::ext_traits::Encode::< - SepaAndBacsBankTransferInstructions, - >::encode_to_value( - &bank_transfer_instructions - )) + Some(bank_transfer_instructions.encode_to_value()) } StripeNextActionResponse::WechatPayDisplayQrCode(response) => { let wechat_pay_instructions = QrCodeNextInstructions { @@ -2449,22 +2445,14 @@ pub fn get_connector_metadata( display_to_timestamp: None, }; - Some( - common_utils::ext_traits::Encode::<QrCodeNextInstructions>::encode_to_value( - &wechat_pay_instructions, - ), - ) + Some(wechat_pay_instructions.encode_to_value()) } StripeNextActionResponse::CashappHandleRedirectOrDisplayQrCode(response) => { let cashapp_qr_instructions: QrCodeNextInstructions = QrCodeNextInstructions { image_data_url: response.qr_code.image_url_png.to_owned(), display_to_timestamp: response.qr_code.expires_at.to_owned(), }; - Some( - common_utils::ext_traits::Encode::<QrCodeNextInstructions>::encode_to_value( - &cashapp_qr_instructions, - ), - ) + Some(cashapp_qr_instructions.encode_to_value()) } _ => None, }) @@ -3144,10 +3132,8 @@ impl<F, T> item: types::ResponseRouterData<F, StripeSourceResponse, T, types::PaymentsResponseData>, ) -> Result<Self, Self::Error> { let connector_source_response = item.response.to_owned(); - let connector_metadata = - common_utils::ext_traits::Encode::<StripeSourceResponse>::encode_to_value( - &connector_source_response, - ) + let connector_metadata = connector_source_response + .encode_to_value() .change_context(errors::ConnectorError::ResponseHandlingFailed)?; // We get pending as the status from stripe, but hyperswitch should give it as requires_customer_action as // customer has to make payment to the virtual account number given in the source response @@ -3201,10 +3187,9 @@ impl<F, T> TryFrom<types::ResponseRouterData<F, ChargesResponse, T, types::Payme item: types::ResponseRouterData<F, ChargesResponse, T, types::PaymentsResponseData>, ) -> Result<Self, Self::Error> { let connector_source_response = item.response.to_owned(); - let connector_metadata = - common_utils::ext_traits::Encode::<StripeSourceResponse>::encode_to_value( - &connector_source_response.source, - ) + let connector_metadata = connector_source_response + .source + .encode_to_value() .change_context(errors::ConnectorError::ResponseHandlingFailed)?; let status = enums::AttemptStatus::from(item.response.status); let response = if connector_util::is_payment_failure(status) { diff --git a/crates/router/src/core/admin.rs b/crates/router/src/core/admin.rs index 024ef653faa..4f0ad733805 100644 --- a/crates/router/src/core/admin.rs +++ b/crates/router/src/core/admin.rs @@ -62,36 +62,39 @@ pub async fn create_merchant_account( let publishable_key = Some(create_merchant_publishable_key()); - let primary_business_details = - utils::Encode::<Vec<admin_types::PrimaryBusinessDetails>>::encode_to_value( - &req.primary_business_details.clone().unwrap_or_default(), - ) + let primary_business_details = req + .primary_business_details + .clone() + .unwrap_or_default() + .encode_to_value() .change_context(errors::ApiErrorResponse::InvalidDataValue { field_name: "primary_business_details", })?; - let merchant_details: OptionalSecretValue = - req.merchant_details - .as_ref() - .map(|merchant_details| { - utils::Encode::<api::MerchantDetails>::encode_to_value(merchant_details) - .change_context(errors::ApiErrorResponse::InvalidDataValue { - field_name: "merchant_details", - }) - }) - .transpose()? - .map(Into::into); + let merchant_details: OptionalSecretValue = req + .merchant_details + .as_ref() + .map(|merchant_details| { + merchant_details.encode_to_value().change_context( + errors::ApiErrorResponse::InvalidDataValue { + field_name: "merchant_details", + }, + ) + }) + .transpose()? + .map(Into::into); - let webhook_details = - req.webhook_details - .as_ref() - .map(|webhook_details| { - utils::Encode::<api::WebhookDetails>::encode_to_value(webhook_details) - .change_context(errors::ApiErrorResponse::InvalidDataValue { - field_name: "webhook details", - }) - }) - .transpose()?; + let webhook_details = req + .webhook_details + .as_ref() + .map(|webhook_details| { + webhook_details.encode_to_value().change_context( + errors::ApiErrorResponse::InvalidDataValue { + field_name: "webhook details", + }, + ) + }) + .transpose()?; if let Some(ref routing_algorithm) = req.routing_algorithm { let _: api_models::routing::RoutingAlgorithm = routing_algorithm @@ -134,7 +137,7 @@ pub async fn create_merchant_account( .metadata .as_ref() .map(|meta| { - utils::Encode::<admin_types::MerchantAccountMetadata>::encode_to_value(meta) + meta.encode_to_value() .change_context(errors::ApiErrorResponse::InvalidDataValue { field_name: "metadata", }) @@ -493,12 +496,11 @@ pub async fn merchant_account_update( .primary_business_details .as_ref() .map(|primary_business_details| { - utils::Encode::<Vec<admin_types::PrimaryBusinessDetails>>::encode_to_value( - primary_business_details, + primary_business_details.encode_to_value().change_context( + errors::ApiErrorResponse::InvalidDataValue { + field_name: "primary_business_details", + }, ) - .change_context(errors::ApiErrorResponse::InvalidDataValue { - field_name: "primary_business_details", - }) }) .transpose()?; @@ -548,7 +550,7 @@ pub async fn merchant_account_update( merchant_details: req .merchant_details .as_ref() - .map(utils::Encode::<api::MerchantDetails>::encode_to_value) + .map(utils::Encode::encode_to_value) .transpose() .change_context(errors::ApiErrorResponse::InternalServerError) .attach_printable("Unable to convert merchant_details to a value")? @@ -563,7 +565,7 @@ pub async fn merchant_account_update( webhook_details: req .webhook_details .as_ref() - .map(utils::Encode::<api::WebhookDetails>::encode_to_value) + .map(utils::Encode::encode_to_value) .transpose() .change_context(errors::ApiErrorResponse::InternalServerError)?, @@ -817,7 +819,8 @@ pub async fn create_payment_connector( let payment_methods_enabled = match req.payment_methods_enabled { Some(val) => { for pm in val.into_iter() { - let pm_value = utils::Encode::<api::PaymentMethodsEnabled>::encode_to_value(&pm) + let pm_value = pm + .encode_to_value() .change_context(errors::ApiErrorResponse::InternalServerError) .attach_printable( "Failed while encoding to serde_json::Value, PaymentMethod", @@ -929,8 +932,7 @@ pub async fn create_payment_connector( id: None, connector_webhook_details: match req.connector_webhook_details { Some(connector_webhook_details) => { - Encode::<api_models::admin::MerchantConnectorWebhookDetails>::encode_to_value( - &connector_webhook_details, + connector_webhook_details.encode_to_value( ) .change_context(errors::ApiErrorResponse::InternalServerError) .attach_printable(format!("Failed to serialize api_models::admin::MerchantConnectorWebhookDetails for Merchant: {}", merchant_id)) @@ -1155,9 +1157,7 @@ pub async fn update_payment_connector( let payment_methods_enabled = req.payment_methods_enabled.map(|pm_enabled| { pm_enabled .iter() - .flat_map(|payment_method| { - utils::Encode::<api::PaymentMethodsEnabled>::encode_to_value(payment_method) - }) + .flat_map(Encode::encode_to_value) .collect::<Vec<serde_json::Value>>() }); @@ -1249,14 +1249,11 @@ pub async fn update_payment_connector( metadata: req.metadata, frm_configs, connector_webhook_details: match &req.connector_webhook_details { - Some(connector_webhook_details) => { - Encode::<api_models::admin::MerchantConnectorWebhookDetails>::encode_to_value( - connector_webhook_details, - ) + Some(connector_webhook_details) => connector_webhook_details + .encode_to_value() .change_context(errors::ApiErrorResponse::InternalServerError) .map(Some)? - .map(masking::Secret::new) - } + .map(masking::Secret::new), None => None, }, applepay_verified_domains: None, @@ -1434,7 +1431,8 @@ pub fn get_frm_config_as_secret( let configs_for_frm_value: Vec<Secret<serde_json::Value>> = frm_value .iter() .map(|config| { - utils::Encode::<api_models::admin::FrmConfigs>::encode_to_value(&config) + config + .encode_to_value() .change_context(errors::ApiErrorResponse::ConfigNotFound) .map(masking::Secret::new) }) @@ -1597,7 +1595,7 @@ pub async fn update_business_profile( .webhook_details .as_ref() .map(|webhook_details| { - utils::Encode::<api::WebhookDetails>::encode_to_value(webhook_details).change_context( + webhook_details.encode_to_value().change_context( errors::ApiErrorResponse::InvalidDataValue { field_name: "webhook details", }, @@ -1619,10 +1617,11 @@ pub async fn update_business_profile( .payment_link_config .as_ref() .map(|pl_metadata| { - utils::Encode::<admin_types::BusinessPaymentLinkConfig>::encode_to_value(pl_metadata) - .change_context(errors::ApiErrorResponse::InvalidDataValue { + pl_metadata.encode_to_value().change_context( + errors::ApiErrorResponse::InvalidDataValue { field_name: "payment_link_config", - }) + }, + ) }) .transpose()?; diff --git a/crates/router/src/core/conditional_config.rs b/crates/router/src/core/conditional_config.rs index e30d11ef6f2..26789470c20 100644 --- a/crates/router/src/core/conditional_config.rs +++ b/crates/router/src/core/conditional_config.rs @@ -1,8 +1,8 @@ use api_models::{ conditional_configs::{DecisionManager, DecisionManagerRecord, DecisionManagerResponse}, - routing::{self}, + routing, }; -use common_utils::ext_traits::{StringExt, ValueExt}; +use common_utils::ext_traits::{Encode, StringExt, ValueExt}; use diesel_models::configs; use error_stack::{IntoReport, ResultExt}; use euclid::frontend::ast; @@ -15,7 +15,7 @@ use crate::{ routes::AppState, services::api as service_api, types::domain, - utils::{self, OptionExt}, + utils::OptionExt, }; pub async fn upsert_conditional_config( @@ -86,10 +86,10 @@ pub async fn upsert_conditional_config( created_at: previous_record.created_at, }; - let serialize_updated_str = - utils::Encode::<DecisionManagerRecord>::encode_to_string_of_json(&new_algo) - .change_context(errors::ApiErrorResponse::InternalServerError) - .attach_printable("Unable to serialize config to string")?; + let serialize_updated_str = new_algo + .encode_to_string_of_json() + .change_context(errors::ApiErrorResponse::InternalServerError) + .attach_printable("Unable to serialize config to string")?; let updated_config = configs::ConfigUpdate::Update { config: Some(serialize_updated_str), @@ -121,10 +121,10 @@ pub async fn upsert_conditional_config( created_at: timestamp, }; - let serialized_str = - utils::Encode::<DecisionManagerRecord>::encode_to_string_of_json(&new_rec) - .change_context(errors::ApiErrorResponse::InternalServerError) - .attach_printable("Error serializing the config")?; + let serialized_str = new_rec + .encode_to_string_of_json() + .change_context(errors::ApiErrorResponse::InternalServerError) + .attach_printable("Error serializing the config")?; let new_config = configs::ConfigNew { key: key.clone(), config: serialized_str, diff --git a/crates/router/src/core/connector_onboarding/paypal.rs b/crates/router/src/core/connector_onboarding/paypal.rs index f18681f8cfd..644a2220aee 100644 --- a/crates/router/src/core/connector_onboarding/paypal.rs +++ b/crates/router/src/core/connector_onboarding/paypal.rs @@ -141,10 +141,10 @@ pub async fn update_mca( connector_id: String, auth_details: oss_types::ConnectorAuthType, ) -> RouterResult<oss_api_types::MerchantConnectorResponse> { - let connector_auth_json = - Encode::<oss_types::ConnectorAuthType>::encode_to_value(&auth_details) - .change_context(ApiErrorResponse::InternalServerError) - .attach_printable("Error while deserializing connector_account_details")?; + let connector_auth_json = auth_details + .encode_to_value() + .change_context(ApiErrorResponse::InternalServerError) + .attach_printable("Error while deserializing connector_account_details")?; let request = MerchantConnectorUpdate { connector_type: common_enums::ConnectorType::PaymentProcessor, diff --git a/crates/router/src/core/disputes.rs b/crates/router/src/core/disputes.rs index 285baa33d1a..f53939a8f9d 100644 --- a/crates/router/src/core/disputes.rs +++ b/crates/router/src/core/disputes.rs @@ -1,5 +1,5 @@ use api_models::{disputes as dispute_models, files as files_api_models}; -use common_utils::ext_traits::ValueExt; +use common_utils::ext_traits::{Encode, ValueExt}; use error_stack::{IntoReport, ResultExt}; use router_env::{instrument, tracing}; pub mod transformers; @@ -20,7 +20,6 @@ use crate::{ AcceptDisputeRequestData, AcceptDisputeResponse, DefendDisputeRequestData, DefendDisputeResponse, SubmitEvidenceRequestData, SubmitEvidenceResponse, }, - utils, }; #[instrument(skip(state))] @@ -384,7 +383,8 @@ pub async fn attach_evidence( file_id, ); let update_dispute = diesel_models::dispute::DisputeUpdate::EvidenceUpdate { - evidence: utils::Encode::<api::DisputeEvidence>::encode_to_value(&updated_dispute_evidence) + evidence: updated_dispute_evidence + .encode_to_value() .change_context(errors::ApiErrorResponse::InternalServerError) .attach_printable("Error while encoding dispute evidence")? .into(), @@ -446,7 +446,8 @@ pub async fn delete_evidence( let updated_dispute_evidence = transformers::delete_evidence_file(dispute_evidence, delete_evidence_request.evidence_type); let update_dispute = diesel_models::dispute::DisputeUpdate::EvidenceUpdate { - evidence: utils::Encode::<api::DisputeEvidence>::encode_to_value(&updated_dispute_evidence) + evidence: updated_dispute_evidence + .encode_to_value() .change_context(errors::ApiErrorResponse::InternalServerError) .attach_printable("Error while encoding dispute evidence")? .into(), diff --git a/crates/router/src/core/fraud_check/operation/fraud_check_post.rs b/crates/router/src/core/fraud_check/operation/fraud_check_post.rs index 8bb8a61402e..95349e44755 100644 --- a/crates/router/src/core/fraud_check/operation/fraud_check_post.rs +++ b/crates/router/src/core/fraud_check/operation/fraud_check_post.rs @@ -77,9 +77,9 @@ impl GetTracker<PaymentToFrmData> for FraudCheckPost { ) -> RouterResult<Option<FrmData>> { let db = &*state.store; - let payment_details: Option<serde_json::Value> = - Encode::<PaymentDetails>::encode_to_value(&PaymentDetails::from(payment_data.clone())) - .ok(); + let payment_details: Option<serde_json::Value> = PaymentDetails::from(payment_data.clone()) + .encode_to_value() + .ok(); let existing_fraud_check = db .find_fraud_check_by_payment_id_if_present( payment_data.payment_intent.payment_id.clone(), diff --git a/crates/router/src/core/fraud_check/operation/fraud_check_pre.rs b/crates/router/src/core/fraud_check/operation/fraud_check_pre.rs index b92df3d3ef9..ed582574bf5 100644 --- a/crates/router/src/core/fraud_check/operation/fraud_check_pre.rs +++ b/crates/router/src/core/fraud_check/operation/fraud_check_pre.rs @@ -72,9 +72,9 @@ impl GetTracker<PaymentToFrmData> for FraudCheckPre { ) -> RouterResult<Option<FrmData>> { let db = &*state.store; - let payment_details: Option<serde_json::Value> = - Encode::<PaymentDetails>::encode_to_value(&PaymentDetails::from(payment_data.clone())) - .ok(); + let payment_details: Option<serde_json::Value> = PaymentDetails::from(payment_data.clone()) + .encode_to_value() + .ok(); let existing_fraud_check = db .find_fraud_check_by_payment_id_if_present( diff --git a/crates/router/src/core/mandate.rs b/crates/router/src/core/mandate.rs index d58eae371e8..ec3bb7e4299 100644 --- a/crates/router/src/core/mandate.rs +++ b/crates/router/src/core/mandate.rs @@ -162,7 +162,7 @@ pub async fn update_connector_mandate_id( let connector_mandate_id = mandate_details .clone() .map(|md| { - Encode::<types::MandateReference>::encode_to_value(&md) + md.encode_to_value() .change_context(errors::ApiErrorResponse::InternalServerError) .map(masking::Secret::new) }) @@ -288,10 +288,10 @@ where update_history: Some(update_history), }; - let connector_mandate_ids = - Encode::<types::MandateReference>::encode_to_value(&updated_mandate_ref) - .change_context(errors::ApiErrorResponse::InternalServerError) - .map(masking::Secret::new)?; + let connector_mandate_ids = updated_mandate_ref + .encode_to_value() + .change_context(errors::ApiErrorResponse::InternalServerError) + .map(masking::Secret::new)?; let _update_mandate_details = state .store @@ -384,7 +384,7 @@ where let mandate_ids = mandate_reference .as_ref() .map(|md| { - Encode::<types::MandateReference>::encode_to_value(&md) + md.encode_to_value() .change_context( errors::ApiErrorResponse::MandateSerializationFailed, ) diff --git a/crates/router/src/core/payment_methods/cards.rs b/crates/router/src/core/payment_methods/cards.rs index 4f6d6b4c62b..823d0e321d9 100644 --- a/crates/router/src/core/payment_methods/cards.rs +++ b/crates/router/src/core/payment_methods/cards.rs @@ -18,7 +18,7 @@ use api_models::{ }; use common_utils::{ consts, - ext_traits::{AsyncExt, StringExt, ValueExt}, + ext_traits::{AsyncExt, Encode, StringExt, ValueExt}, generate_id, }; use diesel_models::{ @@ -1568,7 +1568,8 @@ pub async fn list_payment_methods( routing_info.pre_routing_results = Some(pre_routing_results); - let encoded = utils::Encode::<storage::PaymentRoutingInfo>::encode_to_value(&routing_info) + let encoded = routing_info + .encode_to_value() .change_context(errors::ApiErrorResponse::InternalServerError) .attach_printable("Unable to serialize payment routing info to value")?; @@ -3220,11 +3221,13 @@ impl TempLockerCardSupport { let value1 = vault::VaultPaymentMethod::Card(value1); let value2 = vault::VaultPaymentMethod::Card(value2); - let value1 = utils::Encode::<vault::VaultPaymentMethod>::encode_to_string_of_json(&value1) + let value1 = value1 + .encode_to_string_of_json() .change_context(errors::ApiErrorResponse::InternalServerError) .attach_printable("Wrapped value1 construction failed when saving card to locker")?; - let value2 = utils::Encode::<vault::VaultPaymentMethod>::encode_to_string_of_json(&value2) + let value2 = value2 + .encode_to_string_of_json() .change_context(errors::ApiErrorResponse::InternalServerError) .attach_printable("Wrapped value2 construction failed when saving card to locker")?; @@ -3359,7 +3362,7 @@ pub async fn create_encrypted_payment_method_data( let pm_data_encrypted: Option<Encryption> = pm_data .as_ref() - .map(utils::Encode::<PaymentMethodsData>::encode_to_value) + .map(utils::Encode::encode_to_value) .transpose() .change_context(errors::StorageError::SerializationFailed) .attach_printable("Unable to convert payment method data to a value") diff --git a/crates/router/src/core/payment_methods/transformers.rs b/crates/router/src/core/payment_methods/transformers.rs index 59b02d01933..e6d447b5497 100644 --- a/crates/router/src/core/payment_methods/transformers.rs +++ b/crates/router/src/core/payment_methods/transformers.rs @@ -1,7 +1,11 @@ use std::str::FromStr; use api_models::enums as api_enums; -use common_utils::{ext_traits::StringExt, pii::Email, request::RequestContent}; +use common_utils::{ + ext_traits::{Encode, StringExt}, + pii::Email, + request::RequestContent, +}; use error_stack::ResultExt; use josekit::jwe; use serde::{Deserialize, Serialize}; @@ -13,7 +17,7 @@ use crate::{ pii::{prelude::*, Secret}, services::{api as services, encryption}, types::{api, storage}, - utils::{self, OptionExt}, + utils::OptionExt, }; #[derive(Debug, Serialize)] @@ -261,7 +265,8 @@ pub async fn mk_basilisk_req( let jws_body = generate_jws_body(jws_payload).ok_or(errors::VaultError::SaveCardFailed)?; - let payload = utils::Encode::<encryption::JwsBody>::encode_to_vec(&jws_body) + let payload = jws_body + .encode_to_vec() .change_context(errors::VaultError::SaveCardFailed)?; #[cfg(feature = "aws_kms")] @@ -306,7 +311,8 @@ pub async fn mk_add_locker_request_hs<'a>( payload: &StoreLockerReq<'a>, locker_choice: api_enums::LockerChoice, ) -> CustomResult<services::Request, errors::VaultError> { - let payload = utils::Encode::<StoreLockerReq<'_>>::encode_to_vec(&payload) + let payload = payload + .encode_to_vec() .change_context(errors::VaultError::RequestEncodingFailed)?; #[cfg(feature = "aws_kms")] @@ -484,7 +490,8 @@ pub async fn mk_get_card_request_hs( merchant_customer_id, card_reference: card_reference.to_owned(), }; - let payload = utils::Encode::<CardReqBody<'_>>::encode_to_vec(&card_req_body) + let payload = card_req_body + .encode_to_vec() .change_context(errors::VaultError::RequestEncodingFailed)?; #[cfg(feature = "aws_kms")] @@ -560,7 +567,8 @@ pub async fn mk_delete_card_request_hs( merchant_customer_id, card_reference: card_reference.to_owned(), }; - let payload = utils::Encode::<CardReqBody<'_>>::encode_to_vec(&card_req_body) + let payload = card_req_body + .encode_to_vec() .change_context(errors::VaultError::RequestEncodingFailed)?; #[cfg(feature = "aws_kms")] @@ -672,7 +680,8 @@ pub fn mk_card_value1( card_last_four, card_token, }; - let value1_req = utils::Encode::<api::TokenizedCardValue1>::encode_to_string_of_json(&value1) + let value1_req = value1 + .encode_to_string_of_json() .change_context(errors::VaultError::FetchCardFailed)?; Ok(value1_req) } @@ -691,7 +700,8 @@ pub fn mk_card_value2( customer_id, payment_method_id, }; - let value2_req = utils::Encode::<api::TokenizedCardValue2>::encode_to_string_of_json(&value2) + let value2_req = value2 + .encode_to_string_of_json() .change_context(errors::VaultError::FetchCardFailed)?; Ok(value2_req) } diff --git a/crates/router/src/core/payment_methods/vault.rs b/crates/router/src/core/payment_methods/vault.rs index 25bac8086d7..b547027a1c7 100644 --- a/crates/router/src/core/payment_methods/vault.rs +++ b/crates/router/src/core/payment_methods/vault.rs @@ -1,6 +1,6 @@ use common_utils::{ crypto::{DecodeMessage, EncodeMessage, GcmAes256}, - ext_traits::BytesExt, + ext_traits::{BytesExt, Encode}, generate_id_with_default_len, }; use error_stack::{report, IntoReport, ResultExt}; @@ -19,7 +19,7 @@ use crate::{ api, domain, storage::{self, enums, ProcessTrackerExt}, }, - utils::{self, StringExt}, + utils::StringExt, }; const VAULT_SERVICE_NAME: &str = "CARD"; @@ -54,7 +54,8 @@ impl Vaultable for api::Card { card_token: None, }; - utils::Encode::<api::TokenizedCardValue1>::encode_to_string_of_json(&value1) + value1 + .encode_to_string_of_json() .change_context(errors::VaultError::RequestEncodingFailed) .attach_printable("Failed to encode card value1") } @@ -68,7 +69,8 @@ impl Vaultable for api::Card { payment_method_id: None, }; - utils::Encode::<api::TokenizedCardValue2>::encode_to_string_of_json(&value2) + value2 + .encode_to_string_of_json() .change_context(errors::VaultError::RequestEncodingFailed) .attach_printable("Failed to encode card value2") } @@ -121,7 +123,8 @@ impl Vaultable for api_models::payments::BankTransferData { data: self.to_owned(), }; - utils::Encode::<api_models::payment_methods::TokenizedBankTransferValue1>::encode_to_string_of_json(&value1) + value1 + .encode_to_string_of_json() .change_context(errors::VaultError::RequestEncodingFailed) .attach_printable("Failed to encode bank transfer data") } @@ -129,7 +132,8 @@ impl Vaultable for api_models::payments::BankTransferData { fn get_value2(&self, customer_id: Option<String>) -> CustomResult<String, errors::VaultError> { let value2 = api_models::payment_methods::TokenizedBankTransferValue2 { customer_id }; - utils::Encode::<api_models::payment_methods::TokenizedBankTransferValue2>::encode_to_string_of_json(&value2) + value2 + .encode_to_string_of_json() .change_context(errors::VaultError::RequestEncodingFailed) .attach_printable("Failed to encode bank transfer supplementary data") } @@ -165,7 +169,8 @@ impl Vaultable for api::WalletData { data: self.to_owned(), }; - utils::Encode::<api::TokenizedWalletValue1>::encode_to_string_of_json(&value1) + value1 + .encode_to_string_of_json() .change_context(errors::VaultError::RequestEncodingFailed) .attach_printable("Failed to encode wallet data value1") } @@ -173,7 +178,8 @@ impl Vaultable for api::WalletData { fn get_value2(&self, customer_id: Option<String>) -> CustomResult<String, errors::VaultError> { let value2 = api::TokenizedWalletValue2 { customer_id }; - utils::Encode::<api::TokenizedWalletValue2>::encode_to_string_of_json(&value2) + value2 + .encode_to_string_of_json() .change_context(errors::VaultError::RequestEncodingFailed) .attach_printable("Failed to encode wallet data value2") } @@ -209,7 +215,8 @@ impl Vaultable for api_models::payments::BankRedirectData { data: self.to_owned(), }; - utils::Encode::<api_models::payment_methods::TokenizedBankRedirectValue1>::encode_to_string_of_json(&value1) + value1 + .encode_to_string_of_json() .change_context(errors::VaultError::RequestEncodingFailed) .attach_printable("Failed to encode bank redirect data") } @@ -217,7 +224,8 @@ impl Vaultable for api_models::payments::BankRedirectData { fn get_value2(&self, customer_id: Option<String>) -> CustomResult<String, errors::VaultError> { let value2 = api_models::payment_methods::TokenizedBankRedirectValue2 { customer_id }; - utils::Encode::<api_models::payment_methods::TokenizedBankRedirectValue2>::encode_to_string_of_json(&value2) + value2 + .encode_to_string_of_json() .change_context(errors::VaultError::RequestEncodingFailed) .attach_printable("Failed to encode bank redirect supplementary data") } @@ -272,7 +280,8 @@ impl Vaultable for api::PaymentMethodData { .attach_printable("Payment method not supported")?, }; - utils::Encode::<VaultPaymentMethod>::encode_to_string_of_json(&value1) + value1 + .encode_to_string_of_json() .change_context(errors::VaultError::RequestEncodingFailed) .attach_printable("Failed to encode payment method value1") } @@ -292,7 +301,8 @@ impl Vaultable for api::PaymentMethodData { .attach_printable("Payment method not supported")?, }; - utils::Encode::<VaultPaymentMethod>::encode_to_string_of_json(&value2) + value2 + .encode_to_string_of_json() .change_context(errors::VaultError::RequestEncodingFailed) .attach_printable("Failed to encode payment method value2") } @@ -357,7 +367,8 @@ impl Vaultable for api::CardPayout { card_token: None, }; - utils::Encode::<api::TokenizedCardValue1>::encode_to_string_of_json(&value1) + value1 + .encode_to_string_of_json() .change_context(errors::VaultError::RequestEncodingFailed) .attach_printable("Failed to encode card value1") } @@ -371,7 +382,8 @@ impl Vaultable for api::CardPayout { payment_method_id: None, }; - utils::Encode::<api::TokenizedCardValue2>::encode_to_string_of_json(&value2) + value2 + .encode_to_string_of_json() .change_context(errors::VaultError::RequestEncodingFailed) .attach_printable("Failed to encode card value2") } @@ -420,7 +432,8 @@ impl Vaultable for api::WalletPayout { }, }; - utils::Encode::<api::TokenizedWalletValue1>::encode_to_string_of_json(&value1) + value1 + .encode_to_string_of_json() .change_context(errors::VaultError::RequestEncodingFailed) .attach_printable("Failed to encode wallet value1") } @@ -428,7 +441,8 @@ impl Vaultable for api::WalletPayout { fn get_value2(&self, customer_id: Option<String>) -> CustomResult<String, errors::VaultError> { let value2 = api::TokenizedWalletValue2 { customer_id }; - utils::Encode::<api::TokenizedWalletValue2>::encode_to_string_of_json(&value2) + value2 + .encode_to_string_of_json() .change_context(errors::VaultError::RequestEncodingFailed) .attach_printable("Failed to encode wallet value2") } @@ -509,11 +523,10 @@ impl Vaultable for api::BankPayout { }, }; - utils::Encode::<TokenizedBankSensitiveValues>::encode_to_string_of_json( - &bank_sensitive_data, - ) - .change_context(errors::VaultError::RequestEncodingFailed) - .attach_printable("Failed to encode wallet data bank_sensitive_data") + bank_sensitive_data + .encode_to_string_of_json() + .change_context(errors::VaultError::RequestEncodingFailed) + .attach_printable("Failed to encode wallet data bank_sensitive_data") } fn get_value2(&self, customer_id: Option<String>) -> CustomResult<String, errors::VaultError> { @@ -538,11 +551,10 @@ impl Vaultable for api::BankPayout { }, }; - utils::Encode::<TokenizedBankInsensitiveValues>::encode_to_string_of_json( - &bank_insensitive_data, - ) - .change_context(errors::VaultError::RequestEncodingFailed) - .attach_printable("Failed to encode wallet data bank_insensitive_data") + bank_insensitive_data + .encode_to_string_of_json() + .change_context(errors::VaultError::RequestEncodingFailed) + .attach_printable("Failed to encode wallet data bank_insensitive_data") } fn from_values( @@ -619,7 +631,8 @@ impl Vaultable for api::PayoutMethodData { Self::Wallet(wallet) => VaultPayoutMethod::Wallet(wallet.get_value1(customer_id)?), }; - utils::Encode::<VaultPaymentMethod>::encode_to_string_of_json(&value1) + value1 + .encode_to_string_of_json() .change_context(errors::VaultError::RequestEncodingFailed) .attach_printable("Failed to encode payout method value1") } @@ -631,7 +644,8 @@ impl Vaultable for api::PayoutMethodData { Self::Wallet(wallet) => VaultPayoutMethod::Wallet(wallet.get_value2(customer_id)?), }; - utils::Encode::<VaultPaymentMethod>::encode_to_string_of_json(&value2) + value2 + .encode_to_string_of_json() .change_context(errors::VaultError::RequestEncodingFailed) .attach_printable("Failed to encode payout method value2") } @@ -822,10 +836,9 @@ pub async fn create_tokenize( service_name: VAULT_SERVICE_NAME.to_string(), }; - let payload = utils::Encode::<api::TokenizePayloadRequest>::encode_to_string_of_json( - &payload_to_be_encrypted, - ) - .change_context(errors::ApiErrorResponse::InternalServerError)?; + let payload = payload_to_be_encrypted + .encode_to_string_of_json() + .change_context(errors::ApiErrorResponse::InternalServerError)?; let encrypted_payload = GcmAes256 .encode_message(encryption_key.peek().as_ref(), payload.as_bytes()) diff --git a/crates/router/src/core/payments.rs b/crates/router/src/core/payments.rs index 38f2df57063..7348a2b8f0c 100644 --- a/crates/router/src/core/payments.rs +++ b/crates/router/src/core/payments.rs @@ -2553,10 +2553,11 @@ where ) .await?; - let encoded_info = - Encode::<storage::PaymentRoutingInfo>::encode_to_value(&routing_data.routing_info) - .change_context(errors::ApiErrorResponse::InternalServerError) - .attach_printable("error serializing payment routing info to serde value")?; + let encoded_info = routing_data + .routing_info + .encode_to_value() + .change_context(errors::ApiErrorResponse::InternalServerError) + .attach_printable("error serializing payment routing info to serde value")?; payment_data.payment_attempt.connector = routing_data.routed_through; #[cfg(feature = "connector_choice_mca_id")] diff --git a/crates/router/src/core/payments/operations/payment_complete_authorize.rs b/crates/router/src/core/payments/operations/payment_complete_authorize.rs index 2a0aa793385..6bbe1c89a47 100644 --- a/crates/router/src/core/payments/operations/payment_complete_authorize.rs +++ b/crates/router/src/core/payments/operations/payment_complete_authorize.rs @@ -18,7 +18,6 @@ use crate::{ routes::AppState, services, types::{ - self, api::{self, PaymentIdTypeExt}, domain, storage::{self, enums as storage_enums}, @@ -91,7 +90,8 @@ impl<F: Send + Clone, Ctx: PaymentMethodRetrieve> let browser_info = request .browser_info .clone() - .map(|x| utils::Encode::<types::BrowserInformation>::encode_to_value(&x)) + .as_ref() + .map(utils::Encode::encode_to_value) .transpose() .change_context(errors::ApiErrorResponse::InvalidDataValue { field_name: "browser_info", diff --git a/crates/router/src/core/payments/operations/payment_confirm.rs b/crates/router/src/core/payments/operations/payment_confirm.rs index 8349f050135..734839c9b6d 100644 --- a/crates/router/src/core/payments/operations/payment_confirm.rs +++ b/crates/router/src/core/payments/operations/payment_confirm.rs @@ -25,7 +25,6 @@ use crate::{ routes::AppState, services, types::{ - self, api::{self, PaymentIdTypeExt}, domain, storage::{self, enums as storage_enums}, @@ -354,7 +353,8 @@ impl<F: Send + Clone, Ctx: PaymentMethodRetrieve> .browser_info .clone() .or(payment_attempt.browser_info) - .map(|x| utils::Encode::<types::BrowserInformation>::encode_to_value(&x)) + .as_ref() + .map(Encode::encode_to_value) .transpose() .change_context(errors::ApiErrorResponse::InvalidDataValue { field_name: "browser_info", @@ -697,7 +697,7 @@ impl<F: Clone, Ctx: PaymentMethodRetrieve> }) .await .as_ref() - .map(Encode::<api_models::payments::AdditionalPaymentData>::encode_to_value) + .map(Encode::encode_to_value) .transpose() .change_context(errors::ApiErrorResponse::InternalServerError) .attach_printable("Failed to encode additional pm data")?; diff --git a/crates/router/src/core/payments/operations/payment_create.rs b/crates/router/src/core/payments/operations/payment_create.rs index 0f581be3089..2eaa11f44ee 100644 --- a/crates/router/src/core/payments/operations/payment_create.rs +++ b/crates/router/src/core/payments/operations/payment_create.rs @@ -149,9 +149,8 @@ impl<F: Send + Clone, Ctx: PaymentMethodRetrieve> let browser_info = request .browser_info .clone() - .map(|x| { - common_utils::ext_traits::Encode::<types::BrowserInformation>::encode_to_value(&x) - }) + .as_ref() + .map(Encode::encode_to_value) .transpose() .change_context(errors::ApiErrorResponse::InvalidDataValue { field_name: "browser_info", @@ -708,7 +707,7 @@ impl PaymentCreate { .await; let additional_pm_data_value = additional_pm_data .as_ref() - .map(Encode::<api_models::payments::AdditionalPaymentData>::encode_to_value) + .map(Encode::encode_to_value) .transpose() .change_context(errors::ApiErrorResponse::InternalServerError) .attach_printable("Failed to encode additional pm data")?; @@ -933,12 +932,11 @@ async fn create_payment_link( payment_id.clone() ); - let payment_link_config_encoded_value = common_utils::ext_traits::Encode::< - api_models::admin::PaymentLinkConfig, - >::encode_to_value(&payment_link_config) - .change_context(errors::ApiErrorResponse::InvalidDataValue { - field_name: "payment_link_config", - })?; + let payment_link_config_encoded_value = payment_link_config.encode_to_value().change_context( + errors::ApiErrorResponse::InvalidDataValue { + field_name: "payment_link_config", + }, + )?; let payment_link_req = storage::PaymentLinkNew { payment_link_id: payment_link_id.clone(), diff --git a/crates/router/src/core/payments/operations/payment_response.rs b/crates/router/src/core/payments/operations/payment_response.rs index 0666c921422..6bd6ca91100 100644 --- a/crates/router/src/core/payments/operations/payment_response.rs +++ b/crates/router/src/core/payments/operations/payment_response.rs @@ -2,6 +2,7 @@ use std::collections::HashMap; use async_trait::async_trait; use common_enums::AuthorizationStatus; +use common_utils::ext_traits::Encode; use data_models::payments::payment_attempt::PaymentAttempt; use error_stack::{report, IntoReport, ResultExt}; use futures::FutureExt; @@ -21,7 +22,6 @@ use crate::{ utils as core_utils, }, routes::{metrics, AppState}, - services::RedirectForm, types::{ self, api, storage::{self, enums}, @@ -590,7 +590,8 @@ async fn payment_response_update_tracker<F: Clone, T: types::Capturable>( let encoded_data = payment_data.payment_attempt.encoded_data.clone(); let authentication_data = redirection_data - .map(|data| utils::Encode::<RedirectForm>::encode_to_value(&data)) + .as_ref() + .map(Encode::encode_to_value) .transpose() .change_context(errors::ApiErrorResponse::InternalServerError) .attach_printable("Could not parse the connector response")?; diff --git a/crates/router/src/core/payments/operations/payment_update.rs b/crates/router/src/core/payments/operations/payment_update.rs index 4e301302abc..0ec11e39f62 100644 --- a/crates/router/src/core/payments/operations/payment_update.rs +++ b/crates/router/src/core/payments/operations/payment_update.rs @@ -520,7 +520,7 @@ impl<F: Clone, Ctx: PaymentMethodRetrieve> }) .await .as_ref() - .map(Encode::<api_models::payments::AdditionalPaymentData>::encode_to_value) + .map(Encode::encode_to_value) .transpose() .change_context(errors::ApiErrorResponse::InternalServerError) .attach_printable("Failed to encode additional pm data")?; diff --git a/crates/router/src/core/payments/retry.rs b/crates/router/src/core/payments/retry.rs index 8d74eb3fa96..91b6061c111 100644 --- a/crates/router/src/core/payments/retry.rs +++ b/crates/router/src/core/payments/retry.rs @@ -1,5 +1,6 @@ use std::{str::FromStr, vec::IntoIter}; +use common_utils::ext_traits::Encode; use diesel_models::enums as storage_enums; use error_stack::{IntoReport, ResultExt}; use router_env::{ @@ -20,8 +21,7 @@ use crate::{ db::StorageInterface, routes, routes::{app, metrics}, - services::{self, RedirectForm}, - types, + services, types, types::{api, domain, storage}, utils, }; @@ -352,7 +352,8 @@ where let encoded_data = payment_data.payment_attempt.encoded_data.clone(); let authentication_data = redirection_data - .map(|data| utils::Encode::<RedirectForm>::encode_to_value(&data)) + .as_ref() + .map(Encode::encode_to_value) .transpose() .change_context(errors::ApiErrorResponse::InternalServerError) .attach_printable("Could not parse the connector response")?; diff --git a/crates/router/src/core/payments/types.rs b/crates/router/src/core/payments/types.rs index 41a8850ab3d..e957fe5faa5 100644 --- a/crates/router/src/core/payments/types.rs +++ b/crates/router/src/core/payments/types.rs @@ -336,7 +336,8 @@ impl SurchargeMetadata { for (key, value) in self.get_individual_surcharge_key_value_pairs().into_iter() { value_list.push(( key, - Encode::<SurchargeDetails>::encode_to_string_of_json(&value) + value + .encode_to_string_of_json() .change_context(errors::ApiErrorResponse::InternalServerError) .attach_printable("Failed to encode to string of json")?, )); diff --git a/crates/router/src/core/routing.rs b/crates/router/src/core/routing.rs index e9ddcb4a563..c544a987ba8 100644 --- a/crates/router/src/core/routing.rs +++ b/crates/router/src/core/routing.rs @@ -162,10 +162,10 @@ pub async fn create_routing_config( #[cfg(not(feature = "business_profile_routing"))] { - let algorithm_str = - utils::Encode::<routing_types::RoutingAlgorithm>::encode_to_string_of_json(&algorithm) - .change_context(errors::ApiErrorResponse::InternalServerError) - .attach_printable("Unable to serialize routing algorithm to string")?; + let algorithm_str = algorithm + .encode_to_string_of_json() + .change_context(errors::ApiErrorResponse::InternalServerError) + .attach_printable("Unable to serialize routing algorithm to string")?; let mut algorithm_ref: routing_types::RoutingAlgorithmRef = merchant_account .routing_algorithm @@ -548,10 +548,10 @@ pub async fn unlink_routing_config( ) .await?; - let ref_value = - Encode::<routing_types::RoutingAlgorithmRef>::encode_to_value(&routing_algorithm) - .change_context(errors::ApiErrorResponse::InternalServerError) - .attach_printable("Failed converting routing algorithm ref to json value")?; + let ref_value = routing_algorithm + .encode_to_value() + .change_context(errors::ApiErrorResponse::InternalServerError) + .attach_printable("Failed converting routing algorithm ref to json value")?; let merchant_account_update = storage::MerchantAccountUpdate::Update { merchant_name: None, diff --git a/crates/router/src/core/routing/helpers.rs b/crates/router/src/core/routing/helpers.rs index c86e527b00d..71010e9bf8b 100644 --- a/crates/router/src/core/routing/helpers.rs +++ b/crates/router/src/core/routing/helpers.rs @@ -15,7 +15,7 @@ use crate::{ core::errors::{self, RouterResult}, db::StorageInterface, types::{domain, storage}, - utils::{self, StringExt}, + utils::StringExt, }; /// provides the complete merchant routing dictionary that is basically a list of all the routing @@ -42,10 +42,8 @@ pub async fn get_merchant_routing_dictionary( records: Vec::new(), }; - let serialized = - utils::Encode::<routing_types::RoutingDictionary>::encode_to_string_of_json( - &new_dictionary, - ) + let serialized = new_dictionary + .encode_to_string_of_json() .change_context(errors::ApiErrorResponse::InternalServerError) .attach_printable("Error serializing newly created merchant dictionary")?; @@ -86,10 +84,8 @@ pub async fn get_merchant_default_config( Err(e) if e.current_context().is_db_not_found() => { let new_config_conns = Vec::<routing_types::RoutableConnectorChoice>::new(); - let serialized = - utils::Encode::<Vec<routing_types::RoutableConnectorChoice>>::encode_to_string_of_json( - &new_config_conns, - ) + let serialized = new_config_conns + .encode_to_string_of_json() .change_context(errors::ApiErrorResponse::InternalServerError) .attach_printable( "Error while creating and serializing new merchant default config", @@ -122,10 +118,8 @@ pub async fn update_merchant_default_config( connectors: Vec<routing_types::RoutableConnectorChoice>, ) -> RouterResult<()> { let key = get_default_config_key(merchant_id); - let config_str = - Encode::<Vec<routing_types::RoutableConnectorChoice>>::encode_to_string_of_json( - &connectors, - ) + let config_str = connectors + .encode_to_string_of_json() .change_context(errors::ApiErrorResponse::InternalServerError) .attach_printable("Unable to serialize merchant default routing config during update")?; @@ -147,10 +141,10 @@ pub async fn update_merchant_routing_dictionary( dictionary: routing_types::RoutingDictionary, ) -> RouterResult<()> { let key = get_routing_dictionary_key(merchant_id); - let dictionary_str = - Encode::<routing_types::RoutingDictionary>::encode_to_string_of_json(&dictionary) - .change_context(errors::ApiErrorResponse::InternalServerError) - .attach_printable("Unable to serialize routing dictionary during update")?; + let dictionary_str = dictionary + .encode_to_string_of_json() + .change_context(errors::ApiErrorResponse::InternalServerError) + .attach_printable("Unable to serialize routing dictionary during update")?; let config_update = configs::ConfigUpdate::Update { config: Some(dictionary_str), @@ -169,10 +163,10 @@ pub async fn update_routing_algorithm( algorithm_id: String, algorithm: routing_types::RoutingAlgorithm, ) -> RouterResult<()> { - let algorithm_str = - Encode::<routing_types::RoutingAlgorithm>::encode_to_string_of_json(&algorithm) - .change_context(errors::ApiErrorResponse::InternalServerError) - .attach_printable("Unable to serialize routing algorithm to string")?; + 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), @@ -193,7 +187,8 @@ pub async fn update_merchant_active_algorithm_ref( key_store: &domain::MerchantKeyStore, algorithm_id: routing_types::RoutingAlgorithmRef, ) -> RouterResult<()> { - let ref_value = Encode::<routing_types::RoutingAlgorithmRef>::encode_to_value(&algorithm_id) + let ref_value = algorithm_id + .encode_to_value() .change_context(errors::ApiErrorResponse::InternalServerError) .attach_printable("Failed converting routing algorithm ref to json value")?; @@ -236,7 +231,8 @@ pub async fn update_business_profile_active_algorithm_ref( current_business_profile: BusinessProfile, algorithm_id: routing_types::RoutingAlgorithmRef, ) -> RouterResult<()> { - let ref_val = Encode::<routing_types::RoutingAlgorithmRef>::encode_to_value(&algorithm_id) + let ref_val = algorithm_id + .encode_to_value() .change_context(errors::ApiErrorResponse::InternalServerError) .attach_printable("Failed to convert routing ref to value")?; @@ -282,10 +278,8 @@ pub async fn get_merchant_connector_agnostic_mandate_config( Err(e) if e.current_context().is_db_not_found() => { let new_mandate_config: Vec<routing_types::DetailedConnectorChoice> = Vec::new(); - let serialized = - utils::Encode::<Vec<routing_types::DetailedConnectorChoice>>::encode_to_string_of_json( - &new_mandate_config, - ) + let serialized = new_mandate_config + .encode_to_string_of_json() .change_context(errors::ApiErrorResponse::InternalServerError) .attach_printable("error serializing newly created pg agnostic mandate config")?; @@ -314,10 +308,8 @@ pub async fn update_merchant_connector_agnostic_mandate_config( mandate_config: Vec<routing_types::DetailedConnectorChoice>, ) -> RouterResult<Vec<routing_types::DetailedConnectorChoice>> { let key = get_pg_agnostic_mandate_config_key(merchant_id); - let mandate_config_str = - Encode::<Vec<routing_types::DetailedConnectorChoice>>::encode_to_string_of_json( - &mandate_config, - ) + let mandate_config_str = mandate_config + .encode_to_string_of_json() .change_context(errors::ApiErrorResponse::InternalServerError) .attach_printable("unable to serialize pg agnostic mandate config during update")?; diff --git a/crates/router/src/core/surcharge_decision_config.rs b/crates/router/src/core/surcharge_decision_config.rs index 82615aef284..a17be6ce36e 100644 --- a/crates/router/src/core/surcharge_decision_config.rs +++ b/crates/router/src/core/surcharge_decision_config.rs @@ -1,11 +1,11 @@ use api_models::{ - routing::{self}, + routing, surcharge_decision_configs::{ SurchargeDecisionConfigReq, SurchargeDecisionManagerRecord, SurchargeDecisionManagerResponse, }, }; -use common_utils::ext_traits::{StringExt, ValueExt}; +use common_utils::ext_traits::{Encode, StringExt, ValueExt}; use diesel_models::configs; use error_stack::{IntoReport, ResultExt}; use euclid::frontend::ast; @@ -18,7 +18,7 @@ use crate::{ routes::AppState, services::api as service_api, types::domain, - utils::{self, OptionExt}, + utils::OptionExt, }; pub async fn upsert_surcharge_decision_config( @@ -75,10 +75,8 @@ pub async fn upsert_surcharge_decision_config( merchant_surcharge_configs, }; - let serialize_updated_str = - utils::Encode::<SurchargeDecisionManagerRecord>::encode_to_string_of_json( - &new_algo, - ) + let serialize_updated_str = new_algo + .encode_to_string_of_json() .change_context(errors::ApiErrorResponse::InternalServerError) .attach_printable("Unable to serialize config to string")?; @@ -113,10 +111,10 @@ pub async fn upsert_surcharge_decision_config( created_at: timestamp, }; - let serialized_str = - utils::Encode::<SurchargeDecisionManagerRecord>::encode_to_string_of_json(&new_rec) - .change_context(errors::ApiErrorResponse::InternalServerError) - .attach_printable("Error serializing the config")?; + let serialized_str = new_rec + .encode_to_string_of_json() + .change_context(errors::ApiErrorResponse::InternalServerError) + .attach_printable("Error serializing the config")?; let new_config = configs::ConfigNew { key: key.clone(), config: serialized_str, diff --git a/crates/router/src/core/webhooks/types.rs b/crates/router/src/core/webhooks/types.rs index fd1babc2065..a0e999971c5 100644 --- a/crates/router/src/core/webhooks/types.rs +++ b/crates/router/src/core/webhooks/types.rs @@ -1,5 +1,5 @@ use api_models::webhooks; -use common_utils::{crypto::SignMessage, ext_traits}; +use common_utils::{crypto::SignMessage, ext_traits::Encode}; use error_stack::ResultExt; use serde::Serialize; @@ -21,10 +21,10 @@ impl OutgoingWebhookType for webhooks::OutgoingWebhook { &self, payment_response_hash_key: Option<String>, ) -> errors::CustomResult<Option<String>, errors::WebhooksFlowError> { - let webhook_signature_payload = - ext_traits::Encode::<serde_json::Value>::encode_to_string_of_json(self) - .change_context(errors::WebhooksFlowError::OutgoingWebhookEncodingFailed) - .attach_printable("failed encoding outgoing webhook payload")?; + let webhook_signature_payload = self + .encode_to_string_of_json() + .change_context(errors::WebhooksFlowError::OutgoingWebhookEncodingFailed) + .attach_printable("failed encoding outgoing webhook payload")?; Ok(payment_response_hash_key .map(|key| { diff --git a/crates/router/src/db/merchant_connector_account.rs b/crates/router/src/db/merchant_connector_account.rs index 0dd20721c3a..d01c4f3784d 100644 --- a/crates/router/src/db/merchant_connector_account.rs +++ b/crates/router/src/db/merchant_connector_account.rs @@ -69,9 +69,9 @@ impl ConnectorAccessToken for Store { access_token: types::AccessToken, ) -> CustomResult<(), errors::StorageError> { let key = format!("access_token_{merchant_id}_{connector_name}"); - let serialized_access_token = - Encode::<types::AccessToken>::encode_to_string_of_json(&access_token) - .change_context(errors::StorageError::SerializationFailed)?; + let serialized_access_token = access_token + .encode_to_string_of_json() + .change_context(errors::StorageError::SerializationFailed)?; self.get_redis_conn() .map_err(Into::<errors::StorageError>::into)? .set_key_with_expiry(&key, serialized_access_token, access_token.expires) diff --git a/crates/router/src/db/refund.rs b/crates/router/src/db/refund.rs index accb5e8f3f9..9664c29eedc 100644 --- a/crates/router/src/db/refund.rs +++ b/crates/router/src/db/refund.rs @@ -267,7 +267,7 @@ mod storage { #[cfg(feature = "kv_store")] mod storage { - use common_utils::{date_time, fallback_reverse_lookup_not_found}; + use common_utils::{date_time, ext_traits::Encode, fallback_reverse_lookup_not_found}; use error_stack::{IntoReport, ResultExt}; use redis_interface::HsetnxReply; use storage_impl::redis::kv_store::{kv_wrapper, KvOperation}; @@ -279,7 +279,7 @@ mod storage { db::reverse_lookup::ReverseLookupInterface, services::Store, types::storage::{self as storage_types, enums, kv}, - utils::{self, db_utils}, + utils::db_utils, }; #[async_trait::async_trait] impl RefundInterface for Store { @@ -520,10 +520,8 @@ mod storage { let field = format!("pa_{}_ref_{}", &this.attempt_id, &this.refund_id); let updated_refund = refund.clone().apply_changeset(this.clone()); - let redis_value = - utils::Encode::<storage_types::Refund>::encode_to_string_of_json( - &updated_refund, - ) + let redis_value = updated_refund + .encode_to_string_of_json() .change_context(errors::StorageError::SerializationFailed)?; let redis_entry = kv::TypedSql { diff --git a/crates/router/src/routes/payment_methods.rs b/crates/router/src/routes/payment_methods.rs index ef7047bffab..89ca36c8c15 100644 --- a/crates/router/src/routes/payment_methods.rs +++ b/crates/router/src/routes/payment_methods.rs @@ -299,7 +299,8 @@ impl ParentPaymentMethodToken { token: PaymentTokenData, state: &AppState, ) -> CustomResult<(), errors::ApiErrorResponse> { - let token_json_str = Encode::<PaymentTokenData>::encode_to_string_of_json(&token) + let token_json_str = token + .encode_to_string_of_json() .change_context(errors::ApiErrorResponse::InternalServerError) .attach_printable("failed to serialize hyperswitch token to json")?; let redis_conn = state diff --git a/crates/router/src/routes/payments/helpers.rs b/crates/router/src/routes/payments/helpers.rs index 7a1c26b0572..256767f2aea 100644 --- a/crates/router/src/routes/payments/helpers.rs +++ b/crates/router/src/routes/payments/helpers.rs @@ -73,7 +73,8 @@ pub fn populate_ip_into_browser_info( .or_else(|| ip_address_from_header.map(|ip| masking::Secret::new(ip.to_string()))); } - let encoded = Encode::<types::BrowserInformation>::encode_to_value(&browser_info) + let encoded = browser_info + .encode_to_value() .change_context(errors::ApiErrorResponse::InternalServerError) .attach_printable( "failed to re-encode browser information to json after setting ip address", diff --git a/crates/router/src/services/api.rs b/crates/router/src/services/api.rs index 0157f741d97..b51368da676 100644 --- a/crates/router/src/services/api.rs +++ b/crates/router/src/services/api.rs @@ -407,7 +407,7 @@ where let response = match body { Ok(body) => { let connector_http_status_code = Some(body.status_code); - match connector_integration + let handle_response_result = connector_integration .handle_response(req, Some(&mut connector_event), body) .map_err(|error| { if error.current_context() @@ -423,40 +423,43 @@ where ) } error - }) { - Ok(mut data) => { - - match connector_event.try_into() { - Ok(event) => { - state.event_handler().log_event(event); - } - Err(err) => { - logger::error!(error=?err, "Error Logging Connector Event"); - } - }; - data.connector_http_status_code = connector_http_status_code; - // Add up multiple external latencies in case of multiple external calls within the same request. - data.external_latency = Some( - data.external_latency - .map_or(external_latency, |val| val + external_latency), - ); - Ok(data) - }, - Err(err) => { - - connector_event.set_error(json!({"error": err.to_string()})); - - match connector_event.try_into() { - Ok(event) => { - state.event_handler().log_event(event); - } - Err(err) => { - logger::error!(error=?err, "Error Logging Connector Event"); - } + }); + match handle_response_result { + Ok(mut data) => { + match connector_event.try_into() { + Ok(event) => { + state.event_handler().log_event(event); } - Err(err) - }, - }? + Err(err) => { + logger::error!(error=?err, "Error Logging Connector Event"); + } + }; + data.connector_http_status_code = + connector_http_status_code; + // Add up multiple external latencies in case of multiple external calls within the same request. + data.external_latency = Some( + data.external_latency + .map_or(external_latency, |val| { + val + external_latency + }), + ); + Ok(data) + } + Err(err) => { + connector_event + .set_error(json!({"error": err.to_string()})); + + match connector_event.try_into() { + Ok(event) => { + state.event_handler().log_event(event); + } + Err(err) => { + logger::error!(error=?err, "Error Logging Connector Event"); + } + } + Err(err) + } + }? } Err(body) => { router_data.connector_http_status_code = Some(body.status_code); diff --git a/crates/router/src/types/api/admin.rs b/crates/router/src/types/api/admin.rs index 487cea88d15..bf76a7339a2 100644 --- a/crates/router/src/types/api/admin.rs +++ b/crates/router/src/types/api/admin.rs @@ -7,14 +7,13 @@ pub use api_models::admin::{ PaymentMethodsEnabled, PayoutRoutingAlgorithm, PayoutStraightThroughAlgorithm, ToggleKVRequest, ToggleKVResponse, WebhookDetails, }; -use common_utils::ext_traits::ValueExt; +use common_utils::ext_traits::{Encode, ValueExt}; use error_stack::ResultExt; use masking::Secret; use crate::{ core::errors, types::{domain, storage, transformers::ForeignTryFrom}, - utils::{self}, }; impl TryFrom<domain::MerchantAccount> for MerchantAccountResponse { @@ -95,10 +94,11 @@ impl ForeignTryFrom<(domain::MerchantAccount, BusinessProfileCreate)> .webhook_details .as_ref() .map(|webhook_details| { - common_utils::ext_traits::Encode::<WebhookDetails>::encode_to_value(webhook_details) - .change_context(errors::ApiErrorResponse::InvalidDataValue { + webhook_details.encode_to_value().change_context( + errors::ApiErrorResponse::InvalidDataValue { field_name: "webhook details", - }) + }, + ) }) .transpose()?; @@ -110,12 +110,11 @@ impl ForeignTryFrom<(domain::MerchantAccount, BusinessProfileCreate)> let payment_link_config_value = request .payment_link_config .map(|pl_config| { - utils::Encode::<api_models::admin::BusinessPaymentLinkConfig>::encode_to_value( - &pl_config, + pl_config.encode_to_value().change_context( + errors::ApiErrorResponse::InvalidDataValue { + field_name: "payment_link_config_value", + }, ) - .change_context(errors::ApiErrorResponse::InvalidDataValue { - field_name: "payment_link_config_value", - }) }) .transpose()?; diff --git a/crates/storage_impl/src/payments/payment_intent.rs b/crates/storage_impl/src/payments/payment_intent.rs index 8d20dfe0f32..7efbafb662d 100644 --- a/crates/storage_impl/src/payments/payment_intent.rs +++ b/crates/storage_impl/src/payments/payment_intent.rs @@ -160,9 +160,9 @@ impl<T: DatabaseStore> PaymentIntentInterface for KVRouterStore<T> { .apply_changeset(origin_diesel_intent.clone()); // Check for database presence as well Maybe use a read replica here ? - let redis_value = - Encode::<DieselPaymentIntent>::encode_to_string_of_json(&diesel_intent) - .change_context(StorageError::SerializationFailed)?; + let redis_value = diesel_intent + .encode_to_string_of_json() + .change_context(StorageError::SerializationFailed)?; let redis_entry = kv::TypedSql { op: kv::DBOperation::Update {
2024-02-16T13:05:34Z
## 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 simplifies the definition of the `common_utils::ext_traits::Encode` trait to simplify the invocation of the trait methods. In addition, this PR addresses a clippy lint introduced in Rust 1.76. ## 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 #3685. ## 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 changes in this should work fine as long as the code compiles. However, sanity testing can be performed by running Postman collection(s). I have performed sanity testing locally by successfully creating a payment and refund via Postman. ## 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 - [ ] I added a [CHANGELOG](/CHANGELOG.md) entry if applicable
783fa0b0dff1e157920d683a75fc579942cd9c06
The changes in this should work fine as long as the code compiles. However, sanity testing can be performed by running Postman collection(s). I have performed sanity testing locally by successfully creating a payment and refund via Postman.
juspay/hyperswitch
juspay__hyperswitch-3642
Bug: docs(connector): Add wasm docs in connector integration docs Add connector.md file doesn't have information about connector configs where we add connector to control center from backend configs. Documentation for where to add configs in wasm should be mentioned in add_connector.md
diff --git a/add_connector.md b/add_connector.md index 7fc3dcb27d1..f859c521f0e 100644 --- a/add_connector.md +++ b/add_connector.md @@ -668,6 +668,187 @@ In the `connector/utils.rs` file, you'll discover utility functions that aid in let json_wallet_data: CheckoutGooglePayData =wallet_data.get_wallet_token_as_json()?; ``` +### **Connector configs for control center** + +This section is explicitly for developers who are using the [Hyperswitch Control Center](https://github.com/juspay/hyperswitch-control-center). Below is a more detailed documentation that guides you through updating the connector configuration in the `development.toml` file in Hyperswitch and running the wasm-pack build command. Please replace placeholders such as `/absolute/path/to/` with the actual absolute paths. + +1. Install wasm-pack: Run the following command to install wasm-pack: + +```bash +cargo install wasm-pack +``` + +2. Add connector configuration: + + Open the `development.toml` file located at `crates/connector_configs/toml/development.toml` in your Hyperswitch project. + + Locate the [stripe] section as an example and add the configuration for the `example_connector`. Here's an example: + + ```toml + # crates/connector_configs/toml/development.toml + + # Other connector configurations... + + [stripe] + [stripe.connector_auth.HeaderKey] + api_key="Secret Key" + + # Add any other Stripe-specific configuration here + + [example_connector] + # Your specific connector configuration for reference + # ... + + ``` + + provide the necessary configuration details for the `example_connector`. Don't forget to save the file. + +3. Update paths: + + Replace `/absolute/path/to/hyperswitch-control-center` with the absolute path to your Hyperswitch Control Center repository and `/absolute/path/to/hyperswitch` with the absolute path to your Hyperswitch repository. + +4. Run `wasm-pack` build: + + Execute the following command in your terminal: + + ```bash + wasm-pack build --target web --out-dir /absolute/path/to/hyperswitch-control-center/public/hyperswitch/wasm --out-name euclid /absolute/path/to/hyperswitch/crates/euclid_wasm -- --features dummy_connector + ``` + + This command builds the WebAssembly files for the `dummy_connector` feature and places them in the specified directory. + +Notes: + +- Ensure that you replace placeholders like `/absolute/path/to/` with the actual absolute paths in your file system. +- Verify that your connector configurations in `development.toml` are correct and saved before running the `wasm-pack` command. +- Check for any error messages during the build process and resolve them accordingly. + +By following these steps, you should be able to update the connector configuration and build the WebAssembly files successfully. + +Certainly! Below is a detailed documentation guide on updating the `ConnectorTypes.res` and `ConnectorUtils.res` files in your [Hyperswitch Control Center](https://github.com/juspay/hyperswitch-control-center) project. + +Update `ConnectorTypes.res`: + +1. Open `ConnectorTypes.res`: + + Open the `ConnectorTypes.res` file located at `src/screens/HyperSwitch/Connectors/ConnectorTypes.res` in your Hyperswitch-Control-Center project. + +2. Add Connector enum: + + Add the new connector name enum under the `type connectorName` section. Here's an example: + + ```reason + /* src/screens/HyperSwitch/Connectors/ConnectorTypes.res */ + + type connectorName = + | Stripe + | DummyConnector + | YourNewConnector + /* Add any other connector enums as needed */ + ``` + + Replace `YourNewConnector` with the name of your newly added connector. + +3. Save the file: + + Save the changes made to `ConnectorTypes.res`. + +Update `ConnectorUtils.res`: + +1. Open `ConnectorUtils.res`: + + Open the `ConnectorUtils.res` file located at `src/screens/HyperSwitch/Connectors/ConnectorUtils.res` in your [Hyperswitch Control Center](https://github.com/juspay/hyperswitch-control-center) project. + +2. Add Connector Description: + + Update the following functions in `ConnectorUtils.res`: + + ```reason + /* src/screens/HyperSwitch/Connectors/ConnectorUtils.res */ + + + let connectorList : array<connectorName> = [Stripe,YourNewConnector] + + + let getConnectorNameString = (connectorName: connectorName) => + switch connectorName { + | Stripe => "Stripe" + | DummyConnector => "Dummy Connector" + | YourNewConnector => "Your New Connector" + /* Add cases for other connectors */ + }; + + let getConnectorNameTypeFromString = (str: string) => + switch str { + | "Stripe" => Stripe + | "Dummy Connector" => DummyConnector + | "Your New Connector" => YourNewConnector + /* Add cases for other connectors */ + }; + + let getConnectorInfo = (connectorName: connectorName) => + switch connectorName { + | Stripe => "Stripe connector description." + | DummyConnector => "Dummy Connector description." + | YourNewConnector => "Your New Connector description." + /* Add descriptions for other connectors */ + }; + + let getDisplayNameForConnectors = (connectorName: connectorName) => + switch connectorName { + | Stripe => "Stripe" + | DummyConnector => "Dummy Connector" + | YourNewConnector => "Your New Connector" + /* Add display names for other connectors */ + }; + ``` + + Adjust the strings and descriptions according to your actual connector names and descriptions. + + +4. Save the File: + + Save the changes made to `ConnectorUtils.res`. + +Notes: + +- Ensure that you replace placeholders like `YourNewConnector` with the actual names of your connectors. +- Verify that your connector enums and descriptions are correctly updated. +- Save the files after making the changes. + +By following these steps, you should be able to update the `ConnectorTypes.res` and `ConnectorUtils.res` files with the new connector enum and its related information. + + + +Certainly! Below is a detailed documentation guide on how to add a new connector icon under the `public/hyperswitch/Gateway` folder in your Hyperswitch-Control-Center project. + +Add Connector icon: + +1. Prepare the icon: + + Prepare your connector icon in SVG format. Ensure that the icon is named in uppercase, following the convention. For example, name it `YOURCONNECTOR.SVG`. + +2. Open file explorer: + + Open your file explorer and navigate to the `public/hyperswitch/Gateway` folder in your Hyperswitch-Control-Center project. + +3. Add Icon file: + + Copy and paste your SVG icon file (e.g., `YOURCONNECTOR.SVG`) into the `Gateway` folder. + +4. Verify file structure: + + Ensure that the file structure in the `Gateway` folder follows the uppercase convention. For example: + + ``` + public + └── hyperswitch + └── Gateway + └── YOURCONNECTOR.SVG + ``` + Save the changes made to the `Gateway` folder. + + ### **Test the connector** The template code script generates a test file for the connector, containing 20 sanity tests. We anticipate that you will implement these tests when adding a new connector.
2024-02-13T08:03:22Z
## 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 --> This PR adds documentation to add_connector.md explaining how to add connectors to the Control Center via Wasm configs. ### 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)? --> Testing not 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 - [ ] I added a [CHANGELOG](/CHANGELOG.md) entry if applicable
6e103cef50fea31d2508880985f80f0fd65cd536
Testing not required
juspay/hyperswitch
juspay__hyperswitch-3634
Bug: [FIX] unmask last4 when metadata changed during /payments When a metadata is changed during /payments and list customer payment method is called, last4 digits is getting masked. Unmask it and respond with raw string.
diff --git a/crates/router/src/core/payments/tokenization.rs b/crates/router/src/core/payments/tokenization.rs index 9691ea962fa..7cff6263344 100644 --- a/crates/router/src/core/payments/tokenization.rs +++ b/crates/router/src/core/payments/tokenization.rs @@ -209,9 +209,7 @@ where let updated_card = Some(CardDetailFromLocker { scheme: None, last4_digits: Some( - card.card_number.to_string().split_off( - card.card_number.to_string().len() - 4, - ), + card.card_number.clone().get_last4(), ), issuer_country: None, card_number: Some(card.card_number),
2024-02-12T13:34:27Z
## 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 --> When a metadata is changed during /payments and list customer payment method is called, last4 digits is getting masked. This PR unmasks 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? <!-- Did you write an integration/unit/API test to verify the code changes? Or did you test this change manually (provide relevant screenshots)? --> 1. Save a card in locker using /payments 2. Change the metadata of the saved card and try to save it again in locker using /payments 3. Now when list_customer_payment_method is called, the last4_digits field of the updated card has to be unmasked ## 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 - [ ] I added a [CHANGELOG](/CHANGELOG.md) entry if applicable
cc6759bd2d4207ad874a69546cb0a48db70b8629
1. Save a card in locker using /payments 2. Change the metadata of the saved card and try to save it again in locker using /payments 3. Now when list_customer_payment_method is called, the last4_digits field of the updated card has to be unmasked
juspay/hyperswitch
juspay__hyperswitch-3632
Bug: Add checks in Prod Intent to not sent mail
diff --git a/crates/router/src/core/user/dashboard_metadata.rs b/crates/router/src/core/user/dashboard_metadata.rs index 82f95564768..7318f9973f1 100644 --- a/crates/router/src/core/user/dashboard_metadata.rs +++ b/crates/router/src/core/user/dashboard_metadata.rs @@ -4,10 +4,10 @@ use diesel_models::{ }; use error_stack::ResultExt; #[cfg(feature = "email")] +use masking::ExposeInterface; +#[cfg(feature = "email")] use router_env::logger; -#[cfg(feature = "email")] -use crate::services::email::types as email_types; use crate::{ core::errors::{UserErrors, UserResponse, UserResult}, routes::AppState, @@ -15,6 +15,8 @@ use crate::{ types::domain::{user::dashboard_metadata as types, MerchantKeyStore}, utils::user::dashboard_metadata as utils, }; +#[cfg(feature = "email")] +use crate::{services::email::types as email_types, types::domain}; pub async fn set_metadata( state: AppState, @@ -446,8 +448,8 @@ async fn insert_metadata( metadata = utils::update_user_scoped_metadata( state, user.user_id.clone(), - user.merchant_id, - user.org_id, + user.merchant_id.clone(), + user.org_id.clone(), metadata_key, data.clone(), ) @@ -457,7 +459,13 @@ async fn insert_metadata( #[cfg(feature = "email")] { - if utils::is_prod_email_required(&data) { + let user_data = user.get_user(state).await?; + let user_email = domain::UserEmail::from_pii_email(user_data.email.clone()) + .change_context(UserErrors::InternalServerError)? + .get_secret() + .expose(); + + if utils::is_prod_email_required(&data, user_email) { let email_contents = email_types::BizEmailProd::new(state, data)?; let send_email_result = state .email_client diff --git a/crates/router/src/utils/user/dashboard_metadata.rs b/crates/router/src/utils/user/dashboard_metadata.rs index ac3d918a34f..58841580244 100644 --- a/crates/router/src/utils/user/dashboard_metadata.rs +++ b/crates/router/src/utils/user/dashboard_metadata.rs @@ -279,9 +279,15 @@ pub fn parse_string_to_enums(query: String) -> UserResult<GetMultipleMetaDataPay }) } -pub fn is_prod_email_required(data: &ProdIntent) -> bool { - !(data - .poc_email +fn not_contains_string(value: &Option<String>, value_to_be_checked: &str) -> bool { + value .as_ref() - .map_or(true, |mail| mail.contains("juspay"))) + .map_or(false, |mail| !mail.contains(value_to_be_checked)) +} + +pub fn is_prod_email_required(data: &ProdIntent, user_email: String) -> bool { + not_contains_string(&data.poc_email, "juspay") + && not_contains_string(&data.business_website, "juspay") + && not_contains_string(&data.business_website, "hyperswitch") + && not_contains_string(&Some(user_email), "juspay") }
2024-02-12T12:47:26Z
## Type of Change <!-- Put an `x` in the boxes that apply --> - [ ] Bugfix - [ ] New feature - [x] Enhancement - [ ] Refactoring - [ ] Dependency updates - [ ] Documentation - [ ] CI/CD ## Description Added some checks so unnecessary biz emails won't be sent. ### 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? When we hit this URL the email is sent to biz@hyperswitch.io so to restrict the unnecessary test mails added some checks. ``` curl --location 'http://localhost:8080/user/data' \ --header 'api-key: hyperswitch' \ --header 'Content-Type: text/plain' \ --header 'Authorization: Bearer JWT' \ --data-raw '{ "ProdIntent": { "poc_email": "---", "is_completed": true, "legal_business_name": "---", "business_location": "AX", "business_website": "---", "poc_name": "---", "comments": "---" } }' ``` ## 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 - [ ] I added a [CHANGELOG](/CHANGELOG.md) entry if applicable
8853a60bf4e2ed2490c60df9eaac2a8e46552b96
When we hit this URL the email is sent to biz@hyperswitch.io so to restrict the unnecessary test mails added some checks. ``` curl --location 'http://localhost:8080/user/data' \ --header 'api-key: hyperswitch' \ --header 'Content-Type: text/plain' \ --header 'Authorization: Bearer JWT' \ --data-raw '{ "ProdIntent": { "poc_email": "---", "is_completed": true, "legal_business_name": "---", "business_location": "AX", "business_website": "---", "poc_name": "---", "comments": "---" } }' ```
juspay/hyperswitch
juspay__hyperswitch-3628
Bug: [REFACTOR] Incorporate `hyperswitch_interface` into drainer Refactor drainer to incorporate the newly added crate `hyperswitch_interface` for secrets decryption
diff --git a/Cargo.lock b/Cargo.lock index 4bee1804f4c..dcde5456d7d 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -2342,6 +2342,7 @@ dependencies = [ "diesel_models", "error-stack", "external_services", + "hyperswitch_interfaces", "masking", "mime", "once_cell", diff --git a/config/deployments/drainer.toml b/config/deployments/drainer.toml index 42c89cbfd58..f8bf2826768 100644 --- a/config/deployments/drainer.toml +++ b/config/deployments/drainer.toml @@ -5,7 +5,17 @@ num_partitions = 64 shutdown_interval = 1000 stream_name = "drainer_stream" -[kms] +[secrets_management] +secrets_manager = "aws_kms" + +[secrets_management.aws_kms] +key_id = "kms_key_id" +region = "kms_region" + +[encryption_management] +encryption_manager = "aws_kms" + +[encryption_management.aws_kms] key_id = "kms_key_id" region = "kms_region" diff --git a/crates/drainer/Cargo.toml b/crates/drainer/Cargo.toml index a8972e279a6..f45c1979827 100644 --- a/crates/drainer/Cargo.toml +++ b/crates/drainer/Cargo.toml @@ -35,6 +35,7 @@ async-trait = "0.1.74" common_utils = { version = "0.1.0", path = "../common_utils", features = ["signals"] } diesel_models = { version = "0.1.0", path = "../diesel_models", features = ["kv_store"] } external_services = { version = "0.1.0", path = "../external_services" } +hyperswitch_interfaces = { version = "0.1.0", path = "../hyperswitch_interfaces" } masking = { version = "0.1.0", path = "../masking" } redis_interface = { version = "0.1.0", path = "../redis_interface" } router_env = { version = "0.1.0", path = "../router_env", features = ["log_extra_implicit_fields", "log_custom_entries_to_extra"] } diff --git a/crates/drainer/src/connection.rs b/crates/drainer/src/connection.rs index e01b72150c5..c539e9a734c 100644 --- a/crates/drainer/src/connection.rs +++ b/crates/drainer/src/connection.rs @@ -1,23 +1,13 @@ use bb8::PooledConnection; use diesel::PgConnection; -#[cfg(feature = "aws_kms")] -use external_services::aws_kms::{self, decrypt::AwsKmsDecrypt}; -#[cfg(feature = "hashicorp-vault")] -use external_services::hashicorp_vault::{ - core::{HashiCorpVault, Kv2}, - decrypt::VaultFetch, -}; -#[cfg(not(feature = "aws_kms"))] use masking::PeekInterface; -use crate::settings::Database; +use crate::{settings::Database, Settings}; pub type PgPool = bb8::Pool<async_bb8_diesel::ConnectionManager<PgConnection>>; #[allow(clippy::expect_used)] -pub async fn redis_connection( - conf: &crate::settings::Settings, -) -> redis_interface::RedisConnectionPool { +pub async fn redis_connection(conf: &Settings) -> redis_interface::RedisConnectionPool { redis_interface::RedisConnectionPool::new(&conf.redis) .await .expect("Failed to create Redis connection Pool") @@ -28,31 +18,14 @@ pub async fn redis_connection( /// /// Will panic if could not create a db pool #[allow(clippy::expect_used)] -pub async fn diesel_make_pg_pool( - database: &Database, - _test_transaction: bool, - #[cfg(feature = "aws_kms")] aws_kms_client: &'static aws_kms::core::AwsKmsClient, - #[cfg(feature = "hashicorp-vault")] hashicorp_client: &'static HashiCorpVault, -) -> PgPool { - let password = database.password.clone(); - #[cfg(feature = "hashicorp-vault")] - let password = password - .fetch_inner::<Kv2>(hashicorp_client) - .await - .expect("Failed while fetching db password"); - - #[cfg(feature = "aws_kms")] - let password = password - .decrypt_inner(aws_kms_client) - .await - .expect("Failed to decrypt password"); - - #[cfg(not(feature = "aws_kms"))] - let password = &password.peek(); - +pub async fn diesel_make_pg_pool(database: &Database, _test_transaction: bool) -> PgPool { let database_url = format!( "postgres://{}:{}@{}:{}/{}", - database.username, password, database.host, database.port, database.dbname + database.username, + database.password.peek(), + database.host, + database.port, + database.dbname ); let manager = async_bb8_diesel::ConnectionManager::<PgConnection>::new(database_url); let pool = bb8::Pool::builder() diff --git a/crates/drainer/src/health_check.rs b/crates/drainer/src/health_check.rs index 33b4a1395a8..443cb5b6f3f 100644 --- a/crates/drainer/src/health_check.rs +++ b/crates/drainer/src/health_check.rs @@ -11,7 +11,7 @@ use crate::{ connection::{pg_connection, redis_connection}, errors::HealthCheckError, services::{self, Store}, - settings::Settings, + Settings, }; pub const TEST_STREAM_NAME: &str = "TEST_STREAM_0"; diff --git a/crates/drainer/src/lib.rs b/crates/drainer/src/lib.rs index 909ae065e26..0ed6183faef 100644 --- a/crates/drainer/src/lib.rs +++ b/crates/drainer/src/lib.rs @@ -11,19 +11,20 @@ mod stream; mod types; mod utils; use std::sync::Arc; +mod secrets_transformers; use actix_web::dev::Server; use common_utils::signals::get_allowed_signals; use diesel_models::kv; use error_stack::{IntoReport, ResultExt}; +use hyperswitch_interfaces::secrets_interface::secret_state::RawSecret; use router_env::{instrument, tracing}; use tokio::sync::mpsc; +pub(crate) type Settings = crate::settings::Settings<RawSecret>; + use crate::{ - connection::pg_connection, - services::Store, - settings::{DrainerSettings, Settings}, - types::StreamData, + connection::pg_connection, services::Store, settings::DrainerSettings, types::StreamData, }; pub async fn start_drainer(store: Arc<Store>, conf: DrainerSettings) -> errors::DrainerResult<()> { diff --git a/crates/drainer/src/main.rs b/crates/drainer/src/main.rs index 943a66f6791..377fdcd1569 100644 --- a/crates/drainer/src/main.rs +++ b/crates/drainer/src/main.rs @@ -15,7 +15,9 @@ async fn main() -> DrainerResult<()> { conf.validate() .expect("Failed to validate drainer configuration"); - let store = services::Store::new(&conf, false).await; + let state = settings::AppState::new(conf.clone()).await; + + let store = services::Store::new(&state.conf, false).await; let store = std::sync::Arc::new(store); #[cfg(feature = "vergen")] @@ -28,7 +30,7 @@ async fn main() -> DrainerResult<()> { ); #[allow(clippy::expect_used)] - let web_server = Box::pin(start_web_server(conf.clone(), store.clone())) + let web_server = Box::pin(start_web_server(state.conf.as_ref().clone(), store.clone())) .await .expect("Failed to create the server"); diff --git a/crates/drainer/src/secrets_transformers.rs b/crates/drainer/src/secrets_transformers.rs new file mode 100644 index 00000000000..c0447725a79 --- /dev/null +++ b/crates/drainer/src/secrets_transformers.rs @@ -0,0 +1,50 @@ +use common_utils::errors::CustomResult; +use hyperswitch_interfaces::secrets_interface::{ + secret_handler::SecretsHandler, + secret_state::{RawSecret, SecretStateContainer, SecuredSecret}, + SecretManagementInterface, SecretsManagementError, +}; + +use crate::settings::{Database, Settings}; + +#[async_trait::async_trait] +impl SecretsHandler for Database { + async fn convert_to_raw_secret( + value: SecretStateContainer<Self, SecuredSecret>, + secret_management_client: Box<dyn SecretManagementInterface>, + ) -> CustomResult<SecretStateContainer<Self, RawSecret>, SecretsManagementError> { + let secured_db_config = value.get_inner(); + let raw_db_password = secret_management_client + .get_secret(secured_db_config.password.clone()) + .await?; + + Ok(value.transition_state(|db| Self { + password: raw_db_password, + ..db + })) + } +} + +/// # Panics +/// +/// Will panic even if fetching raw secret fails for at least one config value +#[allow(clippy::unwrap_used)] +pub async fn fetch_raw_secrets( + conf: Settings<SecuredSecret>, + secret_management_client: Box<dyn SecretManagementInterface>, +) -> Settings<RawSecret> { + #[allow(clippy::expect_used)] + let database = Database::convert_to_raw_secret(conf.master_database, secret_management_client) + .await + .expect("Failed to decrypt database password"); + + Settings { + server: conf.server, + master_database: database, + redis: conf.redis, + log: conf.log, + drainer: conf.drainer, + encryption_management: conf.encryption_management, + secrets_management: conf.secrets_management, + } +} diff --git a/crates/drainer/src/services.rs b/crates/drainer/src/services.rs index 3918c756c10..9e0165548a0 100644 --- a/crates/drainer/src/services.rs +++ b/crates/drainer/src/services.rs @@ -28,20 +28,10 @@ impl Store { /// Panics if there is a failure while obtaining the HashiCorp client using the provided configuration. /// This panic indicates a critical failure in setting up external services, and the application cannot proceed without a valid HashiCorp client. /// - pub async fn new(config: &crate::settings::Settings, test_transaction: bool) -> Self { + pub async fn new(config: &crate::Settings, test_transaction: bool) -> Self { Self { - master_pool: diesel_make_pg_pool( - &config.master_database, - test_transaction, - #[cfg(feature = "aws_kms")] - external_services::aws_kms::core::get_aws_kms_client(&config.kms).await, - #[cfg(feature = "hashicorp-vault")] - #[allow(clippy::expect_used)] - external_services::hashicorp_vault::core::get_hashicorp_client(&config.hc_vault) - .await - .expect("Failed while getting hashicorp client"), - ) - .await, + master_pool: diesel_make_pg_pool(config.master_database.get_inner(), test_transaction) + .await, redis_conn: Arc::new(crate::connection::redis_connection(config).await), config: StoreConfig { drainer_stream_name: config.drainer.stream_name.clone(), diff --git a/crates/drainer/src/settings.rs b/crates/drainer/src/settings.rs index de5af654540..ec24c472af2 100644 --- a/crates/drainer/src/settings.rs +++ b/crates/drainer/src/settings.rs @@ -1,22 +1,23 @@ -use std::path::PathBuf; +use std::{path::PathBuf, sync::Arc}; use common_utils::ext_traits::ConfigExt; use config::{Environment, File}; -#[cfg(feature = "aws_kms")] -use external_services::aws_kms; -#[cfg(feature = "hashicorp-vault")] -use external_services::hashicorp_vault; +use external_services::managers::{ + encryption_management::EncryptionManagementConfig, secrets_management::SecretsManagementConfig, +}; +use hyperswitch_interfaces::{ + encryption_interface::EncryptionManagementInterface, + secrets_interface::secret_state::{ + RawSecret, SecretState, SecretStateContainer, SecuredSecret, + }, +}; +use masking::Secret; use redis_interface as redis; pub use router_env::config::{Log, LogConsole, LogFile, LogTelemetry}; use router_env::{env, logger}; use serde::Deserialize; -use crate::errors; - -#[cfg(feature = "aws_kms")] -pub type Password = aws_kms::core::AwsKmsValue; -#[cfg(not(feature = "aws_kms"))] -pub type Password = masking::Secret<String>; +use crate::{errors, secrets_transformers}; #[derive(clap::Parser, Default)] #[cfg_attr(feature = "vergen", command(version = router_env::version!()))] @@ -27,25 +28,58 @@ pub struct CmdLineConf { pub config_path: Option<PathBuf>, } +#[derive(Clone)] +pub struct AppState { + pub conf: Arc<Settings<RawSecret>>, + pub encryption_client: Box<dyn EncryptionManagementInterface>, +} + +impl AppState { + /// # Panics + /// + /// Panics if secret or encryption management client cannot be initiated + pub async fn new(conf: Settings<SecuredSecret>) -> Self { + #[allow(clippy::expect_used)] + let secret_management_client = conf + .secrets_management + .get_secret_management_client() + .await + .expect("Failed to create secret management client"); + + let raw_conf = + secrets_transformers::fetch_raw_secrets(conf, secret_management_client).await; + + #[allow(clippy::expect_used)] + let encryption_client = raw_conf + .encryption_management + .get_encryption_management_client() + .await + .expect("Failed to create encryption management client"); + + Self { + conf: Arc::new(raw_conf), + encryption_client, + } + } +} + #[derive(Debug, Deserialize, Clone, Default)] #[serde(default)] -pub struct Settings { +pub struct Settings<S: SecretState> { pub server: Server, - pub master_database: Database, + pub master_database: SecretStateContainer<Database, S>, pub redis: redis::RedisSettings, pub log: Log, pub drainer: DrainerSettings, - #[cfg(feature = "aws_kms")] - pub kms: aws_kms::core::AwsKmsConfig, - #[cfg(feature = "hashicorp-vault")] - pub hc_vault: hashicorp_vault::core::HashiCorpVaultConfig, + pub encryption_management: EncryptionManagementConfig, + pub secrets_management: SecretsManagementConfig, } #[derive(Debug, Deserialize, Clone)] #[serde(default)] pub struct Database { pub username: String, - pub password: Password, + pub password: Secret<String>, pub host: String, pub port: u16, pub dbname: String, @@ -85,7 +119,7 @@ impl Default for Database { fn default() -> Self { Self { username: String::new(), - password: Password::default(), + password: String::new().into(), host: "localhost".into(), port: 5432, dbname: String::new(), @@ -157,7 +191,7 @@ impl DrainerSettings { } } -impl Settings { +impl Settings<SecuredSecret> { pub fn new() -> Result<Self, errors::DrainerError> { Self::with_config_path(None) } @@ -199,12 +233,25 @@ impl Settings { pub fn validate(&self) -> Result<(), errors::DrainerError> { self.server.validate()?; - self.master_database.validate()?; + self.master_database.get_inner().validate()?; self.redis.validate().map_err(|error| { println!("{error}"); errors::DrainerError::ConfigParsingError("invalid Redis configuration".into()) })?; self.drainer.validate()?; + self.secrets_management.validate().map_err(|error| { + println!("{error}"); + errors::DrainerError::ConfigParsingError( + "invalid secrets management configuration".into(), + ) + })?; + + self.encryption_management.validate().map_err(|error| { + println!("{error}"); + errors::DrainerError::ConfigParsingError( + "invalid encryption management configuration".into(), + ) + })?; Ok(()) } diff --git a/crates/hyperswitch_interfaces/src/secrets_interface/secret_state.rs b/crates/hyperswitch_interfaces/src/secrets_interface/secret_state.rs index 6d3f75500af..d1da6a8c8b6 100644 --- a/crates/hyperswitch_interfaces/src/secrets_interface/secret_state.rs +++ b/crates/hyperswitch_interfaces/src/secrets_interface/secret_state.rs @@ -8,12 +8,12 @@ use serde::{Deserialize, Deserializer}; pub trait SecretState {} /// Decrypted state -#[derive(Debug, Clone, Deserialize)] -pub enum RawSecret {} +#[derive(Debug, Clone, Deserialize, Default)] +pub struct RawSecret {} /// Encrypted state -#[derive(Debug, Clone, Deserialize)] -pub enum SecuredSecret {} +#[derive(Debug, Clone, Deserialize, Default)] +pub struct SecuredSecret {} impl SecretState for RawSecret {} impl SecretState for SecuredSecret {}
2024-02-12T10:38: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 --> Added `AppState` in drainer which now contains `encryption_client` for runtime encryption and decryption of values. This PR also incorporates the newly added `hyperswitch_interface` crate for decrypting the secrets during application startup. ### 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)? --> This PR refactors the way decryption of secrets work in drainer. So this cannot be tested ## 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 - [ ] I added a [CHANGELOG](/CHANGELOG.md) entry if applicable
5fb3c001b5dc371f81fe1708fd9a6c6978fb726e
This PR refactors the way decryption of secrets work in drainer. So this cannot be tested
juspay/hyperswitch
juspay__hyperswitch-3627
Bug: [BUG] Wrong email content in invite users
diff --git a/crates/router/src/services/email/types.rs b/crates/router/src/services/email/types.rs index 389979d5723..598a2620937 100644 --- a/crates/router/src/services/email/types.rs +++ b/crates/router/src/services/email/types.rs @@ -275,7 +275,7 @@ impl EmailData for InviteUser { let invite_user_link = get_link_with_token(&self.settings.email.base_url, token, "set_password"); - let body = html::get_html_body(EmailBody::MagicLink { + let body = html::get_html_body(EmailBody::InviteUser { link: invite_user_link, user_name: self.user_name.clone().get_secret().expose(), });
2024-02-12T08:44:37Z
## Type of Change <!-- Put an `x` in the boxes that apply --> - [X] Bugfix - [ ] New feature - [ ] Enhancement - [ ] Refactoring - [ ] Dependency updates - [ ] Documentation - [ ] CI/CD ## Description Invite users email content was of `magic link`. This PR changed it to `invite users` ### 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 Right content in email body of invite users ## How did you test it? With local SES. ``` curl --location 'http://localhost:8080/user/user/invite' \ --header 'Content-Type: application/json' \ --header 'Authorization: Bearer JWT' \ --data-raw '{ "email": "new_unregistered_email", "name": "username", "role_id": "any role" }' ``` ## 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 - [ ] I added a [CHANGELOG](/CHANGELOG.md) entry if applicable
4ae28e48cd73a9f96b6ae24babf167824fd182a0
With local SES. ``` curl --location 'http://localhost:8080/user/user/invite' \ --header 'Content-Type: application/json' \ --header 'Authorization: Bearer JWT' \ --data-raw '{ "email": "new_unregistered_email", "name": "username", "role_id": "any role" }' ```
juspay/hyperswitch
juspay__hyperswitch-3616
Bug: [DOCS] Update Rustman documentation The current documentation misses some key points that WILL result in people not being able to run the collections and ask for help. We would want to update it so that it look cleaner with `Notes` that are highlighted thereby making it more readable and clearer.
diff --git a/crates/test_utils/README.md b/crates/test_utils/README.md index a82c74cb59f..3c50499adc0 100644 --- a/crates/test_utils/README.md +++ b/crates/test_utils/README.md @@ -2,7 +2,8 @@ The heart of `newman`(with directory support) and `UI-tests` -> If you're developing a collection and you want to learn more about it, click [_**here**_](/README.md) +> [!NOTE] +> If you're developing a collection and you want to learn more about it, click [_**here**_](/postman/README.md) ## Newman @@ -14,10 +15,14 @@ The heart of `newman`(with directory support) and `UI-tests` - Add the connector credentials to the `connector_auth.toml` / `auth.toml` by creating a copy of the `sample_auth.toml` from `router/tests/connectors/sample_auth.toml` - Export the auth file path as an environment variable: + ```shell export CONNECTOR_AUTH_FILE_PATH=/path/to/auth.toml ``` +> [!IMPORTANT] +> You might also need to export the `GATEWAY_MERCHANT_ID`, `GPAY_CERTIFICATE` and `GPAY_CERTIFICATE_KEYS` as environment variables for certain collections with necessary values. Make sure you do that before running the tests + ### Supported Commands Required fields: @@ -40,18 +45,21 @@ Optional fields: - Example: `--header "key1:value1" --header "key2:value2"` - `--verbose` -- A boolean to print detailed logs (requests and responses) -**Note:** Passing `--verbose` will also print the connector as well as admin API keys in the logs. So, make sure you don't push the commands with `--verbose` to any public repository. +> [!Note] +> Passing `--verbose` will also print the connector as well as admin API keys in the logs. So, make sure you don't push the commands with `--verbose` to any public repository. ### Running tests - Tests can be run with the following command: + ```shell cargo run --package test_utils --bin test_utils -- --connector-name=<connector_name> --base-url=<base_url> --admin-api-key=<admin_api_key> \ # optionally --folder "<folder_name_1>,<folder_name_2>,...<folder_name_n>" --verbose ``` -**Note**: You can omit `--package test_utils` at the time of running the above command since it is optional. +> [!Note] +> You can omit `--package test_utils` at the time of running the above command since it is optional. ## UI tests diff --git a/postman/README.md b/postman/README.md index 342e7ebe1bd..c3d3c63e459 100644 --- a/postman/README.md +++ b/postman/README.md @@ -26,10 +26,11 @@ This directory contains the Postman collection for all Hyperswitch supported con - Make sure that you update the `tests` section where the necessary `javascript` code has to written/updated to test the feature (assertion checks where you verify the results obtained with the expected outcome) - If certain `tests` need to be run at the time of making a request, make sure you add them to the `Pre-request Script` section of the request +- Make sure that the request body does not contain any comments else the `newman dir-export` command will fail which is used to export the collection to its directory structure --- - After all the development is done, make sure you right click and run the collection in respective environments to make sure that the collection runs successfully -- Export the collection as `v2.1` and save it `postman/collection-json` directory -- Export the postman-collection to its directory structure by using the command `newman dir-export /path/to/collection.json` and move the folder to `postman/collection-dir` (for more info, refer to [Newman-Fork](https://github.com/juspay/hyperswitch/tree/main/crates/test_utils#newman)) -- You can run the dir postman collection from newman using `rustman` by referring [here](https://github.com/juspay/hyperswitch/tree/main/crates/test_utils#running-tests) \ No newline at end of file +- Export the collection as `v2.1` and save it `postman/collection-json` directory with file name following the format `<connector_name>.postman_collection.json` +- Export the postman-collection to its directory structure by using the command `newman dir-export /path/to/collection.json` and move the folder to `postman/collection-dir` (for more info, refer to [Newman-Fork](/crates/test_utils/README.md#newman)) with the folder renamed with name of the connector +- You can run the postman collection from directory structure by referring [here](/crates/test_utils/README.md#running-tests)
2024-02-09T18:43:21Z
## 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 --> This PR updates the `Rustman` documentation easing the collection development process along with the things to look for before running the collection. Closes #3616 ### 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). --> The documentation misses some key points which is why some of the developers and contributors are finding it difficult to test their work. ## 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)? --> Below 2 files look cleaner and clearer: - https://github.com/juspay/hyperswitch/blob/af7e39e57fd079bad60d8afed97c74fe633e4645/crates/test_utils/README.md - https://github.com/juspay/hyperswitch/blob/af7e39e57fd079bad60d8afed97c74fe633e4645/postman/README.md ## 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 - [ ] I added a [CHANGELOG](/CHANGELOG.md) entry if applicable
b9c29e7fd3bdc5e582a2dddbb98f3d2dbda72dd6
Below 2 files look cleaner and clearer: - https://github.com/juspay/hyperswitch/blob/af7e39e57fd079bad60d8afed97c74fe633e4645/crates/test_utils/README.md - https://github.com/juspay/hyperswitch/blob/af7e39e57fd079bad60d8afed97c74fe633e4645/postman/README.md
juspay/hyperswitch
juspay__hyperswitch-3618
Bug: [BUG] unmask last4 digits of card when listing payment methods for customer When metadata of a saved card is updated and customer payment methods are listed, the updated card's last 4 digit is getting masked in the response. Instead unmask it and return the raw digits.
diff --git a/crates/router/src/core/payment_methods/cards.rs b/crates/router/src/core/payment_methods/cards.rs index 152232d2dec..4f6d6b4c62b 100644 --- a/crates/router/src/core/payment_methods/cards.rs +++ b/crates/router/src/core/payment_methods/cards.rs @@ -248,11 +248,7 @@ pub async fn add_payment_method( Ok(pm) => { let updated_card = Some(api::CardDetailFromLocker { scheme: None, - last4_digits: Some( - card.card_number - .to_string() - .split_off(card.card_number.to_string().len() - 4), - ), + last4_digits: Some(card.card_number.clone().get_last4()), issuer_country: None, card_number: Some(card.card_number), expiry_month: Some(card.card_exp_month),
2024-02-10T16:51:23Z
## 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 --> When metadata of a saved card is updated and customer payment methods are listed, the updated card's last 4 digit is getting masked in the response. This PR unmasks it and returns the raw digits. Bug: `last4_digits` is masked - ![image](https://github.com/juspay/hyperswitch/assets/70657455/6c3b9af6-a584-4c76-9645-aae71e004a4b) Fix: unmasked - ![image](https://github.com/juspay/hyperswitch/assets/70657455/bc5712f5-bd7f-463c-abb4-5f78a5505215) ### 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. Save a card in locker 2. Change the metadata of the saved card and try to save it again in locker 3. Now when `list_customer_payment_method` is called, the `last4_digits` field of the updated card has to be unmasked ## 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 - [ ] I added a [CHANGELOG](/CHANGELOG.md) entry if applicable
b9c29e7fd3bdc5e582a2dddbb98f3d2dbda72dd6
1. Save a card in locker 2. Change the metadata of the saved card and try to save it again in locker 3. Now when `list_customer_payment_method` is called, the `last4_digits` field of the updated card has to be unmasked
juspay/hyperswitch
juspay__hyperswitch-3622
Bug: [FEATURE] Add required fields for giropay ### Feature Description Add giropay wallet required fields for all connectors that implement Giropay ### Possible Implementation Add required fields for Giropay ### 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 87999f0e9e9..f592cfeb9eb 100644 --- a/config/config.example.toml +++ b/config/config.example.toml @@ -390,6 +390,8 @@ bank_debit.sepa = { connector_list = "gocardless" } # Mandate supported payment bank_redirect.ideal = {connector_list = "stripe,adyen,globalpay"} # Mandate supported payment method type and connector for bank_redirect bank_redirect.sofort = {connector_list = "stripe,adyen,globalpay"} wallet.apple_pay = { connector_list = "stripe,adyen,cybersource,noon" } +bank_redirect.giropay = {connector_list = "adyen,globalpay"} + # Required fields info used while listing the payment_method_data diff --git a/config/deployments/integration_test.toml b/config/deployments/integration_test.toml index 2c5d16e3e3c..6c721ab3a9f 100644 --- a/config/deployments/integration_test.toml +++ b/config/deployments/integration_test.toml @@ -117,8 +117,10 @@ pay_later.klarna.connector_list = "adyen" wallet.apple_pay.connector_list = "stripe,adyen,cybersource,noon" wallet.google_pay.connector_list = "stripe,adyen,cybersource" wallet.paypal.connector_list = "adyen" -bank_redirect.ideal = {connector_list = "stripe,adyen,globalpay"} -bank_redirect.sofort = {connector_list = "stripe,adyen,globalpay"} +bank_redirect.ideal.connector_list = "stripe,adyen,globalpay" +bank_redirect.sofort.connector_list = "stripe,adyen,globalpay" +bank_redirect.giropay.connector_list = "adyen,globalpay" + [multiple_api_version_supported_connectors] supported_connectors = "braintree" diff --git a/config/deployments/production.toml b/config/deployments/production.toml index 964281c52bb..b8a4f7ef20f 100644 --- a/config/deployments/production.toml +++ b/config/deployments/production.toml @@ -117,8 +117,9 @@ pay_later.klarna.connector_list = "adyen" wallet.apple_pay.connector_list = "stripe,adyen,cybersource,noon" wallet.google_pay.connector_list = "stripe,adyen,cybersource" wallet.paypal.connector_list = "adyen" -bank_redirect.ideal = {connector_list = "stripe,adyen,globalpay"} -bank_redirect.sofort = {connector_list = "stripe,adyen,globalpay"} +bank_redirect.ideal.connector_list = "stripe,adyen,globalpay" +bank_redirect.sofort.connector_list = "stripe,adyen,globalpay" +bank_redirect.giropay.connector_list = "adyen,globalpay" [multiple_api_version_supported_connectors] supported_connectors = "braintree" diff --git a/config/deployments/sandbox.toml b/config/deployments/sandbox.toml index aa2377cf8a0..f6e1ca01f19 100644 --- a/config/deployments/sandbox.toml +++ b/config/deployments/sandbox.toml @@ -117,8 +117,10 @@ pay_later.klarna.connector_list = "adyen" wallet.apple_pay.connector_list = "stripe,adyen,cybersource,noon" wallet.google_pay.connector_list = "stripe,adyen,cybersource" wallet.paypal.connector_list = "adyen" -bank_redirect.ideal = {connector_list = "stripe,adyen,globalpay"} -bank_redirect.sofort = {connector_list = "stripe,adyen,globalpay"} +bank_redirect.ideal.connector_list = "stripe,adyen,globalpay" +bank_redirect.sofort.connector_list = "stripe,adyen,globalpay" +bank_redirect.giropay.connector_list = "adyen,globalpay" + [multiple_api_version_supported_connectors] supported_connectors = "braintree" diff --git a/config/development.toml b/config/development.toml index 20abb7bd6f3..5343e485a08 100644 --- a/config/development.toml +++ b/config/development.toml @@ -483,6 +483,7 @@ bank_debit.becs = { connector_list = "gocardless"} bank_debit.sepa = { connector_list = "gocardless"} bank_redirect.ideal = {connector_list = "stripe,adyen,globalpay"} bank_redirect.sofort = {connector_list = "stripe,adyen,globalpay"} +bank_redirect.giropay = {connector_list = "adyen,globalpay"} [connector_request_reference_id_config] merchant_ids_send_payment_id_as_connector_request_id = [] diff --git a/config/docker_compose.toml b/config/docker_compose.toml index e6dc01afa74..3aeb6754fbb 100644 --- a/config/docker_compose.toml +++ b/config/docker_compose.toml @@ -348,6 +348,8 @@ bank_debit.becs = { connector_list = "gocardless"} bank_debit.sepa = { connector_list = "gocardless"} bank_redirect.ideal = {connector_list = "stripe,adyen,globalpay"} bank_redirect.sofort = {connector_list = "stripe,adyen,globalpay"} +bank_redirect.giropay = {connector_list = "adyen,globalpay"} + [connector_customer] connector_list = "gocardless,stax,stripe" diff --git a/crates/api_models/src/payments.rs b/crates/api_models/src/payments.rs index a4f052549bd..6a9b7a12a72 100644 --- a/crates/api_models/src/payments.rs +++ b/crates/api_models/src/payments.rs @@ -1272,7 +1272,7 @@ pub enum BankRedirectData { }, Giropay { /// The billing details for bank redirection - billing_details: BankRedirectBilling, + billing_details: Option<BankRedirectBilling>, /// Bank account details for Giropay #[schema(value_type = Option<String>)] diff --git a/crates/router/src/configs/defaults.rs b/crates/router/src/configs/defaults.rs index 7b88c9c2dc7..1f041c27a74 100644 --- a/crates/router/src/configs/defaults.rs +++ b/crates/router/src/configs/defaults.rs @@ -4480,14 +4480,226 @@ impl Default for super::settings::RequiredFields { enums::PaymentMethodType::Giropay, ConnectorFields { fields: HashMap::from([ + ( + enums::Connector::Aci, + RequiredFieldFinal { + mandate: HashMap::new(), + non_mandate: HashMap::from([ + ( + "payment_method_data.bank_redirect.giropay.country".to_string(), + RequiredFieldInfo { + required_field: "payment_method_data.bank_redirect.giropay.country".to_string(), + display_name: "country".to_string(), + field_type: enums::FieldType::UserCountry { + options: vec![ + "DE".to_string(), + ]}, + value: None, + } + ) + ]), + common: HashMap::new(), + } + ), + ( + enums::Connector::Adyen, + RequiredFieldFinal { + mandate: HashMap::new(), + non_mandate: HashMap::new(), + common: HashMap::new(), + } + ), + ( + enums::Connector::Globalpay, + RequiredFieldFinal { + mandate: HashMap::new(), + non_mandate: HashMap::new(), + common: HashMap::from([ + ("billing.address.country".to_string(), + RequiredFieldInfo { + required_field: "billing.address.country".to_string(), + display_name: "country".to_string(), + field_type: enums::FieldType::UserAddressCountry { + options: vec![ + "DE".to_string(), + ] + }, + value: None, + } + ) + ]), + } + ), + ( + enums::Connector::Mollie, + RequiredFieldFinal { + mandate: HashMap::new(), + non_mandate: HashMap::new(), + common: HashMap::new(), + } + ), + ( + enums::Connector::Nuvei, + RequiredFieldFinal { + mandate: HashMap::new(), + non_mandate:HashMap::from([ + ( + "email".to_string(), + RequiredFieldInfo { + required_field: "email".to_string(), + display_name: "email".to_string(), + field_type: enums::FieldType::UserEmailAddress, + value: None, + } + ), + ( + "billing.address.first_name".to_string(), + RequiredFieldInfo { + required_field: "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: "billing.address.last_name".to_string(), + display_name: "billing_last_name".to_string(), + field_type: enums::FieldType::UserBillingName, + value: None, + } + ), + ( + "billing.address.country".to_string(), + RequiredFieldInfo { + required_field: "billing.address.country".to_string(), + display_name: "country".to_string(), + field_type: enums::FieldType::UserAddressCountry{ + options: vec![ + "DE".to_string(), + ] + }, + value: None, + } + )] + ), + common: HashMap::new(), + } + ), + ( + enums::Connector::Paypal, + RequiredFieldFinal { + mandate: HashMap::new(), + non_mandate: HashMap::from([ + ("payment_method_data.bank_redirect.giropay.country".to_string(), + RequiredFieldInfo { + required_field: "payment_method_data.bank_redirect.giropay.country".to_string(), + display_name: "country".to_string(), + field_type: enums::FieldType::UserCountry { + options: vec![ + "DE".to_string(), + ] + }, + value: None, + } + ), + ( + "payment_method_data.bank_redirect.giropay.billing_details.billing_name".to_string(), + RequiredFieldInfo { + required_field: "payment_method_data.bank_redirect.giropay.billing_details.billing_name".to_string(), + display_name: "billing_name".to_string(), + field_type: enums::FieldType::UserBillingName, + value: None, + } + ) + ]), + common: HashMap::new(), + } + ), ( enums::Connector::Stripe, + RequiredFieldFinal { + mandate: HashMap::new(), + non_mandate: HashMap::from([ + ("payment_method_data.bank_redirect.giropay.billing_details.billing_name".to_string(), + RequiredFieldInfo { + required_field: "payment_method_data.bank_redirect.giropay.billing_details.billing_name".to_string(), + display_name: "billing_name".to_string(), + field_type: enums::FieldType::UserBillingName, + value: None, + } + ) + ]), + common: HashMap::new(), + } + ), + ( + enums::Connector::Shift4, RequiredFieldFinal { mandate: HashMap::new(), non_mandate: HashMap::new(), common: HashMap::new(), } ), + ( + enums::Connector::Trustpay, + RequiredFieldFinal { + mandate: HashMap::new(), + non_mandate: HashMap::from([ + ( + "billing.address.first_name".to_string(), + RequiredFieldInfo { + required_field: "billing.address.first_name".to_string(), + display_name: "billing_first_name".to_string(), + field_type: enums::FieldType::UserBillingName, + value: None, + } + ), + ( + "billing.address.line1".to_string(), + RequiredFieldInfo { + required_field: "billing.address.line1".to_string(), + display_name: "line1".to_string(), + field_type: enums::FieldType::UserAddressLine1, + value: None, + } + ), + ( + "billing.address.city".to_string(), + RequiredFieldInfo { + required_field: "billing.address.city".to_string(), + display_name: "city".to_string(), + field_type: enums::FieldType::UserAddressCity, + value: None, + } + ), + ( + "billing.address.zip".to_string(), + RequiredFieldInfo { + required_field: "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: "billing.address.country".to_string(), + display_name: "country".to_string(), + field_type: enums::FieldType::UserAddressCountry { + options: vec![ + "DE".to_string(), + ] + }, + value: None, + } + ), + ]), + common: HashMap::new(), + } + ), ]), }, ), diff --git a/crates/router/src/connector/aci/transformers.rs b/crates/router/src/connector/aci/transformers.rs index 97cef72b02a..92c7e164c4c 100644 --- a/crates/router/src/connector/aci/transformers.rs +++ b/crates/router/src/connector/aci/transformers.rs @@ -166,10 +166,15 @@ impl api_models::payments::BankRedirectData::Giropay { bank_account_bic, bank_account_iban, + country, .. } => Self::BankRedirect(Box::new(BankRedirectionPMData { payment_brand: PaymentBrand::Giropay, - bank_account_country: Some(api_models::enums::CountryAlpha2::DE), + bank_account_country: Some(country.ok_or( + errors::ConnectorError::MissingRequiredField { + field_name: "giropay.country", + }, + )?), bank_account_bank_name: None, bank_account_bic: bank_account_bic.clone(), bank_account_iban: bank_account_iban.clone(), diff --git a/crates/router/src/connector/paypal/transformers.rs b/crates/router/src/connector/paypal/transformers.rs index 88595585fe1..1447cf75be7 100644 --- a/crates/router/src/connector/paypal/transformers.rs +++ b/crates/router/src/connector/paypal/transformers.rs @@ -315,7 +315,12 @@ fn get_payment_source( country, .. } => Ok(PaymentSourceItem::Giropay(RedirectRequest { - name: billing_details.get_billing_name()?, + name: billing_details + .clone() + .ok_or(errors::ConnectorError::MissingRequiredField { + field_name: "giropay.billing_details", + })? + .get_billing_name()?, country_code: country.ok_or(errors::ConnectorError::MissingRequiredField { field_name: "giropay.country", })?, diff --git a/crates/router/src/connector/stripe/transformers.rs b/crates/router/src/connector/stripe/transformers.rs index 8d397d0ebb9..69bbceab133 100644 --- a/crates/router/src/connector/stripe/transformers.rs +++ b/crates/router/src/connector/stripe/transformers.rs @@ -18,7 +18,8 @@ use url::Url; use crate::{ collect_missing_value_keys, connector::utils::{ - self as connector_util, ApplePay, ApplePayDecrypt, PaymentsPreProcessingData, RouterData, + self as connector_util, ApplePay, ApplePayDecrypt, BankRedirectBillingData, + PaymentsPreProcessingData, RouterData, }, core::errors, services, @@ -1108,7 +1109,14 @@ impl TryFrom<(&payments::BankRedirectData, Option<bool>)> for StripeBillingAddre payments::BankRedirectData::Giropay { billing_details, .. } => Ok(Self { - name: billing_details.billing_name.clone(), + name: Some( + billing_details + .clone() + .ok_or(errors::ConnectorError::MissingRequiredField { + field_name: "giropay.billing_details", + })? + .get_billing_name()?, + ), ..Self::default() }), payments::BankRedirectData::Ideal { diff --git a/crates/router/src/connector/worldline/transformers.rs b/crates/router/src/connector/worldline/transformers.rs index c55663d59f4..a21c88a2ce9 100644 --- a/crates/router/src/connector/worldline/transformers.rs +++ b/crates/router/src/connector/worldline/transformers.rs @@ -5,7 +5,7 @@ use serde::{Deserialize, Serialize}; use url::Url; use crate::{ - connector::utils::{self, CardData}, + connector::utils::{self, BankRedirectBillingData, CardData}, core::errors, services, types::{ @@ -385,11 +385,12 @@ fn make_bank_redirect_request( { PaymentMethodSpecificData::PaymentProduct816SpecificInput(Box::new(Giropay { bank_account_iban: BankAccountIban { - account_holder_name: billing_details.billing_name.clone().ok_or( - errors::ConnectorError::MissingRequiredField { - field_name: "billing_details.billing_name", - }, - )?, + account_holder_name: billing_details + .clone() + .ok_or(errors::ConnectorError::MissingRequiredField { + field_name: "giropay.billing_details", + })? + .get_billing_name()?, iban: bank_account_iban.clone(), }, })) diff --git a/loadtest/config/development.toml b/loadtest/config/development.toml index 954336070d5..ee5a0c3b44c 100644 --- a/loadtest/config/development.toml +++ b/loadtest/config/development.toml @@ -248,6 +248,8 @@ bank_debit.becs = { connector_list = "gocardless"} bank_debit.sepa = { connector_list = "gocardless"} bank_redirect.ideal = {connector_list = "stripe,adyen,globalpay"} bank_redirect.sofort = {connector_list = "stripe,adyen,globalpay"} +bank_redirect.giropay = {connector_list = "adyen,globalpay"} + [analytics] source = "sqlx" diff --git a/openapi/openapi_spec.json b/openapi/openapi_spec.json index 9afd5182529..4fef244c461 100644 --- a/openapi/openapi_spec.json +++ b/openapi/openapi_spec.json @@ -5155,12 +5155,16 @@ "giropay": { "type": "object", "required": [ - "billing_details", "country" ], "properties": { "billing_details": { - "$ref": "#/components/schemas/BankRedirectBilling" + "allOf": [ + { + "$ref": "#/components/schemas/BankRedirectBilling" + } + ], + "nullable": true }, "bank_account_bic": { "type": "string",
2023-12-21T15:05:05Z
## 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 --> Resolves [#3622](https://github.com/juspay/hyperswitch/issues/3622) ### Test Cases 1. Create a giropay payment with mollie with empty payment method object. The payment should succeed. ``` { "amount": 1000, "currency": "EUR", "confirm": true, "capture_method": "automatic", "capture_on": "2022-09-10T10:11:12Z", "amount_to_capture": 1000, "customer_id": "StripeCustomer", "email": "abcdef123@gmail.com", "name": "John Doe", "phone": "999999999", "phone_country_code": "+65", "description": "Its my first payment request", "authentication_type": "three_ds", "return_url": "https://google.com", "statement_descriptor_name": "joseph", "statement_descriptor_suffix": "JS", "payment_method": "bank_redirect", "payment_method_type": "giropay", "payment_method_data": { "bank_redirect": { "giropay": { } } } } ``` Must be tested for each of this connectors 1.ACI ``` Required fields: payment_method_data.bank_redirect.giropay.country ``` 2. Adyen ``` None ``` 3. GlobalPayments ``` Required fields: billing.address.country ``` 4. Mollie ``` None ``` 5. Nuvie ``` Required fields: email billing.address.first_name billing.address.last_name billing.address.country ``` 6. Paypal ``` Required fields: payment_method_data.bank_redirect.giropay.billing_details.billing_name payment_method_data.bank_redirect.giropay.country ``` 7. Shift4 ``` None ``` 8. Stripe ``` Required fields payment_method_data.bank_redirect.giropay.billing_details.billing_name ``` 9. Trustpay ``` Required fields: billing.address.first_name billing.address.line1 billing.address.city billing.address.zip billing.address.country ``` -> Create a payment with confirm `false` -> list payment methods, with client secret and publishable key ``` curl --location 'http://localhost:8080/account/payment_methods?client_secret={{client_secret}}' \ --header 'Content-Type: application/json' \ --header 'Accept: application/json' \ --header 'api-key:{{api_key}}' \ --data '' ``` Required fields must be populated, according to the connector ## 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 - [ ] I added a [CHANGELOG](/CHANGELOG.md) entry if applicable
54fb61eeebec503f599774fe9e97f6b6ce3f1458
juspay/hyperswitch
juspay__hyperswitch-3607
Bug: [FEATURE] Add new column in PaymentAttempt for storing mandate_data ### Feature Description Add new column in PaymentAttempt for storing mandate_data to be future compatible ### Possible Implementation Add a column mandate_data which would be a struct , in order to store the mandate details for a mandate in Payment Attempt table ### 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/data_models/src/mandates.rs b/crates/data_models/src/mandates.rs index 319a78cf661..b4478f84ee9 100644 --- a/crates/data_models/src/mandates.rs +++ b/crates/data_models/src/mandates.rs @@ -13,7 +13,6 @@ use time::PrimitiveDateTime; #[serde(rename_all = "snake_case")] pub struct MandateDetails { pub update_mandate_id: Option<String>, - pub mandate_type: Option<MandateDataType>, } #[derive(serde::Serialize, serde::Deserialize, Debug, Clone, PartialEq, Eq)] @@ -23,13 +22,6 @@ pub enum MandateDataType { MultiUse(Option<MandateAmountData>), } -#[derive(serde::Serialize, serde::Deserialize, Debug, Clone, PartialEq, Eq)] -#[serde(rename_all = "snake_case")] -#[serde(untagged)] -pub enum MandateTypeDetails { - MandateType(MandateDataType), - MandateDetails(MandateDetails), -} #[derive(Clone, Debug, serde::Serialize, serde::Deserialize, PartialEq, Eq)] pub struct MandateAmountData { pub amount: i64, diff --git a/crates/data_models/src/payments/payment_attempt.rs b/crates/data_models/src/payments/payment_attempt.rs index 2b5705c155b..084b0ef251e 100644 --- a/crates/data_models/src/payments/payment_attempt.rs +++ b/crates/data_models/src/payments/payment_attempt.rs @@ -4,7 +4,11 @@ use serde::{Deserialize, Serialize}; use time::PrimitiveDateTime; use super::PaymentIntent; -use crate::{errors, mandates::MandateTypeDetails, ForeignIDRef}; +use crate::{ + errors, + mandates::{MandateDataType, MandateDetails}, + ForeignIDRef, +}; #[async_trait::async_trait] pub trait PaymentAttemptInterface { @@ -143,7 +147,7 @@ pub struct PaymentAttempt { pub straight_through_algorithm: Option<serde_json::Value>, pub preprocessing_step_id: Option<String>, // providing a location to store mandate details intermediately for transaction - pub mandate_details: Option<MandateTypeDetails>, + pub mandate_details: Option<MandateDataType>, pub error_reason: Option<String>, pub multiple_capture_count: Option<i16>, // reference to the payment at connector side @@ -155,6 +159,7 @@ pub struct PaymentAttempt { pub merchant_connector_id: Option<String>, pub unified_code: Option<String>, pub unified_message: Option<String>, + pub mandate_data: Option<MandateDetails>, } impl PaymentAttempt { @@ -221,7 +226,7 @@ pub struct PaymentAttemptNew { pub business_sub_label: Option<String>, pub straight_through_algorithm: Option<serde_json::Value>, pub preprocessing_step_id: Option<String>, - pub mandate_details: Option<MandateTypeDetails>, + pub mandate_details: Option<MandateDataType>, pub error_reason: Option<String>, pub connector_response_reference_id: Option<String>, pub multiple_capture_count: Option<i16>, @@ -232,6 +237,7 @@ pub struct PaymentAttemptNew { pub merchant_connector_id: Option<String>, pub unified_code: Option<String>, pub unified_message: Option<String>, + pub mandate_data: Option<MandateDetails>, } impl PaymentAttemptNew { diff --git a/crates/diesel_models/src/enums.rs b/crates/diesel_models/src/enums.rs index babffdbc4a8..d65f6c5efa9 100644 --- a/crates/diesel_models/src/enums.rs +++ b/crates/diesel_models/src/enums.rs @@ -174,20 +174,8 @@ use diesel::{ #[serde(rename_all = "snake_case")] pub struct MandateDetails { pub update_mandate_id: Option<String>, - pub mandate_type: Option<MandateDataType>, } - -#[derive( - serde::Serialize, serde::Deserialize, Debug, Clone, PartialEq, Eq, FromSqlRow, AsExpression, -)] -#[diesel(sql_type = Jsonb)] -#[serde(rename_all = "snake_case")] -pub enum MandateDataType { - SingleUse(MandateAmountData), - MultiUse(Option<MandateAmountData>), -} - -impl<DB: Backend> FromSql<Jsonb, DB> for MandateDataType +impl<DB: Backend> FromSql<Jsonb, DB> for MandateDetails where serde_json::Value: FromSql<Jsonb, DB>, { @@ -197,7 +185,7 @@ where } } -impl ToSql<Jsonb, diesel::pg::Pg> for MandateDataType +impl ToSql<Jsonb, diesel::pg::Pg> for MandateDetails where serde_json::Value: ToSql<Jsonb, diesel::pg::Pg>, { @@ -210,19 +198,17 @@ where <serde_json::Value as ToSql<Jsonb, diesel::pg::Pg>>::to_sql(&value, &mut out.reborrow()) } } - #[derive( serde::Serialize, serde::Deserialize, Debug, Clone, PartialEq, Eq, FromSqlRow, AsExpression, )] #[diesel(sql_type = Jsonb)] -#[serde(untagged)] #[serde(rename_all = "snake_case")] -pub enum MandateTypeDetails { - MandateType(MandateDataType), - MandateDetails(MandateDetails), +pub enum MandateDataType { + SingleUse(MandateAmountData), + MultiUse(Option<MandateAmountData>), } -impl<DB: Backend> FromSql<Jsonb, DB> for MandateTypeDetails +impl<DB: Backend> FromSql<Jsonb, DB> for MandateDataType where serde_json::Value: FromSql<Jsonb, DB>, { @@ -231,7 +217,8 @@ where Ok(serde_json::from_value(value)?) } } -impl ToSql<Jsonb, diesel::pg::Pg> for MandateTypeDetails + +impl ToSql<Jsonb, diesel::pg::Pg> for MandateDataType where serde_json::Value: ToSql<Jsonb, diesel::pg::Pg>, { diff --git a/crates/diesel_models/src/payment_attempt.rs b/crates/diesel_models/src/payment_attempt.rs index d286cc312bc..9af4595c9f4 100644 --- a/crates/diesel_models/src/payment_attempt.rs +++ b/crates/diesel_models/src/payment_attempt.rs @@ -51,7 +51,7 @@ pub struct PaymentAttempt { pub straight_through_algorithm: Option<serde_json::Value>, pub preprocessing_step_id: Option<String>, // providing a location to store mandate details intermediately for transaction - pub mandate_details: Option<storage_enums::MandateTypeDetails>, + pub mandate_details: Option<storage_enums::MandateDataType>, pub error_reason: Option<String>, pub multiple_capture_count: Option<i16>, // reference to the payment at connector side @@ -64,6 +64,7 @@ pub struct PaymentAttempt { pub unified_code: Option<String>, pub unified_message: Option<String>, pub net_amount: Option<i64>, + pub mandate_data: Option<storage_enums::MandateDetails>, } impl PaymentAttempt { @@ -126,7 +127,7 @@ pub struct PaymentAttemptNew { pub business_sub_label: Option<String>, pub straight_through_algorithm: Option<serde_json::Value>, pub preprocessing_step_id: Option<String>, - pub mandate_details: Option<storage_enums::MandateTypeDetails>, + pub mandate_details: Option<storage_enums::MandateDataType>, pub error_reason: Option<String>, pub connector_response_reference_id: Option<String>, pub multiple_capture_count: Option<i16>, @@ -138,6 +139,7 @@ pub struct PaymentAttemptNew { pub unified_code: Option<String>, pub unified_message: Option<String>, pub net_amount: Option<i64>, + pub mandate_data: Option<storage_enums::MandateDetails>, } impl PaymentAttemptNew { diff --git a/crates/diesel_models/src/schema.rs b/crates/diesel_models/src/schema.rs index c9887e1770f..6c28677432b 100644 --- a/crates/diesel_models/src/schema.rs +++ b/crates/diesel_models/src/schema.rs @@ -688,6 +688,7 @@ diesel::table! { #[max_length = 1024] unified_message -> Nullable<Varchar>, net_amount -> Nullable<Int8>, + mandate_data -> Nullable<Jsonb>, } } diff --git a/crates/diesel_models/src/user/sample_data.rs b/crates/diesel_models/src/user/sample_data.rs index 5a2226f0676..6a6d4c52c97 100644 --- a/crates/diesel_models/src/user/sample_data.rs +++ b/crates/diesel_models/src/user/sample_data.rs @@ -5,7 +5,11 @@ use common_enums::{ use serde::{Deserialize, Serialize}; use time::PrimitiveDateTime; -use crate::{enums::MandateTypeDetails, schema::payment_attempt, PaymentAttemptNew}; +use crate::{ + enums::{MandateDataType, MandateDetails}, + schema::payment_attempt, + PaymentAttemptNew, +}; #[derive( Clone, Debug, Default, diesel::Insertable, router_derive::DebugAsDisplay, Serialize, Deserialize, @@ -50,7 +54,7 @@ pub struct PaymentAttemptBatchNew { pub business_sub_label: Option<String>, pub straight_through_algorithm: Option<serde_json::Value>, pub preprocessing_step_id: Option<String>, - pub mandate_details: Option<MandateTypeDetails>, + pub mandate_details: Option<MandateDataType>, pub error_reason: Option<String>, pub connector_response_reference_id: Option<String>, pub connector_transaction_id: Option<String>, @@ -63,6 +67,7 @@ pub struct PaymentAttemptBatchNew { pub unified_code: Option<String>, pub unified_message: Option<String>, pub net_amount: Option<i64>, + pub mandate_data: Option<MandateDetails>, } #[allow(dead_code)] @@ -116,6 +121,7 @@ impl PaymentAttemptBatchNew { unified_code: self.unified_code, unified_message: self.unified_message, net_amount: self.net_amount, + mandate_data: self.mandate_data, } } } diff --git a/crates/router/src/core/payment_methods/cards.rs b/crates/router/src/core/payment_methods/cards.rs index 7b505e7c01c..5d287a89f62 100644 --- a/crates/router/src/core/payment_methods/cards.rs +++ b/crates/router/src/core/payment_methods/cards.rs @@ -1837,17 +1837,8 @@ pub async fn list_payment_methods( merchant_name: merchant_account.merchant_name, payment_type, payment_methods: payment_method_responses, - mandate_payment: payment_attempt - .and_then(|inner| inner.mandate_details) - .and_then(|man_type_details| match man_type_details { - data_models::mandates::MandateTypeDetails::MandateType(mandate_type) => { - Some(mandate_type) - } - data_models::mandates::MandateTypeDetails::MandateDetails(mandate_details) => { - mandate_details.mandate_type - } - }) - .map(|d| match d { + mandate_payment: payment_attempt.and_then(|inner| inner.mandate_details).map( + |d| match d { data_models::mandates::MandateDataType::SingleUse(i) => { api::MandateType::SingleUse(api::MandateAmountData { amount: i.amount, @@ -1869,7 +1860,8 @@ pub async fn list_payment_methods( data_models::mandates::MandateDataType::MultiUse(None) => { api::MandateType::MultiUse(None) } - }), + }, + ), show_surcharge_breakup_screen: merchant_surcharge_configs .show_surcharge_breakup_screen .unwrap_or_default(), @@ -2079,28 +2071,20 @@ pub async fn filter_payment_methods( })?; let filter7 = payment_attempt .and_then(|attempt| attempt.mandate_details.as_ref()) - .map(|mandate_details| { - let (mandate_type_present, update_mandate_id_present) = - match mandate_details { - data_models::mandates::MandateTypeDetails::MandateType(_) => { - (true, false) - } - data_models::mandates::MandateTypeDetails::MandateDetails( - mand_details, - ) => ( - mand_details.mandate_type.is_some(), - mand_details.update_mandate_id.is_some(), - ), - }; - - if mandate_type_present { - filter_pm_based_on_supported_payments_for_mandate( - supported_payment_methods_for_mandate, - &payment_method, - &payment_method_object.payment_method_type, - connector_variant, - ) - } else if update_mandate_id_present { + .map(|_mandate_details| { + filter_pm_based_on_supported_payments_for_mandate( + supported_payment_methods_for_mandate, + &payment_method, + &payment_method_object.payment_method_type, + connector_variant, + ) + }) + .unwrap_or(true); + + let filter8 = payment_attempt + .and_then(|attempt| attempt.mandate_data.as_ref()) + .map(|mandate_detail| { + if mandate_detail.update_mandate_id.is_some() { filter_pm_based_on_update_mandate_support_for_connector( supported_payment_methods_for_update_mandate, &payment_method, @@ -2121,7 +2105,15 @@ pub async fn filter_payment_methods( payment_method, ); - if filter && filter2 && filter3 && filter4 && filter5 && filter6 && filter7 { + if filter + && filter2 + && filter3 + && filter4 + && filter5 + && filter6 + && filter7 + && filter8 + { resp.push(response_pm_type); } } diff --git a/crates/router/src/core/payments/helpers.rs b/crates/router/src/core/payments/helpers.rs index 7ec1f5e9213..c6ba4a4e987 100644 --- a/crates/router/src/core/payments/helpers.rs +++ b/crates/router/src/core/payments/helpers.rs @@ -3201,6 +3201,7 @@ impl AttemptType { unified_code: None, unified_message: None, net_amount: old_payment_attempt.amount, + mandate_data: old_payment_attempt.mandate_data, } } diff --git a/crates/router/src/core/payments/operations/payment_confirm.rs b/crates/router/src/core/payments/operations/payment_confirm.rs index 54ec47ecea5..8349f050135 100644 --- a/crates/router/src/core/payments/operations/payment_confirm.rs +++ b/crates/router/src/core/payments/operations/payment_confirm.rs @@ -441,28 +441,11 @@ impl<F: Send + Clone, Ctx: PaymentMethodRetrieve> // The operation merges mandate data from both request and payment_attempt setup_mandate = setup_mandate.map(|mut sm| { - sm.mandate_type = payment_attempt - .mandate_details - .clone() - .and_then(|mandate| match mandate { - data_models::mandates::MandateTypeDetails::MandateType(mandate_type) => { - Some(mandate_type) - } - data_models::mandates::MandateTypeDetails::MandateDetails(mandate_details) => { - mandate_details.mandate_type - } - }) - .or(sm.mandate_type); + sm.mandate_type = payment_attempt.mandate_details.clone().or(sm.mandate_type); sm.update_mandate_id = payment_attempt - .mandate_details + .mandate_data .clone() - .and_then(|mandate| match mandate { - data_models::mandates::MandateTypeDetails::MandateType(_) => None, - data_models::mandates::MandateTypeDetails::MandateDetails(update_id) => { - Some(update_id.update_mandate_id) - } - }) - .flatten() + .and_then(|mandate| mandate.update_mandate_id) .or(sm.update_mandate_id); sm }); diff --git a/crates/router/src/core/payments/operations/payment_create.rs b/crates/router/src/core/payments/operations/payment_create.rs index 8d37fc486c5..0f581be3089 100644 --- a/crates/router/src/core/payments/operations/payment_create.rs +++ b/crates/router/src/core/payments/operations/payment_create.rs @@ -4,7 +4,7 @@ use api_models::enums::FrmSuggestion; use async_trait::async_trait; use common_utils::ext_traits::{AsyncExt, Encode, ValueExt}; use data_models::{ - mandates::{MandateData, MandateDetails, MandateTypeDetails}, + mandates::{MandateData, MandateDetails}, payments::payment_attempt::PaymentAttempt, }; use diesel_models::ephemeral_key; @@ -733,27 +733,17 @@ impl PaymentCreate { Err(errors::ApiErrorResponse::InvalidRequestData {message:"Only one field out of 'mandate_type' and 'update_mandate_id' was expected, found both".to_string()})? } - let mandate_details = if request.mandate_data.is_none() { - None - } else if let Some(update_id) = request + let mandate_data = if let Some(update_id) = request .mandate_data .as_ref() .and_then(|inner| inner.update_mandate_id.clone()) { - let mandate_data = MandateDetails { + let mandate_details = MandateDetails { update_mandate_id: Some(update_id), - mandate_type: None, }; - Some(MandateTypeDetails::MandateDetails(mandate_data)) + Some(mandate_details) } else { - let mandate_data = MandateDetails { - update_mandate_id: None, - mandate_type: request - .mandate_data - .as_ref() - .and_then(|inner| inner.mandate_type.clone().map(Into::into)), - }; - Some(MandateTypeDetails::MandateDetails(mandate_data)) + None }; Ok(( @@ -782,7 +772,11 @@ impl PaymentCreate { business_sub_label: request.business_sub_label.clone(), surcharge_amount, tax_amount, - mandate_details, + mandate_details: request + .mandate_data + .as_ref() + .and_then(|inner| inner.mandate_type.clone().map(Into::into)), + mandate_data, ..storage::PaymentAttemptNew::default() }, additional_pm_data, diff --git a/crates/storage_impl/src/mock_db/payment_attempt.rs b/crates/storage_impl/src/mock_db/payment_attempt.rs index 24863ddc568..e60e32227d3 100644 --- a/crates/storage_impl/src/mock_db/payment_attempt.rs +++ b/crates/storage_impl/src/mock_db/payment_attempt.rs @@ -147,6 +147,7 @@ impl PaymentAttemptInterface for MockDb { merchant_connector_id: payment_attempt.merchant_connector_id, unified_code: payment_attempt.unified_code, unified_message: payment_attempt.unified_message, + mandate_data: payment_attempt.mandate_data, }; 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 6af136c1062..ec19e30c0ec 100644 --- a/crates/storage_impl/src/payments/payment_attempt.rs +++ b/crates/storage_impl/src/payments/payment_attempt.rs @@ -2,7 +2,7 @@ use api_models::enums::{AuthenticationType, Connector, PaymentMethod, PaymentMet use common_utils::{errors::CustomResult, fallback_reverse_lookup_not_found}; use data_models::{ errors, - mandates::{MandateAmountData, MandateDataType, MandateDetails, MandateTypeDetails}, + mandates::{MandateAmountData, MandateDataType, MandateDetails}, payments::{ payment_attempt::{ PaymentAttempt, PaymentAttemptInterface, PaymentAttemptNew, PaymentAttemptUpdate, @@ -14,8 +14,7 @@ use data_models::{ use diesel_models::{ enums::{ MandateAmountData as DieselMandateAmountData, MandateDataType as DieselMandateType, - MandateDetails as DieselMandateDetails, MandateTypeDetails as DieselMandateTypeOrDetails, - MerchantStorageScheme, + MandateDetails as DieselMandateDetails, MerchantStorageScheme, }, kv, payment_attempt::{ @@ -391,6 +390,7 @@ impl<T: DatabaseStore> PaymentAttemptInterface for KVRouterStore<T> { merchant_connector_id: payment_attempt.merchant_connector_id.clone(), unified_code: payment_attempt.unified_code.clone(), unified_message: payment_attempt.unified_message.clone(), + mandate_data: payment_attempt.mandate_data.clone(), }; let field = format!("pa_{}", created_attempt.attempt_id); @@ -1016,42 +1016,11 @@ impl DataModelExt for MandateDetails { fn to_storage_model(self) -> Self::StorageModel { DieselMandateDetails { update_mandate_id: self.update_mandate_id, - mandate_type: self - .mandate_type - .map(|mand_type| mand_type.to_storage_model()), } } fn from_storage_model(storage_model: Self::StorageModel) -> Self { Self { update_mandate_id: storage_model.update_mandate_id, - mandate_type: storage_model - .mandate_type - .map(MandateDataType::from_storage_model), - } - } -} -impl DataModelExt for MandateTypeDetails { - type StorageModel = DieselMandateTypeOrDetails; - - fn to_storage_model(self) -> Self::StorageModel { - match self { - Self::MandateType(mandate_type) => { - DieselMandateTypeOrDetails::MandateType(mandate_type.to_storage_model()) - } - Self::MandateDetails(mandate_details) => { - DieselMandateTypeOrDetails::MandateDetails(mandate_details.to_storage_model()) - } - } - } - - fn from_storage_model(storage_model: Self::StorageModel) -> Self { - match storage_model { - DieselMandateTypeOrDetails::MandateType(data) => { - Self::MandateType(MandateDataType::from_storage_model(data)) - } - DieselMandateTypeOrDetails::MandateDetails(data) => { - Self::MandateDetails(MandateDetails::from_storage_model(data)) - } } } } @@ -1124,7 +1093,7 @@ impl DataModelExt for PaymentAttempt { business_sub_label: self.business_sub_label, straight_through_algorithm: self.straight_through_algorithm, preprocessing_step_id: self.preprocessing_step_id, - mandate_details: self.mandate_details.map(|md| md.to_storage_model()), + mandate_details: self.mandate_details.map(|d| d.to_storage_model()), error_reason: self.error_reason, multiple_capture_count: self.multiple_capture_count, connector_response_reference_id: self.connector_response_reference_id, @@ -1135,6 +1104,7 @@ impl DataModelExt for PaymentAttempt { merchant_connector_id: self.merchant_connector_id, unified_code: self.unified_code, unified_message: self.unified_message, + mandate_data: self.mandate_data.map(|d| d.to_storage_model()), } } @@ -1179,7 +1149,7 @@ impl DataModelExt for PaymentAttempt { preprocessing_step_id: storage_model.preprocessing_step_id, mandate_details: storage_model .mandate_details - .map(MandateTypeDetails::from_storage_model), + .map(MandateDataType::from_storage_model), error_reason: storage_model.error_reason, multiple_capture_count: storage_model.multiple_capture_count, connector_response_reference_id: storage_model.connector_response_reference_id, @@ -1190,6 +1160,9 @@ impl DataModelExt for PaymentAttempt { merchant_connector_id: storage_model.merchant_connector_id, unified_code: storage_model.unified_code, unified_message: storage_model.unified_message, + mandate_data: storage_model + .mandate_data + .map(MandateDetails::from_storage_model), } } } @@ -1245,6 +1218,7 @@ impl DataModelExt for PaymentAttemptNew { merchant_connector_id: self.merchant_connector_id, unified_code: self.unified_code, unified_message: self.unified_message, + mandate_data: self.mandate_data.map(|d| d.to_storage_model()), } } @@ -1287,7 +1261,7 @@ impl DataModelExt for PaymentAttemptNew { preprocessing_step_id: storage_model.preprocessing_step_id, mandate_details: storage_model .mandate_details - .map(MandateTypeDetails::from_storage_model), + .map(MandateDataType::from_storage_model), error_reason: storage_model.error_reason, connector_response_reference_id: storage_model.connector_response_reference_id, multiple_capture_count: storage_model.multiple_capture_count, @@ -1298,6 +1272,9 @@ impl DataModelExt for PaymentAttemptNew { merchant_connector_id: storage_model.merchant_connector_id, unified_code: storage_model.unified_code, unified_message: storage_model.unified_message, + mandate_data: storage_model + .mandate_data + .map(MandateDetails::from_storage_model), } } } diff --git a/migrations/2024-02-08-142804_add_mandate_data_payment_attempt/down.sql b/migrations/2024-02-08-142804_add_mandate_data_payment_attempt/down.sql new file mode 100644 index 00000000000..9d2071f8dda --- /dev/null +++ b/migrations/2024-02-08-142804_add_mandate_data_payment_attempt/down.sql @@ -0,0 +1,2 @@ +-- This file should undo anything in `up.sql` +ALTER TABLE payment_attempt DROP COLUMN IF EXISTS mandate_data; diff --git a/migrations/2024-02-08-142804_add_mandate_data_payment_attempt/up.sql b/migrations/2024-02-08-142804_add_mandate_data_payment_attempt/up.sql new file mode 100644 index 00000000000..31ed6e88fea --- /dev/null +++ b/migrations/2024-02-08-142804_add_mandate_data_payment_attempt/up.sql @@ -0,0 +1,3 @@ +-- Your SQL goes here +ALTER TABLE payment_attempt +ADD COLUMN IF NOT EXISTS mandate_data JSONB DEFAULT NULL; \ No newline at end of file
2024-02-09T05:57:16Z
## Type of Change <!-- Put an `x` in the boxes that apply --> - [x] Bugfix - [ ] New feature - [ ] Enhancement - [ ] Refactoring - [ ] Dependency updates - [ ] Documentation - [ ] CI/CD ## Description To make the mandate_details forward compatible , instead of storing update mandate id in mandate details we store it in the new column mandate data. Currently in mandate_data column we only store update_mandate_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? - Create an MA and an MCA - Make a mandate_payment - And then make an update_mandate_payment with the mandate_id generated in the previous step - The card would be updated and reflected when we do list mandate <img width="1728" alt="Screenshot 2024-02-09 at 1 08 48 PM" src="https://github.com/juspay/hyperswitch/assets/55580080/13fdc4ba-479f-4f9f-ad65-56c5c14d9dbf"> ![Screenshot 2024-02-09 at 1 11 56 PM](https://github.com/juspay/hyperswitch/assets/55580080/8f22d291-4c06-4bf5-a3cb-d6edf6a43f64) <img width="1728" alt="Screenshot 2024-02-09 at 1 12 35 PM" src="https://github.com/juspay/hyperswitch/assets/55580080/74e4cb0f-aae3-451e-9b7a-647da8167c67"> ![Screenshot 2024-02-09 at 1 13 19 PM](https://github.com/juspay/hyperswitch/assets/55580080/61594860-7353-4ebb-ad5e-a8a565331cb0) ## 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 - [ ] I added a [CHANGELOG](/CHANGELOG.md) entry if applicable
e54b0dd20fabf48cc8f6ea59bb197f05b8b5adeb
- Create an MA and an MCA - Make a mandate_payment - And then make an update_mandate_payment with the mandate_id generated in the previous step - The card would be updated and reflected when we do list mandate <img width="1728" alt="Screenshot 2024-02-09 at 1 08 48 PM" src="https://github.com/juspay/hyperswitch/assets/55580080/13fdc4ba-479f-4f9f-ad65-56c5c14d9dbf"> ![Screenshot 2024-02-09 at 1 11 56 PM](https://github.com/juspay/hyperswitch/assets/55580080/8f22d291-4c06-4bf5-a3cb-d6edf6a43f64) <img width="1728" alt="Screenshot 2024-02-09 at 1 12 35 PM" src="https://github.com/juspay/hyperswitch/assets/55580080/74e4cb0f-aae3-451e-9b7a-647da8167c67"> ![Screenshot 2024-02-09 at 1 13 19 PM](https://github.com/juspay/hyperswitch/assets/55580080/61594860-7353-4ebb-ad5e-a8a565331cb0)
juspay/hyperswitch
juspay__hyperswitch-3599
Bug: permission-info Order change Change the ordering of the [ThreeDsDecisionManagerWrite , ThreeDsDecisionManagerRead] and [SurchargeDecisionManagerWrite, SurchargeDecisionManagerRead] of permissionInfo API.
diff --git a/crates/router/src/services/authorization/info.rs b/crates/router/src/services/authorization/info.rs index 99e4f1b6c09..450a5a738c3 100644 --- a/crates/router/src/services/authorization/info.rs +++ b/crates/router/src/services/authorization/info.rs @@ -159,8 +159,8 @@ impl ModuleInfo { module: module_name, description, permissions: PermissionInfo::new(&[ - Permission::ThreeDsDecisionManagerWrite, Permission::ThreeDsDecisionManagerRead, + Permission::ThreeDsDecisionManagerWrite, ]), }, @@ -168,8 +168,8 @@ impl ModuleInfo { module: module_name, description, permissions: PermissionInfo::new(&[ - Permission::SurchargeDecisionManagerWrite, Permission::SurchargeDecisionManagerRead, + Permission::SurchargeDecisionManagerWrite, ]), }, PermissionModule::AccountCreate => Self {
2024-02-08T09:02:32Z
## 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 --> Change the ordering of the [ThreeDsDecisionManagerWrite , ThreeDsDecisionManagerRead] and [SurchargeDecisionManagerWrite, SurchargeDecisionManagerRead] of permissionInfo 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). --> ``` Previous { "module": "ThreeDsDecisionManager", "description": "View and configure 3DS decision rules configured for a merchant", "permissions": [ { "enum_name": "ThreeDsDecisionManagerWrite", "description": "Create and update 3DS decision rules" }, { "enum_name": "ThreeDsDecisionManagerRead", "description": "View all 3DS decision rules configured for a merchant" } ] } Now { "module": "ThreeDsDecisionManager", "description": "View and configure 3DS decision rules configured for a merchant", "permissions": [ { "enum_name": "ThreeDsDecisionManagerRead", "description": "View all 3DS decision rules configured for a merchant" }, { "enum_name": "ThreeDsDecisionManagerWrite", "description": "Create and update 3DS decision rules" } ] } ``` ## 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/permission_info' \ --header 'api-key: hyperswitch' \ --header 'authorization: Bearer <JWT> \ --header 'content-type: application/json' \ ``` ## 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 - [ ] I added a [CHANGELOG](/CHANGELOG.md) entry if applicable
3a869a2d5731a2393a687ed7773eda5344bd8e3f
``` curl --location 'http://localhost:8080/user/permission_info' \ --header 'api-key: hyperswitch' \ --header 'authorization: Bearer <JWT> \ --header 'content-type: application/json' \ ```
juspay/hyperswitch
juspay__hyperswitch-3604
Bug: chore: address Rust 1.76 clippy lints Address the clippy lints occurring due to new rust version 1.76 See #3391 for more information.
diff --git a/crates/router/src/compatibility/wrap.rs b/crates/router/src/compatibility/wrap.rs index d3ca0172f26..da14475f120 100644 --- a/crates/router/src/compatibility/wrap.rs +++ b/crates/router/src/compatibility/wrap.rs @@ -42,7 +42,7 @@ where let start_instant = Instant::now(); logger::info!(tag = ?Tag::BeginRequest, payload = ?payload); - let res = match metrics::request::record_request_time_metric( + let server_wrap_util_res = metrics::request::record_request_time_metric( api::server_wrap_util( &flow, state.clone().into(), @@ -58,7 +58,9 @@ where .map(|response| { logger::info!(api_response =? response); response - }) { + }); + + let res = match server_wrap_util_res { Ok(api::ApplicationResponse::Json(response)) => { let response = S::try_from(response); match response { diff --git a/crates/router/src/db/address.rs b/crates/router/src/db/address.rs index 689d1f9c789..99006752f57 100644 --- a/crates/router/src/db/address.rs +++ b/crates/router/src/db/address.rs @@ -656,7 +656,7 @@ impl AddressInterface for MockDb { address_update: storage_types::AddressUpdate, key_store: &domain::MerchantKeyStore, ) -> CustomResult<domain::Address, errors::StorageError> { - match self + let updated_addr = self .addresses .lock() .await @@ -667,7 +667,8 @@ impl AddressInterface for MockDb { AddressUpdateInternal::from(address_update).create_address(a.clone()); *a = address_updated.clone(); address_updated - }) { + }); + match updated_addr { Some(address_updated) => address_updated .convert(key_store.key.get_inner()) .await @@ -687,7 +688,7 @@ impl AddressInterface for MockDb { key_store: &domain::MerchantKeyStore, _storage_scheme: MerchantStorageScheme, ) -> CustomResult<domain::Address, errors::StorageError> { - match self + let updated_addr = self .addresses .lock() .await @@ -698,7 +699,8 @@ impl AddressInterface for MockDb { AddressUpdateInternal::from(address_update).create_address(a.clone()); *a = address_updated.clone(); address_updated - }) { + }); + match updated_addr { Some(address_updated) => address_updated .convert(key_store.key.get_inner()) .await @@ -757,7 +759,7 @@ impl AddressInterface for MockDb { address_update: storage_types::AddressUpdate, key_store: &domain::MerchantKeyStore, ) -> CustomResult<Vec<domain::Address>, errors::StorageError> { - match self + let updated_addr = self .addresses .lock() .await @@ -771,7 +773,8 @@ impl AddressInterface for MockDb { AddressUpdateInternal::from(address_update).create_address(a.clone()); *a = address_updated.clone(); address_updated - }) { + }); + match updated_addr { Some(address) => { let address: domain::Address = address .convert(key_store.key.get_inner()) diff --git a/crates/router/src/db/merchant_connector_account.rs b/crates/router/src/db/merchant_connector_account.rs index 3718b962b45..0dd20721c3a 100644 --- a/crates/router/src/db/merchant_connector_account.rs +++ b/crates/router/src/db/merchant_connector_account.rs @@ -691,7 +691,7 @@ impl MerchantConnectorAccountInterface for MockDb { merchant_connector_account: storage::MerchantConnectorAccountUpdateInternal, key_store: &domain::MerchantKeyStore, ) -> CustomResult<domain::MerchantConnectorAccount, errors::StorageError> { - match self + let mca_update_res = self .merchant_connector_accounts .lock() .await @@ -709,8 +709,9 @@ impl MerchantConnectorAccountInterface for MockDb { .await .change_context(errors::StorageError::DecryptionError) }) - .await - { + .await; + + match mca_update_res { Some(result) => result, None => { return Err(errors::StorageError::ValueNotFound( diff --git a/crates/router/src/db/payment_method.rs b/crates/router/src/db/payment_method.rs index dd7cbedd0f4..b109d1fe5bd 100644 --- a/crates/router/src/db/payment_method.rs +++ b/crates/router/src/db/payment_method.rs @@ -212,7 +212,7 @@ impl PaymentMethodInterface for MockDb { payment_method: storage::PaymentMethod, payment_method_update: storage::PaymentMethodUpdate, ) -> CustomResult<storage::PaymentMethod, errors::StorageError> { - match self + let pm_update_res = self .payment_methods .lock() .await @@ -224,7 +224,9 @@ impl PaymentMethodInterface for MockDb { .create_payment_method(pm.clone()); *pm = payment_method_updated.clone(); payment_method_updated - }) { + }); + + match pm_update_res { Some(result) => Ok(result), None => Err(errors::StorageError::ValueNotFound( "cannot find payment method to update".to_string(), diff --git a/crates/router/src/services/api.rs b/crates/router/src/services/api.rs index 5a6ff7e9b67..28405c001eb 100644 --- a/crates/router/src/services/api.rs +++ b/crates/router/src/services/api.rs @@ -1083,7 +1083,7 @@ where let start_instant = Instant::now(); logger::info!(tag = ?Tag::BeginRequest, payload = ?payload); - let res = match metrics::request::record_request_time_metric( + let server_wrap_util_res = metrics::request::record_request_time_metric( server_wrap_util( &flow, state.clone(), @@ -1099,7 +1099,9 @@ where .map(|response| { logger::info!(api_response =? response); response - }) { + }); + + let res = match server_wrap_util_res { Ok(ApplicationResponse::Json(response)) => match serde_json::to_string(&response) { Ok(res) => http_response_json(res), Err(_) => http_response_err( diff --git a/crates/scheduler/src/utils.rs b/crates/scheduler/src/utils.rs index 32fd97fca33..f6a340e9d59 100644 --- a/crates/scheduler/src/utils.rs +++ b/crates/scheduler/src/utils.rs @@ -109,7 +109,7 @@ where { Ok(x) => Ok(x), Err(mut err) => { - match state + let update_res = state .process_tracker_update_process_status_by_ids( pt_batch.trackers.iter().map(|process| process.id.clone()).collect(), storage::ProcessTrackerUpdate::StatusUpdate { @@ -123,12 +123,14 @@ where }, |count| { logger::debug!("Updated status of {count} processes"); Ok(()) - }) { - Ok(_) => (), - Err(inner_err) => { - err.extend_one(inner_err); - } - }; + }); + + match update_res { + Ok(_) => (), + Err(inner_err) => { + err.extend_one(inner_err); + } + }; Err(err) } diff --git a/crates/test_utils/src/newman_runner.rs b/crates/test_utils/src/newman_runner.rs index a6e0268e2c2..961853548a2 100644 --- a/crates/test_utils/src/newman_runner.rs +++ b/crates/test_utils/src/newman_runner.rs @@ -56,7 +56,6 @@ where // Open the file in write mode or create it if it doesn't exist let mut file = std::fs::OpenOptions::new() - .write(true) .append(true) .create(true) .open(file_path)?;
2024-02-08T17:02:07Z
## 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.76 ### 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)? --> Rust updation clippy lints are addressed here. So basic sanity test 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 - [ ] I added a [CHANGELOG](/CHANGELOG.md) entry if applicable
dd5630f070db28051a3dd59a66f0a4ee6777e38f
Rust updation clippy lints are addressed here. So basic sanity test should suffice
juspay/hyperswitch
juspay__hyperswitch-3614
Bug: [BUG] : [Adyen] Handle redirection response incase of no connector_transaction_id ### Bug Description In Adyen, for certain payment methods that involve redirection, the /payments API call doesn't return a psp_reference (Adyen's transaction ID). In such cases, we need to save the redirectResult field from the redirection response parameter into `encoded_data` field of our payment attempt to facilitate a Psync with proper payment context. However, we have observed that our Psync call lacks context of the Adyen payment because the redirectResult is not stored in the encoded_data ### Expected Behavior Psync for all redirection payments must hit Adyen and retrieve the status of appropriate payment. ### Actual Behavior Psync call has no context of the connector_transaction_id ### Steps To Reproduce Provide an unambiguous set of steps to reproduce this bug. Include code or configuration to reproduce, if relevant. 1.Create a payment with adyen wechatpay 2.Do a Psync call (the payment status remains to be `requires_customer_action` ### 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? None
diff --git a/config/config.example.toml b/config/config.example.toml index abe3f6b4e08..760cc2bdd00 100644 --- a/config/config.example.toml +++ b/config/config.example.toml @@ -409,6 +409,10 @@ afterpay_clearpay = { fields = { stripe = [ # payment_method_type = afterpay_cle payout_eligibility = true # Defaults the eligibility of a payout method to true in case connector does not provide checks for payout eligibility [pm_filters.adyen] +sofort = { country = "AT,BE,DE,ES,CH,NL", currency = "CHF,EUR"} +paypal = { country = "AU,NZ,CN,JP,HK,MY,TH,KR,PH,ID,AE,KW,BR,ES,GB,SE,NO,SK,AT,NL,DE,HU,CY,LU,CH,BE,FR,DK,FI,RO,HR,UA,MT,SI,GI,PT,IE,CZ,EE,LT,LV,IT,PL,IS,CA,US", currency = "AUD,BRL,CAD,CZK,DKK,EUR,HKD,HUF,INR,JPY,MYR,MXN,NZD,NOK,PHP,PLN,RUB,GBP,SGD,SEK,CHF,THB,USD" } +klarna = { country = "AU,AT,BE,CA,CZ,DK,FI,FR,DE,GR,IE,IT,NO,PL,PT,RO,ES,SE,CH,NL,GB,US", currency = "AUD,EUR,CAD,CZK,DKK,NOK,PLN,RON,SEK,CHF,GBP,USD"} +ideal = { country = "NL", currency = "EUR" } online_banking_fpx = { country = "MY", currency = "MYR" } online_banking_thailand = { country = "TH", currency = "THB" } touch_n_go = { country = "MY", currency = "MYR" } diff --git a/config/deployments/integration_test.toml b/config/deployments/integration_test.toml index dba591ae679..dd755c9dd22 100644 --- a/config/deployments/integration_test.toml +++ b/config/deployments/integration_test.toml @@ -1,7 +1,7 @@ [bank_config] eps.adyen.banks = "bank_austria,bawag_psk_ag,dolomitenbank,easybank_ag,erste_bank_und_sparkassen,hypo_tirol_bank_ag,posojilnica_bank_e_gen,raiffeisen_bankengruppe_osterreich,schoellerbank_ag,sparda_bank_wien,volksbank_gruppe,volkskreditbank_ag" eps.stripe.banks = "arzte_und_apotheker_bank,austrian_anadi_bank_ag,bank_austria,bankhaus_carl_spangler,bankhaus_schelhammer_und_schattera_ag,bawag_psk_ag,bks_bank_ag,brull_kallmus_bank_ag,btv_vier_lander_bank,capital_bank_grawe_gruppe_ag,dolomitenbank,easybank_ag,erste_bank_und_sparkassen,hypo_alpeadriabank_international_ag,hypo_noe_lb_fur_niederosterreich_u_wien,hypo_oberosterreich_salzburg_steiermark,hypo_tirol_bank_ag,hypo_vorarlberg_bank_ag,hypo_bank_burgenland_aktiengesellschaft,marchfelder_bank,oberbank_ag,raiffeisen_bankengruppe_osterreich,schoellerbank_ag,sparda_bank_wien,volksbank_gruppe,volkskreditbank_ag,vr_bank_braunau" -ideal.adyen.banks = "abn_amro,asn_bank,bunq,handelsbanken,ing,knab,moneyou,rabobank,regiobank,revolut,sns_bank,triodos_bank,van_lanschot" +ideal.adyen.banks = "abn_amro,asn_bank,bunq,ing,knab,n26,nationale_nederlanden,rabobank,regiobank,revolut,sns_bank,triodos_bank,van_lanschot,yoursafe" ideal.stripe.banks = "abn_amro,asn_bank,bunq,handelsbanken,ing,knab,moneyou,rabobank,regiobank,revolut,sns_bank,triodos_bank,van_lanschot" online_banking_czech_republic.adyen.banks = "ceska_sporitelna,komercni_banka,platnosc_online_karta_platnicza" online_banking_fpx.adyen.banks = "affin_bank,agro_bank,alliance_bank,am_bank,bank_islam,bank_muamalat,bank_rakyat,bank_simpanan_nasional,cimb_bank,hong_leong_bank,hsbc_bank,kuwait_finance_house,maybank,ocbc_bank,public_bank,rhb_bank,standard_chartered_bank,uob_bank" @@ -174,7 +174,7 @@ google_pay = { country = "AU,NZ,JP,HK,SG,MY,TH,VN,BH,AE,KW,BR,ES,GB,SE,NO,SK,AT, ideal = { country = "NL", currency = "EUR" } indomaret = { country = "ID", currency = "IDR" } kakao_pay = { country = "KR", currency = "KRW" } -klarna = { country = "AT,ES,GB,SE,NO,AT,NL,DE,CH,BE,FR,DK,FI,PT,IE,IT,PL,CA,US", currency = "USD,GBP,EUR,CHF,DKK,SEK,NOK,AUD,PLN,CAD" } +klarna = { country = "AU,AT,BE,CA,CZ,DK,FI,FR,DE,GR,IE,IT,NO,PL,PT,RO,ES,SE,CH,NL,GB,US", currency = "AUD,EUR,CAD,CZK,DKK,NOK,PLN,RON,SEK,CHF,GBP,USD"} lawson = { country = "JP", currency = "JPY" } mandiri_va = { country = "ID", currency = "IDR" } mb_way = { country = "PT", currency = "EUR" } @@ -193,12 +193,13 @@ oxxo = { country = "MX", currency = "MXN" } pay_bright = { country = "CA", currency = "CAD" } pay_easy = { country = "JP", currency = "JPY" } pay_safe_card = { country = "AT,AU,BE,BR,BE,CA,HR,CY,CZ,DK,FI,FR,GE,DE,GI,HU,IS,IE,KW,LV,IE,LI,LT,LU,MT,MX,MD,ME,NL,NZ,NO,PY,PE,PL,PT,RO,SA,RS,SK,SI,ES,SE,CH,TR,AE,GB,US,UY", currency = "EUR,AUD,BRL,CAD,CZK,DKK,GEL,GIP,HUF,KWD,CHF,MXN,MDL,NZD,NOK,PYG,PEN,PLN,RON,SAR,RSD,SEK,TRY,AED,GBP,USD,UYU" } -paypal = { country = "AU,NZ,CN,JP,HK,MY,TH,KR,PH,ID,AE,KW,BR,ES,GB,SE,NO,SK,AT,NL,DE,HU,CY,LU,CH,BE,FR,DK,FI,RO,HR,UA,MT,SI,GI,PT,IE,CZ,EE,LT,LV,IT,PL,IS,CA,US", currency = "AUD,BRL,CAD,CZK,DKK,EUR,HKD,HUF,INR,JPY,MYR,MXN,NZD,NOK,PHP,PLN,RUB,GBP,SGD,SEK,CHF,THB,USD" } permata_bank_transfer = { country = "ID", currency = "IDR" } seicomart = { country = "JP", currency = "JPY" } sepa = { country = "ES,SK,AT,NL,DE,BE,FR,FI,PT,IE,EE,LT,LV,IT", currency = "EUR" } seven_eleven = { country = "JP", currency = "JPY" } -sofort = { country = "ES,GB,SE,AT,NL,DE,CH,BE,FR,FI,IT,PL", currency = "EUR" } +sofort = { country = "AT,BE,DE,ES,CH,NL", currency = "CHF,EUR"} +paypal = { country = "AU,NZ,CN,JP,HK,MY,TH,KR,PH,ID,AE,KW,BR,ES,GB,SE,NO,SK,AT,NL,DE,HU,CY,LU,CH,BE,FR,DK,FI,RO,HR,UA,MT,SI,GI,PT,IE,CZ,EE,LT,LV,IT,PL,IS,CA,US", currency = "AUD,BRL,CAD,CZK,DKK,EUR,HKD,HUF,INR,JPY,MYR,MXN,NZD,NOK,PHP,PLN,RUB,GBP,SGD,SEK,CHF,THB,USD" } + swish = { country = "SE", currency = "SEK" } touch_n_go = { country = "MY", currency = "MYR" } trustly = { country = "ES,GB,SE,NO,AT,NL,DE,DK,FI,EE,LT,LV", currency = "CZK,DKK,EUR,GBP,NOK,SEK" } diff --git a/config/deployments/production.toml b/config/deployments/production.toml index 48bb9d33e3f..9c2f25b24ff 100644 --- a/config/deployments/production.toml +++ b/config/deployments/production.toml @@ -1,7 +1,7 @@ [bank_config] eps.adyen.banks = "bank_austria,bawag_psk_ag,dolomitenbank,easybank_ag,erste_bank_und_sparkassen,hypo_tirol_bank_ag,posojilnica_bank_e_gen,raiffeisen_bankengruppe_osterreich,schoellerbank_ag,sparda_bank_wien,volksbank_gruppe,volkskreditbank_ag" eps.stripe.banks = "arzte_und_apotheker_bank,austrian_anadi_bank_ag,bank_austria,bankhaus_carl_spangler,bankhaus_schelhammer_und_schattera_ag,bawag_psk_ag,bks_bank_ag,brull_kallmus_bank_ag,btv_vier_lander_bank,capital_bank_grawe_gruppe_ag,dolomitenbank,easybank_ag,erste_bank_und_sparkassen,hypo_alpeadriabank_international_ag,hypo_noe_lb_fur_niederosterreich_u_wien,hypo_oberosterreich_salzburg_steiermark,hypo_tirol_bank_ag,hypo_vorarlberg_bank_ag,hypo_bank_burgenland_aktiengesellschaft,marchfelder_bank,oberbank_ag,raiffeisen_bankengruppe_osterreich,schoellerbank_ag,sparda_bank_wien,volksbank_gruppe,volkskreditbank_ag,vr_bank_braunau" -ideal.adyen.banks = "abn_amro,asn_bank,bunq,handelsbanken,ing,knab,moneyou,rabobank,regiobank,revolut,sns_bank,triodos_bank,van_lanschot" +ideal.adyen.banks = "abn_amro,asn_bank,bunq,ing,knab,n26,nationale_nederlanden,rabobank,regiobank,revolut,sns_bank,triodos_bank,van_lanschot,yoursafe" ideal.stripe.banks = "abn_amro,asn_bank,bunq,handelsbanken,ing,knab,moneyou,rabobank,regiobank,revolut,sns_bank,triodos_bank,van_lanschot" online_banking_czech_republic.adyen.banks = "ceska_sporitelna,komercni_banka,platnosc_online_karta_platnicza" online_banking_fpx.adyen.banks = "affin_bank,agro_bank,alliance_bank,am_bank,bank_islam,bank_muamalat,bank_rakyat,bank_simpanan_nasional,cimb_bank,hong_leong_bank,hsbc_bank,kuwait_finance_house,maybank,ocbc_bank,public_bank,rhb_bank,standard_chartered_bank,uob_bank" @@ -17,8 +17,8 @@ payout_connector_list = "wise" [connectors] aci.base_url = "https://eu-test.oppwa.com/" -adyen.base_url = "https://checkout-test.adyen.com/" -adyen.secondary_base_url = "https://pal-test.adyen.com/" +adyen.base_url = "https://{{merchant_endpoint_prefix}}-checkout-live.adyenpayments.com/" +adyen.secondary_base_url = "https://{{merchant_endpoint_prefix}}-pal-live.adyenpayments.com/" airwallex.base_url = "https://api-demo.airwallex.com/" applepay.base_url = "https://apple-pay-gateway.apple.com/" authorizedotnet.base_url = "https://apitest.authorize.net/xml/v1/request.api" @@ -189,7 +189,7 @@ google_pay = { country = "AE,AG,AL,AO,AR,AS,AT,AU,AZ,BE,BG,BH,BR,BY,CA,CH,CL,CO, ideal = { country = "NL", currency = "EUR" } indomaret = { country = "ID", currency = "IDR" } kakao_pay = { country = "KR", currency = "KRW" } -klarna = { country = "AT,BE,CA,CH,DE,DK,ES,FI,FR,GB,IE,IT,NL,NO,PL,PT,SE,GB,US", currency = "AUD,CAD,CHF,DKK,EUR,GBP,NOK,PLN,SEK,USD" } +klarna = { country = "AU,AT,BE,CA,CZ,DK,FI,FR,DE,GR,IE,IT,NO,PL,PT,RO,ES,SE,CH,NL,GB,US", currency = "AUD,EUR,CAD,CZK,DKK,NOK,PLN,RON,SEK,CHF,GBP,USD"} lawson = { country = "JP", currency = "JPY" } mandiri_va = { country = "ID", currency = "IDR" } mb_way = { country = "PT", currency = "EUR" } @@ -213,7 +213,7 @@ permata_bank_transfer = { country = "ID", currency = "IDR" } seicomart = { country = "JP", currency = "JPY" } sepa = { country = "ES,SK,AT,NL,DE,BE,FR,FI,PT,IE,EE,LT,LV,IT", currency = "EUR" } seven_eleven = { country = "JP", currency = "JPY" } -sofort = { country = "AT,BE,CH,DE,ES,FI,FR,GB,IT,NL,PL,SE,GB", currency = "EUR" } +sofort = { country = "AT,BE,DE,ES,CH,NL", currency = "CHF,EUR"} swish = { country = "SE", currency = "SEK" } touch_n_go = { country = "MY", currency = "MYR" } trustly = { country = "ES,GB,SE,NO,AT,NL,DE,DK,FI,EE,LT,LV", currency = "CZK,DKK,EUR,GBP,NOK,SEK" } diff --git a/config/deployments/sandbox.toml b/config/deployments/sandbox.toml index 8723f871c34..5c052e5c85f 100644 --- a/config/deployments/sandbox.toml +++ b/config/deployments/sandbox.toml @@ -1,7 +1,7 @@ [bank_config] eps.adyen.banks = "bank_austria,bawag_psk_ag,dolomitenbank,easybank_ag,erste_bank_und_sparkassen,hypo_tirol_bank_ag,posojilnica_bank_e_gen,raiffeisen_bankengruppe_osterreich,schoellerbank_ag,sparda_bank_wien,volksbank_gruppe,volkskreditbank_ag" eps.stripe.banks = "arzte_und_apotheker_bank,austrian_anadi_bank_ag,bank_austria,bankhaus_carl_spangler,bankhaus_schelhammer_und_schattera_ag,bawag_psk_ag,bks_bank_ag,brull_kallmus_bank_ag,btv_vier_lander_bank,capital_bank_grawe_gruppe_ag,dolomitenbank,easybank_ag,erste_bank_und_sparkassen,hypo_alpeadriabank_international_ag,hypo_noe_lb_fur_niederosterreich_u_wien,hypo_oberosterreich_salzburg_steiermark,hypo_tirol_bank_ag,hypo_vorarlberg_bank_ag,hypo_bank_burgenland_aktiengesellschaft,marchfelder_bank,oberbank_ag,raiffeisen_bankengruppe_osterreich,schoellerbank_ag,sparda_bank_wien,volksbank_gruppe,volkskreditbank_ag,vr_bank_braunau" -ideal.adyen.banks = "abn_amro,asn_bank,bunq,handelsbanken,ing,knab,moneyou,rabobank,regiobank,revolut,sns_bank,triodos_bank,van_lanschot" +ideal.adyen.banks = "abn_amro,asn_bank,bunq,ing,knab,n26,nationale_nederlanden,rabobank,regiobank,revolut,sns_bank,triodos_bank,van_lanschot,yoursafe" ideal.stripe.banks = "abn_amro,asn_bank,bunq,handelsbanken,ing,knab,moneyou,rabobank,regiobank,revolut,sns_bank,triodos_bank,van_lanschot" online_banking_czech_republic.adyen.banks = "ceska_sporitelna,komercni_banka,platnosc_online_karta_platnicza" online_banking_fpx.adyen.banks = "affin_bank,agro_bank,alliance_bank,am_bank,bank_islam,bank_muamalat,bank_rakyat,bank_simpanan_nasional,cimb_bank,hong_leong_bank,hsbc_bank,kuwait_finance_house,maybank,ocbc_bank,public_bank,rhb_bank,standard_chartered_bank,uob_bank" @@ -189,7 +189,7 @@ google_pay = { country = "AU,NZ,JP,HK,SG,MY,TH,VN,BH,AE,KW,BR,ES,GB,SE,NO,SK,AT, ideal = { country = "NL", currency = "EUR" } indomaret = { country = "ID", currency = "IDR" } kakao_pay = { country = "KR", currency = "KRW" } -klarna = { country = "AT,ES,GB,SE,NO,AT,NL,DE,CH,BE,FR,DK,FI,PT,IE,IT,PL,CA,US", currency = "USD,GBP,EUR,CHF,DKK,SEK,NOK,AUD,PLN,CAD" } +klarna = { country = "AU,AT,BE,CA,CZ,DK,FI,FR,DE,GR,IE,IT,NO,PL,PT,RO,ES,SE,CH,NL,GB,US", currency = "AUD,EUR,CAD,CZK,DKK,NOK,PLN,RON,SEK,CHF,GBP,USD"} lawson = { country = "JP", currency = "JPY" } mandiri_va = { country = "ID", currency = "IDR" } mb_way = { country = "PT", currency = "EUR" } @@ -213,7 +213,7 @@ permata_bank_transfer = { country = "ID", currency = "IDR" } seicomart = { country = "JP", currency = "JPY" } sepa = { country = "ES,SK,AT,NL,DE,BE,FR,FI,PT,IE,EE,LT,LV,IT", currency = "EUR" } seven_eleven = { country = "JP", currency = "JPY" } -sofort = { country = "ES,GB,SE,AT,NL,DE,CH,BE,FR,FI,IT,PL", currency = "EUR" } +sofort = { country = "AT,BE,DE,ES,CH,NL", currency = "CHF,EUR"} swish = { country = "SE", currency = "SEK" } touch_n_go = { country = "MY", currency = "MYR" } trustly = { country = "ES,GB,SE,NO,AT,NL,DE,DK,FI,EE,LT,LV", currency = "CZK,DKK,EUR,GBP,NOK,SEK" } diff --git a/config/development.toml b/config/development.toml index d69719bd419..824ceaa8eb6 100644 --- a/config/development.toml +++ b/config/development.toml @@ -256,7 +256,7 @@ adyen = { banks = "bank_austria,bawag_psk_ag,dolomitenbank,easybank_ag,erste_ban [bank_config.ideal] stripe = { banks = "abn_amro,asn_bank,bunq,handelsbanken,ing,knab,moneyou,rabobank,regiobank,revolut,sns_bank,triodos_bank,van_lanschot" } -adyen = { banks = "abn_amro,asn_bank,bunq,handelsbanken,ing,knab,moneyou,rabobank,regiobank,revolut,sns_bank,triodos_bank,van_lanschot" } +adyen = { banks = "abn_amro,asn_bank,bunq,ing,knab,n26,nationale_nederlanden,rabobank,regiobank,revolut,sns_bank,triodos_bank,van_lanschot, yoursafe" } [bank_config.online_banking_czech_republic] adyen = { banks = "ceska_sporitelna,komercni_banka,platnosc_online_karta_platnicza" } @@ -314,14 +314,14 @@ mobile_pay = { country = "DK,FI", currency = "DKK,SEK,NOK,EUR" } ali_pay = { country = "AU,JP,HK,SG,MY,TH,ES,GB,SE,NO,AT,NL,DE,CY,CH,BE,FR,DK,FI,RO,MT,SI,GR,PT,IE,IT,CA,US", currency = "USD,EUR,GBP,JPY,AUD,SGD,CHF,SEK,NOK,NZD,THB,HKD,CAD" } we_chat_pay = { country = "AU,NZ,CN,JP,HK,SG,ES,GB,SE,NO,AT,NL,DE,CY,CH,BE,FR,DK,LI,MT,SI,GR,PT,IT,CA,US", currency = "AUD,CAD,CNY,EUR,GBP,HKD,JPY,NZD,SGD,USD" } mb_way = { country = "PT", currency = "EUR" } -klarna = { country = "AT,ES,GB,SE,NO,AT,NL,DE,CH,BE,FR,DK,FI,PT,IE,IT,PL,CA,US", currency = "USD,GBP,EUR,CHF,DKK,SEK,NOK,AUD,PLN,CAD" } +klarna = { country = "AU,AT,BE,CA,CZ,DK,FI,FR,DE,GR,IE,IT,NO,PL,PT,RO,ES,SE,CH,NL,GB,US", currency = "AUD,EUR,CAD,CZK,DKK,NOK,PLN,RON,SEK,CHF,GBP,USD"} affirm = { country = "US", currency = "USD" } afterpay_clearpay = { country = "AU,NZ,ES,GB,FR,IT,CA,US", currency = "GBP" } pay_bright = { country = "CA", currency = "CAD" } walley = { country = "SE,NO,DK,FI", currency = "DKK,EUR,NOK,SEK" } giropay = { country = "DE", currency = "EUR" } eps = { country = "AT", currency = "EUR" } -sofort = { country = "ES,GB,SE,AT,NL,DE,CH,BE,FR,FI,IT,PL", currency = "EUR" } +sofort = { country = "AT,BE,DE,ES,CH,NL", currency = "CHF,EUR"} ideal = { country = "NL", currency = "EUR" } blik = {country = "PL", currency = "PLN"} trustly = {country = "ES,GB,SE,NO,AT,NL,DE,DK,FI,EE,LT,LV", currency = "CZK,DKK,EUR,GBP,NOK,SEK"} diff --git a/config/docker_compose.toml b/config/docker_compose.toml index 8170132bb85..0aaeefb7ae8 100644 --- a/config/docker_compose.toml +++ b/config/docker_compose.toml @@ -305,6 +305,11 @@ family_mart = {country = "JP", currency = "JPY"} seicomart = {country = "JP", currency = "JPY"} pay_easy = {country = "JP", currency = "JPY"} boleto = { country = "BR", currency = "BRL" } +ideal = { country = "NL", currency = "EUR" } +klarna = { country = "AU,AT,BE,CA,CZ,DK,FI,FR,DE,GR,IE,IT,NO,PL,PT,RO,ES,SE,CH,NL,GB,US", currency = "AUD,EUR,CAD,CZK,DKK,NOK,PLN,RON,SEK,CHF,GBP,USD"} +paypal = { country = "AU,NZ,CN,JP,HK,MY,TH,KR,PH,ID,AE,KW,BR,ES,GB,SE,NO,SK,AT,NL,DE,HU,CY,LU,CH,BE,FR,DK,FI,RO,HR,UA,MT,SI,GI,PT,IE,CZ,EE,LT,LV,IT,PL,IS,CA,US", currency = "AUD,BRL,CAD,CZK,DKK,EUR,HKD,HUF,INR,JPY,MYR,MXN,NZD,NOK,PHP,PLN,RUB,GBP,SGD,SEK,CHF,THB,USD" } +sofort = { country = "AT,BE,DE,ES,CH,NL", currency = "CHF,EUR"} + [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"} diff --git a/crates/api_models/src/enums.rs b/crates/api_models/src/enums.rs index 45851e4c11b..60c48f3d03c 100644 --- a/crates/api_models/src/enums.rs +++ b/crates/api_models/src/enums.rs @@ -434,6 +434,9 @@ pub enum BankNames { TsbBank, TescoBank, UlsterBank, + Yoursafe, + N26, + NationaleNederlanden, } #[derive( diff --git a/crates/connector_configs/toml/development.toml b/crates/connector_configs/toml/development.toml index 693ea69ff4e..e1f731c25e4 100644 --- a/crates/connector_configs/toml/development.toml +++ b/crates/connector_configs/toml/development.toml @@ -232,6 +232,8 @@ api_key="Adyen API Key" key1="Adyen Account Id" [adyen.connector_webhook_details] merchant_secret="Source verification key" +[adyen.metadata] +endpoint_prefix="Live endpoint prefix" [adyen.metadata.google_pay] merchant_name="Google Pay Merchant Name" gateway_merchant_id="Google Pay Merchant Key" @@ -2506,6 +2508,8 @@ api_key="Api Key" payment_method_type = "sepa" [[adyen_payout.wallet]] payment_method_type = "paypal" +[adyen_payout.metadata] + endpoint_prefix="Live endpoint prefix" [adyen_payout.connector_auth.SignatureKey] api_key = "Adyen API Key (Payout creation)" api_secret = "Adyen Key (Payout submission)" diff --git a/crates/connector_configs/toml/production.toml b/crates/connector_configs/toml/production.toml index 78f6f8d2a76..a463d546ffb 100644 --- a/crates/connector_configs/toml/production.toml +++ b/crates/connector_configs/toml/production.toml @@ -124,6 +124,9 @@ key1="Adyen Account Id" [adyen.connector_webhook_details] merchant_secret="Source verification key" +[adyen.metadata] +endpoint_prefix="Live endpoint prefix" + [adyen.metadata.google_pay] merchant_name="Google Pay Merchant Name" gateway_merchant_id="Google Pay Merchant Key" diff --git a/crates/connector_configs/toml/sandbox.toml b/crates/connector_configs/toml/sandbox.toml index dbb6284fbe9..cf94e1d6222 100644 --- a/crates/connector_configs/toml/sandbox.toml +++ b/crates/connector_configs/toml/sandbox.toml @@ -232,6 +232,8 @@ api_key="Adyen API Key" key1="Adyen Account Id" [adyen.connector_webhook_details] merchant_secret="Source verification key" +[adyen.metadata] +endpoint_prefix="Live endpoint prefix" [adyen.metadata.google_pay] merchant_name="Google Pay Merchant Name" gateway_merchant_id="Google Pay Merchant Key" @@ -2508,6 +2510,8 @@ api_key="Api Key" payment_method_type = "sepa" [[adyen_payout.wallet]] payment_method_type = "paypal" +[adyen_payout.metadata] + endpoint_prefix="Live endpoint prefix" [adyen_payout.connector_auth.SignatureKey] api_key = "Adyen API Key (Payout creation)" api_secret = "Adyen Key (Payout submission)" diff --git a/crates/router/src/connector/adyen.rs b/crates/router/src/connector/adyen.rs index 771ad993ac9..261495e2bfa 100644 --- a/crates/router/src/connector/adyen.rs +++ b/crates/router/src/connector/adyen.rs @@ -33,6 +33,8 @@ use crate::{ utils::{crypto, ByteSliceExt, BytesExt, OptionExt}, }; +const ADYEN_API_VERSION: &str = "v68"; + #[derive(Debug, Clone)] pub struct Adyen; @@ -268,6 +270,23 @@ impl // Not Implemented (R) } +fn build_env_specific_endpoint( + base_url: &str, + test_mode: Option<bool>, + connector_metadata: &Option<common_utils::pii::SecretSerdeValue>, +) -> CustomResult<String, errors::ConnectorError> { + if test_mode.unwrap_or(true) { + Ok(base_url.to_string()) + } else { + let adyen_connector_metadata_object = + transformers::AdyenConnectorMetadataObject::try_from(connector_metadata)?; + Ok(base_url.replace( + "{{merchant_endpoint_prefix}}", + &adyen_connector_metadata_object.endpoint_prefix, + )) + } +} + impl services::ConnectorIntegration< api::SetupMandate, @@ -293,10 +312,15 @@ impl fn get_url( &self, - _req: &types::SetupMandateRouterData, + req: &types::SetupMandateRouterData, connectors: &settings::Connectors, ) -> CustomResult<String, errors::ConnectorError> { - Ok(format!("{}{}", self.base_url(connectors), "v68/payments")) + let endpoint = build_env_specific_endpoint( + self.base_url(connectors), + req.test_mode, + &req.connector_meta_data, + )?; + Ok(format!("{}{}/payments", endpoint, ADYEN_API_VERSION)) } fn get_request_body( &self, @@ -418,11 +442,15 @@ impl connectors: &settings::Connectors, ) -> CustomResult<String, errors::ConnectorError> { let id = req.request.connector_transaction_id.as_str(); - Ok(format!( - "{}{}/{}/captures", + + let endpoint = build_env_specific_endpoint( self.base_url(connectors), - "v68/payments", - id + req.test_mode, + &req.connector_meta_data, + )?; + Ok(format!( + "{}{}/payments/{}/captures", + endpoint, ADYEN_API_VERSION, id )) } fn get_request_body( @@ -560,13 +588,17 @@ impl fn get_url( &self, - _req: &types::RouterData<api::PSync, types::PaymentsSyncData, types::PaymentsResponseData>, + req: &types::RouterData<api::PSync, types::PaymentsSyncData, types::PaymentsResponseData>, connectors: &settings::Connectors, ) -> CustomResult<String, errors::ConnectorError> { - Ok(format!( - "{}{}", + let endpoint = build_env_specific_endpoint( self.base_url(connectors), - "v68/payments/details" + req.test_mode, + &req.connector_meta_data, + )?; + Ok(format!( + "{}{}/payments/details", + endpoint, ADYEN_API_VERSION )) } @@ -681,10 +713,15 @@ impl fn get_url( &self, - _req: &types::PaymentsAuthorizeRouterData, + req: &types::PaymentsAuthorizeRouterData, connectors: &settings::Connectors, ) -> CustomResult<String, errors::ConnectorError> { - Ok(format!("{}{}", self.base_url(connectors), "v68/payments")) + let endpoint = build_env_specific_endpoint( + self.base_url(connectors), + req.test_mode, + &req.connector_meta_data, + )?; + Ok(format!("{}{}/payments", endpoint, ADYEN_API_VERSION)) } fn get_request_body( @@ -785,12 +822,17 @@ impl fn get_url( &self, - _req: &types::PaymentsPreProcessingRouterData, + req: &types::PaymentsPreProcessingRouterData, connectors: &settings::Connectors, ) -> CustomResult<String, errors::ConnectorError> { + let endpoint = build_env_specific_endpoint( + self.base_url(connectors), + req.test_mode, + &req.connector_meta_data, + )?; Ok(format!( - "{}v69/paymentMethods/balance", - self.base_url(connectors) + "{}{}/paymentMethods/balance", + endpoint, ADYEN_API_VERSION )) } @@ -911,11 +953,16 @@ impl req: &types::PaymentsCancelRouterData, connectors: &settings::Connectors, ) -> CustomResult<String, errors::ConnectorError> { - let id = req.request.connector_transaction_id.as_str(); - Ok(format!( - "{}v68/payments/{}/cancels", + let id = req.request.connector_transaction_id.clone(); + + let endpoint = build_env_specific_endpoint( self.base_url(connectors), - id + req.test_mode, + &req.connector_meta_data, + )?; + Ok(format!( + "{}{}/payments/{}/cancels", + endpoint, ADYEN_API_VERSION, id )) } @@ -991,12 +1038,17 @@ impl services::ConnectorIntegration<api::PoCancel, types::PayoutsData, types::Pa { fn get_url( &self, - _req: &types::PayoutsRouterData<api::PoCancel>, + req: &types::PayoutsRouterData<api::PoCancel>, connectors: &settings::Connectors, ) -> CustomResult<String, errors::ConnectorError> { + let endpoint = build_env_specific_endpoint( + connectors.adyen.secondary_base_url.as_str(), + req.test_mode, + &req.connector_meta_data, + )?; Ok(format!( - "{}pal/servlet/Payout/v68/declineThirdParty", - connectors.adyen.secondary_base_url + "{}pal/servlet/Payout/{}/declineThirdParty", + endpoint, ADYEN_API_VERSION )) } @@ -1083,12 +1135,17 @@ impl services::ConnectorIntegration<api::PoCreate, types::PayoutsData, types::Pa { fn get_url( &self, - _req: &types::PayoutsRouterData<api::PoCreate>, + req: &types::PayoutsRouterData<api::PoCreate>, connectors: &settings::Connectors, ) -> CustomResult<String, errors::ConnectorError> { + let endpoint = build_env_specific_endpoint( + connectors.adyen.secondary_base_url.as_str(), + req.test_mode, + &req.connector_meta_data, + )?; Ok(format!( - "{}pal/servlet/Payout/v68/storeDetailAndSubmitThirdParty", - connectors.adyen.secondary_base_url + "{}pal/servlet/Payout/{}/storeDetailAndSubmitThirdParty", + endpoint, ADYEN_API_VERSION )) } @@ -1180,10 +1237,15 @@ impl { fn get_url( &self, - _req: &types::PayoutsRouterData<api::PoEligibility>, + req: &types::PayoutsRouterData<api::PoEligibility>, connectors: &settings::Connectors, ) -> CustomResult<String, errors::ConnectorError> { - Ok(format!("{}v68/payments", self.base_url(connectors),)) + let endpoint = build_env_specific_endpoint( + self.base_url(connectors), + req.test_mode, + &req.connector_meta_data, + )?; + Ok(format!("{}{}/payments", endpoint, ADYEN_API_VERSION)) } fn get_headers( @@ -1277,9 +1339,15 @@ impl services::ConnectorIntegration<api::PoFulfill, types::PayoutsData, types::P req: &types::PayoutsRouterData<api::PoFulfill>, connectors: &settings::Connectors, ) -> CustomResult<String, errors::ConnectorError> { + let endpoint = build_env_specific_endpoint( + connectors.adyen.secondary_base_url.as_str(), + req.test_mode, + &req.connector_meta_data, + )?; Ok(format!( - "{}pal/servlet/Payout/v68/{}", - connectors.adyen.secondary_base_url, + "{}pal/servlet/Payout/{}/{}", + endpoint, + ADYEN_API_VERSION, match req.request.payout_type { storage_enums::PayoutType::Bank | storage_enums::PayoutType::Wallet => "confirmThirdParty".to_string(), @@ -1407,10 +1475,15 @@ impl services::ConnectorIntegration<api::Execute, types::RefundsData, types::Ref connectors: &settings::Connectors, ) -> CustomResult<String, errors::ConnectorError> { let connector_payment_id = req.request.connector_transaction_id.clone(); - Ok(format!( - "{}v68/payments/{}/refunds", + + let endpoint = build_env_specific_endpoint( self.base_url(connectors), - connector_payment_id + req.test_mode, + &req.connector_meta_data, + )?; + Ok(format!( + "{}{}/payments/{}/refunds", + endpoint, ADYEN_API_VERSION, connector_payment_id )) } @@ -1483,6 +1556,17 @@ impl services::ConnectorIntegration<api::Execute, types::RefundsData, types::Ref impl services::ConnectorIntegration<api::RSync, types::RefundsData, types::RefundsResponseData> for Adyen { + fn build_request( + &self, + _req: &types::RefundsRouterData<api::RSync>, + _connectors: &settings::Connectors, + ) -> CustomResult<Option<services::Request>, errors::ConnectorError> { + Err(errors::ConnectorError::FlowNotSupported { + flow: "Rsync".to_owned(), + connector: "Adyen".to_owned(), + } + .into()) + } } fn get_webhook_object_from_body( @@ -1591,7 +1675,7 @@ impl api::IncomingWebhook for Adyen { let notif = get_webhook_object_from_body(request.body) .change_context(errors::ConnectorError::WebhookReferenceIdNotFound)?; // for capture_event, original_reference field will have the authorized payment's PSP reference - if adyen::is_capture_event(&notif.event_code) { + if adyen::is_capture_or_cancel_event(&notif.event_code) { return Ok(api_models::webhooks::ObjectReferenceId::PaymentId( api_models::payments::PaymentIdType::ConnectorTransactionId( notif @@ -1630,6 +1714,7 @@ impl api::IncomingWebhook for Adyen { .change_context(errors::ConnectorError::WebhookEventTypeNotFound)?; Ok(IncomingWebhookEvent::foreign_from(( notif.event_code, + notif.success, notif.additional_data.dispute_status, ))) } diff --git a/crates/router/src/connector/adyen/transformers.rs b/crates/router/src/connector/adyen/transformers.rs index a2fc7cc7ba4..7f20041e1fc 100644 --- a/crates/router/src/connector/adyen/transformers.rs +++ b/crates/router/src/connector/adyen/transformers.rs @@ -2,7 +2,7 @@ use api_models::payouts::PayoutMethodData; use api_models::{enums, payments, webhooks}; use cards::CardNumber; -use common_utils::ext_traits::Encode; +use common_utils::{ext_traits::Encode, pii}; use error_stack::ResultExt; use masking::{ExposeInterface, PeekInterface}; use reqwest::Url; @@ -61,6 +61,21 @@ impl<T> }) } } +#[derive(Debug, Default, Serialize, Deserialize)] +pub struct AdyenConnectorMetadataObject { + pub endpoint_prefix: String, +} + +impl TryFrom<&Option<pii::SecretSerdeValue>> for AdyenConnectorMetadataObject { + type Error = error_stack::Report<errors::ConnectorError>; + fn try_from(meta_data: &Option<pii::SecretSerdeValue>) -> Result<Self, Self::Error> { + let metadata: Self = utils::to_connector_meta_from_secret::<Self>(meta_data.clone()) + .change_context(errors::ConnectorError::InvalidConnectorConfig { + config: "metadata", + })?; + Ok(metadata) + } +} // Adyen Types Definition // Payments Request and Response Types @@ -230,7 +245,7 @@ impl ForeignFrom<(bool, AdyenStatus, Option<common_enums::PaymentMethodType>)> ) -> Self { match adyen_status { AdyenStatus::AuthenticationFinished => Self::AuthenticationSuccessful, - AdyenStatus::AuthenticationNotRequired => Self::Pending, + AdyenStatus::AuthenticationNotRequired | AdyenStatus::Received => Self::Pending, AdyenStatus::Authorised => match is_manual_capture { true => Self::Authorized, // In case of Automatic capture Authorized is the final status of the payment @@ -245,7 +260,6 @@ impl ForeignFrom<(bool, AdyenStatus, Option<common_enums::PaymentMethodType>)> Some(common_enums::PaymentMethodType::Pix) => Self::AuthenticationPending, _ => Self::Pending, }, - AdyenStatus::Received => Self::Started, #[cfg(feature = "payouts")] AdyenStatus::PayoutConfirmReceived => Self::Started, #[cfg(feature = "payouts")] @@ -281,7 +295,6 @@ pub struct AdyenRefusal { #[derive(Debug, Clone, Serialize, serde::Deserialize, Eq, PartialEq)] #[serde(rename_all = "camelCase")] pub struct AdyenRedirection { - #[serde(rename = "redirectResult")] pub redirect_result: String, #[serde(rename = "type")] pub type_of_redirection_result: Option<String>, @@ -432,6 +445,7 @@ pub struct Amount { #[derive(Debug, Clone, Serialize)] #[serde(tag = "type")] +#[serde(rename_all = "lowercase")] pub enum AdyenPaymentMethod<'a> { AdyenAffirm(Box<PmdForPaymentType>), AdyenCard(Box<AdyenCard>), @@ -1016,6 +1030,9 @@ impl TryFrom<&api_enums::BankNames> for OpenBankingUKIssuer { | enums::BankNames::KrungsriBank | enums::BankNames::KrungThaiBank | enums::BankNames::TheSiamCommercialBank + | enums::BankNames::Yoursafe + | enums::BankNames::N26 + | enums::BankNames::NationaleNederlanden | enums::BankNames::KasikornBank => Err(errors::ConnectorError::NotSupported { message: String::from("BankRedirect"), connector: "Adyen", @@ -1079,8 +1096,9 @@ pub struct AdyenCancelRequest { #[derive(Default, Debug, Deserialize, Serialize)] #[serde(rename_all = "camelCase")] pub struct AdyenCancelResponse { - psp_reference: String, + payment_psp_reference: String, status: CancelStatus, + reference: String, } #[derive(Default, Debug, Deserialize, Serialize)] @@ -1365,16 +1383,17 @@ impl<'a> TryFrom<&api_enums::BankNames> for AdyenTestBankNames<'a> { api_models::enums::BankNames::AbnAmro => Self("1121"), api_models::enums::BankNames::AsnBank => Self("1151"), api_models::enums::BankNames::Bunq => Self("1152"), - api_models::enums::BankNames::Handelsbanken => Self("1153"), api_models::enums::BankNames::Ing => Self("1154"), api_models::enums::BankNames::Knab => Self("1155"), - api_models::enums::BankNames::Moneyou => Self("1156"), + api_models::enums::BankNames::N26 => Self("1156"), + api_models::enums::BankNames::NationaleNederlanden => Self("1157"), api_models::enums::BankNames::Rabobank => Self("1157"), api_models::enums::BankNames::Regiobank => Self("1158"), api_models::enums::BankNames::Revolut => Self("1159"), api_models::enums::BankNames::SnsBank => Self("1159"), api_models::enums::BankNames::TriodosBank => Self("1159"), api_models::enums::BankNames::VanLanschot => Self("1159"), + api_models::enums::BankNames::Yoursafe => Self("1159"), api_models::enums::BankNames::BankAustria => { Self("e6819e7a-f663-414b-92ec-cf7c82d2f4e5") } @@ -1419,6 +1438,34 @@ impl<'a> TryFrom<&api_enums::BankNames> for AdyenTestBankNames<'a> { } } +pub struct AdyenBankNames<'a>(&'a str); + +impl<'a> TryFrom<&api_enums::BankNames> for AdyenBankNames<'a> { + type Error = Error; + fn try_from(bank: &api_enums::BankNames) -> Result<Self, Self::Error> { + Ok(match bank { + api_models::enums::BankNames::AbnAmro => Self("0031"), + api_models::enums::BankNames::AsnBank => Self("0761"), + api_models::enums::BankNames::Bunq => Self("0802"), + api_models::enums::BankNames::Ing => Self("0721"), + api_models::enums::BankNames::Knab => Self("0801"), + api_models::enums::BankNames::N26 => Self("0807"), + api_models::enums::BankNames::NationaleNederlanden => Self("0808"), + api_models::enums::BankNames::Rabobank => Self("0021"), + api_models::enums::BankNames::Regiobank => Self("0771"), + api_models::enums::BankNames::Revolut => Self("0805"), + api_models::enums::BankNames::SnsBank => Self("0751"), + api_models::enums::BankNames::TriodosBank => Self("0511"), + api_models::enums::BankNames::VanLanschot => Self("0161"), + api_models::enums::BankNames::Yoursafe => Self("0806"), + _ => Err(errors::ConnectorError::NotSupported { + message: String::from("BankRedirect"), + connector: "Adyen", + })?, + }) + } +} + impl TryFrom<&types::ConnectorAuthType> for AdyenAuthType { type Error = Error; fn try_from(auth_type: &types::ConnectorAuthType) -> Result<Self, Self::Error> { @@ -2079,10 +2126,12 @@ impl<'a> TryFrom<(&api::PayLaterData, Option<api_enums::CountryAlpha2>)> } } -impl<'a> TryFrom<&api_models::payments::BankRedirectData> for AdyenPaymentMethod<'a> { +impl<'a> TryFrom<(&api_models::payments::BankRedirectData, Option<bool>)> + for AdyenPaymentMethod<'a> +{ type Error = Error; fn try_from( - bank_redirect_data: &api_models::payments::BankRedirectData, + (bank_redirect_data, test_mode): (&api_models::payments::BankRedirectData, Option<bool>), ) -> Result<Self, Self::Error> { match bank_redirect_data { api_models::payments::BankRedirectData::BancontactCard { @@ -2154,19 +2203,33 @@ impl<'a> TryFrom<&api_models::payments::BankRedirectData> for AdyenPaymentMethod payment_type: PaymentType::Giropay, }))) } - api_models::payments::BankRedirectData::Ideal { bank_name, .. } => Ok( - AdyenPaymentMethod::Ideal(Box::new(BankRedirectionWithIssuer { - payment_type: PaymentType::Ideal, - issuer: Some( + api_models::payments::BankRedirectData::Ideal { bank_name, .. } => { + let issuer = if test_mode.unwrap_or(true) { + Some( AdyenTestBankNames::try_from(&bank_name.ok_or( errors::ConnectorError::MissingRequiredField { field_name: "ideal.bank_name", }, )?)? .0, - ), - })), - ), + ) + } else { + Some( + AdyenBankNames::try_from(&bank_name.ok_or( + errors::ConnectorError::MissingRequiredField { + field_name: "ideal.bank_name", + }, + )?)? + .0, + ) + }; + Ok(AdyenPaymentMethod::Ideal(Box::new( + BankRedirectionWithIssuer { + payment_type: PaymentType::Ideal, + issuer, + }, + ))) + } api_models::payments::BankRedirectData::OnlineBankingCzechRepublic { issuer } => { Ok(AdyenPaymentMethod::OnlineBankingCzechRepublic(Box::new( OnlineBankingCzechRepublicData { @@ -2692,7 +2755,8 @@ impl<'a> let browser_info = get_browser_info(item.router_data)?; let additional_data = get_additional_data(item.router_data); let return_url = item.router_data.request.get_return_url()?; - let payment_method = AdyenPaymentMethod::try_from(bank_redirect_data)?; + let payment_method = + AdyenPaymentMethod::try_from((bank_redirect_data, item.router_data.test_mode))?; let (shopper_locale, country) = get_redirect_extra_details(item.router_data)?; let line_items = Some(get_line_items(item)); @@ -2939,15 +3003,6 @@ impl TryFrom<&types::PaymentsCancelRouterData> for AdyenCancelRequest { } } -impl From<CancelStatus> for storage_enums::AttemptStatus { - fn from(status: CancelStatus) -> Self { - match status { - CancelStatus::Received => Self::Voided, - CancelStatus::Processing => Self::Pending, - } - } -} - impl TryFrom<types::PaymentsCancelResponseRouterData<AdyenCancelResponse>> for types::PaymentsCancelRouterData { @@ -2956,14 +3011,16 @@ impl TryFrom<types::PaymentsCancelResponseRouterData<AdyenCancelResponse>> item: types::PaymentsCancelResponseRouterData<AdyenCancelResponse>, ) -> Result<Self, Self::Error> { Ok(Self { - status: item.response.status.into(), + status: enums::AttemptStatus::Pending, response: Ok(types::PaymentsResponseData::TransactionResponse { - resource_id: types::ResponseId::ConnectorTransactionId(item.response.psp_reference), + resource_id: types::ResponseId::ConnectorTransactionId( + item.response.payment_psp_reference, + ), redirection_data: None, mandate_reference: None, connector_metadata: None, network_txn_id: None, - connector_response_reference_id: None, + connector_response_reference_id: Some(item.response.reference), incremental_authorization_allowed: None, }), ..item.data @@ -3683,11 +3740,7 @@ impl TryFrom<types::PaymentsCaptureResponseRouterData<AdyenCaptureResponse>> mandate_reference: None, connector_metadata: None, network_txn_id: None, - connector_response_reference_id: item - .response - .merchant_reference - .clone() - .or(Some(item.response.psp_reference)), + connector_response_reference_id: Some(item.response.reference), incremental_authorization_allowed: None, }), amount_captured: Some(item.response.amount.value), @@ -3829,7 +3882,9 @@ pub enum WebhookEventCode { Authorisation, Refund, CancelOrRefund, + Cancellation, RefundFailed, + RefundReversed, NotificationOfChargeback, Chargeback, ChargebackReversed, @@ -3846,10 +3901,12 @@ pub fn is_transaction_event(event_code: &WebhookEventCode) -> bool { matches!(event_code, WebhookEventCode::Authorisation) } -pub fn is_capture_event(event_code: &WebhookEventCode) -> bool { +pub fn is_capture_or_cancel_event(event_code: &WebhookEventCode) -> bool { matches!( event_code, - WebhookEventCode::Capture | WebhookEventCode::CaptureFailed + WebhookEventCode::Capture + | WebhookEventCode::CaptureFailed + | WebhookEventCode::Cancellation ) } @@ -3859,6 +3916,7 @@ pub fn is_refund_event(event_code: &WebhookEventCode) -> bool { WebhookEventCode::Refund | WebhookEventCode::CancelOrRefund | WebhookEventCode::RefundFailed + | WebhookEventCode::RefundReversed ) } @@ -3874,31 +3932,66 @@ pub fn is_chargeback_event(event_code: &WebhookEventCode) -> bool { ) } -impl ForeignFrom<(WebhookEventCode, Option<DisputeStatus>)> for webhooks::IncomingWebhookEvent { - fn foreign_from((code, status): (WebhookEventCode, Option<DisputeStatus>)) -> Self { - match (code, status) { - (WebhookEventCode::Authorisation, _) => Self::PaymentIntentSuccess, - (WebhookEventCode::Refund, _) => Self::RefundSuccess, - (WebhookEventCode::CancelOrRefund, _) => Self::RefundSuccess, - (WebhookEventCode::RefundFailed, _) => Self::RefundFailure, - (WebhookEventCode::NotificationOfChargeback, _) => Self::DisputeOpened, - (WebhookEventCode::Chargeback, None) => Self::DisputeLost, - (WebhookEventCode::Chargeback, Some(DisputeStatus::Won)) => Self::DisputeWon, - (WebhookEventCode::Chargeback, Some(DisputeStatus::Lost)) => Self::DisputeLost, - (WebhookEventCode::Chargeback, Some(_)) => Self::DisputeOpened, - (WebhookEventCode::ChargebackReversed, Some(DisputeStatus::Pending)) => { - Self::DisputeChallenged +fn is_success_scenario(is_success: String) -> bool { + is_success.as_str() == "true" +} + +impl ForeignFrom<(WebhookEventCode, String, Option<DisputeStatus>)> + for webhooks::IncomingWebhookEvent +{ + fn foreign_from( + (code, is_success, dispute_status): (WebhookEventCode, String, Option<DisputeStatus>), + ) -> Self { + match code { + WebhookEventCode::Authorisation => { + if is_success_scenario(is_success) { + Self::PaymentIntentSuccess + } else { + Self::PaymentIntentFailure + } + } + WebhookEventCode::Refund | WebhookEventCode::CancelOrRefund => { + if is_success_scenario(is_success) { + Self::RefundSuccess + } else { + Self::RefundFailure + } + } + WebhookEventCode::Cancellation => { + if is_success_scenario(is_success) { + Self::PaymentIntentCancelled + } else { + Self::PaymentIntentCancelFailure + } } - (WebhookEventCode::ChargebackReversed, _) => Self::DisputeWon, - (WebhookEventCode::SecondChargeback, _) => Self::DisputeLost, - (WebhookEventCode::PrearbitrationWon, Some(DisputeStatus::Pending)) => { - Self::DisputeOpened + WebhookEventCode::RefundFailed | WebhookEventCode::RefundReversed => { + Self::RefundFailure } - (WebhookEventCode::PrearbitrationWon, _) => Self::DisputeWon, - (WebhookEventCode::PrearbitrationLost, _) => Self::DisputeLost, - (WebhookEventCode::Unknown, _) => Self::EventNotSupported, - (WebhookEventCode::Capture, _) => Self::PaymentIntentSuccess, - (WebhookEventCode::CaptureFailed, _) => Self::PaymentIntentFailure, + WebhookEventCode::NotificationOfChargeback => Self::DisputeOpened, + WebhookEventCode::Chargeback => match dispute_status { + Some(DisputeStatus::Won) => Self::DisputeWon, + Some(DisputeStatus::Lost) | None => Self::DisputeLost, + Some(_) => Self::DisputeOpened, + }, + WebhookEventCode::ChargebackReversed => match dispute_status { + Some(DisputeStatus::Pending) => Self::DisputeChallenged, + _ => Self::DisputeWon, + }, + WebhookEventCode::SecondChargeback => Self::DisputeLost, + WebhookEventCode::PrearbitrationWon => match dispute_status { + Some(DisputeStatus::Pending) => Self::DisputeOpened, + _ => Self::DisputeWon, + }, + WebhookEventCode::PrearbitrationLost => Self::DisputeLost, + WebhookEventCode::Capture => { + if is_success_scenario(is_success) { + Self::PaymentIntentCaptureSuccess + } else { + Self::PaymentIntentCaptureFailure + } + } + WebhookEventCode::CaptureFailed => Self::PaymentIntentCaptureFailure, + WebhookEventCode::Unknown => Self::EventNotSupported, } } } @@ -3949,7 +4042,13 @@ impl From<AdyenNotificationRequestItemWH> for Response { psp_reference: notif.psp_reference, merchant_reference: notif.merchant_reference, result_code: match notif.success.as_str() { - "true" => AdyenStatus::Authorised, + "true" => { + if notif.event_code == WebhookEventCode::Cancellation { + AdyenStatus::Cancelled + } else { + AdyenStatus::Authorised + } + } _ => AdyenStatus::Refused, }, amount: Some(Amount { diff --git a/crates/router/src/connector/nuvei/transformers.rs b/crates/router/src/connector/nuvei/transformers.rs index d5dd6e813ae..13d522b86cc 100644 --- a/crates/router/src/connector/nuvei/transformers.rs +++ b/crates/router/src/connector/nuvei/transformers.rs @@ -615,6 +615,9 @@ impl TryFrom<api_models::enums::BankNames> for NuveiBIC { | api_models::enums::BankNames::Starling | api_models::enums::BankNames::TsbBank | api_models::enums::BankNames::TescoBank + | api_models::enums::BankNames::Yoursafe + | api_models::enums::BankNames::N26 + | api_models::enums::BankNames::NationaleNederlanden | api_models::enums::BankNames::UlsterBank => { Err(errors::ConnectorError::NotImplemented( utils::get_unimplemented_payment_method_error_message("Nuvei"), diff --git a/crates/router/src/core/admin.rs b/crates/router/src/core/admin.rs index 87886c2c861..2b87d64c6ac 100644 --- a/crates/router/src/core/admin.rs +++ b/crates/router/src/core/admin.rs @@ -1695,6 +1695,7 @@ pub(crate) fn validate_auth_and_metadata_type( } api_enums::Connector::Adyen => { adyen::transformers::AdyenAuthType::try_from(val)?; + adyen::transformers::AdyenConnectorMetadataObject::try_from(connector_meta_data)?; Ok(()) } api_enums::Connector::Airwallex => { diff --git a/crates/router/src/core/payments/operations/payment_status.rs b/crates/router/src/core/payments/operations/payment_status.rs index 81dfb7127db..ed96feb2b5e 100644 --- a/crates/router/src/core/payments/operations/payment_status.rs +++ b/crates/router/src/core/payments/operations/payment_status.rs @@ -238,7 +238,7 @@ async fn get_tracker_for_sync< operation: Op, storage_scheme: enums::MerchantStorageScheme, ) -> RouterResult<operations::GetTrackerResponse<'a, F, api::PaymentsRetrieveRequest, Ctx>> { - let (payment_intent, payment_attempt, currency, amount); + let (payment_intent, mut payment_attempt, currency, amount); (payment_intent, payment_attempt) = get_payment_intent_payment_attempt( db, @@ -274,6 +274,8 @@ async fn get_tracker_for_sync< ) .await?; + payment_attempt.encoded_data = request.param.clone(); + let attempts = match request.expand_attempts { Some(true) => { Some(db diff --git a/loadtest/config/development.toml b/loadtest/config/development.toml index 2f35958ae6d..aa0d75d609f 100644 --- a/loadtest/config/development.toml +++ b/loadtest/config/development.toml @@ -191,6 +191,10 @@ open_banking_uk = {country = "DE,GB,AT,BE,CY,EE,ES,FI,FR,GR,HR,IE,IT,LT,LU,LV,MT [pm_filters.adyen] boleto = { country = "BR", currency = "BRL" } +sofort = { country = "AT,BE,DE,ES,CH,NL", currency = "CHF,EUR"} +paypal = { country = "AU,NZ,CN,JP,HK,MY,TH,KR,PH,ID,AE,KW,BR,ES,GB,SE,NO,SK,AT,NL,DE,HU,CY,LU,CH,BE,FR,DK,FI,RO,HR,UA,MT,SI,GI,PT,IE,CZ,EE,LT,LV,IT,PL,IS,CA,US", currency = "AUD,BRL,CAD,CZK,DKK,EUR,HKD,HUF,INR,JPY,MYR,MXN,NZD,NOK,PHP,PLN,RUB,GBP,SGD,SEK,CHF,THB,USD" } +klarna = { country = "AU,AT,BE,CA,CZ,DK,FI,FR,DE,GR,IE,IT,NO,PL,PT,RO,ES,SE,CH,NL,GB,US", currency = "AUD,EUR,CAD,CZK,DKK,NOK,PLN,RON,SEK,CHF,GBP,USD"} +ideal = { country = "NL", currency = "EUR" } [pm_filters.zen] credit = { not_available_flows = { capture_method = "manual" } } diff --git a/openapi/openapi_spec.json b/openapi/openapi_spec.json index 30e75c028d5..ce4c4c2a0ef 100644 --- a/openapi/openapi_spec.json +++ b/openapi/openapi_spec.json @@ -5092,7 +5092,10 @@ "starling", "tsb_bank", "tesco_bank", - "ulster_bank" + "ulster_bank", + "yoursafe", + "n26", + "nationale_nederlanden" ] }, "BankRedirectBilling": {
2024-02-29T12:17:48Z
## 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 --> - Add production live endpoint for Adyen - Fix webhooks status mapping - Fix redirection data not getting populated in encoded data - Add Live Bank Names for Ideal - Add Currency, Country config for `klarna, ideal, sofort, paypal` ### 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` --> - Added configs for Currency, Country for `klarna, ideal, sofort, paypal` - Update payment endpoints for production ## 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). --> #3614 #3903 ## 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 flows of Adyen are required to be tested as base url and status mapping along with webhooks is changed. - Test Webhooks Extensively, the outgoing webhooks and the status updates webhooks are triggering. Please use the postman collection defined here: `postman/collection-json/adyen_uk.postman_collection.json` ## 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 - [ ] I added a [CHANGELOG](/CHANGELOG.md) entry if applicable
7db499d8a9388b9a3674f7fa130bc389151840ec
- All the flows of Adyen are required to be tested as base url and status mapping along with webhooks is changed. - Test Webhooks Extensively, the outgoing webhooks and the status updates webhooks are triggering. Please use the postman collection defined here: `postman/collection-json/adyen_uk.postman_collection.json`
juspay/hyperswitch
juspay__hyperswitch-3593
Bug: [FEATURE]:(doc) Add list mandates for customer in api reference ### Feature Description Add `list mandates for customer` docs in api reference ### Possible Implementation Add in open_api spec ### 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/openapi/src/openapi.rs b/crates/openapi/src/openapi.rs index 1936300ee14..dc38181a683 100644 --- a/crates/openapi/src/openapi.rs +++ b/crates/openapi/src/openapi.rs @@ -114,6 +114,7 @@ Never share your secret api keys. Keep them guarded and secure. routes::customers::customers_list, routes::customers::customers_update, routes::customers::customers_delete, + routes::customers::customers_mandates_list, //Routes for payment methods routes::payment_method::create_payment_method_api, diff --git a/crates/openapi/src/routes/customers.rs b/crates/openapi/src/routes/customers.rs index 7517cdc61a0..19901cbbeb9 100644 --- a/crates/openapi/src/routes/customers.rs +++ b/crates/openapi/src/routes/customers.rs @@ -100,3 +100,19 @@ pub async fn customers_delete() {} security(("api_key" = [])) )] pub async fn customers_list() {} + +/// Customers - Mandates List +/// +/// Lists all the mandates for a particular customer id. +#[utoipa::path( + post, + path = "/customers/{customer_id}/mandates", + responses( + (status = 200, description = "List of retrieved mandates for a customer", body = Vec<MandateResponse>), + (status = 400, description = "Invalid Data"), + ), + tag = "Customers Mandates List", + operation_id = "List all Mandates for a Customer", + security(("api_key" = [])) +)] +pub async fn customers_mandates_list() {} diff --git a/openapi/openapi_spec.json b/openapi/openapi_spec.json index 2803141b38b..be011422e03 100644 --- a/openapi/openapi_spec.json +++ b/openapi/openapi_spec.json @@ -1608,6 +1608,39 @@ ] } }, + "/customers/{customer_id}/mandates": { + "post": { + "tags": [ + "Customers Mandates List" + ], + "summary": "Customers - Mandates List", + "description": "Customers - Mandates List\n\nLists all the mandates for a particular customer id.", + "operationId": "List all Mandates for a Customer", + "responses": { + "200": { + "description": "List of retrieved mandates for a customer", + "content": { + "application/json": { + "schema": { + "type": "array", + "items": { + "$ref": "#/components/schemas/MandateResponse" + } + } + } + } + }, + "400": { + "description": "Invalid Data" + } + }, + "security": [ + { + "api_key": [] + } + ] + } + }, "/customers/{customer_id}/payment_methods": { "get": { "tags": [
2024-02-08T07:59:52Z
## 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 --> add list mandates for customer ### 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't be tested as this is a doc update PR ## 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 - [ ] I added a [CHANGELOG](/CHANGELOG.md) entry if applicable
c2b2b65b9cfc43b5999888635c7b03b1d2de78b3
Can't be tested as this is a doc update PR
juspay/hyperswitch
juspay__hyperswitch-3600
Bug: [Refactor] Send an appropriate error if update_mandate is not supported ### Feature Description Send an appropriate error if update_mandate is not also add support for allowing the payment with payment_method _type as None ### Possible Implementation - Improvise theImplementation if its a Card - Thorw an appropriate error ### 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/router/src/core/payment_methods/cards.rs b/crates/router/src/core/payment_methods/cards.rs index 7b505e7c01c..b8b0fffe339 100644 --- a/crates/router/src/core/payment_methods/cards.rs +++ b/crates/router/src/core/payment_methods/cards.rs @@ -2136,12 +2136,33 @@ pub fn filter_pm_based_on_update_mandate_support_for_connector( payment_method_type: &api_enums::PaymentMethodType, connector: api_enums::Connector, ) -> bool { - supported_payment_methods_for_mandate - .0 - .get(payment_method) - .and_then(|payment_method_type_hm| payment_method_type_hm.0.get(payment_method_type)) - .map(|supported_connectors| supported_connectors.connector_list.contains(&connector)) - .unwrap_or(false) + if payment_method == &api_enums::PaymentMethod::Card { + supported_payment_methods_for_mandate + .0 + .get(payment_method) + .map(|payment_method_type_hm| { + let pm_credit = payment_method_type_hm + .0 + .get(&api_enums::PaymentMethodType::Credit) + .map(|conn| conn.connector_list.clone()) + .unwrap_or_default(); + let pm_debit = payment_method_type_hm + .0 + .get(&api_enums::PaymentMethodType::Debit) + .map(|conn| conn.connector_list.clone()) + .unwrap_or_default(); + &pm_credit | &pm_debit + }) + .map(|supported_connectors| supported_connectors.contains(&connector)) + .unwrap_or(false) + } else { + supported_payment_methods_for_mandate + .0 + .get(payment_method) + .and_then(|payment_method_type_hm| payment_method_type_hm.0.get(payment_method_type)) + .map(|supported_connectors| supported_connectors.connector_list.contains(&connector)) + .unwrap_or(false) + } } fn filter_pm_based_on_supported_payments_for_mandate( diff --git a/crates/router/src/core/payments/flows/setup_mandate_flow.rs b/crates/router/src/core/payments/flows/setup_mandate_flow.rs index a81f97851d9..30918b2fe4e 100644 --- a/crates/router/src/core/payments/flows/setup_mandate_flow.rs +++ b/crates/router/src/core/payments/flows/setup_mandate_flow.rs @@ -1,3 +1,4 @@ +use api_models::enums::{PaymentMethod, PaymentMethodType}; use async_trait::async_trait; use error_stack::{IntoReport, ResultExt}; @@ -275,17 +276,33 @@ impl types::SetupMandateRouterData { let payment_method_type = self.request.payment_method_type; let payment_method = self.request.payment_method_data.get_payment_method(); - let supported_connectors_config = - payment_method - .zip(payment_method_type) - .map_or(false, |(pm, pmt)| { + let supported_connectors_config = payment_method.zip(payment_method_type).map_or_else( + || { + if payment_method == Some(PaymentMethod::Card) { cards::filter_pm_based_on_update_mandate_support_for_connector( supported_connectors_for_update_mandate, - &pm, - &pmt, + &PaymentMethod::Card, + &PaymentMethodType::Credit, + connector.connector_name, + ) && cards::filter_pm_based_on_update_mandate_support_for_connector( + supported_connectors_for_update_mandate, + &PaymentMethod::Card, + &PaymentMethodType::Debit, connector.connector_name, ) - }); + } else { + false + } + }, + |(pm, pmt)| { + cards::filter_pm_based_on_update_mandate_support_for_connector( + supported_connectors_for_update_mandate, + &pm, + &pmt, + connector.connector_name, + ) + }, + ); if supported_connectors_config { let connector_integration: services::BoxedConnectorIntegration< '_, @@ -378,9 +395,13 @@ impl types::SetupMandateRouterData { Err(_) => Ok(resp), } } else { - Err(errors::ApiErrorResponse::InternalServerError) - .into_report() - .attach_printable("Update Mandate Flow not implemented for the connector ")? + Err(errors::ApiErrorResponse::PreconditionFailed { + message: format!( + "Update Mandate flow not implemented for the connector {:?}", + connector.connector_name + ), + }) + .into_report() } } } diff --git a/loadtest/config/development.toml b/loadtest/config/development.toml index 14d119768d0..c5232378615 100644 --- a/loadtest/config/development.toml +++ b/loadtest/config/development.toml @@ -256,9 +256,6 @@ bank_redirect.sofort = {connector_list = "stripe,adyen,globalpay"} card.credit ={connector_list ="cybersource"} card.debit = {connector_list ="cybersource"} -[mandates.update_mandate_supported] -connector_list = "cybersource" - [analytics] source = "sqlx" diff --git a/postman/collection-dir/adyen_uk/Flow Testcases/Happy Cases/Scenario16-Bank debit-ach/Payments - Create/request.json b/postman/collection-dir/adyen_uk/Flow Testcases/Happy Cases/Scenario16-Bank debit-ach/Payments - Create/request.json index bc160467bf8..21c079e0ad0 100644 --- a/postman/collection-dir/adyen_uk/Flow Testcases/Happy Cases/Scenario16-Bank debit-ach/Payments - Create/request.json +++ b/postman/collection-dir/adyen_uk/Flow Testcases/Happy Cases/Scenario16-Bank debit-ach/Payments - Create/request.json @@ -31,7 +31,7 @@ "description": "Its my first payment request", "authentication_type": "three_ds", "return_url": "https://duck.com", - "setup_future_usage": "off_session", + "setup_future_usage": "on_session", "billing": { "address": { "line1": "1467", diff --git a/postman/collection-dir/adyen_uk/Flow Testcases/Happy Cases/Scenario17-Bank debit-Bacs/Payments - Create/request.json b/postman/collection-dir/adyen_uk/Flow Testcases/Happy Cases/Scenario17-Bank debit-Bacs/Payments - Create/request.json index 9340a493524..1ec9a829a48 100644 --- a/postman/collection-dir/adyen_uk/Flow Testcases/Happy Cases/Scenario17-Bank debit-Bacs/Payments - Create/request.json +++ b/postman/collection-dir/adyen_uk/Flow Testcases/Happy Cases/Scenario17-Bank debit-Bacs/Payments - Create/request.json @@ -31,7 +31,7 @@ "description": "Its my first payment request", "authentication_type": "no_three_ds", "return_url": "https://duck.com", - "setup_future_usage": "off_session", + "setup_future_usage": "on_session", "billing": { "address": { "line1": "1467", diff --git a/postman/collection-dir/paypal/Flow Testcases/Happy Cases/Scenario6-Create Wallet - Paypal/Payments - Create/request.json b/postman/collection-dir/paypal/Flow Testcases/Happy Cases/Scenario6-Create Wallet - Paypal/Payments - Create/request.json index f0066e67bbc..824bfb49230 100644 --- a/postman/collection-dir/paypal/Flow Testcases/Happy Cases/Scenario6-Create Wallet - Paypal/Payments - Create/request.json +++ b/postman/collection-dir/paypal/Flow Testcases/Happy Cases/Scenario6-Create Wallet - Paypal/Payments - Create/request.json @@ -32,7 +32,7 @@ "description": "Its my first payment request", "authentication_type": "three_ds", "return_url": "https://duck.com", - "setup_future_usage": "off_session", + "setup_future_usage": "on_session", "billing": { "address": { "line1": "1467", diff --git a/postman/collection-dir/paypal/Flow Testcases/Happy Cases/Scenario7-Create Wallet - Paypal with confrm false/Payments - Create/request.json b/postman/collection-dir/paypal/Flow Testcases/Happy Cases/Scenario7-Create Wallet - Paypal with confrm false/Payments - Create/request.json index 792e7c399fc..9778d0ee32b 100644 --- a/postman/collection-dir/paypal/Flow Testcases/Happy Cases/Scenario7-Create Wallet - Paypal with confrm false/Payments - Create/request.json +++ b/postman/collection-dir/paypal/Flow Testcases/Happy Cases/Scenario7-Create Wallet - Paypal with confrm false/Payments - Create/request.json @@ -32,7 +32,7 @@ "description": "Its my first payment request", "authentication_type": "three_ds", "return_url": "https://duck.com", - "setup_future_usage": "off_session", + "setup_future_usage": "on_session", "billing": { "address": { "line1": "1467", diff --git a/postman/collection-dir/zen/Flow Testcases/Happy Cases/Scenario1-Create payment with confirm true/Payments - Create/request.json b/postman/collection-dir/zen/Flow Testcases/Happy Cases/Scenario1-Create payment with confirm true/Payments - Create/request.json index 0bf606d869e..7afc6d61c49 100644 --- a/postman/collection-dir/zen/Flow Testcases/Happy Cases/Scenario1-Create payment with confirm true/Payments - Create/request.json +++ b/postman/collection-dir/zen/Flow Testcases/Happy Cases/Scenario1-Create payment with confirm true/Payments - Create/request.json @@ -31,7 +31,7 @@ "description": "Its my first payment request", "authentication_type": "no_three_ds", "return_url": "https://duck.com", - "setup_future_usage": "off_session", + "setup_future_usage": "on_session", "billing": { "address": { "line1": "1467", diff --git a/postman/collection-dir/zen/Flow Testcases/Happy Cases/Scenario3-Create payment without PMD/Payments - Create/request.json b/postman/collection-dir/zen/Flow Testcases/Happy Cases/Scenario3-Create payment without PMD/Payments - Create/request.json index c2d7c7bf9c0..a6aef6ecb71 100644 --- a/postman/collection-dir/zen/Flow Testcases/Happy Cases/Scenario3-Create payment without PMD/Payments - Create/request.json +++ b/postman/collection-dir/zen/Flow Testcases/Happy Cases/Scenario3-Create payment without PMD/Payments - Create/request.json @@ -31,7 +31,7 @@ "description": "Its my first payment request", "authentication_type": "no_three_ds", "return_url": "https://duck.com", - "setup_future_usage": "off_session", + "setup_future_usage": "on_session", "billing": { "address": { "line1": "1467", diff --git a/postman/collection-dir/zen/Flow Testcases/Happy Cases/Scenario5-Create 3DS payment with confrm false/Payments - Create/request.json b/postman/collection-dir/zen/Flow Testcases/Happy Cases/Scenario5-Create 3DS payment with confrm false/Payments - Create/request.json index caa19cc5c67..01fa4013653 100644 --- a/postman/collection-dir/zen/Flow Testcases/Happy Cases/Scenario5-Create 3DS payment with confrm false/Payments - Create/request.json +++ b/postman/collection-dir/zen/Flow Testcases/Happy Cases/Scenario5-Create 3DS payment with confrm false/Payments - Create/request.json @@ -31,7 +31,7 @@ "description": "Its my first payment request", "authentication_type": "no_three_ds", "return_url": "https://duck.com", - "setup_future_usage": "off_session", + "setup_future_usage": "on_session", "billing": { "address": { "line1": "1467", diff --git a/postman/collection-dir/zen/Flow Testcases/Variation Cases/Scenario2-Confirming the payment without PMD/Payments - Create/request.json b/postman/collection-dir/zen/Flow Testcases/Variation Cases/Scenario2-Confirming the payment without PMD/Payments - Create/request.json index c2d7c7bf9c0..a6aef6ecb71 100644 --- a/postman/collection-dir/zen/Flow Testcases/Variation Cases/Scenario2-Confirming the payment without PMD/Payments - Create/request.json +++ b/postman/collection-dir/zen/Flow Testcases/Variation Cases/Scenario2-Confirming the payment without PMD/Payments - Create/request.json @@ -31,7 +31,7 @@ "description": "Its my first payment request", "authentication_type": "no_three_ds", "return_url": "https://duck.com", - "setup_future_usage": "off_session", + "setup_future_usage": "on_session", "billing": { "address": { "line1": "1467",
2024-02-08T12:17:35Z
## Type of Change <!-- Put an `x` in the boxes that apply --> - [ ] Bugfix - [ ] New feature - [ ] Enhancement - [x] Refactoring - [ ] Dependency updates - [ ] Documentation - [ ] CI/CD ## Description Send an appropriate error if update_mandate is not also add support for allowing the payment with payment_method _type as None and also fix the failing postman collection ### 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 an MCA with Cybersource > Make a UpdateMandatePayment with `payment_method_type` as null >Payment would succeed ![Screenshot 2024-02-08 at 4 48 42 PM](https://github.com/juspay/hyperswitch/assets/55580080/d362b690-1610-4e9a-a30e-c3a27e60f9b5) - Create a MA and an MCA with Cybersource - >Make a Payment , would throw a 4xx ## 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 - [ ] I added a [CHANGELOG](/CHANGELOG.md) entry if applicable
96f82cb21233677968aade844db91f91e3918843
- Create a MA and an MCA with Cybersource > Make a UpdateMandatePayment with `payment_method_type` as null >Payment would succeed ![Screenshot 2024-02-08 at 4 48 42 PM](https://github.com/juspay/hyperswitch/assets/55580080/d362b690-1610-4e9a-a30e-c3a27e60f9b5) - Create a MA and an MCA with Cybersource - >Make a Payment , would throw a 4xx
juspay/hyperswitch
juspay__hyperswitch-3595
Bug: feat(user_role): Transfer ownership api
diff --git a/crates/api_models/src/events/user_role.rs b/crates/api_models/src/events/user_role.rs index 3ec30d6bd97..2b8d0221497 100644 --- a/crates/api_models/src/events/user_role.rs +++ b/crates/api_models/src/events/user_role.rs @@ -2,7 +2,7 @@ use common_utils::events::{ApiEventMetric, ApiEventsType}; use crate::user_role::{ AcceptInvitationRequest, AuthorizationInfoResponse, DeleteUserRoleRequest, GetRoleRequest, - ListRolesResponse, RoleInfoResponse, UpdateUserRoleRequest, + ListRolesResponse, RoleInfoResponse, TransferOrgOwnershipRequest, UpdateUserRoleRequest, }; common_utils::impl_misc_api_event_type!( @@ -12,5 +12,6 @@ common_utils::impl_misc_api_event_type!( AuthorizationInfoResponse, UpdateUserRoleRequest, AcceptInvitationRequest, - DeleteUserRoleRequest + DeleteUserRoleRequest, + TransferOrgOwnershipRequest ); diff --git a/crates/api_models/src/user_role.rs b/crates/api_models/src/user_role.rs index 2672293390e..78df1d6823e 100644 --- a/crates/api_models/src/user_role.rs +++ b/crates/api_models/src/user_role.rs @@ -108,3 +108,8 @@ pub type AcceptInvitationResponse = DashboardEntryResponse; pub struct DeleteUserRoleRequest { pub email: pii::Email, } + +#[derive(Debug, serde::Deserialize, serde::Serialize)] +pub struct TransferOrgOwnershipRequest { + pub email: pii::Email, +} diff --git a/crates/diesel_models/src/query/user_role.rs b/crates/diesel_models/src/query/user_role.rs index e67eba64c7c..5e759cf826b 100644 --- a/crates/diesel_models/src/query/user_role.rs +++ b/crates/diesel_models/src/query/user_role.rs @@ -54,6 +54,20 @@ impl UserRole { .await } + pub async fn update_by_user_id_org_id( + conn: &PgPooledConn, + user_id: String, + org_id: String, + update: UserRoleUpdate, + ) -> 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)), + UserRoleUpdateInternal::from(update), + ) + .await + } + pub async fn delete_by_user_id_merchant_id( conn: &PgPooledConn, user_id: String, diff --git a/crates/router/src/core/user_role.rs b/crates/router/src/core/user_role.rs index b48b39eea14..14be9bb6991 100644 --- a/crates/router/src/core/user_role.rs +++ b/crates/router/src/core/user_role.rs @@ -1,10 +1,11 @@ -use api_models::user_role as user_role_api; +use api_models::{user as user_api, user_role as user_role_api}; use diesel_models::{enums::UserStatus, user_role::UserRoleUpdate}; use error_stack::ResultExt; use masking::ExposeInterface; use router_env::logger; use crate::{ + consts, core::errors::{StorageErrorExt, UserErrors, UserResponse}, routes::AppState, services::{ @@ -135,6 +136,55 @@ pub async fn update_user_role( Ok(ApplicationResponse::StatusOk) } +pub async fn transfer_org_ownership( + state: AppState, + user_from_token: auth::UserFromToken, + req: user_role_api::TransferOrgOwnershipRequest, +) -> UserResponse<user_api::DashboardEntryResponse> { + if user_from_token.role_id != consts::user_role::ROLE_ID_ORGANIZATION_ADMIN { + return Err(UserErrors::InvalidRoleOperation.into()).attach_printable(format!( + "role_id = {} is not org_admin", + user_from_token.role_id + )); + } + + let user_to_be_updated = + utils::user::get_user_from_db_by_email(&state, domain::UserEmail::try_from(req.email)?) + .await + .to_not_found_response(UserErrors::InvalidRoleOperation) + .attach_printable("User not found in our records".to_string())?; + + if user_from_token.user_id == user_to_be_updated.get_user_id() { + return Err(UserErrors::InvalidRoleOperation.into()) + .attach_printable("User transferring ownership to themselves".to_string()); + } + + state + .store + .transfer_org_ownership_between_users( + &user_from_token.user_id, + user_to_be_updated.get_user_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?; + + let user_from_db = domain::UserFromStorage::from(user_from_token.get_user(&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)?; + + let token = utils::user::generate_jwt_auth_token(&state, &user_from_db, &user_role).await?; + + Ok(ApplicationResponse::Json( + utils::user::get_dashboard_entry_response(&state, user_from_db, user_role, token)?, + )) +} + pub async fn accept_invitation( state: AppState, user_token: auth::UserWithoutMerchantFromToken, diff --git a/crates/router/src/db/kafka_store.rs b/crates/router/src/db/kafka_store.rs index 029b1a57764..a5e5f216a8b 100644 --- a/crates/router/src/db/kafka_store.rs +++ b/crates/router/src/db/kafka_store.rs @@ -1965,6 +1965,17 @@ impl UserRoleInterface for KafkaStore { .await } + async fn update_user_roles_by_user_id_org_id( + &self, + user_id: &str, + org_id: &str, + update: user_storage::UserRoleUpdate, + ) -> CustomResult<Vec<user_storage::UserRole>, errors::StorageError> { + self.diesel_store + .update_user_roles_by_user_id_org_id(user_id, org_id, update) + .await + } + async fn delete_user_role_by_user_id_merchant_id( &self, user_id: &str, @@ -1981,6 +1992,17 @@ impl UserRoleInterface for KafkaStore { ) -> CustomResult<Vec<user_storage::UserRole>, errors::StorageError> { self.diesel_store.list_user_roles_by_user_id(user_id).await } + + async fn transfer_org_ownership_between_users( + &self, + from_user_id: &str, + to_user_id: &str, + org_id: &str, + ) -> CustomResult<(), errors::StorageError> { + self.diesel_store + .transfer_org_ownership_between_users(from_user_id, to_user_id, org_id) + .await + } } #[async_trait::async_trait] diff --git a/crates/router/src/db/user_role.rs b/crates/router/src/db/user_role.rs index f02e6d60b3b..12816fa006b 100644 --- a/crates/router/src/db/user_role.rs +++ b/crates/router/src/db/user_role.rs @@ -1,9 +1,12 @@ -use diesel_models::user_role as storage; +use std::{collections::HashSet, ops::Not}; + +use async_bb8_diesel::AsyncConnection; +use diesel_models::{enums, user_role as storage}; use error_stack::{IntoReport, ResultExt}; use super::MockDb; use crate::{ - connection, + connection, consts, core::errors::{self, CustomResult}, services::Store, }; @@ -32,6 +35,14 @@ pub trait UserRoleInterface { merchant_id: &str, update: storage::UserRoleUpdate, ) -> CustomResult<storage::UserRole, errors::StorageError>; + + async fn update_user_roles_by_user_id_org_id( + &self, + user_id: &str, + org_id: &str, + update: storage::UserRoleUpdate, + ) -> CustomResult<Vec<storage::UserRole>, errors::StorageError>; + async fn delete_user_role_by_user_id_merchant_id( &self, user_id: &str, @@ -42,6 +53,13 @@ pub trait UserRoleInterface { &self, user_id: &str, ) -> CustomResult<Vec<storage::UserRole>, errors::StorageError>; + + async fn transfer_org_ownership_between_users( + &self, + from_user_id: &str, + to_user_id: &str, + org_id: &str, + ) -> CustomResult<(), errors::StorageError>; } #[async_trait::async_trait] @@ -103,6 +121,24 @@ impl UserRoleInterface for Store { .into_report() } + async fn update_user_roles_by_user_id_org_id( + &self, + user_id: &str, + org_id: &str, + update: storage::UserRoleUpdate, + ) -> 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, + ) + .await + .map_err(Into::into) + .into_report() + } + async fn delete_user_role_by_user_id_merchant_id( &self, user_id: &str, @@ -129,6 +165,86 @@ impl UserRoleInterface for Store { .map_err(Into::into) .into_report() } + + async fn transfer_org_ownership_between_users( + &self, + from_user_id: &str, + to_user_id: &str, + org_id: &str, + ) -> 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(), + }, + ) + .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(), + }, + ) + .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()) + .collect::<HashSet<String>>(); + + let now = common_utils::date_time::now(); + + let missing_new_user_roles = + old_org_admin_user_roles.into_iter().filter_map(|old_role| { + new_org_admin_merchant_ids + .contains(&old_role.merchant_id) + .not() + .then_some({ + storage::UserRoleNew { + user_id: to_user_id.to_string(), + merchant_id: old_role.merchant_id, + role_id: consts::user_role::ROLE_ID_ORGANIZATION_ADMIN.to_string(), + org_id: org_id.to_string(), + 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, + } + }) + }); + + futures::future::try_join_all(missing_new_user_roles.map(|user_role| async { + user_role + .insert(&conn) + .await + .map_err(|e| *e.current_context()) + })) + .await?; + + Ok::<_, errors::DatabaseError>(()) + }) + .await + .into_report() + .map_err(Into::into) + .into_report()?; + + Ok(()) + } } #[async_trait::async_trait] @@ -241,6 +357,107 @@ impl UserRoleInterface for MockDb { ) } + async fn update_user_roles_by_user_id_org_id( + &self, + user_id: &str, + org_id: &str, + update: storage::UserRoleUpdate, + ) -> 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() { + if user_role.user_id == user_id && user_role.org_id == org_id { + 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.to_owned(); + user_role.last_modified_by = modified_by.to_owned(); + } + } + 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: &str, + ) -> 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(), + }, + ) + .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(), + }, + ) + .await?; + + let new_org_admin_merchant_ids = new_org_admin_user_roles + .iter() + .map(|user_role| user_role.merchant_id.to_owned()) + .collect::<HashSet<String>>(); + + let now = common_utils::date_time::now(); + + let missing_new_user_roles = old_org_admin_user_roles + .into_iter() + .filter_map(|old_roles| { + if !new_org_admin_merchant_ids.contains(&old_roles.merchant_id) { + Some(storage::UserRoleNew { + user_id: to_user_id.to_string(), + merchant_id: old_roles.merchant_id, + role_id: consts::user_role::ROLE_ID_ORGANIZATION_ADMIN.to_string(), + org_id: org_id.to_string(), + 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, + }) + } else { + None + } + }); + + for user_role in missing_new_user_roles { + self.insert_user_role(user_role).await?; + } + + Ok(()) + } + async fn delete_user_role_by_user_id_merchant_id( &self, user_id: &str, diff --git a/crates/router/src/routes/app.rs b/crates/router/src/routes/app.rs index 651d3c0026f..65caa2b5c04 100644 --- a/crates/router/src/routes/app.rs +++ b/crates/router/src/routes/app.rs @@ -1026,6 +1026,10 @@ impl User { ) .service(web::resource("/invite/accept").route(web::post().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/lock_utils.rs b/crates/router/src/routes/lock_utils.rs index 1636ed3a764..02a45408baf 100644 --- a/crates/router/src/routes/lock_utils.rs +++ b/crates/router/src/routes/lock_utils.rs @@ -196,7 +196,8 @@ impl From<Flow> for ApiIdentifier { | Flow::UpdateUserRole | Flow::GetAuthorizationInfo | Flow::AcceptInvitation - | Flow::DeleteUserRole => Self::UserRole, + | Flow::DeleteUserRole + | Flow::TransferOrgOwnership => 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 ec05db1d615..f84c158332b 100644 --- a/crates/router/src/routes/user_role.rs +++ b/crates/router/src/routes/user_role.rs @@ -97,6 +97,25 @@ 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_env/src/logger/types.rs b/crates/router_env/src/logger/types.rs index 4344acf89ff..2f4d48bea74 100644 --- a/crates/router_env/src/logger/types.rs +++ b/crates/router_env/src/logger/types.rs @@ -311,6 +311,8 @@ 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-02-08T13:34: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 --> This PR will add a new api to transfer ownership of an organization to other. ### 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). --> To allow users to change the ownership of an organization. ## 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)? --> Postman ``` curl --location 'http://localhost:8080/user/user/transfer_ownership' \ --header 'Content-Type: application/json' \ --header 'Authorization: Bearer JWT of org_admin user' \ --data-raw '{ "email": "email of the user who is not org_admin" }' ``` If the api is successful, it will return the following response. ``` { "token": "JWT", "merchant_id": "merchant_id", "name": "name of old org_admin", "email": "email of old org_admin", "verification_days_left": null, "user_role": "merchant_admin" } ``` ## 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 - [ ] I added a [CHANGELOG](/CHANGELOG.md) entry if applicable
cfa10aa60ef16d2302787f7ecf7c129228fc0549
Postman ``` curl --location 'http://localhost:8080/user/user/transfer_ownership' \ --header 'Content-Type: application/json' \ --header 'Authorization: Bearer JWT of org_admin user' \ --data-raw '{ "email": "email of the user who is not org_admin" }' ``` If the api is successful, it will return the following response. ``` { "token": "JWT", "merchant_id": "merchant_id", "name": "name of old org_admin", "email": "email of old org_admin", "verification_days_left": null, "user_role": "merchant_admin" } ```
juspay/hyperswitch
juspay__hyperswitch-3610
Bug: [FEATURE] Update Payment Connector Create to incorporate recipient creation ### Feature Description In Open banking payments, some connector offer a recipient creation flow, where a `recipient_id` can be created against merchant's bank account data. The `recipient_id` can be stored in the DB. Alternatively, for the connectors that don't offer this flow, we can offer to store the data in locker. ### Possible Implementation A recipient creation API call would have to be incorporated in the payment connector create flow, some type changes would be required a as well. ### 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 9b855b1e956..5b4c1bbd762 100644 --- a/config/config.example.toml +++ b/config/config.example.toml @@ -698,3 +698,6 @@ public = { name = "hyperswitch", base_url = "http://localhost:8080", schema = "p [user_auth_methods] encryption_key = "" # Encryption key used for encrypting data in user_authentication_methods table + +[locker_based_open_banking_connectors] +connector_list = "" \ No newline at end of file diff --git a/config/deployments/integration_test.toml b/config/deployments/integration_test.toml index b8945db5f24..060756cf910 100644 --- a/config/deployments/integration_test.toml +++ b/config/deployments/integration_test.toml @@ -347,3 +347,6 @@ keys = "user-agent" [saved_payment_methods] sdk_eligible_payment_methods = "card" + +[locker_based_open_banking_connectors] +connector_list = "" diff --git a/config/deployments/production.toml b/config/deployments/production.toml index acc28a32c5f..ce7e6df9897 100644 --- a/config/deployments/production.toml +++ b/config/deployments/production.toml @@ -366,3 +366,6 @@ keys = "user-agent" [saved_payment_methods] sdk_eligible_payment_methods = "card" + +[locker_based_open_banking_connectors] +connector_list = "" diff --git a/config/deployments/sandbox.toml b/config/deployments/sandbox.toml index d776483ebcc..4920ca8589e 100644 --- a/config/deployments/sandbox.toml +++ b/config/deployments/sandbox.toml @@ -370,3 +370,6 @@ keys = "user-agent" [saved_payment_methods] sdk_eligible_payment_methods = "card" + +[locker_based_open_banking_connectors] +connector_list = "" diff --git a/config/development.toml b/config/development.toml index c35de87e808..2b7cc68e8b5 100644 --- a/config/development.toml +++ b/config/development.toml @@ -695,3 +695,6 @@ public = { name = "hyperswitch", base_url = "http://localhost:8080", schema = "p [user_auth_methods] encryption_key = "A8EF32E029BC3342E54BF2E172A4D7AA43E8EF9D2C3A624A9F04E2EF79DC698F" + +[locker_based_open_banking_connectors] +connector_list = "" diff --git a/config/docker_compose.toml b/config/docker_compose.toml index c26055f436a..18a3189e4fd 100644 --- a/config/docker_compose.toml +++ b/config/docker_compose.toml @@ -351,7 +351,7 @@ sofort = { country = "AT,BE,DE,ES,CH,NL", currency = "CHF,EUR" } 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" } [pm_filters.razorpay] -upi_collect = {country = "IN", currency = "INR"} +upi_collect = { country = "IN", currency = "INR" } [pm_filters.zen] credit = { not_available_flows = { capture_method = "manual" } } @@ -442,7 +442,7 @@ delay_between_retries_in_milliseconds = 500 [events.kafka] brokers = ["localhost:9092"] -fraud_check_analytics_topic= "hyperswitch-fraud-check-events" +fraud_check_analytics_topic = "hyperswitch-fraud-check-events" intent_analytics_topic = "hyperswitch-payment-intent-events" attempt_analytics_topic = "hyperswitch-payment-attempt-events" refund_analytics_topic = "hyperswitch-refund-events" @@ -519,7 +519,7 @@ enabled = false global_tenant = { schema = "public", redis_key_prefix = "" } [multitenancy.tenants] -public = { name = "hyperswitch", base_url = "http://localhost:8080", schema = "public", redis_key_prefix = "", clickhouse_database = "default"} +public = { name = "hyperswitch", base_url = "http://localhost:8080", schema = "public", redis_key_prefix = "", clickhouse_database = "default" } [user_auth_methods] encryption_key = "A8EF32E029BC3342E54BF2E172A4D7AA43E8EF9D2C3A624A9F04E2EF79DC698F" @@ -548,7 +548,10 @@ merchant_name = "HyperSwitch" card = "credit,debit" [payout_method_filters.adyenplatform] -sepa = { country = "ES,SK,AT,NL,DE,BE,FR,FI,PT,IE,EE,LT,LV,IT,CZ,DE,HU,NO,PL,SE,GB,CH" , currency = "EUR,CZK,DKK,HUF,NOR,PLN,SEK,GBP,CHF" } +sepa = { country = "ES,SK,AT,NL,DE,BE,FR,FI,PT,IE,EE,LT,LV,IT,CZ,DE,HU,NO,PL,SE,GB,CH", currency = "EUR,CZK,DKK,HUF,NOR,PLN,SEK,GBP,CHF" } [payout_method_filters.stripe] ach = { country = "US", currency = "USD" } + +[locker_based_open_banking_connectors] +connector_list = "" diff --git a/crates/api_models/src/admin.rs b/crates/api_models/src/admin.rs index ec9172b7fdf..20129e4b239 100644 --- a/crates/api_models/src/admin.rs +++ b/crates/api_models/src/admin.rs @@ -652,6 +652,49 @@ pub struct MerchantConnectorCreate { #[schema(value_type = Option<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>, +} + +#[derive(Debug, Clone, serde::Deserialize, serde::Serialize, ToSchema)] +#[serde(rename_all = "snake_case")] +pub enum AdditionalMerchantData { + OpenBankingRecipientData(MerchantRecipientData), +} + +#[derive(Debug, Clone, serde::Deserialize, serde::Serialize, ToSchema)] +#[serde(rename_all = "snake_case")] +pub enum MerchantAccountData { + Iban { + #[schema(value_type= String)] + iban: Secret<String>, + name: String, + #[schema(value_type= Option<String>)] + #[serde(skip_serializing_if = "Option::is_none")] + connector_recipient_id: Option<Secret<String>>, + }, + Bacs { + #[schema(value_type= String)] + account_number: Secret<String>, + #[schema(value_type= String)] + sort_code: Secret<String>, + name: String, + #[schema(value_type= Option<String>)] + #[serde(skip_serializing_if = "Option::is_none")] + connector_recipient_id: Option<Secret<String>>, + }, +} + +#[derive(Debug, Clone, serde::Deserialize, serde::Serialize, ToSchema)] +#[serde(rename_all = "snake_case")] +pub enum MerchantRecipientData { + #[schema(value_type= Option<String>)] + ConnectorRecipientId(Secret<String>), + #[schema(value_type= Option<String>)] + WalletId(Secret<String>), + AccountData(MerchantAccountData), } // Different patterns of authentication. @@ -805,6 +848,9 @@ pub struct MerchantConnectorResponse { #[schema(value_type = ConnectorStatus, example = "inactive")] pub status: api_enums::ConnectorStatus, + + #[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." diff --git a/crates/common_enums/src/enums.rs b/crates/common_enums/src/enums.rs index 87d4f5e775a..ca37332cb76 100644 --- a/crates/common_enums/src/enums.rs +++ b/crates/common_enums/src/enums.rs @@ -176,6 +176,7 @@ pub enum RoutableConnectors { Worldline, Worldpay, Zen, + Plaid, Zsl, } diff --git a/crates/diesel_models/src/merchant_connector_account.rs b/crates/diesel_models/src/merchant_connector_account.rs index 680e3dacc85..e01c465d1b4 100644 --- a/crates/diesel_models/src/merchant_connector_account.rs +++ b/crates/diesel_models/src/merchant_connector_account.rs @@ -43,6 +43,7 @@ pub struct MerchantConnectorAccount { pub applepay_verified_domains: Option<Vec<String>>, pub pm_auth_config: Option<serde_json::Value>, pub status: storage_enums::ConnectorStatus, + pub additional_merchant_data: Option<Encryption>, pub connector_wallets_details: Option<Encryption>, } @@ -73,6 +74,7 @@ pub struct MerchantConnectorAccountNew { pub applepay_verified_domains: Option<Vec<String>>, pub pm_auth_config: Option<serde_json::Value>, pub status: storage_enums::ConnectorStatus, + pub additional_merchant_data: Option<Encryption>, pub connector_wallets_details: Option<Encryption>, } diff --git a/crates/diesel_models/src/schema.rs b/crates/diesel_models/src/schema.rs index 8d51e378fd9..d9f5b299862 100644 --- a/crates/diesel_models/src/schema.rs +++ b/crates/diesel_models/src/schema.rs @@ -707,6 +707,7 @@ diesel::table! { applepay_verified_domains -> Nullable<Array<Nullable<Text>>>, pm_auth_config -> Nullable<Jsonb>, status -> ConnectorStatus, + additional_merchant_data -> Nullable<Bytea>, connector_wallets_details -> Nullable<Bytea>, } } diff --git a/crates/kgraph_utils/benches/evaluation.rs b/crates/kgraph_utils/benches/evaluation.rs index 820e3da42d8..a137a6fd54d 100644 --- a/crates/kgraph_utils/benches/evaluation.rs +++ b/crates/kgraph_utils/benches/evaluation.rs @@ -71,6 +71,7 @@ fn build_test_data( applepay_verified_domains: None, pm_auth_config: None, status: api_enums::ConnectorStatus::Inactive, + additional_merchant_data: None, }; let config = CountryCurrencyFilter { connector_configs: HashMap::new(), diff --git a/crates/kgraph_utils/src/mca.rs b/crates/kgraph_utils/src/mca.rs index 74cc096e730..0cbf171495b 100644 --- a/crates/kgraph_utils/src/mca.rs +++ b/crates/kgraph_utils/src/mca.rs @@ -759,6 +759,7 @@ mod tests { applepay_verified_domains: None, pm_auth_config: None, status: api_enums::ConnectorStatus::Inactive, + additional_merchant_data: None, }; let config_map = kgraph_types::CountryCurrencyFilter { diff --git a/crates/openapi/src/openapi.rs b/crates/openapi/src/openapi.rs index 82bde980a1f..d2e669175eb 100644 --- a/crates/openapi/src/openapi.rs +++ b/crates/openapi/src/openapi.rs @@ -256,6 +256,9 @@ Never share your secret api keys. Keep them guarded and secure. api_models::enums::AuthorizationStatus, api_models::enums::PaymentMethodStatus, api_models::admin::MerchantConnectorCreate, + api_models::admin::AdditionalMerchantData, + api_models::admin::MerchantRecipientData, + api_models::admin::MerchantAccountData, api_models::admin::MerchantConnectorUpdate, api_models::admin::PrimaryBusinessDetails, api_models::admin::FrmConfigs, diff --git a/crates/pm_auth/src/connector/plaid.rs b/crates/pm_auth/src/connector/plaid.rs index dfcfbb7eddc..6f91b2cb1a2 100644 --- a/crates/pm_auth/src/connector/plaid.rs +++ b/crates/pm_auth/src/connector/plaid.rs @@ -15,7 +15,9 @@ use crate::{ types::{ self as auth_types, api::{ - auth_service::{self, BankAccountCredentials, ExchangeToken, LinkToken}, + auth_service::{ + self, BankAccountCredentials, ExchangeToken, LinkToken, RecipientCreate, + }, ConnectorCommon, ConnectorCommonExt, ConnectorIntegration, }, }, @@ -89,6 +91,8 @@ impl ConnectorCommon for Plaid { } impl auth_service::AuthService for Plaid {} +impl auth_service::PaymentInitiationRecipientCreate for Plaid {} +impl auth_service::PaymentInitiation for Plaid {} impl auth_service::AuthServiceLinkToken for Plaid {} impl ConnectorIntegration<LinkToken, auth_types::LinkTokenRequest, auth_types::LinkTokenResponse> @@ -338,3 +342,91 @@ impl self.build_error_response(res) } } + +impl + ConnectorIntegration< + RecipientCreate, + auth_types::RecipientCreateRequest, + auth_types::RecipientCreateResponse, + > for Plaid +{ + fn get_headers( + &self, + req: &auth_types::RecipientCreateRouterData, + connectors: &auth_types::PaymentMethodAuthConnectors, + ) -> errors::CustomResult<Vec<(String, 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: &auth_types::RecipientCreateRouterData, + connectors: &auth_types::PaymentMethodAuthConnectors, + ) -> errors::CustomResult<String, errors::ConnectorError> { + Ok(format!( + "{}{}", + self.base_url(connectors), + "/payment_initiation/recipient/create" + )) + } + + fn get_request_body( + &self, + req: &auth_types::RecipientCreateRouterData, + ) -> errors::CustomResult<RequestContent, errors::ConnectorError> { + let req_obj = plaid::PlaidRecipientCreateRequest::from(req); + Ok(RequestContent::Json(Box::new(req_obj))) + } + + fn build_request( + &self, + req: &auth_types::RecipientCreateRouterData, + connectors: &auth_types::PaymentMethodAuthConnectors, + ) -> errors::CustomResult<Option<Request>, errors::ConnectorError> { + Ok(Some( + RequestBuilder::new() + .method(Method::Post) + .url(&auth_types::PaymentInitiationRecipientCreateType::get_url( + self, req, connectors, + )?) + .attach_default_headers() + .headers( + auth_types::PaymentInitiationRecipientCreateType::get_headers( + self, req, connectors, + )?, + ) + .set_body( + auth_types::PaymentInitiationRecipientCreateType::get_request_body(self, req)?, + ) + .build(), + )) + } + + fn handle_response( + &self, + data: &auth_types::RecipientCreateRouterData, + res: auth_types::Response, + ) -> errors::CustomResult<auth_types::RecipientCreateRouterData, errors::ConnectorError> { + let response: plaid::PlaidRecipientCreateResponse = res + .response + .parse_struct("PlaidRecipientCreateResponse") + .change_context(errors::ConnectorError::ResponseDeserializationFailed)?; + Ok(<auth_types::RecipientCreateRouterData>::from( + auth_types::ResponseRouterData { + response, + data: data.clone(), + http_code: res.status_code, + }, + )) + } + fn get_error_response( + &self, + res: auth_types::Response, + ) -> errors::CustomResult<auth_types::ErrorResponse, errors::ConnectorError> { + self.build_error_response(res) + } +} diff --git a/crates/pm_auth/src/connector/plaid/transformers.rs b/crates/pm_auth/src/connector/plaid/transformers.rs index 8ce5aca7b83..571f27f5b20 100644 --- a/crates/pm_auth/src/connector/plaid/transformers.rs +++ b/crates/pm_auth/src/connector/plaid/transformers.rs @@ -113,6 +113,103 @@ impl TryFrom<&types::ExchangeTokenRouterData> for PlaidExchangeTokenRequest { } } +#[derive(Debug, Serialize, Eq, PartialEq)] +pub struct PlaidRecipientCreateRequest { + pub name: String, + #[serde(flatten)] + pub account_data: PlaidRecipientAccountData, + pub address: Option<PlaidRecipientCreateAddress>, +} + +#[derive(Debug, Deserialize, Eq, PartialEq)] +pub struct PlaidRecipientCreateResponse { + pub recipient_id: String, +} + +#[derive(Debug, Serialize, Eq, PartialEq)] +#[serde(rename_all = "lowercase")] +pub enum PlaidRecipientAccountData { + Iban(Secret<String>), + Bacs { + sort_code: Secret<String>, + account: Secret<String>, + }, +} + +impl From<&types::RecipientAccountData> for PlaidRecipientAccountData { + fn from(item: &types::RecipientAccountData) -> Self { + match item { + types::RecipientAccountData::Iban(iban) => Self::Iban(iban.clone()), + types::RecipientAccountData::Bacs { + sort_code, + account_number, + } => Self::Bacs { + sort_code: sort_code.clone(), + account: account_number.clone(), + }, + } + } +} + +#[derive(Debug, Serialize, Eq, PartialEq)] +pub struct PlaidRecipientCreateAddress { + pub street: String, + pub city: String, + pub postal_code: String, + pub country: String, +} + +impl From<&types::RecipientCreateAddress> for PlaidRecipientCreateAddress { + fn from(item: &types::RecipientCreateAddress) -> Self { + Self { + street: item.street.clone(), + city: item.city.clone(), + postal_code: item.postal_code.clone(), + country: common_enums::CountryAlpha2::to_string(&item.country), + } + } +} + +impl From<&types::RecipientCreateRouterData> for PlaidRecipientCreateRequest { + fn from(item: &types::RecipientCreateRouterData) -> Self { + Self { + name: item.request.name.clone(), + account_data: PlaidRecipientAccountData::from(&item.request.account_data), + address: item + .request + .address + .as_ref() + .map(PlaidRecipientCreateAddress::from), + } + } +} + +impl<F, T> + From< + types::ResponseRouterData< + F, + PlaidRecipientCreateResponse, + T, + types::RecipientCreateResponse, + >, + > for types::PaymentAuthRouterData<F, T, types::RecipientCreateResponse> +{ + fn from( + item: types::ResponseRouterData< + F, + PlaidRecipientCreateResponse, + T, + types::RecipientCreateResponse, + >, + ) -> Self { + Self { + response: Ok(types::RecipientCreateResponse { + recipient_id: item.response.recipient_id, + }), + ..item.data + } + } +} #[derive(Debug, Serialize, Eq, PartialEq)] #[serde(rename_all = "snake_case")] pub struct PlaidBankAccountCredentialsRequest { @@ -351,6 +448,7 @@ impl<F, T> pub struct PlaidAuthType { pub client_id: Secret<String>, pub secret: Secret<String>, + pub merchant_data: Option<types::MerchantRecipientData>, } impl TryFrom<&types::ConnectorAuthType> for PlaidAuthType { @@ -360,6 +458,16 @@ impl TryFrom<&types::ConnectorAuthType> for PlaidAuthType { types::ConnectorAuthType::BodyKey { client_id, secret } => Ok(Self { client_id: client_id.to_owned(), secret: secret.to_owned(), + merchant_data: None, + }), + types::ConnectorAuthType::OpenBankingAuth { + api_key, + key1, + merchant_data, + } => Ok(Self { + client_id: api_key.to_owned(), + secret: key1.to_owned(), + merchant_data: Some(merchant_data.clone()), }), _ => Err(errors::ConnectorError::FailedToObtainAuthType.into()), } diff --git a/crates/pm_auth/src/types.rs b/crates/pm_auth/src/types.rs index 2537cdc6a36..7450251f157 100644 --- a/crates/pm_auth/src/types.rs +++ b/crates/pm_auth/src/types.rs @@ -2,10 +2,11 @@ pub mod api; use std::marker::PhantomData; -use api::auth_service::{BankAccountCredentials, ExchangeToken, LinkToken}; -use common_enums::{PaymentMethod, PaymentMethodType}; +use api::auth_service::{BankAccountCredentials, ExchangeToken, LinkToken, RecipientCreate}; +use common_enums::{CountryAlpha2, PaymentMethod, PaymentMethodType}; use common_utils::{id_type, types}; use masking::Secret; + #[derive(Debug, Clone)] pub struct PaymentAuthRouterData<F, Request, Response> { pub flow: PhantomData<F>, @@ -111,6 +112,38 @@ pub type BankDetailsRouterData = PaymentAuthRouterData< BankAccountCredentialsResponse, >; +#[derive(Debug, Clone)] +pub struct RecipientCreateRequest { + pub name: String, + pub account_data: RecipientAccountData, + pub address: Option<RecipientCreateAddress>, +} + +#[derive(Debug, Clone)] +pub struct RecipientCreateResponse { + pub recipient_id: String, +} + +#[derive(Debug, Clone)] +pub enum RecipientAccountData { + Iban(Secret<String>), + Bacs { + sort_code: Secret<String>, + account_number: Secret<String>, + }, +} + +#[derive(Debug, Clone)] +pub struct RecipientCreateAddress { + pub street: String, + pub city: String, + pub postal_code: String, + pub country: CountryAlpha2, +} + +pub type RecipientCreateRouterData = + PaymentAuthRouterData<RecipientCreate, RecipientCreateRequest, RecipientCreateResponse>; + pub type PaymentAuthLinkTokenType = dyn api::ConnectorIntegration<LinkToken, LinkTokenRequest, LinkTokenResponse>; @@ -123,6 +156,9 @@ pub type PaymentAuthBankAccountDetailsType = dyn api::ConnectorIntegration< BankAccountCredentialsResponse, >; +pub type PaymentInitiationRecipientCreateType = + dyn api::ConnectorIntegration<RecipientCreate, RecipientCreateRequest, RecipientCreateResponse>; + #[derive(Clone, Debug, strum::EnumString, strum::Display)] #[strum(serialize_all = "snake_case")] pub enum PaymentMethodAuthConnectors { @@ -155,12 +191,38 @@ impl ErrorResponse { } } +#[derive(Debug, Clone, serde::Deserialize, serde::Serialize)] +pub enum MerchantAccountData { + Iban { + iban: Secret<String>, + name: String, + }, + Bacs { + account_number: Secret<String>, + sort_code: Secret<String>, + name: String, + }, +} + +#[derive(Debug, Clone, serde::Deserialize, serde::Serialize)] +#[serde(rename_all = "snake_case")] +pub enum MerchantRecipientData { + ConnectorRecipientId(Secret<String>), + WalletId(Secret<String>), + AccountData(MerchantAccountData), +} + #[derive(Default, Debug, Clone, serde::Deserialize)] pub enum ConnectorAuthType { BodyKey { client_id: Secret<String>, secret: Secret<String>, }, + OpenBankingAuth { + api_key: Secret<String>, + key1: Secret<String>, + merchant_data: MerchantRecipientData, + }, #[default] NoKey, } diff --git a/crates/pm_auth/src/types/api.rs b/crates/pm_auth/src/types/api.rs index 3684e34ec05..d4edf160985 100644 --- a/crates/pm_auth/src/types/api.rs +++ b/crates/pm_auth/src/types/api.rs @@ -10,7 +10,10 @@ use masking::Maskable; use crate::{ core::errors::ConnectorError, - types::{self as auth_types, api::auth_service::AuthService}, + types::{ + self as auth_types, + api::auth_service::{AuthService, PaymentInitiation}, + }, }; #[async_trait::async_trait] @@ -125,9 +128,9 @@ where } } -pub trait AuthServiceConnector: AuthService + Send + Debug {} +pub trait AuthServiceConnector: AuthService + Send + Debug + PaymentInitiation {} -impl<T: Send + Debug + AuthService> AuthServiceConnector for T {} +impl<T: Send + Debug + AuthService + PaymentInitiation> AuthServiceConnector for T {} pub type BoxedPaymentAuthConnector = Box<&'static (dyn AuthServiceConnector + Sync)>; diff --git a/crates/pm_auth/src/types/api/auth_service.rs b/crates/pm_auth/src/types/api/auth_service.rs index 35d44970d51..498b6bec40e 100644 --- a/crates/pm_auth/src/types/api/auth_service.rs +++ b/crates/pm_auth/src/types/api/auth_service.rs @@ -1,6 +1,7 @@ use crate::types::{ BankAccountCredentialsRequest, BankAccountCredentialsResponse, ExchangeTokenRequest, - ExchangeTokenResponse, LinkTokenRequest, LinkTokenResponse, + ExchangeTokenResponse, LinkTokenRequest, LinkTokenResponse, RecipientCreateRequest, + RecipientCreateResponse, }; pub trait AuthService: @@ -11,6 +12,8 @@ pub trait AuthService: { } +pub trait PaymentInitiation: super::ConnectorCommon + PaymentInitiationRecipientCreate {} + #[derive(Debug, Clone)] pub struct LinkToken; @@ -38,3 +41,11 @@ pub trait AuthServiceBankAccountCredentials: > { } + +#[derive(Debug, Clone)] +pub struct RecipientCreate; + +pub trait PaymentInitiationRecipientCreate: + super::ConnectorIntegration<RecipientCreate, RecipientCreateRequest, RecipientCreateResponse> +{ +} diff --git a/crates/router/src/configs/secrets_transformers.rs b/crates/router/src/configs/secrets_transformers.rs index 9f6c797cde8..de53f9c189e 100644 --- a/crates/router/src/configs/secrets_transformers.rs +++ b/crates/router/src/configs/secrets_transformers.rs @@ -434,5 +434,6 @@ pub(crate) async fn fetch_raw_secrets( multitenancy: conf.multitenancy, user_auth_methods, decision: conf.decision, + locker_based_open_banking_connectors: conf.locker_based_open_banking_connectors, } } diff --git a/crates/router/src/configs/settings.rs b/crates/router/src/configs/settings.rs index b96784eb714..26685d63583 100644 --- a/crates/router/src/configs/settings.rs +++ b/crates/router/src/configs/settings.rs @@ -128,6 +128,7 @@ pub struct Settings<S: SecretState> { pub saved_payment_methods: EligiblePaymentMethods, pub user_auth_methods: SecretStateContainer<UserAuthMethodSettings, S>, pub decision: Option<DecisionConfig>, + pub locker_based_open_banking_connectors: LockerBasedRecipientConnectorList, } #[derive(Debug, Deserialize, Clone, Default)] @@ -690,6 +691,13 @@ pub struct ApplePayDecryptConifg { pub apple_pay_merchant_cert_key: Secret<String>, } +#[derive(Debug, Deserialize, Clone, Default)] +#[serde(default)] +pub struct LockerBasedRecipientConnectorList { + #[serde(deserialize_with = "deserialize_hashset")] + pub connector_list: HashSet<String>, +} + #[derive(Debug, Deserialize, Clone, Default)] pub struct ConnectorRequestReferenceIdConfig { pub merchant_ids_send_payment_id_as_connector_request_id: HashSet<String>, diff --git a/crates/router/src/core/admin.rs b/crates/router/src/core/admin.rs index 67b3a05adb7..88f11fdfce8 100644 --- a/crates/router/src/core/admin.rs +++ b/crates/router/src/core/admin.rs @@ -7,7 +7,7 @@ use api_models::{ use common_utils::{ date_time, ext_traits::{AsyncExt, ConfigExt, Encode, ValueExt}, - pii, + id_type, pii, }; #[cfg(all(feature = "keymanager_create", feature = "olap"))] use common_utils::{keymanager, types::keymanager as km_types}; @@ -15,24 +15,25 @@ use diesel_models::configs; use error_stack::{report, FutureExt, ResultExt}; use futures::future::try_join_all; use masking::{PeekInterface, Secret}; -use pm_auth::connector::plaid::transformers::PlaidAuthType; +use pm_auth::{connector::plaid::transformers::PlaidAuthType, types as pm_auth_types}; +use regex::Regex; use router_env::metrics::add_attributes; use uuid::Uuid; -#[cfg(all(not(feature = "v2"), feature = "olap"))] -use crate::types::transformers::ForeignFrom; use crate::{ consts, core::{ encryption::transfer_encryption_key, errors::{self, RouterResponse, RouterResult, StorageErrorExt}, + payment_methods::{cards, transformers}, payments::helpers, + pm_auth::helpers::PaymentAuthConnectorDataExt, routing::helpers as routing_helpers, utils as core_utils, }, db::StorageInterface, routes::{metrics, SessionState}, - services::{self, api as service_api, authentication}, + services::{self, api as service_api, authentication, pm_auth as payment_initiation_service}, types::{ self, api, domain::{ @@ -40,11 +41,15 @@ use crate::{ types::{self as domain_types, AsyncLift}, }, storage::{self, enums::MerchantStorageScheme}, - transformers::ForeignTryFrom, + transformers::{ForeignFrom, ForeignTryFrom}, }, utils::{self, OptionExt}, }; +const IBAN_MAX_LENGTH: usize = 34; +const BACS_SORT_CODE_LENGTH: usize = 6; +const BACS_MAX_ACCOUNT_NUMBER_LENGTH: usize = 8; + #[inline] pub fn create_merchant_publishable_key() -> String { format!( @@ -1107,7 +1112,9 @@ pub async fn create_payment_connector( api_enums::convert_authentication_connector(req.connector_name.to_string().as_str()); if pm_auth_connector.is_some() { - if req.connector_type != api_enums::ConnectorType::PaymentMethodAuth { + if req.connector_type != api_enums::ConnectorType::PaymentMethodAuth + && req.connector_type != api_enums::ConnectorType::PaymentProcessor + { return Err(errors::ApiErrorResponse::InvalidRequestData { message: "Invalid connector type given".to_string(), } @@ -1172,6 +1179,30 @@ pub async fn create_payment_connector( expected_format: "auth_type and api_key".to_string(), })?; + let merchant_recipient_data = if let Some(data) = &req.additional_merchant_data { + Some( + process_open_banking_connectors( + &state, + merchant_id.as_str(), + &auth, + &req.connector_type, + &req.connector_name, + 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 get MerchantRecipientData")?; + validate_auth_and_metadata_type(req.connector_name, &auth, &req.metadata)?; let frm_configs = get_frm_config_as_secret(req.frm_configs); @@ -1192,7 +1223,7 @@ pub async fn create_payment_connector( let (connector_status, disabled) = validate_status_and_disabled( req.status, req.disabled, - auth, + auth.clone(), // The validate_status_and_disabled function will use this value only // when the status can be active. So we are passing this as fallback. api_enums::ConnectorStatus::Active, @@ -1212,17 +1243,18 @@ pub async fn create_payment_connector( } } + let connector_auth = serde_json::to_value(auth) + .change_context(errors::ApiErrorResponse::InternalServerError) + .attach_printable("Failed while encoding ConnectorAuthType to serde_json::Value")?; + let conn_auth = Secret::new(connector_auth); + let merchant_connector_account = domain::MerchantConnectorAccount { merchant_id: merchant_id.to_string(), connector_type: req.connector_type, connector_name: req.connector_name.to_string(), merchant_connector_id: utils::generate_id(consts::ID_LENGTH, "mca"), connector_account_details: domain_types::encrypt( - req.connector_account_details.ok_or( - errors::ApiErrorResponse::MissingRequiredField { - field_name: "connector_account_details", - }, - )?, + conn_auth, key_store.key.peek(), ) .await @@ -1256,6 +1288,17 @@ pub async fn create_payment_connector( pm_auth_config: req.pm_auth_config.clone(), status: connector_status, connector_wallets_details: helpers::get_encrypted_apple_pay_connector_wallets_details(&key_store, &req.metadata).await?, + additional_merchant_data: if let Some(mcd) = merchant_recipient_data { + Some(domain_types::encrypt( + Secret::new(mcd), + key_store.key.peek(), + ) + .await + .change_context(errors::ApiErrorResponse::InternalServerError) + .attach_printable("Unable to encrypt additional_merchant_data")?) + } else { + None + }, }; let transaction_type = match req.connector_type { @@ -2577,3 +2620,285 @@ pub fn validate_status_and_disabled( Ok((connector_status, disabled)) } + +async fn process_open_banking_connectors( + state: &SessionState, + merchant_id: &str, + auth: &types::ConnectorAuthType, + connector_type: &api_enums::ConnectorType, + connector: &api_enums::Connector, + additional_merchant_data: types::AdditionalMerchantData, +) -> RouterResult<types::MerchantRecipientData> { + let new_merchant_data = match additional_merchant_data { + types::AdditionalMerchantData::OpenBankingRecipientData(merchant_data) => { + if connector_type != &api_enums::ConnectorType::PaymentProcessor { + return Err(errors::ApiErrorResponse::InvalidConnectorConfiguration { + config: + "OpenBanking connector for Payment Initiation should be a payment processor" + .to_string(), + } + .into()); + } + match &merchant_data { + types::MerchantRecipientData::AccountData(acc_data) => { + validate_bank_account_data(acc_data)?; + + let connector_name = api_enums::Connector::to_string(connector); + + let recipient_creation_not_supported = state + .conf + .locker_based_open_banking_connectors + .connector_list + .contains(connector_name.as_str()); + + let recipient_id = if recipient_creation_not_supported { + locker_recipient_create_call(state, merchant_id, acc_data).await + } else { + connector_recipient_create_call( + state, + merchant_id, + connector_name, + auth, + acc_data, + ) + .await + } + .attach_printable("failed to get recipient_id")?; + + let conn_recipient_id = if recipient_creation_not_supported { + Some(types::RecipientIdType::LockerId(Secret::new(recipient_id))) + } else { + Some(types::RecipientIdType::ConnectorId(Secret::new( + recipient_id, + ))) + }; + + let account_data = match &acc_data { + types::MerchantAccountData::Iban { iban, name, .. } => { + types::MerchantAccountData::Iban { + iban: iban.clone(), + name: name.clone(), + connector_recipient_id: conn_recipient_id.clone(), + } + } + types::MerchantAccountData::Bacs { + account_number, + sort_code, + name, + .. + } => types::MerchantAccountData::Bacs { + account_number: account_number.clone(), + sort_code: sort_code.clone(), + name: name.clone(), + connector_recipient_id: conn_recipient_id.clone(), + }, + }; + + types::MerchantRecipientData::AccountData(account_data) + } + _ => merchant_data.clone(), + } + } + }; + + Ok(new_merchant_data) +} + +fn validate_bank_account_data(data: &types::MerchantAccountData) -> RouterResult<()> { + match data { + types::MerchantAccountData::Iban { iban, .. } => { + // IBAN check algorithm + if iban.peek().len() > IBAN_MAX_LENGTH { + return Err(errors::ApiErrorResponse::InvalidRequestData { + message: "IBAN length must be up to 34 characters".to_string(), + } + .into()); + } + let pattern = Regex::new(r"^[A-Z0-9]*$") + .change_context(errors::ApiErrorResponse::InternalServerError) + .attach_printable("failed to create regex pattern")?; + + let mut iban = iban.peek().to_string(); + + if !pattern.is_match(iban.as_str()) { + return Err(errors::ApiErrorResponse::InvalidRequestData { + message: "IBAN data must be alphanumeric".to_string(), + } + .into()); + } + + // MOD check + let first_4 = iban.chars().take(4).collect::<String>(); + iban.push_str(first_4.as_str()); + let len = iban.len(); + + let rearranged_iban = iban + .chars() + .rev() + .take(len - 4) + .collect::<String>() + .chars() + .rev() + .collect::<String>(); + + let mut result = String::new(); + + rearranged_iban.chars().for_each(|c| { + if c.is_ascii_uppercase() { + let digit = (u32::from(c) - u32::from('A')) + 10; + result.push_str(&format!("{:02}", digit)); + } else { + result.push(c); + } + }); + + let num = result + .parse::<u128>() + .change_context(errors::ApiErrorResponse::InternalServerError) + .attach_printable("failed to validate IBAN")?; + + if num % 97 != 1 { + return Err(errors::ApiErrorResponse::InvalidRequestData { + message: "Invalid IBAN".to_string(), + } + .into()); + } + + Ok(()) + } + types::MerchantAccountData::Bacs { + account_number, + sort_code, + .. + } => { + if account_number.peek().len() > BACS_MAX_ACCOUNT_NUMBER_LENGTH + || sort_code.peek().len() != BACS_SORT_CODE_LENGTH + { + return Err(errors::ApiErrorResponse::InvalidRequestData { + message: "Invalid BACS numbers".to_string(), + } + .into()); + } + + Ok(()) + } + } +} + +async fn connector_recipient_create_call( + state: &SessionState, + merchant_id: &str, + connector_name: String, + auth: &types::ConnectorAuthType, + data: &types::MerchantAccountData, +) -> RouterResult<String> { + let connector = pm_auth_types::api::PaymentAuthConnectorData::get_connector_by_name( + connector_name.as_str(), + )?; + + let auth = pm_auth_types::ConnectorAuthType::foreign_try_from(auth.clone()) + .change_context(errors::ApiErrorResponse::InternalServerError) + .attach_printable("Failed while converting ConnectorAuthType")?; + + let connector_integration: pm_auth_types::api::BoxedConnectorIntegration< + '_, + pm_auth_types::api::auth_service::RecipientCreate, + pm_auth_types::RecipientCreateRequest, + pm_auth_types::RecipientCreateResponse, + > = connector.connector.get_connector_integration(); + + let req = match data { + types::MerchantAccountData::Iban { iban, name, .. } => { + pm_auth_types::RecipientCreateRequest { + name: name.clone(), + account_data: pm_auth_types::RecipientAccountData::Iban(iban.clone()), + address: None, + } + } + types::MerchantAccountData::Bacs { + account_number, + sort_code, + name, + .. + } => pm_auth_types::RecipientCreateRequest { + name: name.clone(), + account_data: pm_auth_types::RecipientAccountData::Bacs { + sort_code: sort_code.clone(), + account_number: account_number.clone(), + }, + address: None, + }, + }; + + let router_data = pm_auth_types::RecipientCreateRouterData { + flow: std::marker::PhantomData, + merchant_id: Some(merchant_id.to_owned()), + connector: Some(connector_name), + request: req, + response: Err(pm_auth_types::ErrorResponse { + status_code: http::StatusCode::INTERNAL_SERVER_ERROR.as_u16(), + code: consts::NO_ERROR_CODE.to_string(), + message: consts::UNSUPPORTED_ERROR_MESSAGE.to_string(), + reason: None, + }), + connector_http_status_code: None, + connector_auth_type: auth, + }; + + let resp = payment_initiation_service::execute_connector_processing_step( + state, + connector_integration, + &router_data, + &connector.connector_name, + ) + .await + .change_context(errors::ApiErrorResponse::InternalServerError) + .attach_printable("Failed while calling recipient create connector api")?; + + let recipient_create_resp = + resp.response + .map_err(|err| errors::ApiErrorResponse::ExternalConnectorError { + code: err.code, + message: err.message, + connector: connector.connector_name.to_string(), + status_code: err.status_code, + reason: err.reason, + })?; + + let recipient_id = recipient_create_resp.recipient_id; + + Ok(recipient_id) +} + +async fn locker_recipient_create_call( + state: &SessionState, + merchant_id: &str, + data: &types::MerchantAccountData, +) -> RouterResult<String> { + let enc_data = serde_json::to_string(data) + .change_context(errors::ApiErrorResponse::InternalServerError) + .attach_printable("Failed to convert to MerchantAccountData json to String")?; + + let cust_id = id_type::CustomerId::from(merchant_id.to_string().into()) + .change_context(errors::ApiErrorResponse::InternalServerError) + .attach_printable("Failed to convert to CustomerId")?; + + let payload = transformers::StoreLockerReq::LockerGeneric(transformers::StoreGenericReq { + merchant_id, + merchant_customer_id: cust_id.clone(), + enc_data, + ttl: state.conf.locker.ttl_for_storage_in_secs, + }); + + let store_resp = cards::call_to_locker_hs( + state, + &payload, + &cust_id, + api_enums::LockerChoice::HyperswitchCardVault, + ) + .await + .change_context(errors::ApiErrorResponse::InternalServerError) + .attach_printable("Failed to encrypt merchant bank account data")?; + + Ok(store_resp.card_reference) +} diff --git a/crates/router/src/core/pm_auth.rs b/crates/router/src/core/pm_auth.rs index d3393b5b1f7..6eea962b9e5 100644 --- a/crates/router/src/core/pm_auth.rs +++ b/crates/router/src/core/pm_auth.rs @@ -209,6 +209,7 @@ impl ForeignTryFrom<&types::ConnectorAuthType> for PlaidAuthType { Ok::<Self, errors::ConnectorError>(Self { client_id: api_key.to_owned(), secret: key1.to_owned(), + merchant_data: None, }) } _ => Err(errors::ConnectorError::FailedToObtainAuthType), diff --git a/crates/router/src/core/pm_auth/transformers.rs b/crates/router/src/core/pm_auth/transformers.rs index 8a1369c2e02..d516cab62fe 100644 --- a/crates/router/src/core/pm_auth/transformers.rs +++ b/crates/router/src/core/pm_auth/transformers.rs @@ -2,6 +2,36 @@ use pm_auth::types::{self as pm_auth_types}; use crate::{core::errors, types, types::transformers::ForeignTryFrom}; +impl From<types::MerchantAccountData> for pm_auth_types::MerchantAccountData { + fn from(from: types::MerchantAccountData) -> Self { + match from { + types::MerchantAccountData::Iban { iban, name, .. } => Self::Iban { iban, name }, + types::MerchantAccountData::Bacs { + account_number, + sort_code, + name, + .. + } => Self::Bacs { + account_number, + sort_code, + name, + }, + } + } +} + +impl From<types::MerchantRecipientData> for pm_auth_types::MerchantRecipientData { + fn from(value: types::MerchantRecipientData) -> Self { + match value { + types::MerchantRecipientData::ConnectorRecipientId(id) => { + Self::ConnectorRecipientId(id) + } + types::MerchantRecipientData::WalletId(id) => Self::WalletId(id), + types::MerchantRecipientData::AccountData(data) => Self::AccountData(data.into()), + } + } +} + impl ForeignTryFrom<types::ConnectorAuthType> for pm_auth_types::ConnectorAuthType { type Error = errors::ConnectorError; fn foreign_try_from(auth_type: types::ConnectorAuthType) -> Result<Self, Self::Error> { diff --git a/crates/router/src/db/merchant_connector_account.rs b/crates/router/src/db/merchant_connector_account.rs index a176db26549..567d16ee269 100644 --- a/crates/router/src/db/merchant_connector_account.rs +++ b/crates/router/src/db/merchant_connector_account.rs @@ -440,7 +440,7 @@ impl MerchantConnectorAccountInterface for Store { #[cfg(feature = "accounts_cache")] // Redact all caches as any of might be used because of backwards compatibility - cache::publish_and_redact_multiple( + Box::pin(cache::publish_and_redact_multiple( self, [ cache::CacheKind::Accounts( @@ -454,7 +454,7 @@ impl MerchantConnectorAccountInterface for Store { ), ], || update, - ) + )) .await .map_err(|error| { // Returning `DatabaseConnectionError` after logging the actual error because @@ -784,6 +784,7 @@ impl MerchantConnectorAccountInterface for MockDb { pm_auth_config: t.pm_auth_config, status: t.status, connector_wallets_details: t.connector_wallets_details.map(Encryption::from), + additional_merchant_data: t.additional_merchant_data.map(|data| data.into()), }; accounts.push(account.clone()); account @@ -991,6 +992,7 @@ mod merchant_connector_account_cache_tests { .await .unwrap(), ), + additional_merchant_data: None, }; db.insert_merchant_connector_account(mca.clone(), &merchant_key) diff --git a/crates/router/src/types.rs b/crates/router/src/types.rs index c457ca59df8..cc735612ac3 100644 --- a/crates/router/src/types.rs +++ b/crates/router/src/types.rs @@ -12,7 +12,7 @@ pub mod domain; #[cfg(feature = "frm")] pub mod fraud_check; pub mod pm_auth; - +use masking::Secret; pub mod storage; pub mod transformers; use std::marker::PhantomData; @@ -606,6 +606,150 @@ pub struct ResponseRouterData<Flow, R, Request, Response> { pub http_code: u16, } +#[derive(Debug, Clone, serde::Deserialize, serde::Serialize)] +pub enum RecipientIdType { + ConnectorId(Secret<String>), + LockerId(Secret<String>), +} + +#[derive(Debug, Clone, serde::Deserialize, serde::Serialize)] +#[serde(rename_all = "snake_case")] +pub enum MerchantAccountData { + Iban { + iban: Secret<String>, + name: String, + connector_recipient_id: Option<RecipientIdType>, + }, + Bacs { + account_number: Secret<String>, + sort_code: Secret<String>, + name: String, + connector_recipient_id: Option<RecipientIdType>, + }, +} + +impl ForeignFrom<MerchantAccountData> for api_models::admin::MerchantAccountData { + fn foreign_from(from: MerchantAccountData) -> Self { + match from { + MerchantAccountData::Iban { + iban, + name, + connector_recipient_id, + } => Self::Iban { + iban, + name, + connector_recipient_id: match connector_recipient_id { + Some(RecipientIdType::ConnectorId(id)) => Some(id.clone()), + _ => None, + }, + }, + MerchantAccountData::Bacs { + account_number, + sort_code, + name, + connector_recipient_id, + } => Self::Bacs { + account_number, + sort_code, + name, + connector_recipient_id: match connector_recipient_id { + Some(RecipientIdType::ConnectorId(id)) => Some(id.clone()), + _ => None, + }, + }, + } + } +} + +impl From<api_models::admin::MerchantAccountData> for MerchantAccountData { + fn from(from: api_models::admin::MerchantAccountData) -> Self { + match from { + api_models::admin::MerchantAccountData::Iban { + iban, + name, + connector_recipient_id, + } => Self::Iban { + iban, + name, + connector_recipient_id: connector_recipient_id.map(RecipientIdType::ConnectorId), + }, + api_models::admin::MerchantAccountData::Bacs { + account_number, + sort_code, + name, + connector_recipient_id, + } => Self::Bacs { + account_number, + sort_code, + name, + connector_recipient_id: connector_recipient_id.map(RecipientIdType::ConnectorId), + }, + } + } +} + +#[derive(Debug, Clone, serde::Deserialize, serde::Serialize)] +#[serde(rename_all = "snake_case")] +pub enum MerchantRecipientData { + ConnectorRecipientId(Secret<String>), + WalletId(Secret<String>), + AccountData(MerchantAccountData), +} + +impl ForeignFrom<MerchantRecipientData> for api_models::admin::MerchantRecipientData { + fn foreign_from(value: MerchantRecipientData) -> Self { + match value { + MerchantRecipientData::ConnectorRecipientId(id) => Self::ConnectorRecipientId(id), + MerchantRecipientData::WalletId(id) => Self::WalletId(id), + MerchantRecipientData::AccountData(data) => { + Self::AccountData(api_models::admin::MerchantAccountData::foreign_from(data)) + } + } + } +} + +impl From<api_models::admin::MerchantRecipientData> for MerchantRecipientData { + fn from(value: api_models::admin::MerchantRecipientData) -> Self { + match value { + api_models::admin::MerchantRecipientData::ConnectorRecipientId(id) => { + Self::ConnectorRecipientId(id) + } + api_models::admin::MerchantRecipientData::WalletId(id) => Self::WalletId(id), + api_models::admin::MerchantRecipientData::AccountData(data) => { + Self::AccountData(data.into()) + } + } + } +} + +#[derive(Debug, Clone, serde::Deserialize, serde::Serialize)] +#[serde(rename_all = "snake_case")] +pub enum AdditionalMerchantData { + OpenBankingRecipientData(MerchantRecipientData), +} + +impl ForeignFrom<api_models::admin::AdditionalMerchantData> for AdditionalMerchantData { + fn foreign_from(value: api_models::admin::AdditionalMerchantData) -> Self { + match value { + api_models::admin::AdditionalMerchantData::OpenBankingRecipientData(data) => { + Self::OpenBankingRecipientData(MerchantRecipientData::from(data)) + } + } + } +} + +impl ForeignFrom<AdditionalMerchantData> for api_models::admin::AdditionalMerchantData { + fn foreign_from(value: AdditionalMerchantData) -> Self { + match value { + AdditionalMerchantData::OpenBankingRecipientData(data) => { + Self::OpenBankingRecipientData( + api_models::admin::MerchantRecipientData::foreign_from(data), + ) + } + } + } +} + impl ForeignFrom<api_models::admin::ConnectorAuthType> for ConnectorAuthType { fn foreign_from(value: api_models::admin::ConnectorAuthType) -> Self { match value { diff --git a/crates/router/src/types/domain/merchant_connector_account.rs b/crates/router/src/types/domain/merchant_connector_account.rs index 6c2f6a06e1e..2cf091eda12 100644 --- a/crates/router/src/types/domain/merchant_connector_account.rs +++ b/crates/router/src/types/domain/merchant_connector_account.rs @@ -40,6 +40,7 @@ pub struct MerchantConnectorAccount { pub pm_auth_config: Option<serde_json::Value>, pub status: enums::ConnectorStatus, pub connector_wallets_details: Option<Encryptable<Secret<serde_json::Value>>>, + pub additional_merchant_data: Option<Encryptable<Secret<serde_json::Value>>>, } #[derive(Debug)] @@ -101,6 +102,7 @@ impl behaviour::Conversion for MerchantConnectorAccount { pm_auth_config: self.pm_auth_config, status: self.status, connector_wallets_details: self.connector_wallets_details.map(Encryption::from), + additional_merchant_data: self.additional_merchant_data.map(|data| data.into()), }, ) } @@ -148,6 +150,17 @@ impl behaviour::Conversion for MerchantConnectorAccount { .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) + .await + .change_context(ValidationError::InvalidValue { + message: "Failed while decrypting additional_merchant_data".to_string(), + })?, + ) + } else { + None + }, }) } @@ -177,6 +190,7 @@ impl behaviour::Conversion for MerchantConnectorAccount { pm_auth_config: self.pm_auth_config, status: self.status, connector_wallets_details: self.connector_wallets_details.map(Encryption::from), + additional_merchant_data: self.additional_merchant_data.map(|data| data.into()), }) } } diff --git a/crates/router/src/types/transformers.rs b/crates/router/src/types/transformers.rs index b06599769f4..d1f01ac8ef7 100644 --- a/crates/router/src/types/transformers.rs +++ b/crates/router/src/types/transformers.rs @@ -26,6 +26,7 @@ use crate::{ }, services::authentication::get_header_value_by_key, types::{ + self as router_types, api::{self as api_types, routing as routing_types}, storage, }, @@ -977,6 +978,19 @@ impl TryFrom<domain::MerchantConnectorAccount> for api_models::admin::MerchantCo applepay_verified_domains: item.applepay_verified_domains, pm_auth_config: item.pm_auth_config, status: item.status, + additional_merchant_data: item + .additional_merchant_data + .map(|data| { + let data = data.into_inner(); + serde_json::Value::parse_value::<router_types::AdditionalMerchantData>( + data.expose(), + "AdditionalMerchantData", + ) + .attach_printable("Unable to deserialize additional_merchant_data") + .change_context(errors::ApiErrorResponse::InternalServerError) + }) + .transpose()? + .map(api_models::admin::AdditionalMerchantData::foreign_from), }) } } diff --git a/migrations/2024-04-12-100925_mca_additional_merchant_data/down.sql b/migrations/2024-04-12-100925_mca_additional_merchant_data/down.sql new file mode 100644 index 00000000000..7614b52872d --- /dev/null +++ b/migrations/2024-04-12-100925_mca_additional_merchant_data/down.sql @@ -0,0 +1,2 @@ +-- This file should undo anything in `up.sql` +ALTER TABLE merchant_connector_account DROP COLUMN IF EXISTS additional_merchant_data; \ No newline at end of file diff --git a/migrations/2024-04-12-100925_mca_additional_merchant_data/up.sql b/migrations/2024-04-12-100925_mca_additional_merchant_data/up.sql new file mode 100644 index 00000000000..4b48796785e --- /dev/null +++ b/migrations/2024-04-12-100925_mca_additional_merchant_data/up.sql @@ -0,0 +1,2 @@ +-- Your SQL goes here +ALTER TABLE merchant_connector_account ADD COLUMN IF NOT EXISTS additional_merchant_data BYTEA DEFAULT NULL; \ No newline at end of file
2024-02-21T14:45:22Z
## 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 call in payment connector create to facilitate merchant recipient creation at connector end. - Added alternative locker call for creation of recipient at Hyperswitch's end in case the connector does not support it. - Added validation for merchant bank account data ### Additional Changes - [x] This PR modifies the API contract - [x] 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)? --> 1. Create an MCA account with `connector_type` as `payment_processor` and an open banking connector ``` curl --location --request POST 'http://localhost:8080/account/merchant_1720607250/connectors' \ --header 'api-key: test_admin' \ --header 'Content-Type: application/json' \ --data-raw '{ "connector_type": "payment_processor", "connector_name": "plaid", "connector_label": "plaid3", "connector_account_details": { "auth_type": "BodyKey", "api_key": "Some_key", "key1": "Some_key" }, "test_mode": false, "disabled": false, "payment_methods_enabled": [ { "payment_method": "bank_redirect", "payment_method_types": [ { "payment_method_type": "eps", "recurring_enabled": true, "installment_payment_enabled": true, "accepted_currencies": { "type": "enable_only", "list": [ "EUR" ] } }, { "payment_method_type": "giropay", "recurring_enabled": true, "installment_payment_enabled": true, "accepted_currencies": { "type": "enable_only", "list": [ "EUR" ] } }, { "payment_method_type": "ideal", "recurring_enabled": true, "installment_payment_enabled": true, "accepted_currencies": { "type": "enable_only", "list": [ "EUR" ] } } ] }, { "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": "apple_pay", "payment_experience": "invoke_sdk_client", "card_networks": null, "accepted_countries": null, "minimum_amount": 1, "maximum_amount": 68607706, "recurring_enabled": true, "installment_payment_enabled": true, "accepted_currencies": { "type": "enable_only", "list": [ "USD", "GBP", "CAD", "AUD", "EUR" ] } } ] } ], "additional_merchant_data": { "open_banking_recipient_data": { "account_data": { "bacs": { "sort_code": "200000", "account_number": "55779911", "name": "merchant_name" } } } }, "metadata": { "city": "NY", "unit": "246" } }' ``` Successful Response should look like this - ``` { "connector_type": "payment_processor", "connector_name": "plaid", "connector_label": "plaid3", "merchant_connector_id": "mca_c0iTEayEJMViYwEhTCOG", "profile_id": "pro_UgP3FfqWGhfPLuUqYtJF", "connector_account_details": { "auth_type": "BodyKey", "api_key": "Some_key", "key1": "Some_key" }, "payment_methods_enabled": [ { "payment_method": "bank_redirect", "payment_method_types": [ { "payment_method_type": "eps", "payment_experience": null, "card_networks": null, "accepted_currencies": { "type": "enable_only", "list": [ "EUR" ] }, "accepted_countries": null, "minimum_amount": null, "maximum_amount": null, "recurring_enabled": true, "installment_payment_enabled": true }, { "payment_method_type": "giropay", "payment_experience": null, "card_networks": null, "accepted_currencies": { "type": "enable_only", "list": [ "EUR" ] }, "accepted_countries": null, "minimum_amount": null, "maximum_amount": null, "recurring_enabled": true, "installment_payment_enabled": true }, { "payment_method_type": "ideal", "payment_experience": null, "card_networks": null, "accepted_currencies": { "type": "enable_only", "list": [ "EUR" ] }, "accepted_countries": null, "minimum_amount": null, "maximum_amount": null, "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": 0, "maximum_amount": 10000, "recurring_enabled": true, "installment_payment_enabled": true } ] }, { "payment_method": "wallet", "payment_method_types": [ { "payment_method_type": "apple_pay", "payment_experience": "invoke_sdk_client", "card_networks": null, "accepted_currencies": { "type": "enable_only", "list": [ "USD", "GBP", "CAD", "AUD", "EUR" ] }, "accepted_countries": null, "minimum_amount": 1, "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": { "bacs": { "account_number": "55779911", "sort_code": "200000", "name": "merchant_name", "connector_recipient_id": "recipient-id-sandbox-45beb880-9e3d-4ae3-927b-052f5610fd74" } } } } } ``` Response when the connector does not support recipient creation (locker call to be made in this) ``` { "connector_type": "payment_processor", "connector_name": "plaid", "connector_label": "plaid3", "merchant_connector_id": "mca_6bIUIrWNSbqssRO89Zxx", "profile_id": "pro_UgP3FfqWGhfPLuUqYtJF", "connector_account_details": { "auth_type": "BodyKey", "api_key": "Some_key", "key1": "Some_key" }, "payment_methods_enabled": [ { "payment_method": "bank_redirect", "payment_method_types": [ { "payment_method_type": "eps", "payment_experience": null, "card_networks": null, "accepted_currencies": { "type": "enable_only", "list": [ "EUR" ] }, "accepted_countries": null, "minimum_amount": null, "maximum_amount": null, "recurring_enabled": true, "installment_payment_enabled": true }, { "payment_method_type": "giropay", "payment_experience": null, "card_networks": null, "accepted_currencies": { "type": "enable_only", "list": [ "EUR" ] }, "accepted_countries": null, "minimum_amount": null, "maximum_amount": null, "recurring_enabled": true, "installment_payment_enabled": true }, { "payment_method_type": "ideal", "payment_experience": null, "card_networks": null, "accepted_currencies": { "type": "enable_only", "list": [ "EUR" ] }, "accepted_countries": null, "minimum_amount": null, "maximum_amount": null, "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": 0, "maximum_amount": 10000, "recurring_enabled": true, "installment_payment_enabled": true } ] }, { "payment_method": "wallet", "payment_method_types": [ { "payment_method_type": "apple_pay", "payment_experience": "invoke_sdk_client", "card_networks": null, "accepted_currencies": { "type": "enable_only", "list": [ "USD", "GBP", "CAD", "AUD", "EUR" ] }, "accepted_countries": null, "minimum_amount": 1, "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": { "bacs": { "account_number": "55779911", "sort_code": "200000", "name": "merchant_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` - [ ] I reviewed the submitted code - [ ] I added unit tests for my changes where possible - [ ] I added a [CHANGELOG](/CHANGELOG.md) entry if applicable
43741df4a76a66faa472dacd66b396232a2fbdbf
1. Create an MCA account with `connector_type` as `payment_processor` and an open banking connector ``` curl --location --request POST 'http://localhost:8080/account/merchant_1720607250/connectors' \ --header 'api-key: test_admin' \ --header 'Content-Type: application/json' \ --data-raw '{ "connector_type": "payment_processor", "connector_name": "plaid", "connector_label": "plaid3", "connector_account_details": { "auth_type": "BodyKey", "api_key": "Some_key", "key1": "Some_key" }, "test_mode": false, "disabled": false, "payment_methods_enabled": [ { "payment_method": "bank_redirect", "payment_method_types": [ { "payment_method_type": "eps", "recurring_enabled": true, "installment_payment_enabled": true, "accepted_currencies": { "type": "enable_only", "list": [ "EUR" ] } }, { "payment_method_type": "giropay", "recurring_enabled": true, "installment_payment_enabled": true, "accepted_currencies": { "type": "enable_only", "list": [ "EUR" ] } }, { "payment_method_type": "ideal", "recurring_enabled": true, "installment_payment_enabled": true, "accepted_currencies": { "type": "enable_only", "list": [ "EUR" ] } } ] }, { "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": "apple_pay", "payment_experience": "invoke_sdk_client", "card_networks": null, "accepted_countries": null, "minimum_amount": 1, "maximum_amount": 68607706, "recurring_enabled": true, "installment_payment_enabled": true, "accepted_currencies": { "type": "enable_only", "list": [ "USD", "GBP", "CAD", "AUD", "EUR" ] } } ] } ], "additional_merchant_data": { "open_banking_recipient_data": { "account_data": { "bacs": { "sort_code": "200000", "account_number": "55779911", "name": "merchant_name" } } } }, "metadata": { "city": "NY", "unit": "246" } }' ``` Successful Response should look like this - ``` { "connector_type": "payment_processor", "connector_name": "plaid", "connector_label": "plaid3", "merchant_connector_id": "mca_c0iTEayEJMViYwEhTCOG", "profile_id": "pro_UgP3FfqWGhfPLuUqYtJF", "connector_account_details": { "auth_type": "BodyKey", "api_key": "Some_key", "key1": "Some_key" }, "payment_methods_enabled": [ { "payment_method": "bank_redirect", "payment_method_types": [ { "payment_method_type": "eps", "payment_experience": null, "card_networks": null, "accepted_currencies": { "type": "enable_only", "list": [ "EUR" ] }, "accepted_countries": null, "minimum_amount": null, "maximum_amount": null, "recurring_enabled": true, "installment_payment_enabled": true }, { "payment_method_type": "giropay", "payment_experience": null, "card_networks": null, "accepted_currencies": { "type": "enable_only", "list": [ "EUR" ] }, "accepted_countries": null, "minimum_amount": null, "maximum_amount": null, "recurring_enabled": true, "installment_payment_enabled": true }, { "payment_method_type": "ideal", "payment_experience": null, "card_networks": null, "accepted_currencies": { "type": "enable_only", "list": [ "EUR" ] }, "accepted_countries": null, "minimum_amount": null, "maximum_amount": null, "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": 0, "maximum_amount": 10000, "recurring_enabled": true, "installment_payment_enabled": true } ] }, { "payment_method": "wallet", "payment_method_types": [ { "payment_method_type": "apple_pay", "payment_experience": "invoke_sdk_client", "card_networks": null, "accepted_currencies": { "type": "enable_only", "list": [ "USD", "GBP", "CAD", "AUD", "EUR" ] }, "accepted_countries": null, "minimum_amount": 1, "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": { "bacs": { "account_number": "55779911", "sort_code": "200000", "name": "merchant_name", "connector_recipient_id": "recipient-id-sandbox-45beb880-9e3d-4ae3-927b-052f5610fd74" } } } } } ``` Response when the connector does not support recipient creation (locker call to be made in this) ``` { "connector_type": "payment_processor", "connector_name": "plaid", "connector_label": "plaid3", "merchant_connector_id": "mca_6bIUIrWNSbqssRO89Zxx", "profile_id": "pro_UgP3FfqWGhfPLuUqYtJF", "connector_account_details": { "auth_type": "BodyKey", "api_key": "Some_key", "key1": "Some_key" }, "payment_methods_enabled": [ { "payment_method": "bank_redirect", "payment_method_types": [ { "payment_method_type": "eps", "payment_experience": null, "card_networks": null, "accepted_currencies": { "type": "enable_only", "list": [ "EUR" ] }, "accepted_countries": null, "minimum_amount": null, "maximum_amount": null, "recurring_enabled": true, "installment_payment_enabled": true }, { "payment_method_type": "giropay", "payment_experience": null, "card_networks": null, "accepted_currencies": { "type": "enable_only", "list": [ "EUR" ] }, "accepted_countries": null, "minimum_amount": null, "maximum_amount": null, "recurring_enabled": true, "installment_payment_enabled": true }, { "payment_method_type": "ideal", "payment_experience": null, "card_networks": null, "accepted_currencies": { "type": "enable_only", "list": [ "EUR" ] }, "accepted_countries": null, "minimum_amount": null, "maximum_amount": null, "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": 0, "maximum_amount": 10000, "recurring_enabled": true, "installment_payment_enabled": true } ] }, { "payment_method": "wallet", "payment_method_types": [ { "payment_method_type": "apple_pay", "payment_experience": "invoke_sdk_client", "card_networks": null, "accepted_currencies": { "type": "enable_only", "list": [ "USD", "GBP", "CAD", "AUD", "EUR" ] }, "accepted_countries": null, "minimum_amount": 1, "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": { "bacs": { "account_number": "55779911", "sort_code": "200000", "name": "merchant_name" } } } } } ```
juspay/hyperswitch
juspay__hyperswitch-3612
Bug: [FEATURE] Incorporate Open Banking flows in Payments Core ### Feature Description Need to support Open banking framework in Payments core to handle integrations of open banking connectors ### Possible Implementation Will be using the payments core for implementation of open banking payment flows ### 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 bcc67100e1c..f53507fc13a 100644 --- a/crates/api_models/src/payments.rs +++ b/crates/api_models/src/payments.rs @@ -1600,6 +1600,7 @@ mod payment_method_data_serde { | PaymentMethodData::Voucher(_) | PaymentMethodData::Card(_) | PaymentMethodData::MandatePayment + | PaymentMethodData::OpenBanking(_) | PaymentMethodData::Wallet(_) => { payment_method_data_request.serialize(serializer) } @@ -1657,6 +1658,8 @@ pub enum PaymentMethodData { GiftCard(Box<GiftCardData>), #[schema(title = "CardToken")] CardToken(CardToken), + #[schema(title = "OpenBanking")] + OpenBanking(OpenBankingData), } pub trait GetAddressFromPaymentMethodData { @@ -1680,6 +1683,7 @@ impl GetAddressFromPaymentMethodData for PaymentMethodData { | Self::Upi(_) | Self::GiftCard(_) | Self::CardToken(_) + | Self::OpenBanking(_) | Self::MandatePayment => None, } } @@ -1717,6 +1721,7 @@ impl PaymentMethodData { Self::Upi(_) => Some(api_enums::PaymentMethod::Upi), Self::Voucher(_) => Some(api_enums::PaymentMethod::Voucher), Self::GiftCard(_) => Some(api_enums::PaymentMethod::GiftCard), + Self::OpenBanking(_) => Some(api_enums::PaymentMethod::OpenBanking), Self::CardToken(_) | Self::MandatePayment => None, } } @@ -1785,6 +1790,14 @@ impl GetPaymentMethodType for PayLaterData { } } +impl GetPaymentMethodType for OpenBankingData { + fn get_payment_method_type(&self) -> api_enums::PaymentMethodType { + match self { + Self::OpenBankingPIS {} => api_enums::PaymentMethodType::OpenBankingPIS, + } + } +} + impl GetPaymentMethodType for BankRedirectData { fn get_payment_method_type(&self) -> api_enums::PaymentMethodType { match self { @@ -1983,6 +1996,7 @@ pub enum AdditionalPaymentData { Voucher {}, CardRedirect {}, CardToken {}, + OpenBanking {}, } #[derive(Debug, Clone, Eq, PartialEq, serde::Deserialize, serde::Serialize)] @@ -2673,6 +2687,12 @@ pub struct SamsungPayWalletData { pub token: Secret<String>, } +#[derive(Eq, PartialEq, Clone, Debug, serde::Deserialize, serde::Serialize, ToSchema)] +#[serde(rename_all = "snake_case")] +pub enum OpenBankingData { + #[serde(rename = "open_banking_pis")] + OpenBankingPIS {}, +} #[derive(Eq, PartialEq, Clone, Debug, serde::Deserialize, serde::Serialize, ToSchema)] #[serde(rename_all = "snake_case")] pub struct GooglePayWalletData { @@ -2946,6 +2966,7 @@ where | PaymentMethodDataResponse::Upi {} | PaymentMethodDataResponse::Wallet {} | PaymentMethodDataResponse::BankTransfer {} + | PaymentMethodDataResponse::OpenBanking {} | PaymentMethodDataResponse::Voucher {} => { payment_method_data_response.serialize(serializer) } @@ -2979,6 +3000,7 @@ pub enum PaymentMethodDataResponse { GiftCard {}, CardRedirect {}, CardToken {}, + OpenBanking {}, } #[derive(Eq, PartialEq, Clone, Debug, serde::Serialize, serde::Deserialize, ToSchema)] @@ -4146,6 +4168,7 @@ impl From<AdditionalPaymentData> for PaymentMethodDataResponse { AdditionalPaymentData::GiftCard {} => Self::GiftCard {}, AdditionalPaymentData::CardRedirect {} => Self::CardRedirect {}, AdditionalPaymentData::CardToken {} => Self::CardToken {}, + AdditionalPaymentData::OpenBanking {} => Self::OpenBanking {}, } } } @@ -4531,6 +4554,8 @@ pub enum SessionToken { Paypal(Box<PaypalSessionTokenResponse>), /// The session response structure for Apple Pay ApplePay(Box<ApplepaySessionTokenResponse>), + /// Session token for OpenBanking PIS flow + OpenBanking(OpenBankingSessionToken), /// Whenever there is no session token response or an error in session response NoSessionTokenReceived, } @@ -4607,6 +4632,13 @@ pub struct PaypalSessionTokenResponse { pub sdk_next_action: SdkNextAction, } +#[derive(Debug, Clone, Eq, PartialEq, serde::Serialize, ToSchema)] +#[serde(rename_all = "lowercase")] +pub struct OpenBankingSessionToken { + /// The session token for OpenBanking Connectors + pub open_banking_session_token: String, +} + #[derive(Debug, Clone, Eq, PartialEq, serde::Serialize, ToSchema)] #[serde(rename_all = "lowercase")] pub struct ApplepaySessionTokenResponse { diff --git a/crates/common_enums/src/enums.rs b/crates/common_enums/src/enums.rs index 129e83ce2b6..12281350af2 100644 --- a/crates/common_enums/src/enums.rs +++ b/crates/common_enums/src/enums.rs @@ -1569,6 +1569,8 @@ pub enum PaymentMethodType { PayEasy, LocalBankTransfer, Mifinity, + #[serde(rename = "open_banking_pis")] + OpenBankingPIS, } /// Indicates the type of payment method. Eg: 'card', 'wallet', etc. @@ -1606,6 +1608,7 @@ pub enum PaymentMethod { Upi, Voucher, GiftCard, + OpenBanking, } /// The type of the payment that differentiates between normal and various types of mandate payments. Use 'setup_mandate' in case of zero auth flow. diff --git a/crates/common_enums/src/transformers.rs b/crates/common_enums/src/transformers.rs index fc39cd1cf50..fab570542c8 100644 --- a/crates/common_enums/src/transformers.rs +++ b/crates/common_enums/src/transformers.rs @@ -1882,6 +1882,7 @@ impl From<PaymentMethodType> for PaymentMethod { PaymentMethodType::FamilyMart => Self::Voucher, PaymentMethodType::Seicomart => Self::Voucher, PaymentMethodType::PayEasy => Self::Voucher, + PaymentMethodType::OpenBankingPIS => Self::OpenBanking, } } } diff --git a/crates/connector_configs/src/response_modifier.rs b/crates/connector_configs/src/response_modifier.rs index 38dc4130cf0..06f9d25b65d 100644 --- a/crates/connector_configs/src/response_modifier.rs +++ b/crates/connector_configs/src/response_modifier.rs @@ -19,6 +19,7 @@ impl ConnectorApiIntegrationPayload { let mut voucher_details: Vec<Provider> = Vec::new(); let mut gift_card_details: Vec<Provider> = Vec::new(); let mut card_redirect_details: Vec<Provider> = Vec::new(); + let mut open_banking_details: Vec<Provider> = Vec::new(); if let Some(payment_methods_enabled) = response.payment_methods_enabled.clone() { for methods in payment_methods_enabled { @@ -160,6 +161,18 @@ impl ConnectorApiIntegrationPayload { } } } + api_models::enums::PaymentMethod::OpenBanking => { + if let Some(payment_method_types) = methods.payment_method_types { + for method_type in payment_method_types { + open_banking_details.push(Provider { + payment_method_type: method_type.payment_method_type, + accepted_currencies: method_type.accepted_currencies.clone(), + accepted_countries: method_type.accepted_countries.clone(), + payment_experience: method_type.payment_experience, + }) + } + } + } api_models::enums::PaymentMethod::Upi => { if let Some(payment_method_types) = methods.payment_method_types { for method_type in payment_method_types { diff --git a/crates/connector_configs/src/transformer.rs b/crates/connector_configs/src/transformer.rs index 1a54dc9ae0d..fe39da67a93 100644 --- a/crates/connector_configs/src/transformer.rs +++ b/crates/connector_configs/src/transformer.rs @@ -138,6 +138,7 @@ impl DashboardRequestPayload { | PaymentMethod::Upi | PaymentMethod::Voucher | PaymentMethod::GiftCard + | PaymentMethod::OpenBanking | PaymentMethod::CardRedirect => { if let Some(provider) = payload.provider { let val = Self::transform_payment_method( diff --git a/crates/euclid/src/dssa/graph.rs b/crates/euclid/src/dssa/graph.rs index 008b5628512..13e11515382 100644 --- a/crates/euclid/src/dssa/graph.rs +++ b/crates/euclid/src/dssa/graph.rs @@ -69,6 +69,7 @@ impl cgraph::NodeViz for dir::DirValue { Self::SetupFutureUsage(sfu) => sfu.to_string(), Self::CardRedirectType(crt) => crt.to_string(), Self::RealTimePaymentType(rtpt) => rtpt.to_string(), + Self::OpenBankingType(ob) => ob.to_string(), } } } diff --git a/crates/euclid/src/frontend/ast/lowering.rs b/crates/euclid/src/frontend/ast/lowering.rs index 48a1a0ab8bf..8a8ba695e9f 100644 --- a/crates/euclid/src/frontend/ast/lowering.rs +++ b/crates/euclid/src/frontend/ast/lowering.rs @@ -264,6 +264,8 @@ fn lower_comparison_inner<O: EuclidDirFilter>( dir::DirKeyKind::UpiType => lower_enum!(UpiType, value), + dir::DirKeyKind::OpenBankingType => lower_enum!(OpenBankingType, value), + dir::DirKeyKind::VoucherType => lower_enum!(VoucherType, value), dir::DirKeyKind::GiftCardType => lower_enum!(GiftCardType, value), diff --git a/crates/euclid/src/frontend/dir.rs b/crates/euclid/src/frontend/dir.rs index a21ae104882..8cfdf656716 100644 --- a/crates/euclid/src/frontend/dir.rs +++ b/crates/euclid/src/frontend/dir.rs @@ -319,6 +319,13 @@ pub enum DirKeyKind { props(Category = "Payment Method Types") )] RealTimePaymentType, + #[serde(rename = "open_banking")] + #[strum( + serialize = "open_banking", + detailed_message = "Supported types of open banking payment method", + props(Category = "Payment Method Types") + )] + OpenBankingType, } pub trait EuclidDirFilter: Sized @@ -367,6 +374,7 @@ impl DirKeyKind { Self::SetupFutureUsage => types::DataType::EnumVariant, Self::CardRedirectType => types::DataType::EnumVariant, Self::RealTimePaymentType => types::DataType::EnumVariant, + Self::OpenBankingType => types::DataType::EnumVariant, } } pub fn get_value_set(&self) -> Option<Vec<DirValue>> { @@ -498,6 +506,11 @@ impl DirKeyKind { .map(DirValue::RealTimePaymentType) .collect(), ), + Self::OpenBankingType => Some( + enums::OpenBankingType::iter() + .map(DirValue::OpenBankingType) + .collect(), + ), } } } @@ -565,6 +578,8 @@ pub enum DirValue { CardRedirectType(enums::CardRedirectType), #[serde(rename = "real_time_payment")] RealTimePaymentType(enums::RealTimePaymentType), + #[serde(rename = "open_banking")] + OpenBankingType(enums::OpenBankingType), } impl DirValue { @@ -599,6 +614,7 @@ impl DirValue { Self::VoucherType(_) => (DirKeyKind::VoucherType, None), Self::GiftCardType(_) => (DirKeyKind::GiftCardType, None), Self::RealTimePaymentType(_) => (DirKeyKind::RealTimePaymentType, None), + Self::OpenBankingType(_) => (DirKeyKind::OpenBankingType, None), }; DirKey::new(kind, data) @@ -634,6 +650,7 @@ impl DirValue { Self::SetupFutureUsage(_) => None, Self::CardRedirectType(_) => None, Self::RealTimePaymentType(_) => None, + Self::OpenBankingType(_) => None, } } diff --git a/crates/euclid/src/frontend/dir/enums.rs b/crates/euclid/src/frontend/dir/enums.rs index 5d0defc7357..0d2f959c702 100644 --- a/crates/euclid/src/frontend/dir/enums.rs +++ b/crates/euclid/src/frontend/dir/enums.rs @@ -160,6 +160,26 @@ pub enum BankRedirectType { Przelewy24, Trustly, } + +#[derive( + Clone, + Debug, + Hash, + PartialEq, + Eq, + strum::Display, + strum::VariantNames, + strum::EnumIter, + strum::EnumString, + serde::Serialize, + serde::Deserialize, +)] +#[serde(rename_all = "snake_case")] +#[strum(serialize_all = "snake_case")] +pub enum OpenBankingType { + OpenBankingPIS, +} + #[derive( Clone, Debug, @@ -350,3 +370,4 @@ collect_variants!(VoucherType); collect_variants!(GiftCardType); collect_variants!(BankTransferType); collect_variants!(CardRedirectType); +collect_variants!(OpenBankingType); diff --git a/crates/euclid/src/frontend/dir/lowering.rs b/crates/euclid/src/frontend/dir/lowering.rs index f91c63a8166..33d368e9696 100644 --- a/crates/euclid/src/frontend/dir/lowering.rs +++ b/crates/euclid/src/frontend/dir/lowering.rs @@ -168,6 +168,14 @@ impl From<enums::BankRedirectType> for global_enums::PaymentMethodType { } } +impl From<enums::OpenBankingType> for global_enums::PaymentMethodType { + fn from(value: enums::OpenBankingType) -> Self { + match value { + enums::OpenBankingType::OpenBankingPIS => Self::OpenBankingPIS, + } + } +} + impl From<enums::CryptoType> for global_enums::PaymentMethodType { fn from(value: enums::CryptoType) -> Self { match value { @@ -238,6 +246,7 @@ fn lower_value(dir_value: dir::DirValue) -> Result<EuclidValue, AnalysisErrorTyp dir::DirValue::RewardType(rt) => EuclidValue::PaymentMethodType(rt.into()), dir::DirValue::BusinessLabel(bl) => EuclidValue::BusinessLabel(bl), dir::DirValue::SetupFutureUsage(sfu) => EuclidValue::SetupFutureUsage(sfu), + dir::DirValue::OpenBankingType(ob) => EuclidValue::PaymentMethodType(ob.into()), }) } diff --git a/crates/euclid/src/frontend/dir/transformers.rs b/crates/euclid/src/frontend/dir/transformers.rs index 3f83ee3db01..3e35bcd391c 100644 --- a/crates/euclid/src/frontend/dir/transformers.rs +++ b/crates/euclid/src/frontend/dir/transformers.rs @@ -38,6 +38,7 @@ impl IntoDirValue for (global_enums::PaymentMethodType, global_enums::PaymentMet | global_enums::PaymentMethod::RealTimePayment | global_enums::PaymentMethod::Upi | global_enums::PaymentMethod::Voucher + | global_enums::PaymentMethod::OpenBanking | global_enums::PaymentMethod::GiftCard => Err(AnalysisErrorType::NotSupported), }, global_enums::PaymentMethodType::Bacs => match self.1 { @@ -53,6 +54,7 @@ impl IntoDirValue for (global_enums::PaymentMethodType, global_enums::PaymentMet | global_enums::PaymentMethod::RealTimePayment | global_enums::PaymentMethod::Upi | global_enums::PaymentMethod::Voucher + | global_enums::PaymentMethod::OpenBanking | global_enums::PaymentMethod::GiftCard => Err(AnalysisErrorType::NotSupported), }, global_enums::PaymentMethodType::Becs => Ok(dirval!(BankDebitType = Becs)), @@ -69,6 +71,7 @@ impl IntoDirValue for (global_enums::PaymentMethodType, global_enums::PaymentMet | global_enums::PaymentMethod::RealTimePayment | global_enums::PaymentMethod::Upi | global_enums::PaymentMethod::Voucher + | global_enums::PaymentMethod::OpenBanking | global_enums::PaymentMethod::GiftCard => Err(AnalysisErrorType::NotSupported), }, global_enums::PaymentMethodType::AliPay => Ok(dirval!(WalletType = AliPay)), @@ -182,6 +185,9 @@ impl IntoDirValue for (global_enums::PaymentMethodType, global_enums::PaymentMet } global_enums::PaymentMethodType::Venmo => Ok(dirval!(WalletType = Venmo)), global_enums::PaymentMethodType::Mifinity => Ok(dirval!(WalletType = Mifinity)), + global_enums::PaymentMethodType::OpenBankingPIS => { + Ok(dirval!(OpenBankingType = OpenBankingPIS)) + } } } } diff --git a/crates/euclid_wasm/src/lib.rs b/crates/euclid_wasm/src/lib.rs index e92552002b5..031440ae541 100644 --- a/crates/euclid_wasm/src/lib.rs +++ b/crates/euclid_wasm/src/lib.rs @@ -263,6 +263,7 @@ pub fn get_variant_values(key: &str) -> Result<JsValue, JsValue> { dir::DirKeyKind::VoucherType => dir_enums::VoucherType::VARIANTS, dir::DirKeyKind::BankDebitType => dir_enums::BankDebitType::VARIANTS, dir::DirKeyKind::RealTimePaymentType => dir_enums::RealTimePaymentType::VARIANTS, + dir::DirKeyKind::OpenBankingType => dir_enums::OpenBankingType::VARIANTS, dir::DirKeyKind::PaymentAmount | dir::DirKeyKind::Connector diff --git a/crates/hyperswitch_domain_models/src/payment_method_data.rs b/crates/hyperswitch_domain_models/src/payment_method_data.rs index 005e21743d9..49b6951f5f8 100644 --- a/crates/hyperswitch_domain_models/src/payment_method_data.rs +++ b/crates/hyperswitch_domain_models/src/payment_method_data.rs @@ -22,6 +22,7 @@ pub enum PaymentMethodData { Voucher(VoucherData), GiftCard(Box<GiftCardData>), CardToken(CardToken), + OpenBanking(OpenBankingData), } #[derive(Debug, Clone, PartialEq, Eq)] @@ -46,6 +47,7 @@ impl PaymentMethodData { Self::Upi(_) => Some(common_enums::PaymentMethod::Upi), Self::Voucher(_) => Some(common_enums::PaymentMethod::Voucher), Self::GiftCard(_) => Some(common_enums::PaymentMethod::GiftCard), + Self::OpenBanking(_) => Some(common_enums::PaymentMethod::OpenBanking), Self::CardToken(_) | Self::MandatePayment => None, } } @@ -318,6 +320,12 @@ pub enum BankRedirectData { LocalBankRedirect {}, } +#[derive(Debug, Clone, Eq, PartialEq, serde::Deserialize, serde::Serialize)] +#[serde(rename_all = "snake_case")] +pub enum OpenBankingData { + OpenBankingPIS {}, +} + #[derive(Debug, Clone, Eq, PartialEq, serde::Deserialize, serde::Serialize)] #[serde(rename_all = "snake_case")] pub struct CryptoData { @@ -495,6 +503,9 @@ impl From<api_models::payments::PaymentMethodData> for PaymentMethodData { api_models::payments::PaymentMethodData::CardToken(card_token) => { Self::CardToken(From::from(card_token)) } + api_models::payments::PaymentMethodData::OpenBanking(ob_data) => { + Self::OpenBanking(From::from(ob_data)) + } } } } @@ -922,3 +933,11 @@ impl From<api_models::payments::RealTimePaymentData> for RealTimePaymentData { } } } + +impl From<api_models::payments::OpenBankingData> for OpenBankingData { + fn from(value: api_models::payments::OpenBankingData) -> Self { + match value { + api_models::payments::OpenBankingData::OpenBankingPIS {} => Self::OpenBankingPIS {}, + } + } +} diff --git a/crates/hyperswitch_domain_models/src/router_flow_types/payments.rs b/crates/hyperswitch_domain_models/src/router_flow_types/payments.rs index 046866beea5..1263f8f975a 100644 --- a/crates/hyperswitch_domain_models/src/router_flow_types/payments.rs +++ b/crates/hyperswitch_domain_models/src/router_flow_types/payments.rs @@ -46,3 +46,6 @@ pub struct PreProcessing; #[derive(Debug, Clone)] pub struct IncrementalAuthorization; + +#[derive(Debug, Clone)] +pub struct PostProcessing; diff --git a/crates/hyperswitch_domain_models/src/router_request_types.rs b/crates/hyperswitch_domain_models/src/router_request_types.rs index f30e6010cff..26db7eed01d 100644 --- a/crates/hyperswitch_domain_models/src/router_request_types.rs +++ b/crates/hyperswitch_domain_models/src/router_request_types.rs @@ -54,7 +54,7 @@ pub struct PaymentsAuthorizeData { pub payment_experience: Option<storage_enums::PaymentExperience>, pub payment_method_type: Option<storage_enums::PaymentMethodType>, pub surcharge_details: Option<SurchargeDetails>, - pub customer_id: Option<String>, + pub customer_id: Option<id_type::CustomerId>, pub request_incremental_authorization: bool, pub metadata: Option<serde_json::Value>, pub authentication_data: Option<AuthenticationData>, @@ -336,6 +336,35 @@ impl TryFrom<CompleteAuthorizeData> for PaymentsPreProcessingData { }) } } + +#[derive(Debug, Clone)] +pub struct PaymentsPostProcessingData { + pub payment_method_data: PaymentMethodData, + pub customer_id: Option<id_type::CustomerId>, + pub connector_transaction_id: Option<String>, +} + +impl<F> TryFrom<RouterData<F, PaymentsAuthorizeData, response_types::PaymentsResponseData>> + for PaymentsPostProcessingData +{ + type Error = error_stack::Report<ApiErrorResponse>; + + fn try_from( + data: RouterData<F, PaymentsAuthorizeData, response_types::PaymentsResponseData>, + ) -> Result<Self, Self::Error> { + Ok(Self { + payment_method_data: data.request.payment_method_data, + connector_transaction_id: match data.response { + Ok(response_types::PaymentsResponseData::TransactionResponse { + resource_id: ResponseId::ConnectorTransactionId(id), + .. + }) => Some(id.clone()), + _ => None, + }, + customer_id: data.request.customer_id, + }) + } +} #[derive(Debug, Clone)] pub struct CompleteAuthorizeData { pub payment_method_data: Option<PaymentMethodData>, diff --git a/crates/hyperswitch_domain_models/src/router_response_types.rs b/crates/hyperswitch_domain_models/src/router_response_types.rs index a5c6aafdab1..e41b0aa78b9 100644 --- a/crates/hyperswitch_domain_models/src/router_response_types.rs +++ b/crates/hyperswitch_domain_models/src/router_response_types.rs @@ -65,6 +65,9 @@ pub enum PaymentsResponseData { error_code: Option<String>, error_message: Option<String>, }, + PostProcessingResponse { + session_token: Option<api_models::payments::OpenBankingSessionToken>, + }, } #[derive(serde::Serialize, Debug, Clone)] diff --git a/crates/kgraph_utils/src/mca.rs b/crates/kgraph_utils/src/mca.rs index 0cbf171495b..5b31a6be648 100644 --- a/crates/kgraph_utils/src/mca.rs +++ b/crates/kgraph_utils/src/mca.rs @@ -143,6 +143,9 @@ fn get_dir_value_payment_method( api_enums::PaymentMethodType::DuitNow => Ok(dirval!(RealTimePaymentType = DuitNow)), api_enums::PaymentMethodType::PromptPay => Ok(dirval!(RealTimePaymentType = PromptPay)), api_enums::PaymentMethodType::VietQr => Ok(dirval!(RealTimePaymentType = VietQr)), + api_enums::PaymentMethodType::OpenBankingPIS => { + Ok(dirval!(OpenBankingType = OpenBankingPIS)) + } } } @@ -416,9 +419,11 @@ fn global_vec_pmt( global_vector.append(collect_global_variants!(GiftCardType)); global_vector.append(collect_global_variants!(BankTransferType)); global_vector.append(collect_global_variants!(CardRedirectType)); + global_vector.append(collect_global_variants!(OpenBankingType)); global_vector.push(dir::DirValue::PaymentMethod( dir::enums::PaymentMethod::Card, )); + let global_vector = global_vector .into_iter() .filter(|global_value| !enabled_pmt.contains(global_value)) diff --git a/crates/kgraph_utils/src/transformers.rs b/crates/kgraph_utils/src/transformers.rs index 1b1bd931200..758a0dd3de0 100644 --- a/crates/kgraph_utils/src/transformers.rs +++ b/crates/kgraph_utils/src/transformers.rs @@ -103,6 +103,7 @@ impl IntoDirValue for api_enums::PaymentMethod { Self::Voucher => Ok(dirval!(PaymentMethod = Voucher)), Self::GiftCard => Ok(dirval!(PaymentMethod = GiftCard)), Self::CardRedirect => Ok(dirval!(PaymentMethod = CardRedirect)), + Self::OpenBanking => Ok(dirval!(PaymentMethod = OpenBanking)), } } } @@ -158,6 +159,7 @@ impl IntoDirValue for (api_enums::PaymentMethodType, api_enums::PaymentMethod) { | api_enums::PaymentMethod::RealTimePayment | api_enums::PaymentMethod::Upi | api_enums::PaymentMethod::Voucher + | api_enums::PaymentMethod::OpenBanking | api_enums::PaymentMethod::GiftCard => Err(KgraphError::ContextConstructionError( AnalysisErrorType::NotSupported, )), @@ -175,6 +177,7 @@ impl IntoDirValue for (api_enums::PaymentMethodType, api_enums::PaymentMethod) { | api_enums::PaymentMethod::RealTimePayment | api_enums::PaymentMethod::Upi | api_enums::PaymentMethod::Voucher + | api_enums::PaymentMethod::OpenBanking | api_enums::PaymentMethod::GiftCard => Err(KgraphError::ContextConstructionError( AnalysisErrorType::NotSupported, )), @@ -193,6 +196,7 @@ impl IntoDirValue for (api_enums::PaymentMethodType, api_enums::PaymentMethod) { | api_enums::PaymentMethod::RealTimePayment | api_enums::PaymentMethod::Upi | api_enums::PaymentMethod::Voucher + | api_enums::PaymentMethod::OpenBanking | api_enums::PaymentMethod::GiftCard => Err(KgraphError::ContextConstructionError( AnalysisErrorType::NotSupported, )), @@ -300,6 +304,9 @@ impl IntoDirValue for (api_enums::PaymentMethodType, api_enums::PaymentMethod) { api_enums::PaymentMethodType::DuitNow => Ok(dirval!(RealTimePaymentType = DuitNow)), api_enums::PaymentMethodType::PromptPay => Ok(dirval!(RealTimePaymentType = PromptPay)), api_enums::PaymentMethodType::VietQr => Ok(dirval!(RealTimePaymentType = VietQr)), + api_enums::PaymentMethodType::OpenBankingPIS => { + Ok(dirval!(OpenBankingType = OpenBankingPIS)) + } } } } diff --git a/crates/openapi/src/openapi.rs b/crates/openapi/src/openapi.rs index d2e669175eb..233f43b0846 100644 --- a/crates/openapi/src/openapi.rs +++ b/crates/openapi/src/openapi.rs @@ -557,6 +557,8 @@ Never share your secret api keys. Keep them guarded and secure. api_models::payments::PaymentChargeResponse, api_models::refunds::ChargeRefunds, api_models::payments::CustomerDetailsResponse, + api_models::payments::OpenBankingData, + api_models::payments::OpenBankingSessionToken, )), modifiers(&SecurityAddon) )] diff --git a/crates/router/src/compatibility/stripe/payment_intents/types.rs b/crates/router/src/compatibility/stripe/payment_intents/types.rs index 81dbbb748e3..62cf9416b24 100644 --- a/crates/router/src/compatibility/stripe/payment_intents/types.rs +++ b/crates/router/src/compatibility/stripe/payment_intents/types.rs @@ -864,6 +864,7 @@ pub(crate) fn into_stripe_next_action( payments::NextActionData::ThirdPartySdkSessionToken { session_token } => { StripeNextAction::ThirdPartySdkSessionToken { session_token } } + payments::NextActionData::QrCodeInformation { image_data_url, display_to_timestamp, diff --git a/crates/router/src/compatibility/stripe/setup_intents/types.rs b/crates/router/src/compatibility/stripe/setup_intents/types.rs index db5ada51529..b5408f600b4 100644 --- a/crates/router/src/compatibility/stripe/setup_intents/types.rs +++ b/crates/router/src/compatibility/stripe/setup_intents/types.rs @@ -418,6 +418,7 @@ pub(crate) fn into_stripe_next_action( payments::NextActionData::ThirdPartySdkSessionToken { session_token } => { StripeNextAction::ThirdPartySdkSessionToken { session_token } } + payments::NextActionData::QrCodeInformation { image_data_url, display_to_timestamp, diff --git a/crates/router/src/connector/aci/transformers.rs b/crates/router/src/connector/aci/transformers.rs index c9f81ec722b..175138add75 100644 --- a/crates/router/src/connector/aci/transformers.rs +++ b/crates/router/src/connector/aci/transformers.rs @@ -447,6 +447,7 @@ impl TryFrom<&AciRouterData<&types::PaymentsAuthorizeRouterData>> for AciPayment | domain::PaymentMethodData::CardRedirect(_) | domain::PaymentMethodData::Upi(_) | domain::PaymentMethodData::Voucher(_) + | domain::PaymentMethodData::OpenBanking(_) | domain::PaymentMethodData::CardToken(_) => { Err(errors::ConnectorError::NotImplemented( utils::get_unimplemented_payment_method_error_message("Aci"), diff --git a/crates/router/src/connector/adyen.rs b/crates/router/src/connector/adyen.rs index 4fee5ea9bb0..9122f579656 100644 --- a/crates/router/src/connector/adyen.rs +++ b/crates/router/src/connector/adyen.rs @@ -223,7 +223,8 @@ impl ConnectorValidation for Adyen { | PaymentMethodType::UpiIntent | PaymentMethodType::VietQr | PaymentMethodType::Mifinity - | PaymentMethodType::LocalBankRedirect => { + | PaymentMethodType::LocalBankRedirect + | PaymentMethodType::OpenBankingPIS => { capture_method_not_supported!(connector, capture_method, payment_method_type) } }, diff --git a/crates/router/src/connector/adyen/transformers.rs b/crates/router/src/connector/adyen/transformers.rs index 6b0e251691e..4d3855654ad 100644 --- a/crates/router/src/connector/adyen/transformers.rs +++ b/crates/router/src/connector/adyen/transformers.rs @@ -1581,6 +1581,7 @@ impl<'a> TryFrom<&AdyenRouterData<&types::PaymentsAuthorizeRouterData>> | domain::PaymentMethodData::Reward | domain::PaymentMethodData::RealTimePayment(_) | domain::PaymentMethodData::Upi(_) + | domain::PaymentMethodData::OpenBanking(_) | domain::PaymentMethodData::CardToken(_) => { Err(errors::ConnectorError::NotImplemented( utils::get_unimplemented_payment_method_error_message("Adyen"), @@ -2575,6 +2576,7 @@ impl<'a> | domain::PaymentMethodData::Upi(_) | domain::PaymentMethodData::Voucher(_) | domain::PaymentMethodData::GiftCard(_) + | domain::PaymentMethodData::OpenBanking(_) | domain::PaymentMethodData::CardToken(_) => { Err(errors::ConnectorError::NotSupported { message: "Network tokenization for payment method".to_string(), diff --git a/crates/router/src/connector/airwallex/transformers.rs b/crates/router/src/connector/airwallex/transformers.rs index fcb492bedfa..9fab84559b5 100644 --- a/crates/router/src/connector/airwallex/transformers.rs +++ b/crates/router/src/connector/airwallex/transformers.rs @@ -204,6 +204,7 @@ impl TryFrom<&AirwallexRouterData<&types::PaymentsAuthorizeRouterData>> | 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("airwallex"), diff --git a/crates/router/src/connector/authorizedotnet/transformers.rs b/crates/router/src/connector/authorizedotnet/transformers.rs index 651054552f8..33570a782fd 100644 --- a/crates/router/src/connector/authorizedotnet/transformers.rs +++ b/crates/router/src/connector/authorizedotnet/transformers.rs @@ -342,6 +342,7 @@ impl TryFrom<&types::SetupMandateRouterData> for CreateCustomerProfileRequest { | 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("authorizedotnet"), @@ -520,6 +521,7 @@ impl TryFrom<&AuthorizedotnetRouterData<&types::PaymentsAuthorizeRouterData>> | 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( @@ -578,6 +580,7 @@ impl | 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("authorizedotnet"), diff --git a/crates/router/src/connector/bambora/transformers.rs b/crates/router/src/connector/bambora/transformers.rs index 6bb96f5e9bf..b2e9b1a032e 100644 --- a/crates/router/src/connector/bambora/transformers.rs +++ b/crates/router/src/connector/bambora/transformers.rs @@ -185,6 +185,7 @@ impl TryFrom<BamboraRouterData<&types::PaymentsAuthorizeRouterData>> for Bambora | 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"), diff --git a/crates/router/src/connector/bankofamerica/transformers.rs b/crates/router/src/connector/bankofamerica/transformers.rs index c0434572ce1..34244bbb819 100644 --- a/crates/router/src/connector/bankofamerica/transformers.rs +++ b/crates/router/src/connector/bankofamerica/transformers.rs @@ -321,6 +321,7 @@ impl TryFrom<&types::SetupMandateRouterData> for BankOfAmericaPaymentsRequest { | 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("BankOfAmerica"), @@ -395,6 +396,7 @@ impl<F, T> | common_enums::PaymentMethod::RealTimePayment | common_enums::PaymentMethod::Upi | common_enums::PaymentMethod::Voucher + | common_enums::PaymentMethod::OpenBanking | common_enums::PaymentMethod::GiftCard => None, }; @@ -1070,6 +1072,7 @@ impl TryFrom<&BankOfAmericaRouterData<&types::PaymentsAuthorizeRouterData>> | 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( @@ -1557,6 +1560,7 @@ impl<F> | common_enums::PaymentMethod::RealTimePayment | common_enums::PaymentMethod::Upi | common_enums::PaymentMethod::Voucher + | common_enums::PaymentMethod::OpenBanking | common_enums::PaymentMethod::GiftCard => None, }; @@ -1773,6 +1777,7 @@ impl<F> | common_enums::PaymentMethod::RealTimePayment | common_enums::PaymentMethod::Upi | common_enums::PaymentMethod::Voucher + | common_enums::PaymentMethod::OpenBanking | common_enums::PaymentMethod::GiftCard => None, }; diff --git a/crates/router/src/connector/billwerk/transformers.rs b/crates/router/src/connector/billwerk/transformers.rs index c00303fc5e9..4a4521f31a0 100644 --- a/crates/router/src/connector/billwerk/transformers.rs +++ b/crates/router/src/connector/billwerk/transformers.rs @@ -103,6 +103,7 @@ impl TryFrom<&types::TokenizationRouterData> for BillwerkTokenRequest { | domain::payments::PaymentMethodData::Upi(_) | domain::payments::PaymentMethodData::Voucher(_) | domain::payments::PaymentMethodData::GiftCard(_) + | domain::payments::PaymentMethodData::OpenBanking(_) | domain::payments::PaymentMethodData::CardToken(_) => { Err(errors::ConnectorError::NotImplemented( utils::get_unimplemented_payment_method_error_message("billwerk"), diff --git a/crates/router/src/connector/bluesnap/transformers.rs b/crates/router/src/connector/bluesnap/transformers.rs index d1d5f1d8c9e..f354bf1c2db 100644 --- a/crates/router/src/connector/bluesnap/transformers.rs +++ b/crates/router/src/connector/bluesnap/transformers.rs @@ -233,6 +233,7 @@ impl TryFrom<&BluesnapRouterData<&types::PaymentsAuthorizeRouterData>> | domain::PaymentMethodData::CardRedirect(_) | domain::PaymentMethodData::Voucher(_) | domain::PaymentMethodData::GiftCard(_) + | domain::PaymentMethodData::OpenBanking(_) | domain::PaymentMethodData::CardToken(_) => { Err(errors::ConnectorError::NotImplemented( "Selected payment method via Token flow through bluesnap".to_string(), @@ -397,6 +398,7 @@ impl TryFrom<&BluesnapRouterData<&types::PaymentsAuthorizeRouterData>> for Blues | domain::PaymentMethodData::CardRedirect(_) | domain::PaymentMethodData::Voucher(_) | domain::PaymentMethodData::GiftCard(_) + | domain::PaymentMethodData::OpenBanking(_) | domain::PaymentMethodData::CardToken(_) => { Err(errors::ConnectorError::NotImplemented( utils::get_unimplemented_payment_method_error_message("bluesnap"), diff --git a/crates/router/src/connector/boku/transformers.rs b/crates/router/src/connector/boku/transformers.rs index a1a239a6e1b..a8b4d8c0ec2 100644 --- a/crates/router/src/connector/boku/transformers.rs +++ b/crates/router/src/connector/boku/transformers.rs @@ -92,6 +92,7 @@ impl TryFrom<&types::PaymentsAuthorizeRouterData> for BokuPaymentsRequest { | 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("boku"), diff --git a/crates/router/src/connector/braintree/braintree_graphql_transformers.rs b/crates/router/src/connector/braintree/braintree_graphql_transformers.rs index d52328a7783..af50bd10ce7 100644 --- a/crates/router/src/connector/braintree/braintree_graphql_transformers.rs +++ b/crates/router/src/connector/braintree/braintree_graphql_transformers.rs @@ -209,6 +209,7 @@ impl TryFrom<&BraintreeRouterData<&types::PaymentsAuthorizeRouterData>> | 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("braintree"), @@ -241,6 +242,7 @@ impl TryFrom<&BraintreeRouterData<&types::PaymentsCompleteAuthorizeRouterData>> | api_models::enums::PaymentMethod::RealTimePayment | api_models::enums::PaymentMethod::Upi | api_models::enums::PaymentMethod::Voucher + | api_models::enums::PaymentMethod::OpenBanking | api_models::enums::PaymentMethod::GiftCard => { Err(errors::ConnectorError::NotImplemented( utils::get_unimplemented_payment_method_error_message( @@ -994,6 +996,7 @@ impl TryFrom<&types::TokenizationRouterData> for BraintreeTokenRequest { | 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("braintree"), @@ -1584,6 +1587,7 @@ fn get_braintree_redirect_form( | domain::PaymentMethodData::Upi(_) | domain::PaymentMethodData::Voucher(_) | domain::PaymentMethodData::GiftCard(_) + | domain::PaymentMethodData::OpenBanking(_) | domain::PaymentMethodData::CardToken(_) => Err( errors::ConnectorError::NotImplemented("given payment method".to_owned()), )?, diff --git a/crates/router/src/connector/braintree/transformers.rs b/crates/router/src/connector/braintree/transformers.rs index 7fc34e75f97..717c4afc195 100644 --- a/crates/router/src/connector/braintree/transformers.rs +++ b/crates/router/src/connector/braintree/transformers.rs @@ -175,6 +175,7 @@ impl TryFrom<&types::PaymentsAuthorizeRouterData> for BraintreePaymentsRequest { | 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("braintree"), diff --git a/crates/router/src/connector/checkout/transformers.rs b/crates/router/src/connector/checkout/transformers.rs index e035c102d20..db09e93701b 100644 --- a/crates/router/src/connector/checkout/transformers.rs +++ b/crates/router/src/connector/checkout/transformers.rs @@ -131,6 +131,7 @@ impl TryFrom<&types::TokenizationRouterData> for TokenRequest { | domain::PaymentMethodData::Voucher(_) | domain::PaymentMethodData::CardRedirect(_) | domain::PaymentMethodData::GiftCard(_) + | domain::PaymentMethodData::OpenBanking(_) | domain::PaymentMethodData::CardToken(_) => { Err(errors::ConnectorError::NotImplemented( utils::get_unimplemented_payment_method_error_message("checkout"), @@ -367,6 +368,7 @@ impl TryFrom<&CheckoutRouterData<&types::PaymentsAuthorizeRouterData>> for Payme | domain::PaymentMethodData::Voucher(_) | domain::PaymentMethodData::CardRedirect(_) | domain::PaymentMethodData::GiftCard(_) + | domain::PaymentMethodData::OpenBanking(_) | domain::PaymentMethodData::CardToken(_) => { Err(errors::ConnectorError::NotImplemented( utils::get_unimplemented_payment_method_error_message("checkout"), diff --git a/crates/router/src/connector/cryptopay/transformers.rs b/crates/router/src/connector/cryptopay/transformers.rs index 215003f8fb2..c15afd7fd44 100644 --- a/crates/router/src/connector/cryptopay/transformers.rs +++ b/crates/router/src/connector/cryptopay/transformers.rs @@ -78,6 +78,7 @@ impl TryFrom<&CryptopayRouterData<&types::PaymentsAuthorizeRouterData>> | 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("CryptoPay"), diff --git a/crates/router/src/connector/cybersource/transformers.rs b/crates/router/src/connector/cybersource/transformers.rs index 1cd6066ad69..2f286964e3e 100644 --- a/crates/router/src/connector/cybersource/transformers.rs +++ b/crates/router/src/connector/cybersource/transformers.rs @@ -214,6 +214,7 @@ impl TryFrom<&types::SetupMandateRouterData> for CybersourceZeroMandateRequest { | 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("Cybersource"), @@ -1384,6 +1385,7 @@ impl TryFrom<&CybersourceRouterData<&types::PaymentsAuthorizeRouterData>> | 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("Cybersource"), @@ -1490,6 +1492,7 @@ impl TryFrom<&CybersourceRouterData<&types::PaymentsAuthorizeRouterData>> | 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("Cybersource"), @@ -2208,6 +2211,7 @@ impl TryFrom<&CybersourceRouterData<&types::PaymentsPreProcessingRouterData>> | 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("Cybersource"), @@ -2317,6 +2321,7 @@ impl TryFrom<&CybersourceRouterData<&types::PaymentsCompleteAuthorizeRouterData> | 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("Cybersource"), diff --git a/crates/router/src/connector/datatrans/transformers.rs b/crates/router/src/connector/datatrans/transformers.rs index bb8c85b77da..9c4ab6cf6a6 100644 --- a/crates/router/src/connector/datatrans/transformers.rs +++ b/crates/router/src/connector/datatrans/transformers.rs @@ -193,6 +193,7 @@ impl TryFrom<&DatatransRouterData<&types::PaymentsAuthorizeRouterData>> | domain::PaymentMethodData::CardRedirect(_) | domain::PaymentMethodData::Voucher(_) | domain::PaymentMethodData::GiftCard(_) + | domain::PaymentMethodData::OpenBanking(_) | domain::PaymentMethodData::CardToken(_) => { Err(errors::ConnectorError::NotImplemented( connector_utils::get_unimplemented_payment_method_error_message("Datatrans"), diff --git a/crates/router/src/connector/dlocal/transformers.rs b/crates/router/src/connector/dlocal/transformers.rs index b018dbcd2e9..ca18d12a088 100644 --- a/crates/router/src/connector/dlocal/transformers.rs +++ b/crates/router/src/connector/dlocal/transformers.rs @@ -166,6 +166,7 @@ impl TryFrom<&DlocalRouterData<&types::PaymentsAuthorizeRouterData>> for DlocalP | domain::PaymentMethodData::Upi(_) | domain::PaymentMethodData::Voucher(_) | domain::PaymentMethodData::GiftCard(_) + | domain::PaymentMethodData::OpenBanking(_) | domain::PaymentMethodData::CardToken(_) => { Err(errors::ConnectorError::NotImplemented( crate::connector::utils::get_unimplemented_payment_method_error_message( diff --git a/crates/router/src/connector/fiserv/transformers.rs b/crates/router/src/connector/fiserv/transformers.rs index eee518187a2..1a149c6af78 100644 --- a/crates/router/src/connector/fiserv/transformers.rs +++ b/crates/router/src/connector/fiserv/transformers.rs @@ -188,6 +188,7 @@ impl TryFrom<&FiservRouterData<&types::PaymentsAuthorizeRouterData>> for FiservP | 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("fiserv"), diff --git a/crates/router/src/connector/forte/transformers.rs b/crates/router/src/connector/forte/transformers.rs index 637a3acd1e1..0533d71ffeb 100644 --- a/crates/router/src/connector/forte/transformers.rs +++ b/crates/router/src/connector/forte/transformers.rs @@ -115,6 +115,7 @@ impl TryFrom<&types::PaymentsAuthorizeRouterData> for FortePaymentsRequest { | 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("Forte"), diff --git a/crates/router/src/connector/globepay/transformers.rs b/crates/router/src/connector/globepay/transformers.rs index 3cf1204a697..8974c9f94b9 100644 --- a/crates/router/src/connector/globepay/transformers.rs +++ b/crates/router/src/connector/globepay/transformers.rs @@ -73,6 +73,7 @@ impl TryFrom<&types::PaymentsAuthorizeRouterData> for GlobepayPaymentsRequest { | 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("globepay"), diff --git a/crates/router/src/connector/gocardless/transformers.rs b/crates/router/src/connector/gocardless/transformers.rs index d31d985500a..fb27f5138a9 100644 --- a/crates/router/src/connector/gocardless/transformers.rs +++ b/crates/router/src/connector/gocardless/transformers.rs @@ -246,6 +246,7 @@ impl TryFrom<&types::TokenizationRouterData> for CustomerBankAccount { | 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("Gocardless"), @@ -415,6 +416,7 @@ impl TryFrom<&types::SetupMandateRouterData> for GocardlessMandateRequest { | domain::PaymentMethodData::Upi(_) | domain::PaymentMethodData::Voucher(_) | domain::PaymentMethodData::GiftCard(_) + | domain::PaymentMethodData::OpenBanking(_) | domain::PaymentMethodData::CardToken(_) => { Err(errors::ConnectorError::NotImplemented( "Setup Mandate flow for selected payment method through Gocardless".to_string(), diff --git a/crates/router/src/connector/helcim/transformers.rs b/crates/router/src/connector/helcim/transformers.rs index f882b341f63..2f6cf61e759 100644 --- a/crates/router/src/connector/helcim/transformers.rs +++ b/crates/router/src/connector/helcim/transformers.rs @@ -163,6 +163,7 @@ impl TryFrom<&types::SetupMandateRouterData> for HelcimVerifyRequest { | 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("Helcim"), @@ -265,6 +266,7 @@ impl TryFrom<&HelcimRouterData<&types::PaymentsAuthorizeRouterData>> for HelcimP | 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("Helcim"), diff --git a/crates/router/src/connector/iatapay/transformers.rs b/crates/router/src/connector/iatapay/transformers.rs index 71aeed0f7dd..1ce07fb49e3 100644 --- a/crates/router/src/connector/iatapay/transformers.rs +++ b/crates/router/src/connector/iatapay/transformers.rs @@ -204,7 +204,8 @@ impl | domain::PaymentMethodData::Reward | domain::PaymentMethodData::Voucher(_) | domain::PaymentMethodData::GiftCard(_) - | domain::PaymentMethodData::CardToken(_) => { + | domain::PaymentMethodData::CardToken(_) + | domain::PaymentMethodData::OpenBanking(_) => { Err(errors::ConnectorError::NotImplemented( connector_util::get_unimplemented_payment_method_error_message("iatapay"), ))? diff --git a/crates/router/src/connector/klarna.rs b/crates/router/src/connector/klarna.rs index 4796f15cb64..fbfb8b71974 100644 --- a/crates/router/src/connector/klarna.rs +++ b/crates/router/src/connector/klarna.rs @@ -628,7 +628,8 @@ impl | common_enums::PaymentMethodType::Fps | common_enums::PaymentMethodType::DuitNow | common_enums::PaymentMethodType::PromptPay - | common_enums::PaymentMethodType::VietQr, + | common_enums::PaymentMethodType::VietQr + | common_enums::PaymentMethodType::OpenBankingPIS, ) => Err(error_stack::report!(errors::ConnectorError::NotSupported { message: payment_method_type.to_string(), connector: "klarna", @@ -649,6 +650,7 @@ impl | domain::PaymentMethodData::RealTimePayment(_) | domain::PaymentMethodData::Upi(_) | domain::PaymentMethodData::Voucher(_) + | domain::PaymentMethodData::OpenBanking(_) | domain::PaymentMethodData::GiftCard(_) | domain::PaymentMethodData::CardToken(_) => { Err(report!(errors::ConnectorError::NotImplemented( diff --git a/crates/router/src/connector/mifinity/transformers.rs b/crates/router/src/connector/mifinity/transformers.rs index 5d18834de86..0e52f7d3b50 100644 --- a/crates/router/src/connector/mifinity/transformers.rs +++ b/crates/router/src/connector/mifinity/transformers.rs @@ -196,6 +196,7 @@ impl TryFrom<&MifinityRouterData<&types::PaymentsAuthorizeRouterData>> for Mifin | 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("Mifinity"), diff --git a/crates/router/src/connector/multisafepay/transformers.rs b/crates/router/src/connector/multisafepay/transformers.rs index 2daf83cbacf..ac0a04de182 100644 --- a/crates/router/src/connector/multisafepay/transformers.rs +++ b/crates/router/src/connector/multisafepay/transformers.rs @@ -606,6 +606,7 @@ impl TryFrom<&MultisafepayRouterData<&types::PaymentsAuthorizeRouterData>> | 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("multisafepay"), @@ -786,7 +787,8 @@ impl TryFrom<&MultisafepayRouterData<&types::PaymentsAuthorizeRouterData>> | domain::PaymentMethodData::Upi(_) | domain::PaymentMethodData::Voucher(_) | domain::PaymentMethodData::GiftCard(_) - | domain::PaymentMethodData::CardToken(_) => { + | domain::PaymentMethodData::CardToken(_) + | domain::PaymentMethodData::OpenBanking(_) => { Err(errors::ConnectorError::NotImplemented( utils::get_unimplemented_payment_method_error_message("multisafepay"), ))? diff --git a/crates/router/src/connector/nexinets/transformers.rs b/crates/router/src/connector/nexinets/transformers.rs index c25da631b71..7e32ae5ebed 100644 --- a/crates/router/src/connector/nexinets/transformers.rs +++ b/crates/router/src/connector/nexinets/transformers.rs @@ -625,6 +625,7 @@ fn get_payment_details_and_product( | PaymentMethodData::Upi(_) | PaymentMethodData::Voucher(_) | PaymentMethodData::GiftCard(_) + | PaymentMethodData::OpenBanking(_) | PaymentMethodData::CardToken(_) => Err(errors::ConnectorError::NotImplemented( utils::get_unimplemented_payment_method_error_message("nexinets"), ))?, diff --git a/crates/router/src/connector/nmi/transformers.rs b/crates/router/src/connector/nmi/transformers.rs index a87b8e6176d..e0858e16a4a 100644 --- a/crates/router/src/connector/nmi/transformers.rs +++ b/crates/router/src/connector/nmi/transformers.rs @@ -584,6 +584,7 @@ impl | 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("nmi"), diff --git a/crates/router/src/connector/noon/transformers.rs b/crates/router/src/connector/noon/transformers.rs index 6de5ba5e6d1..8336cbf1318 100644 --- a/crates/router/src/connector/noon/transformers.rs +++ b/crates/router/src/connector/noon/transformers.rs @@ -352,6 +352,7 @@ impl TryFrom<&NoonRouterData<&types::PaymentsAuthorizeRouterData>> for NoonPayme | domain::PaymentMethodData::Upi(_) | domain::PaymentMethodData::Voucher(_) | domain::PaymentMethodData::GiftCard(_) + | domain::PaymentMethodData::OpenBanking(_) | domain::PaymentMethodData::CardToken(_) => { Err(errors::ConnectorError::NotImplemented( conn_utils::get_unimplemented_payment_method_error_message("Noon"), diff --git a/crates/router/src/connector/nuvei/transformers.rs b/crates/router/src/connector/nuvei/transformers.rs index a23a05e34e3..1aa34517357 100644 --- a/crates/router/src/connector/nuvei/transformers.rs +++ b/crates/router/src/connector/nuvei/transformers.rs @@ -995,6 +995,7 @@ where | domain::PaymentMethodData::Voucher(_) | domain::PaymentMethodData::CardRedirect(_) | domain::PaymentMethodData::GiftCard(_) + | domain::PaymentMethodData::OpenBanking(_) | domain::PaymentMethodData::CardToken(_) => { Err(errors::ConnectorError::NotImplemented( utils::get_unimplemented_payment_method_error_message("nuvei"), @@ -1196,6 +1197,7 @@ impl TryFrom<(&types::PaymentsCompleteAuthorizeRouterData, Secret<String>)> | Some(domain::PaymentMethodData::Reward) | Some(domain::PaymentMethodData::RealTimePayment(..)) | Some(domain::PaymentMethodData::Upi(..)) + | Some(domain::PaymentMethodData::OpenBanking(_)) | Some(domain::PaymentMethodData::CardToken(..)) | None => Err(errors::ConnectorError::NotImplemented( utils::get_unimplemented_payment_method_error_message("nuvei"), diff --git a/crates/router/src/connector/opayo/transformers.rs b/crates/router/src/connector/opayo/transformers.rs index b6c05dff2d3..5771b45100b 100644 --- a/crates/router/src/connector/opayo/transformers.rs +++ b/crates/router/src/connector/opayo/transformers.rs @@ -56,6 +56,7 @@ impl TryFrom<&types::PaymentsAuthorizeRouterData> for OpayoPaymentsRequest { | 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("Opayo"), diff --git a/crates/router/src/connector/payeezy/transformers.rs b/crates/router/src/connector/payeezy/transformers.rs index c2d8e0dfddb..8da3e7502be 100644 --- a/crates/router/src/connector/payeezy/transformers.rs +++ b/crates/router/src/connector/payeezy/transformers.rs @@ -137,6 +137,7 @@ impl TryFrom<&PayeezyRouterData<&types::PaymentsAuthorizeRouterData>> for Payeez | diesel_models::enums::PaymentMethod::RealTimePayment | diesel_models::enums::PaymentMethod::Upi | diesel_models::enums::PaymentMethod::Voucher + | diesel_models::enums::PaymentMethod::OpenBanking | diesel_models::enums::PaymentMethod::GiftCard => { Err(errors::ConnectorError::NotImplemented("Payment methods".to_string()).into()) } @@ -259,6 +260,7 @@ fn get_payment_method_data( | 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("Payeezy"), ))?, diff --git a/crates/router/src/connector/payme/transformers.rs b/crates/router/src/connector/payme/transformers.rs index 47942d7de43..2ec35b7a7de 100644 --- a/crates/router/src/connector/payme/transformers.rs +++ b/crates/router/src/connector/payme/transformers.rs @@ -429,6 +429,7 @@ impl TryFrom<&PaymentMethodData> for SalePaymentMethod { | PaymentMethodData::CardRedirect(_) | PaymentMethodData::Upi(_) | PaymentMethodData::Voucher(_) + | PaymentMethodData::OpenBanking(_) | PaymentMethodData::CardToken(_) => { Err(errors::ConnectorError::NotImplemented("Payment methods".to_string()).into()) } @@ -673,6 +674,7 @@ impl TryFrom<&types::PaymentsAuthorizeRouterData> for PayRequest { | PaymentMethodData::Upi(_) | PaymentMethodData::Voucher(_) | PaymentMethodData::GiftCard(_) + | PaymentMethodData::OpenBanking(_) | PaymentMethodData::CardToken(_) => Err(errors::ConnectorError::NotImplemented( utils::get_unimplemented_payment_method_error_message("payme"), ))?, @@ -732,6 +734,7 @@ impl TryFrom<&types::PaymentsCompleteAuthorizeRouterData> for Pay3dsRequest { | Some(PaymentMethodData::Upi(_)) | Some(PaymentMethodData::Voucher(_)) | Some(PaymentMethodData::GiftCard(_)) + | Some(PaymentMethodData::OpenBanking(_)) | Some(PaymentMethodData::CardToken(_)) | None => { Err(errors::ConnectorError::NotImplemented("Tokenize Flow".to_string()).into()) @@ -771,6 +774,7 @@ impl TryFrom<&types::TokenizationRouterData> for CaptureBuyerRequest { | PaymentMethodData::Upi(_) | PaymentMethodData::Voucher(_) | PaymentMethodData::GiftCard(_) + | PaymentMethodData::OpenBanking(_) | PaymentMethodData::CardToken(_) => { Err(errors::ConnectorError::NotImplemented("Tokenize Flow".to_string()).into()) } diff --git a/crates/router/src/connector/paypal/transformers.rs b/crates/router/src/connector/paypal/transformers.rs index 283b6c80a8e..9718fd5a8de 100644 --- a/crates/router/src/connector/paypal/transformers.rs +++ b/crates/router/src/connector/paypal/transformers.rs @@ -551,6 +551,7 @@ impl TryFrom<&PaypalRouterData<&types::PaymentsAuthorizeRouterData>> for PaypalP | domain::PaymentMethodData::RealTimePayment(_) | domain::PaymentMethodData::Crypto(_) | domain::PaymentMethodData::Upi(_) + | domain::PaymentMethodData::OpenBanking(_) | domain::PaymentMethodData::CardToken(_) => { Err(errors::ConnectorError::NotImplemented( utils::get_unimplemented_payment_method_error_message("Paypal"), diff --git a/crates/router/src/connector/placetopay/transformers.rs b/crates/router/src/connector/placetopay/transformers.rs index 50813a81629..6ecaabd3fe6 100644 --- a/crates/router/src/connector/placetopay/transformers.rs +++ b/crates/router/src/connector/placetopay/transformers.rs @@ -151,6 +151,7 @@ impl TryFrom<&PlacetopayRouterData<&types::PaymentsAuthorizeRouterData>> | 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("Placetopay"), diff --git a/crates/router/src/connector/powertranz/transformers.rs b/crates/router/src/connector/powertranz/transformers.rs index 6fe1a7173be..40fe8235956 100644 --- a/crates/router/src/connector/powertranz/transformers.rs +++ b/crates/router/src/connector/powertranz/transformers.rs @@ -116,6 +116,7 @@ impl TryFrom<&types::PaymentsAuthorizeRouterData> for PowertranzPaymentsRequest | domain::PaymentMethodData::Upi(_) | domain::PaymentMethodData::Voucher(_) | domain::PaymentMethodData::GiftCard(_) + | domain::PaymentMethodData::OpenBanking(_) | domain::PaymentMethodData::CardToken(_) => { Err(errors::ConnectorError::NotSupported { message: utils::SELECTED_PAYMENT_METHOD.to_string(), diff --git a/crates/router/src/connector/razorpay/transformers.rs b/crates/router/src/connector/razorpay/transformers.rs index 5618c85d531..8cf32891886 100644 --- a/crates/router/src/connector/razorpay/transformers.rs +++ b/crates/router/src/connector/razorpay/transformers.rs @@ -398,6 +398,7 @@ impl | domain::PaymentMethodData::RealTimePayment(_) | domain::PaymentMethodData::Voucher(_) | domain::PaymentMethodData::GiftCard(_) + | domain::PaymentMethodData::OpenBanking(_) | domain::PaymentMethodData::CardToken(_) => { Err(errors::ConnectorError::NotImplemented("Payment methods".to_string()).into()) } diff --git a/crates/router/src/connector/shift4/transformers.rs b/crates/router/src/connector/shift4/transformers.rs index 80ef0daaf21..f384d8d296d 100644 --- a/crates/router/src/connector/shift4/transformers.rs +++ b/crates/router/src/connector/shift4/transformers.rs @@ -247,6 +247,7 @@ where | domain::PaymentMethodData::Reward | domain::PaymentMethodData::RealTimePayment(_) | domain::PaymentMethodData::Upi(_) + | domain::PaymentMethodData::OpenBanking(_) | domain::PaymentMethodData::CardToken(_) => { Err(errors::ConnectorError::NotImplemented( utils::get_unimplemented_payment_method_error_message("Shift4"), @@ -469,6 +470,7 @@ impl<T> TryFrom<&types::RouterData<T, types::CompleteAuthorizeData, types::Payme | Some(domain::PaymentMethodData::Reward) | Some(domain::PaymentMethodData::RealTimePayment(_)) | Some(domain::PaymentMethodData::Upi(_)) + | Some(domain::PaymentMethodData::OpenBanking(_)) | Some(domain::PaymentMethodData::CardToken(_)) | None => Err(errors::ConnectorError::NotImplemented( utils::get_unimplemented_payment_method_error_message("Shift4"), diff --git a/crates/router/src/connector/square/transformers.rs b/crates/router/src/connector/square/transformers.rs index 15de18c8890..67be82bb2d9 100644 --- a/crates/router/src/connector/square/transformers.rs +++ b/crates/router/src/connector/square/transformers.rs @@ -174,6 +174,7 @@ impl TryFrom<&types::TokenizationRouterData> for SquareTokenRequest { | domain::PaymentMethodData::RealTimePayment(_) | domain::PaymentMethodData::Upi(_) | domain::PaymentMethodData::Voucher(_) + | domain::PaymentMethodData::OpenBanking(_) | domain::PaymentMethodData::CardToken(_) => { Err(errors::ConnectorError::NotImplemented( utils::get_unimplemented_payment_method_error_message("Square"), @@ -290,6 +291,7 @@ impl TryFrom<&types::PaymentsAuthorizeRouterData> for SquarePaymentsRequest { | domain::PaymentMethodData::RealTimePayment(_) | domain::PaymentMethodData::Upi(_) | domain::PaymentMethodData::Voucher(_) + | domain::PaymentMethodData::OpenBanking(_) | domain::PaymentMethodData::CardToken(_) => { Err(errors::ConnectorError::NotImplemented( utils::get_unimplemented_payment_method_error_message("Square"), diff --git a/crates/router/src/connector/stax/transformers.rs b/crates/router/src/connector/stax/transformers.rs index 65ee90830a3..d814deef264 100644 --- a/crates/router/src/connector/stax/transformers.rs +++ b/crates/router/src/connector/stax/transformers.rs @@ -108,6 +108,7 @@ impl TryFrom<&StaxRouterData<&types::PaymentsAuthorizeRouterData>> for StaxPayme | 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"), @@ -260,6 +261,7 @@ impl TryFrom<&types::TokenizationRouterData> for StaxTokenRequest { | 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"), diff --git a/crates/router/src/connector/stripe/transformers.rs b/crates/router/src/connector/stripe/transformers.rs index aa792db04bd..2524a1aeacf 100644 --- a/crates/router/src/connector/stripe/transformers.rs +++ b/crates/router/src/connector/stripe/transformers.rs @@ -704,6 +704,7 @@ impl TryFrom<enums::PaymentMethodType> for StripePaymentMethodType { | enums::PaymentMethodType::OnlineBankingPoland | enums::PaymentMethodType::OnlineBankingSlovakia | enums::PaymentMethodType::OpenBankingUk + | enums::PaymentMethodType::OpenBankingPIS | enums::PaymentMethodType::PagoEfectivo | enums::PaymentMethodType::PayBright | enums::PaymentMethodType::Pse @@ -1330,6 +1331,7 @@ fn create_stripe_payment_method( domain::PaymentMethodData::Upi(_) | domain::PaymentMethodData::RealTimePayment(_) | domain::PaymentMethodData::MandatePayment + | domain::PaymentMethodData::OpenBanking(_) | domain::PaymentMethodData::CardToken(_) => Err(errors::ConnectorError::NotImplemented( connector_util::get_unimplemented_payment_method_error_message("stripe"), ) @@ -1706,6 +1708,7 @@ impl TryFrom<(&types::PaymentsAuthorizeRouterData, MinorUnit)> for PaymentIntent | domain::payments::PaymentMethodData::Upi(_) | domain::payments::PaymentMethodData::Voucher(_) | domain::payments::PaymentMethodData::GiftCard(_) + | domain::payments::PaymentMethodData::OpenBanking(_) | domain::payments::PaymentMethodData::CardToken(_) => { Err(errors::ConnectorError::NotSupported { message: "Network tokenization for payment method".to_string(), @@ -3281,6 +3284,7 @@ impl | Some(domain::PaymentMethodData::GiftCard(..)) | Some(domain::PaymentMethodData::CardRedirect(..)) | Some(domain::PaymentMethodData::Voucher(..)) + | Some(domain::PaymentMethodData::OpenBanking(..)) | Some(domain::PaymentMethodData::CardToken(..)) | None => Err(errors::ConnectorError::NotImplemented( connector_util::get_unimplemented_payment_method_error_message("stripe"), @@ -3734,6 +3738,7 @@ impl | domain::PaymentMethodData::Upi(_) | domain::PaymentMethodData::CardRedirect(_) | domain::PaymentMethodData::Voucher(_) + | domain::PaymentMethodData::OpenBanking(_) | domain::PaymentMethodData::CardToken(_) => { Err(errors::ConnectorError::NotImplemented( connector_util::get_unimplemented_payment_method_error_message("stripe"), diff --git a/crates/router/src/connector/trustpay/transformers.rs b/crates/router/src/connector/trustpay/transformers.rs index 77d85393d29..85539e253b7 100644 --- a/crates/router/src/connector/trustpay/transformers.rs +++ b/crates/router/src/connector/trustpay/transformers.rs @@ -433,6 +433,7 @@ impl TryFrom<&TrustpayRouterData<&types::PaymentsAuthorizeRouterData>> for Trust | 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("trustpay"), diff --git a/crates/router/src/connector/tsys/transformers.rs b/crates/router/src/connector/tsys/transformers.rs index cea51ce77e1..53561d93a92 100644 --- a/crates/router/src/connector/tsys/transformers.rs +++ b/crates/router/src/connector/tsys/transformers.rs @@ -76,6 +76,7 @@ impl TryFrom<&types::PaymentsAuthorizeRouterData> for TsysPaymentsRequest { | 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("tsys"), diff --git a/crates/router/src/connector/utils.rs b/crates/router/src/connector/utils.rs index d56de472eb3..3377a946fbd 100644 --- a/crates/router/src/connector/utils.rs +++ b/crates/router/src/connector/utils.rs @@ -2668,6 +2668,7 @@ pub enum PaymentMethodDataType { Fps, PromptPay, VietQr, + OpenBanking, } impl From<domain::payments::PaymentMethodData> for PaymentMethodDataType { @@ -2848,6 +2849,9 @@ impl From<domain::payments::PaymentMethodData> for PaymentMethodDataType { } } domain::payments::PaymentMethodData::CardToken(_) => Self::CardToken, + domain::payments::PaymentMethodData::OpenBanking(data) => match data { + hyperswitch_domain_models::payment_method_data::OpenBankingData::OpenBankingPIS { } => Self::OpenBanking + }, } } } diff --git a/crates/router/src/connector/volt/transformers.rs b/crates/router/src/connector/volt/transformers.rs index 12064fdf0f4..ac55f55d536 100644 --- a/crates/router/src/connector/volt/transformers.rs +++ b/crates/router/src/connector/volt/transformers.rs @@ -150,6 +150,7 @@ impl TryFrom<&VoltRouterData<&types::PaymentsAuthorizeRouterData>> for VoltPayme | 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("Volt"), diff --git a/crates/router/src/connector/worldline/transformers.rs b/crates/router/src/connector/worldline/transformers.rs index fe1bcab0bb2..365ddda4d53 100644 --- a/crates/router/src/connector/worldline/transformers.rs +++ b/crates/router/src/connector/worldline/transformers.rs @@ -249,6 +249,7 @@ impl | 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("worldline"), diff --git a/crates/router/src/connector/worldpay/transformers.rs b/crates/router/src/connector/worldpay/transformers.rs index 5caf6b0e1f1..892b6644722 100644 --- a/crates/router/src/connector/worldpay/transformers.rs +++ b/crates/router/src/connector/worldpay/transformers.rs @@ -108,6 +108,7 @@ fn fetch_payment_instrument( | domain::PaymentMethodData::Voucher(_) | domain::PaymentMethodData::CardRedirect(_) | domain::PaymentMethodData::GiftCard(_) + | domain::PaymentMethodData::OpenBanking(_) | domain::PaymentMethodData::CardToken(_) => Err(errors::ConnectorError::NotImplemented( utils::get_unimplemented_payment_method_error_message("worldpay"), ) diff --git a/crates/router/src/connector/zen/transformers.rs b/crates/router/src/connector/zen/transformers.rs index 026c39f0e3e..2562277ee9b 100644 --- a/crates/router/src/connector/zen/transformers.rs +++ b/crates/router/src/connector/zen/transformers.rs @@ -694,6 +694,7 @@ impl TryFrom<&ZenRouterData<&types::PaymentsAuthorizeRouterData>> for ZenPayment | domain::PaymentMethodData::Reward | domain::PaymentMethodData::RealTimePayment(_) | domain::PaymentMethodData::Upi(_) + | domain::PaymentMethodData::OpenBanking(_) | domain::PaymentMethodData::CardToken(_) => { Err(errors::ConnectorError::NotImplemented( utils::get_unimplemented_payment_method_error_message("Zen"), diff --git a/crates/router/src/connector/zsl/transformers.rs b/crates/router/src/connector/zsl/transformers.rs index f44d46cd8e0..ada1de0e618 100644 --- a/crates/router/src/connector/zsl/transformers.rs +++ b/crates/router/src/connector/zsl/transformers.rs @@ -181,7 +181,8 @@ impl TryFrom<&ZslRouterData<&types::PaymentsAuthorizeRouterData>> for ZslPayment | domain::PaymentMethodData::Upi(_) | domain::PaymentMethodData::Voucher(_) | domain::PaymentMethodData::GiftCard(_) - | domain::PaymentMethodData::CardToken(_) => { + | domain::PaymentMethodData::CardToken(_) + | domain::PaymentMethodData::OpenBanking(_) => { Err(errors::ConnectorError::NotImplemented( connector_utils::get_unimplemented_payment_method_error_message( item.router_data.connector.as_str(), diff --git a/crates/router/src/core/fraud_check.rs b/crates/router/src/core/fraud_check.rs index 0d0eace13e3..331eb430211 100644 --- a/crates/router/src/core/fraud_check.rs +++ b/crates/router/src/core/fraud_check.rs @@ -91,6 +91,7 @@ where key_store, customer, &merchant_connector_account, + None, ) .await?; diff --git a/crates/router/src/core/fraud_check/flows/checkout_flow.rs b/crates/router/src/core/fraud_check/flows/checkout_flow.rs index d897b9e6339..47ab1810f75 100644 --- a/crates/router/src/core/fraud_check/flows/checkout_flow.rs +++ b/crates/router/src/core/fraud_check/flows/checkout_flow.rs @@ -13,11 +13,14 @@ use crate::{ }, errors, services, types::{ - api::fraud_check::{self as frm_api, FraudCheckConnectorData}, + api::{ + self, + fraud_check::{self as frm_api, FraudCheckConnectorData}, + }, domain, fraud_check::{FraudCheckCheckoutData, FraudCheckResponseData, FrmCheckoutRouterData}, storage::enums as storage_enums, - BrowserInformation, ConnectorAuthType, ResponseId, RouterData, + BrowserInformation, ConnectorAuthType, MerchantRecipientData, ResponseId, RouterData, }, SessionState, }; @@ -34,6 +37,7 @@ impl ConstructFlowSpecificData<frm_api::Checkout, FraudCheckCheckoutData, FraudC _key_store: &domain::MerchantKeyStore, customer: &Option<domain::Customer>, merchant_connector_account: &helpers::MerchantConnectorAccountType, + _merchant_recipient_data: Option<MerchantRecipientData>, ) -> RouterResult<RouterData<frm_api::Checkout, FraudCheckCheckoutData, FraudCheckResponseData>> { let status = storage_enums::AttemptStatus::Pending; @@ -135,6 +139,17 @@ impl ConstructFlowSpecificData<frm_api::Checkout, FraudCheckCheckoutData, FraudC Ok(router_data) } + + async fn get_merchant_recipient_data<'a>( + &self, + _state: &SessionState, + _merchant_account: &domain::MerchantAccount, + _key_store: &domain::MerchantKeyStore, + _merchant_connector_account: &helpers::MerchantConnectorAccountType, + _connector: &api::ConnectorData, + ) -> RouterResult<Option<MerchantRecipientData>> { + Ok(None) + } } #[async_trait] diff --git a/crates/router/src/core/fraud_check/flows/record_return.rs b/crates/router/src/core/fraud_check/flows/record_return.rs index b44f2d3d4fc..2f263124083 100644 --- a/crates/router/src/core/fraud_check/flows/record_return.rs +++ b/crates/router/src/core/fraud_check/flows/record_return.rs @@ -11,13 +11,13 @@ use crate::{ }, errors, services, types::{ - api::RecordReturn, + api::{self, RecordReturn}, domain, fraud_check::{ FraudCheckRecordReturnData, FraudCheckResponseData, FrmRecordReturnRouterData, }, storage::enums as storage_enums, - ConnectorAuthType, ResponseId, RouterData, + ConnectorAuthType, MerchantRecipientData, ResponseId, RouterData, }, utils, SessionState, }; @@ -34,6 +34,7 @@ impl ConstructFlowSpecificData<RecordReturn, FraudCheckRecordReturnData, FraudCh _key_store: &domain::MerchantKeyStore, customer: &Option<domain::Customer>, merchant_connector_account: &helpers::MerchantConnectorAccountType, + _merchant_recipient_data: Option<MerchantRecipientData>, ) -> RouterResult<RouterData<RecordReturn, FraudCheckRecordReturnData, FraudCheckResponseData>> { let status = storage_enums::AttemptStatus::Pending; @@ -107,6 +108,17 @@ impl ConstructFlowSpecificData<RecordReturn, FraudCheckRecordReturnData, FraudCh Ok(router_data) } + + async fn get_merchant_recipient_data<'a>( + &self, + _state: &SessionState, + _merchant_account: &domain::MerchantAccount, + _key_store: &domain::MerchantKeyStore, + _merchant_connector_account: &helpers::MerchantConnectorAccountType, + _connector: &api::ConnectorData, + ) -> RouterResult<Option<MerchantRecipientData>> { + Ok(None) + } } #[async_trait] diff --git a/crates/router/src/core/fraud_check/flows/sale_flow.rs b/crates/router/src/core/fraud_check/flows/sale_flow.rs index 907b941ee67..fee1964a42a 100644 --- a/crates/router/src/core/fraud_check/flows/sale_flow.rs +++ b/crates/router/src/core/fraud_check/flows/sale_flow.rs @@ -11,11 +11,11 @@ use crate::{ }, errors, services, types::{ - api::fraud_check as frm_api, + api::{self, fraud_check as frm_api}, domain, fraud_check::{FraudCheckResponseData, FraudCheckSaleData, FrmSaleRouterData}, storage::enums as storage_enums, - ConnectorAuthType, ResponseId, RouterData, + ConnectorAuthType, MerchantRecipientData, ResponseId, RouterData, }, SessionState, }; @@ -32,6 +32,7 @@ impl ConstructFlowSpecificData<frm_api::Sale, FraudCheckSaleData, FraudCheckResp _key_store: &domain::MerchantKeyStore, customer: &Option<domain::Customer>, merchant_connector_account: &helpers::MerchantConnectorAccountType, + _merchant_recipient_data: Option<MerchantRecipientData>, ) -> RouterResult<RouterData<frm_api::Sale, FraudCheckSaleData, FraudCheckResponseData>> { let status = storage_enums::AttemptStatus::Pending; @@ -116,6 +117,17 @@ impl ConstructFlowSpecificData<frm_api::Sale, FraudCheckSaleData, FraudCheckResp Ok(router_data) } + + async fn get_merchant_recipient_data<'a>( + &self, + _state: &SessionState, + _merchant_account: &domain::MerchantAccount, + _key_store: &domain::MerchantKeyStore, + _merchant_connector_account: &helpers::MerchantConnectorAccountType, + _connector: &api::ConnectorData, + ) -> RouterResult<Option<MerchantRecipientData>> { + Ok(None) + } } #[async_trait] diff --git a/crates/router/src/core/fraud_check/flows/transaction_flow.rs b/crates/router/src/core/fraud_check/flows/transaction_flow.rs index dd042a6b593..c5d00c4a8e9 100644 --- a/crates/router/src/core/fraud_check/flows/transaction_flow.rs +++ b/crates/router/src/core/fraud_check/flows/transaction_flow.rs @@ -10,13 +10,13 @@ use crate::{ }, errors, services, types::{ - api::fraud_check as frm_api, + api::{self, fraud_check as frm_api}, domain, fraud_check::{ FraudCheckResponseData, FraudCheckTransactionData, FrmTransactionRouterData, }, storage::enums as storage_enums, - ConnectorAuthType, ResponseId, RouterData, + ConnectorAuthType, MerchantRecipientData, ResponseId, RouterData, }, SessionState, }; @@ -37,6 +37,7 @@ impl _key_store: &domain::MerchantKeyStore, customer: &Option<domain::Customer>, merchant_connector_account: &helpers::MerchantConnectorAccountType, + _merchant_recipient_data: Option<MerchantRecipientData>, ) -> RouterResult< RouterData<frm_api::Transaction, FraudCheckTransactionData, FraudCheckResponseData>, > { @@ -120,6 +121,17 @@ impl Ok(router_data) } + + async fn get_merchant_recipient_data<'a>( + &self, + _state: &SessionState, + _merchant_account: &domain::MerchantAccount, + _key_store: &domain::MerchantKeyStore, + _merchant_connector_account: &helpers::MerchantConnectorAccountType, + _connector: &api::ConnectorData, + ) -> RouterResult<Option<MerchantRecipientData>> { + Ok(None) + } } #[async_trait] diff --git a/crates/router/src/core/payment_methods.rs b/crates/router/src/core/payment_methods.rs index a7a87b6d96e..00b51b9f09e 100644 --- a/crates/router/src/core/payment_methods.rs +++ b/crates/router/src/core/payment_methods.rs @@ -71,6 +71,7 @@ pub async fn retrieve_payment_method( pm @ Some(api::PaymentMethodData::RealTimePayment(_)) => Ok((pm.to_owned(), None)), pm @ Some(api::PaymentMethodData::CardRedirect(_)) => Ok((pm.to_owned(), None)), pm @ Some(api::PaymentMethodData::GiftCard(_)) => Ok((pm.to_owned(), None)), + pm @ Some(api::PaymentMethodData::OpenBanking(_)) => Ok((pm.to_owned(), None)), pm_opt @ Some(pm @ api::PaymentMethodData::BankTransfer(_)) => { let payment_token = helpers::store_payment_method_data_in_vault( state, diff --git a/crates/router/src/core/payments.rs b/crates/router/src/core/payments.rs index ccca6eaed60..2e197516ed6 100644 --- a/crates/router/src/core/payments.rs +++ b/crates/router/src/core/payments.rs @@ -27,7 +27,7 @@ use api_models::{ }; use common_utils::{ ext_traits::{AsyncExt, StringExt}, - pii, + id_type, pii, types::{MinorUnit, Surcharge}, }; use diesel_models::{ephemeral_key, fraud_check::FraudCheck}; @@ -41,7 +41,7 @@ pub use hyperswitch_domain_models::{ router_data::RouterData, router_request_types::CustomerDetails, }; -use masking::{ExposeInterface, Secret}; +use masking::{ExposeInterface, PeekInterface, Secret}; use redis_interface::errors::RedisError; use router_env::{instrument, metrics::add_attributes, tracing}; #[cfg(feature = "olap")] @@ -74,6 +74,7 @@ use crate::{ core::{ authentication as authentication_core, errors::{self, CustomResult, RouterResponse, RouterResult}, + payment_methods::cards, utils, }, db::StorageInterface, @@ -285,7 +286,7 @@ where } else { None }; - let router_data = call_connector_service( + let (router_data, mca) = call_connector_service( state, req_state.clone(), &merchant_account, @@ -307,6 +308,9 @@ where ) .await?; + let op_ref = &operation; + let should_trigger_post_processing_flows = is_operation_confirm(&operation); + let operation = Box::new(PaymentResponse); connector_http_status_code = router_data.connector_http_status_code; @@ -326,7 +330,7 @@ where ) .await?; - operation + let mut payment_data = operation .to_post_update_tracker()? .update_tracker( state, @@ -336,7 +340,23 @@ where &key_store, merchant_account.storage_scheme, ) - .await? + .await?; + + if should_trigger_post_processing_flows { + complete_postprocessing_steps_if_required( + state, + &merchant_account, + &key_store, + &customer, + &mca, + &connector, + &mut payment_data, + op_ref, + ) + .await?; + } + + payment_data } ConnectorCallType::Retryable(connectors) => { @@ -357,7 +377,7 @@ where } else { None }; - let router_data = call_connector_service( + let (router_data, mca) = call_connector_service( state, req_state.clone(), &merchant_account, @@ -414,6 +434,9 @@ where }; } + let op_ref = &operation; + let should_trigger_post_processing_flows = is_operation_confirm(&operation); + let operation = Box::new(PaymentResponse); connector_http_status_code = router_data.connector_http_status_code; external_latency = router_data.external_latency; @@ -432,7 +455,7 @@ where ) .await?; - operation + let mut payment_data = operation .to_post_update_tracker()? .update_tracker( state, @@ -442,7 +465,23 @@ where &key_store, merchant_account.storage_scheme, ) - .await? + .await?; + + if should_trigger_post_processing_flows { + complete_postprocessing_steps_if_required( + state, + &merchant_account, + &key_store, + &customer, + &mca, + &connector_data, + &mut payment_data, + op_ref, + ) + .await?; + } + + payment_data } ConnectorCallType::SessionMultiple(connectors) => { @@ -1400,7 +1439,10 @@ pub async fn call_connector_service<F, RouterDReq, ApiRequest>( frm_suggestion: Option<storage_enums::FrmSuggestion>, business_profile: &storage::business_profile::BusinessProfile, is_retry_payment: bool, -) -> RouterResult<RouterData<F, RouterDReq, router_types::PaymentsResponseData>> +) -> RouterResult<( + RouterData<F, RouterDReq, router_types::PaymentsResponseData>, + helpers::MerchantConnectorAccountType, +)> where F: Send + Clone + Sync, RouterDReq: Send + Sync, @@ -1461,6 +1503,16 @@ where ) .await?; + let merchant_recipient_data = 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( state, @@ -1469,6 +1521,7 @@ where key_store, customer, &merchant_connector_account, + merchant_recipient_data, ) .await?; @@ -1611,7 +1664,7 @@ where ) .await?; - let router_data_res = if should_continue_further { + let router_data = if should_continue_further { // The status of payment_attempt and intent will be updated in the previous step // update this in router_data. // This is added because few connector integrations do not update the status, @@ -1629,13 +1682,75 @@ where .await } else { Ok(router_data) - }; + }?; let etime_connector = Instant::now(); let duration_connector = etime_connector.saturating_duration_since(stime_connector); tracing::info!(duration = format!("Duration taken: {}", duration_connector.as_millis())); - router_data_res + Ok((router_data, merchant_connector_account)) +} + +pub async fn get_merchant_bank_data_for_open_banking_connectors( + merchant_connector_account: &helpers::MerchantConnectorAccountType, + key_store: &domain::MerchantKeyStore, + connector: &api::ConnectorData, + state: &SessionState, + merchant_account: &domain::MerchantAccount, +) -> RouterResult<Option<router_types::MerchantRecipientData>> { + let merchant_data = merchant_connector_account + .get_additional_merchant_data() + .get_required_value("additional_merchant_data")? + .into_inner() + .peek() + .clone(); + + let merchant_recipient_data = merchant_data + .parse_value::<router_types::AdditionalMerchantData>("AdditionalMerchantData") + .change_context(errors::ApiErrorResponse::InternalServerError) + .attach_printable("failed to decode MerchantRecipientData")?; + + let connector_name = enums::Connector::to_string(&connector.connector_name); + let locker_based_connector_list = state.conf.locker_based_open_banking_connectors.clone(); + let contains = locker_based_connector_list + .connector_list + .contains(connector_name.as_str()); + + let recipient_id = helpers::get_recipient_id_for_open_banking(&merchant_recipient_data)?; + let final_recipient_data = if let Some(id) = recipient_id { + if contains { + // Customer Id for OpenBanking connectors will be merchant_id as the account data stored at locker belongs to the merchant + let cust_id = id_type::CustomerId::from(merchant_account.merchant_id.clone().into()) + .change_context(errors::ApiErrorResponse::InternalServerError) + .attach_printable("Failed to convert to CustomerId")?; + let locker_resp = cards::get_payment_method_from_hs_locker( + state, + key_store, + &cust_id, + merchant_account.merchant_id.as_str(), + id.as_str(), + Some(enums::LockerChoice::HyperswitchCardVault), + ) + .await + .change_context(errors::ApiErrorResponse::InternalServerError) + .attach_printable("Merchant bank account data could not be fetched from locker")?; + + let parsed: router_types::MerchantAccountData = locker_resp + .peek() + .to_string() + .parse_struct("MerchantAccountData") + .change_context(errors::ApiErrorResponse::InternalServerError)?; + + Some(router_types::MerchantRecipientData::AccountData(parsed)) + } else { + Some(router_types::MerchantRecipientData::ConnectorRecipientId( + Secret::new(id), + )) + } + } else { + None + }; + Ok(final_recipient_data) } async fn blocklist_guard<F, ApiRequest>( @@ -1743,6 +1858,7 @@ where key_store, customer, &merchant_connector_account, + None, ) .await?; @@ -1875,6 +1991,7 @@ where key_store, customer, merchant_connector_account, + None, ) .await?; @@ -2043,6 +2160,69 @@ where Ok(router_data_and_should_continue_payment) } +#[allow(clippy::too_many_arguments)] +async fn complete_postprocessing_steps_if_required<F, Q, RouterDReq>( + state: &SessionState, + merchant_account: &domain::MerchantAccount, + key_store: &domain::MerchantKeyStore, + customer: &Option<domain::Customer>, + merchant_conn_account: &helpers::MerchantConnectorAccountType, + connector: &api::ConnectorData, + payment_data: &mut PaymentData<F>, + _operation: &BoxedOperation<'_, F, Q>, +) -> RouterResult<RouterData<F, RouterDReq, router_types::PaymentsResponseData>> +where + F: Send + Clone + Sync, + RouterDReq: Send + Sync, + + RouterData<F, RouterDReq, router_types::PaymentsResponseData>: Feature<F, RouterDReq> + Send, + dyn api::Connector: + services::api::ConnectorIntegration<F, RouterDReq, router_types::PaymentsResponseData>, + PaymentData<F>: ConstructFlowSpecificData<F, RouterDReq, router_types::PaymentsResponseData>, +{ + let mut router_data = payment_data + .construct_router_data( + state, + connector.connector.id(), + merchant_account, + key_store, + customer, + merchant_conn_account, + None, + ) + .await?; + + match payment_data.payment_method_data.clone() { + Some(api_models::payments::PaymentMethodData::OpenBanking( + api_models::payments::OpenBankingData::OpenBankingPIS { .. }, + )) => { + if connector.connector_name == router_types::Connector::Plaid { + router_data = router_data.postprocessing_steps(state, connector).await?; + let token = if let Ok(ref res) = router_data.response { + match res { + router_types::PaymentsResponseData::PostProcessingResponse { + session_token, + } => session_token + .as_ref() + .map(|token| api::SessionToken::OpenBanking(token.clone())), + _ => None, + } + } else { + None + }; + if let Some(t) = token { + payment_data.sessions_token.push(t); + } + + Ok(router_data) + } else { + Ok(router_data) + } + } + _ => Ok(router_data), + } +} + pub fn is_preprocessing_required_for_wallets(connector_name: String) -> bool { connector_name == *"trustpay" || connector_name == *"payme" } 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 178b14dde54..fbedca14aeb 100644 --- a/crates/router/src/core/payments/connector_integration_v2_impls.rs +++ b/crates/router/src/core/payments/connector_integration_v2_impls.rs @@ -40,6 +40,8 @@ mod dummy_connector_default_impl { impl<const T: u8> api::PaymentsPreProcessingV2 for connector::DummyConnector<T> {} + impl<const T: u8> api::PaymentsPostProcessingV2 for connector::DummyConnector<T> {} + impl<const T: u8> services::ConnectorIntegrationV2< api::Authorize, @@ -170,6 +172,16 @@ mod dummy_connector_default_impl { { } + impl<const T: u8> + services::ConnectorIntegrationV2< + api::PostProcessing, + types::PaymentFlowData, + types::PaymentsPostProcessingData, + types::PaymentsResponseData, + > for connector::DummyConnector<T> + { + } + impl<const T: u8> services::ConnectorIntegrationV2< api::AuthorizeSessionToken, @@ -544,6 +556,7 @@ macro_rules! default_imp_for_new_connector_integration_payment { impl api::PaymentTokenV2 for $path::$connector{} impl api::ConnectorCustomerV2 for $path::$connector{} impl api::PaymentsPreProcessingV2 for $path::$connector{} + impl api::PaymentsPostProcessingV2 for $path::$connector{} impl services::ConnectorIntegrationV2<api::Authorize,types::PaymentFlowData, types::PaymentsAuthorizeData, types::PaymentsResponseData> for $path::$connector{} @@ -603,6 +616,12 @@ macro_rules! default_imp_for_new_connector_integration_payment { types::PaymentsPreProcessingData, types::PaymentsResponseData, > for $path::$connector{} + impl services::ConnectorIntegrationV2< + api::PostProcessing, + types::PaymentFlowData, + types::PaymentsPostProcessingData, + types::PaymentsResponseData, + > for $path::$connector{} impl services::ConnectorIntegrationV2< api::AuthorizeSessionToken, diff --git a/crates/router/src/core/payments/flows.rs b/crates/router/src/core/payments/flows.rs index 815b02285dd..53ca8d02451 100644 --- a/crates/router/src/core/payments/flows.rs +++ b/crates/router/src/core/payments/flows.rs @@ -25,6 +25,7 @@ use crate::{ }; #[async_trait] +#[allow(clippy::too_many_arguments)] pub trait ConstructFlowSpecificData<F, Req, Res> { async fn construct_router_data<'a>( &self, @@ -34,7 +35,17 @@ pub trait ConstructFlowSpecificData<F, Req, Res> { key_store: &domain::MerchantKeyStore, customer: &Option<domain::Customer>, merchant_connector_account: &helpers::MerchantConnectorAccountType, + merchant_recipient_data: Option<types::MerchantRecipientData>, ) -> RouterResult<types::RouterData<F, Req, Res>>; + + async fn get_merchant_recipient_data<'a>( + &self, + state: &SessionState, + merchant_account: &domain::MerchantAccount, + key_store: &domain::MerchantKeyStore, + merchant_connector_account: &helpers::MerchantConnectorAccountType, + connector: &api::ConnectorData, + ) -> RouterResult<Option<types::MerchantRecipientData>>; } #[allow(clippy::too_many_arguments)] @@ -110,6 +121,19 @@ pub trait Feature<F, T> { Ok(self) } + async fn postprocessing_steps<'a>( + self, + _state: &SessionState, + _connector: &api::ConnectorData, + ) -> RouterResult<Self> + where + F: Clone, + Self: Sized, + dyn api::Connector: services::ConnectorIntegration<F, T, types::PaymentsResponseData>, + { + Ok(self) + } + async fn create_connector_customer<'a>( &self, _state: &SessionState, @@ -970,6 +994,21 @@ macro_rules! default_imp_for_pre_processing_steps{ }; } +macro_rules! default_imp_for_post_processing_steps{ + ($($path:ident::$connector:ident),*)=> { + $( + impl api::PaymentsPostProcessing for $path::$connector {} + impl + services::ConnectorIntegration< + api::PostProcessing, + types::PaymentsPostProcessingData, + types::PaymentsResponseData, + > for $path::$connector + {} + )* + }; +} + #[cfg(feature = "dummy_connector")] impl<const T: u8> api::PaymentsPreProcessing for connector::DummyConnector<T> {} #[cfg(feature = "dummy_connector")] @@ -1039,6 +1078,86 @@ default_imp_for_pre_processing_steps!( connector::Zsl ); +#[cfg(feature = "dummy_connector")] +impl<const T: u8> api::PaymentsPostProcessing for connector::DummyConnector<T> {} +#[cfg(feature = "dummy_connector")] +impl<const T: u8> + services::ConnectorIntegration< + api::PostProcessing, + types::PaymentsPostProcessingData, + types::PaymentsResponseData, + > for connector::DummyConnector<T> +{ +} + +default_imp_for_post_processing_steps!( + connector::Adyenplatform, + connector::Adyen, + connector::Airwallex, + connector::Bankofamerica, + connector::Cybersource, + connector::Gocardless, + connector::Nmi, + connector::Nuvei, + connector::Payme, + connector::Paypal, + connector::Shift4, + connector::Stripe, + connector::Trustpay, + connector::Aci, + connector::Authorizedotnet, + connector::Bambora, + connector::Bamboraapac, + connector::Billwerk, + connector::Bitpay, + connector::Bluesnap, + connector::Boku, + connector::Braintree, + connector::Cashtocode, + connector::Checkout, + connector::Coinbase, + connector::Cryptopay, + connector::Datatrans, + connector::Dlocal, + connector::Ebanx, + connector::Iatapay, + connector::Fiserv, + connector::Forte, + connector::Globalpay, + connector::Globepay, + connector::Gpayments, + connector::Helcim, + connector::Klarna, + connector::Mifinity, + connector::Mollie, + connector::Multisafepay, + connector::Netcetera, + connector::Nexinets, + connector::Noon, + connector::Opayo, + connector::Opennode, + connector::Payeezy, + connector::Payone, + connector::Payu, + connector::Placetopay, + connector::Powertranz, + connector::Prophetpay, + connector::Rapyd, + connector::Riskified, + connector::Signifyd, + connector::Square, + connector::Stax, + connector::Threedsecureio, + connector::Tsys, + connector::Volt, + connector::Wise, + connector::Worldline, + connector::Worldpay, + connector::Zen, + connector::Zsl, + connector::Razorpay +); + macro_rules! default_imp_for_payouts { ($($path:ident::$connector:ident),*) => { $( diff --git a/crates/router/src/core/payments/flows/approve_flow.rs b/crates/router/src/core/payments/flows/approve_flow.rs index f4f8409912e..63224f5b0cf 100644 --- a/crates/router/src/core/payments/flows/approve_flow.rs +++ b/crates/router/src/core/payments/flows/approve_flow.rs @@ -24,6 +24,7 @@ impl key_store: &domain::MerchantKeyStore, customer: &Option<domain::Customer>, merchant_connector_account: &helpers::MerchantConnectorAccountType, + merchant_recipient_data: Option<types::MerchantRecipientData>, ) -> RouterResult<types::PaymentsApproveRouterData> { Box::pin(transformers::construct_payment_router_data::< api::Approve, @@ -36,9 +37,21 @@ impl key_store, customer, merchant_connector_account, + merchant_recipient_data, )) .await } + + async fn get_merchant_recipient_data<'a>( + &self, + _state: &SessionState, + _merchant_account: &domain::MerchantAccount, + _key_store: &domain::MerchantKeyStore, + _merchant_connector_account: &helpers::MerchantConnectorAccountType, + _connector: &api::ConnectorData, + ) -> RouterResult<Option<types::MerchantRecipientData>> { + Ok(None) + } } #[async_trait] diff --git a/crates/router/src/core/payments/flows/authorize_flow.rs b/crates/router/src/core/payments/flows/authorize_flow.rs index 50cf31730a9..db34c40d928 100644 --- a/crates/router/src/core/payments/flows/authorize_flow.rs +++ b/crates/router/src/core/payments/flows/authorize_flow.rs @@ -1,4 +1,5 @@ use async_trait::async_trait; +use common_enums as enums; use router_env::metrics::add_attributes; // use router_env::tracing::Instrument; @@ -16,6 +17,7 @@ use crate::{ services, services::api::ConnectorValidation, types::{self, api, domain, storage, transformers::ForeignFrom}, + utils::OptionExt, }; #[async_trait] @@ -34,6 +36,7 @@ impl key_store: &domain::MerchantKeyStore, customer: &Option<domain::Customer>, merchant_connector_account: &helpers::MerchantConnectorAccountType, + merchant_recipient_data: Option<types::MerchantRecipientData>, ) -> RouterResult< types::RouterData< api::Authorize, @@ -52,9 +55,39 @@ impl key_store, customer, merchant_connector_account, + merchant_recipient_data, )) .await } + + async fn get_merchant_recipient_data<'a>( + &self, + state: &SessionState, + merchant_account: &domain::MerchantAccount, + key_store: &domain::MerchantKeyStore, + merchant_connector_account: &helpers::MerchantConnectorAccountType, + connector: &api::ConnectorData, + ) -> RouterResult<Option<types::MerchantRecipientData>> { + let payment_method = &self + .payment_attempt + .payment_method + .get_required_value("PaymentMethod")?; + + let data = if *payment_method == enums::PaymentMethod::OpenBanking { + payments::get_merchant_bank_data_for_open_banking_connectors( + merchant_connector_account, + key_store, + connector, + state, + merchant_account, + ) + .await? + } else { + None + }; + + Ok(data) + } } #[async_trait] impl Feature<api::Authorize, types::PaymentsAuthorizeData> for types::PaymentsAuthorizeRouterData { @@ -170,6 +203,14 @@ impl Feature<api::Authorize, types::PaymentsAuthorizeData> for types::PaymentsAu authorize_preprocessing_steps(state, &self, true, connector).await } + async fn postprocessing_steps<'a>( + self, + state: &SessionState, + connector: &api::ConnectorData, + ) -> RouterResult<Self> { + authorize_postprocessing_steps(state, &self, true, connector).await + } + async fn create_connector_customer<'a>( &self, state: &SessionState, @@ -399,3 +440,53 @@ pub async fn authorize_preprocessing_steps<F: Clone>( Ok(router_data.clone()) } } + +pub async fn authorize_postprocessing_steps<F: Clone>( + state: &SessionState, + router_data: &types::RouterData<F, types::PaymentsAuthorizeData, types::PaymentsResponseData>, + confirm: bool, + connector: &api::ConnectorData, +) -> RouterResult<types::RouterData<F, types::PaymentsAuthorizeData, types::PaymentsResponseData>> { + if confirm { + let connector_integration: services::BoxedPaymentConnectorIntegrationInterface< + api::PostProcessing, + types::PaymentsPostProcessingData, + types::PaymentsResponseData, + > = connector.connector.get_connector_integration(); + + let postprocessing_request_data = + types::PaymentsPostProcessingData::try_from(router_data.to_owned())?; + + let postprocessing_response_data: Result< + types::PaymentsResponseData, + types::ErrorResponse, + > = Err(types::ErrorResponse::default()); + + let postprocessing_router_data = + helpers::router_data_type_conversion::<_, api::PostProcessing, _, _, _, _>( + router_data.clone(), + postprocessing_request_data, + postprocessing_response_data, + ); + + let resp = services::execute_connector_processing_step( + state, + connector_integration, + &postprocessing_router_data, + payments::CallConnectorAction::Trigger, + None, + ) + .await + .to_payment_failed_response()?; + + let authorize_router_data = helpers::router_data_type_conversion::<_, F, _, _, _, _>( + resp.clone(), + router_data.request.to_owned(), + resp.response, + ); + + Ok(authorize_router_data) + } else { + Ok(router_data.clone()) + } +} diff --git a/crates/router/src/core/payments/flows/cancel_flow.rs b/crates/router/src/core/payments/flows/cancel_flow.rs index d61730117a8..486e8bb75dc 100644 --- a/crates/router/src/core/payments/flows/cancel_flow.rs +++ b/crates/router/src/core/payments/flows/cancel_flow.rs @@ -24,6 +24,7 @@ impl ConstructFlowSpecificData<api::Void, types::PaymentsCancelData, types::Paym key_store: &domain::MerchantKeyStore, customer: &Option<domain::Customer>, merchant_connector_account: &helpers::MerchantConnectorAccountType, + merchant_recipient_data: Option<types::MerchantRecipientData>, ) -> RouterResult<types::PaymentsCancelRouterData> { Box::pin(transformers::construct_payment_router_data::< api::Void, @@ -36,9 +37,21 @@ impl ConstructFlowSpecificData<api::Void, types::PaymentsCancelData, types::Paym key_store, customer, merchant_connector_account, + merchant_recipient_data, )) .await } + + async fn get_merchant_recipient_data<'a>( + &self, + _state: &SessionState, + _merchant_account: &domain::MerchantAccount, + _key_store: &domain::MerchantKeyStore, + _merchant_connector_account: &helpers::MerchantConnectorAccountType, + _connector: &api::ConnectorData, + ) -> RouterResult<Option<types::MerchantRecipientData>> { + Ok(None) + } } #[async_trait] diff --git a/crates/router/src/core/payments/flows/capture_flow.rs b/crates/router/src/core/payments/flows/capture_flow.rs index 1c4f76d9833..a7f30f2a41b 100644 --- a/crates/router/src/core/payments/flows/capture_flow.rs +++ b/crates/router/src/core/payments/flows/capture_flow.rs @@ -24,6 +24,7 @@ impl key_store: &domain::MerchantKeyStore, customer: &Option<domain::Customer>, merchant_connector_account: &helpers::MerchantConnectorAccountType, + merchant_recipient_data: Option<types::MerchantRecipientData>, ) -> RouterResult<types::PaymentsCaptureRouterData> { Box::pin(transformers::construct_payment_router_data::< api::Capture, @@ -36,9 +37,21 @@ impl key_store, customer, merchant_connector_account, + merchant_recipient_data, )) .await } + + async fn get_merchant_recipient_data<'a>( + &self, + _state: &SessionState, + _merchant_account: &domain::MerchantAccount, + _key_store: &domain::MerchantKeyStore, + _merchant_connector_account: &helpers::MerchantConnectorAccountType, + _connector: &api::ConnectorData, + ) -> RouterResult<Option<types::MerchantRecipientData>> { + Ok(None) + } } #[async_trait] diff --git a/crates/router/src/core/payments/flows/complete_authorize_flow.rs b/crates/router/src/core/payments/flows/complete_authorize_flow.rs index 6bef7e95859..d3ae67f46c3 100644 --- a/crates/router/src/core/payments/flows/complete_authorize_flow.rs +++ b/crates/router/src/core/payments/flows/complete_authorize_flow.rs @@ -28,6 +28,7 @@ impl key_store: &domain::MerchantKeyStore, customer: &Option<domain::Customer>, merchant_connector_account: &helpers::MerchantConnectorAccountType, + merchant_recipient_data: Option<types::MerchantRecipientData>, ) -> RouterResult< types::RouterData< api::CompleteAuthorize, @@ -46,9 +47,21 @@ impl key_store, customer, merchant_connector_account, + merchant_recipient_data, )) .await } + + async fn get_merchant_recipient_data<'a>( + &self, + _state: &SessionState, + _merchant_account: &domain::MerchantAccount, + _key_store: &domain::MerchantKeyStore, + _merchant_connector_account: &helpers::MerchantConnectorAccountType, + _connector: &api::ConnectorData, + ) -> RouterResult<Option<types::MerchantRecipientData>> { + Ok(None) + } } #[async_trait] diff --git a/crates/router/src/core/payments/flows/incremental_authorization_flow.rs b/crates/router/src/core/payments/flows/incremental_authorization_flow.rs index 2aa808f9532..3bc05cedb45 100644 --- a/crates/router/src/core/payments/flows/incremental_authorization_flow.rs +++ b/crates/router/src/core/payments/flows/incremental_authorization_flow.rs @@ -27,6 +27,7 @@ impl key_store: &domain::MerchantKeyStore, customer: &Option<domain::Customer>, merchant_connector_account: &helpers::MerchantConnectorAccountType, + merchant_recipient_data: Option<types::MerchantRecipientData>, ) -> RouterResult<types::PaymentsIncrementalAuthorizationRouterData> { Box::pin(transformers::construct_payment_router_data::< api::IncrementalAuthorization, @@ -39,9 +40,21 @@ impl key_store, customer, merchant_connector_account, + merchant_recipient_data, )) .await } + + async fn get_merchant_recipient_data<'a>( + &self, + _state: &SessionState, + _merchant_account: &domain::MerchantAccount, + _key_store: &domain::MerchantKeyStore, + _merchant_connector_account: &helpers::MerchantConnectorAccountType, + _connector: &api::ConnectorData, + ) -> RouterResult<Option<types::MerchantRecipientData>> { + Ok(None) + } } #[async_trait] diff --git a/crates/router/src/core/payments/flows/psync_flow.rs b/crates/router/src/core/payments/flows/psync_flow.rs index d094fe6a21d..cb6c6f50d5e 100644 --- a/crates/router/src/core/payments/flows/psync_flow.rs +++ b/crates/router/src/core/payments/flows/psync_flow.rs @@ -25,6 +25,7 @@ impl ConstructFlowSpecificData<api::PSync, types::PaymentsSyncData, types::Payme key_store: &domain::MerchantKeyStore, customer: &Option<domain::Customer>, merchant_connector_account: &helpers::MerchantConnectorAccountType, + merchant_recipient_data: Option<types::MerchantRecipientData>, ) -> RouterResult< types::RouterData<api::PSync, types::PaymentsSyncData, types::PaymentsResponseData>, > { @@ -39,9 +40,21 @@ impl ConstructFlowSpecificData<api::PSync, types::PaymentsSyncData, types::Payme key_store, customer, merchant_connector_account, + merchant_recipient_data, )) .await } + + async fn get_merchant_recipient_data<'a>( + &self, + _state: &SessionState, + _merchant_account: &domain::MerchantAccount, + _key_store: &domain::MerchantKeyStore, + _merchant_connector_account: &helpers::MerchantConnectorAccountType, + _connector: &api::ConnectorData, + ) -> RouterResult<Option<types::MerchantRecipientData>> { + Ok(None) + } } #[async_trait] diff --git a/crates/router/src/core/payments/flows/reject_flow.rs b/crates/router/src/core/payments/flows/reject_flow.rs index cb1dcd5b19f..501c0a40dab 100644 --- a/crates/router/src/core/payments/flows/reject_flow.rs +++ b/crates/router/src/core/payments/flows/reject_flow.rs @@ -23,6 +23,7 @@ impl ConstructFlowSpecificData<api::Reject, types::PaymentsRejectData, types::Pa key_store: &domain::MerchantKeyStore, customer: &Option<domain::Customer>, merchant_connector_account: &helpers::MerchantConnectorAccountType, + merchant_recipient_data: Option<types::MerchantRecipientData>, ) -> RouterResult<types::PaymentsRejectRouterData> { Box::pin(transformers::construct_payment_router_data::< api::Reject, @@ -35,9 +36,21 @@ impl ConstructFlowSpecificData<api::Reject, types::PaymentsRejectData, types::Pa key_store, customer, merchant_connector_account, + merchant_recipient_data, )) .await } + + async fn get_merchant_recipient_data<'a>( + &self, + _state: &SessionState, + _merchant_account: &domain::MerchantAccount, + _key_store: &domain::MerchantKeyStore, + _merchant_connector_account: &helpers::MerchantConnectorAccountType, + _connector: &api::ConnectorData, + ) -> RouterResult<Option<types::MerchantRecipientData>> { + Ok(None) + } } #[async_trait] diff --git a/crates/router/src/core/payments/flows/session_flow.rs b/crates/router/src/core/payments/flows/session_flow.rs index 664038454a4..883203ad99e 100644 --- a/crates/router/src/core/payments/flows/session_flow.rs +++ b/crates/router/src/core/payments/flows/session_flow.rs @@ -39,6 +39,7 @@ impl key_store: &domain::MerchantKeyStore, customer: &Option<domain::Customer>, merchant_connector_account: &helpers::MerchantConnectorAccountType, + merchant_recipient_data: Option<types::MerchantRecipientData>, ) -> RouterResult<types::PaymentsSessionRouterData> { Box::pin(transformers::construct_payment_router_data::< api::Session, @@ -51,9 +52,21 @@ impl key_store, customer, merchant_connector_account, + merchant_recipient_data, )) .await } + + async fn get_merchant_recipient_data<'a>( + &self, + _state: &routes::SessionState, + _merchant_account: &domain::MerchantAccount, + _key_store: &domain::MerchantKeyStore, + _merchant_connector_account: &helpers::MerchantConnectorAccountType, + _connector: &api::ConnectorData, + ) -> RouterResult<Option<types::MerchantRecipientData>> { + Ok(None) + } } #[async_trait] diff --git a/crates/router/src/core/payments/flows/setup_mandate_flow.rs b/crates/router/src/core/payments/flows/setup_mandate_flow.rs index 773677f3e7c..0d4648b81f4 100644 --- a/crates/router/src/core/payments/flows/setup_mandate_flow.rs +++ b/crates/router/src/core/payments/flows/setup_mandate_flow.rs @@ -31,6 +31,7 @@ impl key_store: &domain::MerchantKeyStore, customer: &Option<domain::Customer>, merchant_connector_account: &helpers::MerchantConnectorAccountType, + merchant_recipient_data: Option<types::MerchantRecipientData>, ) -> RouterResult<types::SetupMandateRouterData> { Box::pin(transformers::construct_payment_router_data::< api::SetupMandate, @@ -43,9 +44,21 @@ impl key_store, customer, merchant_connector_account, + merchant_recipient_data, )) .await } + + async fn get_merchant_recipient_data<'a>( + &self, + _state: &SessionState, + _merchant_account: &domain::MerchantAccount, + _key_store: &domain::MerchantKeyStore, + _merchant_connector_account: &helpers::MerchantConnectorAccountType, + _connector: &api::ConnectorData, + ) -> RouterResult<Option<types::MerchantRecipientData>> { + Ok(None) + } } #[async_trait] diff --git a/crates/router/src/core/payments/helpers.rs b/crates/router/src/core/payments/helpers.rs index da44703732f..1579322995b 100644 --- a/crates/router/src/core/payments/helpers.rs +++ b/crates/router/src/core/payments/helpers.rs @@ -66,8 +66,9 @@ use crate::{ self, enums as storage_enums, ephemeral_key, CardTokenData, CustomerUpdate::Update, }, transformers::{ForeignFrom, ForeignTryFrom}, - AdditionalPaymentMethodConnectorResponse, ErrorResponse, MandateReference, - PaymentsResponseData, RecurringMandatePaymentData, RouterData, + AdditionalMerchantData, AdditionalPaymentMethodConnectorResponse, ErrorResponse, + MandateReference, MerchantAccountData, MerchantRecipientData, PaymentsResponseData, + RecipientIdType, RecurringMandatePaymentData, RouterData, }, utils::{ self, @@ -2429,6 +2430,7 @@ pub fn validate_payment_method_type_against_payment_method( | api_enums::PaymentMethodType::Bizum | api_enums::PaymentMethodType::Interac | api_enums::PaymentMethodType::OpenBankingUk + | api_enums::PaymentMethodType::OpenBankingPIS ), api_enums::PaymentMethod::BankTransfer => matches!( payment_method_type, @@ -2503,6 +2505,10 @@ pub fn validate_payment_method_type_against_payment_method( | api_enums::PaymentMethodType::MomoAtm | api_enums::PaymentMethodType::CardRedirect ), + api_enums::PaymentMethod::OpenBanking => matches!( + payment_method_type, + api_enums::PaymentMethodType::OpenBankingPIS + ), } } @@ -3341,6 +3347,15 @@ impl MerchantConnectorAccountType { Self::CacheVal(_) => None, } } + + pub fn get_additional_merchant_data( + &self, + ) -> Option<Encryptable<masking::Secret<serde_json::Value>>> { + match self { + Self::DbVal(db_val) => db_val.additional_merchant_data.clone(), + Self::CacheVal(_) => None, + } + } } /// Query for merchant connector account either by business label or profile id @@ -4024,6 +4039,9 @@ pub async fn get_additional_payment_data( api_models::payments::PaymentMethodData::CardToken(_) => { api_models::payments::AdditionalPaymentData::CardToken {} } + api_models::payments::PaymentMethodData::OpenBanking(_) => { + api_models::payments::AdditionalPaymentData::OpenBanking {} + } } } @@ -4572,6 +4590,11 @@ pub fn get_key_params_for_surcharge_details( gift_card.get_payment_method_type(), None, )), + api_models::payments::PaymentMethodData::OpenBanking(ob_data) => Some(( + common_enums::PaymentMethod::OpenBanking, + ob_data.get_payment_method_type(), + None, + )), api_models::payments::PaymentMethodData::CardToken(_) => None, } } @@ -4669,6 +4692,40 @@ pub fn validate_session_expiry(session_expiry: u32) -> Result<(), errors::ApiErr } } +pub fn get_recipient_id_for_open_banking( + merchant_data: &AdditionalMerchantData, +) -> Result<Option<String>, errors::ApiErrorResponse> { + match merchant_data { + AdditionalMerchantData::OpenBankingRecipientData(data) => match data { + MerchantRecipientData::ConnectorRecipientId(id) => Ok(Some(id.peek().clone())), + MerchantRecipientData::AccountData(acc_data) => match acc_data { + MerchantAccountData::Bacs { + connector_recipient_id, + .. + } => match connector_recipient_id { + Some(RecipientIdType::ConnectorId(id)) => Ok(Some(id.peek().clone())), + Some(RecipientIdType::LockerId(id)) => Ok(Some(id.peek().clone())), + _ => Err(errors::ApiErrorResponse::InvalidConnectorConfiguration { + config: "recipient_id".to_string(), + }), + }, + MerchantAccountData::Iban { + connector_recipient_id, + .. + } => match connector_recipient_id { + Some(RecipientIdType::ConnectorId(id)) => Ok(Some(id.peek().clone())), + Some(RecipientIdType::LockerId(id)) => Ok(Some(id.peek().clone())), + _ => Err(errors::ApiErrorResponse::InvalidConnectorConfiguration { + config: "recipient_id".to_string(), + }), + }, + }, + _ => Err(errors::ApiErrorResponse::InvalidConnectorConfiguration { + config: "recipient_id".to_string(), + }), + }, + } +} // This function validates the intent fulfillment time expiry set by the merchant in the request pub fn validate_intent_fulfillment_expiry( intent_fulfillment_time: u32, diff --git a/crates/router/src/core/payments/operations/payment_response.rs b/crates/router/src/core/payments/operations/payment_response.rs index a28b9fe3dd2..fc075f29799 100644 --- a/crates/router/src/core/payments/operations/payment_response.rs +++ b/crates/router/src/core/payments/operations/payment_response.rs @@ -1116,6 +1116,7 @@ async fn payment_response_update_tracker<F: Clone, T: types::Capturable>( types::PaymentsResponseData::ThreeDSEnrollmentResponse { .. } => { (None, None) } + types::PaymentsResponseData::PostProcessingResponse { .. } => (None, None), types::PaymentsResponseData::IncrementalAuthorizationResponse { .. } => (None, None), @@ -1338,13 +1339,14 @@ async fn payment_response_update_tracker<F: Clone, T: types::Capturable>( .in_current_span(), ); - let (payment_intent, _, _) = futures::try_join!( + let (payment_intent, _, payment_attempt) = futures::try_join!( utils::flatten_join_error(payment_intent_fut), utils::flatten_join_error(mandate_update_fut), utils::flatten_join_error(payment_attempt_fut) )?; payment_data.payment_intent = payment_intent; + payment_data.payment_attempt = payment_attempt; router_data.payment_method_status.and_then(|status| { payment_data .payment_method_info diff --git a/crates/router/src/core/payments/retry.rs b/crates/router/src/core/payments/retry.rs index 6160ffacb0a..bf5ae5aa635 100644 --- a/crates/router/src/core/payments/retry.rs +++ b/crates/router/src/core/payments/retry.rs @@ -306,7 +306,7 @@ where ) .await?; - payments::call_connector_service( + let (router_data, _mca) = payments::call_connector_service( state, req_state, merchant_account, @@ -323,7 +323,9 @@ where business_profile, true, ) - .await + .await?; + + Ok(router_data) } #[instrument(skip_all)] diff --git a/crates/router/src/core/payments/transformers.rs b/crates/router/src/core/payments/transformers.rs index a5648af427c..9f9231b1d4e 100644 --- a/crates/router/src/core/payments/transformers.rs +++ b/crates/router/src/core/payments/transformers.rs @@ -38,6 +38,7 @@ use crate::{ }; #[instrument(skip_all)] +#[allow(clippy::too_many_arguments)] pub async fn construct_payment_router_data<'a, F, T>( state: &'a SessionState, payment_data: PaymentData<F>, @@ -46,6 +47,7 @@ pub async fn construct_payment_router_data<'a, F, T>( _key_store: &domain::MerchantKeyStore, customer: &'a Option<domain::Customer>, merchant_connector_account: &helpers::MerchantConnectorAccountType, + merchant_recipient_data: Option<types::MerchantRecipientData>, ) -> RouterResult<types::RouterData<F, T, types::PaymentsResponseData>> where T: TryFrom<PaymentAdditionalData<'a, F>>, @@ -157,7 +159,14 @@ where .payment_attempt .authentication_type .unwrap_or_default(), - connector_meta_data: merchant_connector_account.get_metadata(), + connector_meta_data: if let Some(data) = merchant_recipient_data { + let val = serde_json::to_value(data) + .change_context(errors::ApiErrorResponse::InternalServerError) + .attach_printable("Failed while encoding MerchantRecipientData")?; + Some(Secret::new(val)) + } else { + merchant_connector_account.get_metadata() + }, connector_wallets_details: merchant_connector_account.get_connector_wallets_details(), request: T::try_from(additional_data)?, response, @@ -909,7 +918,7 @@ where { // If the operation is confirm, we will send session token response in next action if format!("{operation:?}").eq("PaymentConfirm") { - payment_attempt + let condition1 = payment_attempt .connector .as_ref() .map(|connector| { @@ -924,7 +933,36 @@ where Some(false) } }) - .unwrap_or(false) + .unwrap_or(false); + + // This condition to be triggered for open banking connectors, third party SDK session token will be provided + let condition2 = payment_attempt + .connector + .as_ref() + .map(|connector| matches!(connector.as_str(), "plaid")) + .and_then(|is_connector_supports_third_party_sdk| { + if is_connector_supports_third_party_sdk { + payment_attempt + .payment_method + .map(|pm| matches!(pm, diesel_models::enums::PaymentMethod::OpenBanking)) + .and_then(|first_match| { + payment_attempt + .payment_method_type + .map(|pmt| { + matches!( + pmt, + diesel_models::enums::PaymentMethodType::OpenBankingPIS + ) + }) + .map(|second_match| first_match && second_match) + }) + } else { + Some(false) + } + }) + .unwrap_or(false); + + condition1 || condition2 } else { false } @@ -1297,6 +1335,11 @@ impl<F: Clone> TryFrom<PaymentAdditionalData<'_, F>> for types::PaymentsAuthoriz .map(|customer| customer.clone().into_inner()) }); + let customer_id = additional_data + .customer_data + .as_ref() + .map(|data| data.customer_id.clone()); + let charges = match payment_data.payment_intent.charges { Some(charges) => charges .peek() @@ -1340,7 +1383,7 @@ impl<F: Clone> TryFrom<PaymentAdditionalData<'_, F>> for types::PaymentsAuthoriz router_return_url, webhook_url, complete_authorize_url, - customer_id: None, + customer_id, surcharge_details: payment_data.surcharge_details, request_incremental_authorization: matches!( payment_data diff --git a/crates/router/src/core/payout_link.rs b/crates/router/src/core/payout_link.rs index 0d4c525f104..e91a55e860c 100644 --- a/crates/router/src/core/payout_link.rs +++ b/crates/router/src/core/payout_link.rs @@ -329,6 +329,7 @@ pub async fn filter_payout_methods( | common_enums::PaymentMethod::RealTimePayment | common_enums::PaymentMethod::Upi | common_enums::PaymentMethod::Voucher + | common_enums::PaymentMethod::OpenBanking | common_enums::PaymentMethod::GiftCard => continue, } } diff --git a/crates/router/src/types.rs b/crates/router/src/types.rs index b5f97a09f70..c5e536de3aa 100644 --- a/crates/router/src/types.rs +++ b/crates/router/src/types.rs @@ -42,9 +42,10 @@ pub use hyperswitch_domain_models::{ DestinationChargeRefund, DirectChargeRefund, MandateRevokeRequestData, MultipleCaptureRequestData, PaymentMethodTokenizationData, PaymentsApproveData, PaymentsAuthorizeData, PaymentsCancelData, PaymentsCaptureData, - PaymentsIncrementalAuthorizationData, PaymentsPreProcessingData, PaymentsRejectData, - PaymentsSessionData, PaymentsSyncData, RefundsData, ResponseId, RetrieveFileRequestData, - SetupMandateRequestData, SubmitEvidenceRequestData, SyncRequestType, UploadFileRequestData, + PaymentsIncrementalAuthorizationData, PaymentsPostProcessingData, + PaymentsPreProcessingData, PaymentsRejectData, PaymentsSessionData, PaymentsSyncData, + RefundsData, ResponseId, RetrieveFileRequestData, SetupMandateRequestData, + SubmitEvidenceRequestData, SyncRequestType, UploadFileRequestData, VerifyWebhookSourceRequestData, }, router_response_types::{ @@ -80,6 +81,8 @@ pub type PaymentsAuthorizeRouterData = RouterData<api::Authorize, PaymentsAuthorizeData, PaymentsResponseData>; pub type PaymentsPreProcessingRouterData = RouterData<api::PreProcessing, PaymentsPreProcessingData, PaymentsResponseData>; +pub type PaymentsPostProcessingRouterData = + RouterData<api::PostProcessing, PaymentsPostProcessingData, PaymentsResponseData>; pub type PaymentsAuthorizeSessionTokenRouterData = RouterData<api::AuthorizeSessionToken, AuthorizeSessionTokenData, PaymentsResponseData>; pub type PaymentsCompleteAuthorizeRouterData = @@ -163,6 +166,11 @@ pub type PaymentsPreProcessingType = dyn services::ConnectorIntegration< PaymentsPreProcessingData, PaymentsResponseData, >; +pub type PaymentsPostProcessingType = dyn services::ConnectorIntegration< + api::PostProcessing, + PaymentsPostProcessingData, + PaymentsResponseData, +>; pub type PaymentsCompleteAuthorizeType = dyn services::ConnectorIntegration< api::CompleteAuthorize, CompleteAuthorizeData, diff --git a/crates/router/src/types/api/payments.rs b/crates/router/src/types/api/payments.rs index e1dbf452eff..3c1d8175e8b 100644 --- a/crates/router/src/types/api/payments.rs +++ b/crates/router/src/types/api/payments.rs @@ -2,10 +2,10 @@ pub use api_models::payments::{ AcceptanceType, Address, AddressDetails, Amount, AuthenticationForStartResponse, Card, CryptoData, CustomerAcceptance, HeaderPayload, MandateAmountData, MandateData, MandateTransactionType, MandateType, MandateValidationFields, NextActionType, OnlineMandate, - PayLaterData, PaymentIdType, PaymentListConstraints, PaymentListFilterConstraints, - PaymentListFilters, PaymentListFiltersV2, PaymentListResponse, PaymentListResponseV2, - PaymentMethodData, PaymentMethodDataRequest, PaymentMethodDataResponse, PaymentOp, - PaymentRetrieveBody, PaymentRetrieveBodyWithCredentials, PaymentsApproveRequest, + OpenBankingSessionToken, PayLaterData, PaymentIdType, PaymentListConstraints, + PaymentListFilterConstraints, PaymentListFilters, PaymentListFiltersV2, PaymentListResponse, + PaymentListResponseV2, PaymentMethodData, PaymentMethodDataRequest, PaymentMethodDataResponse, + PaymentOp, PaymentRetrieveBody, PaymentRetrieveBodyWithCredentials, PaymentsApproveRequest, PaymentsCancelRequest, PaymentsCaptureRequest, PaymentsCompleteAuthorizeRequest, PaymentsExternalAuthenticationRequest, PaymentsIncrementalAuthorizationRequest, PaymentsManualUpdateRequest, PaymentsRedirectRequest, PaymentsRedirectionResponse, @@ -18,14 +18,14 @@ use error_stack::ResultExt; pub use hyperswitch_domain_models::router_flow_types::payments::{ Approve, Authorize, AuthorizeSessionToken, Balance, Capture, CompleteAuthorize, CreateConnectorCustomer, IncrementalAuthorization, InitPayment, PSync, PaymentMethodToken, - PreProcessing, Reject, Session, SetupMandate, Void, + PostProcessing, PreProcessing, Reject, Session, SetupMandate, Void, }; pub use super::payments_v2::{ ConnectorCustomerV2, MandateSetupV2, PaymentApproveV2, PaymentAuthorizeSessionTokenV2, PaymentAuthorizeV2, PaymentCaptureV2, PaymentIncrementalAuthorizationV2, PaymentRejectV2, PaymentSessionV2, PaymentSyncV2, PaymentTokenV2, PaymentV2, PaymentVoidV2, - PaymentsCompleteAuthorizeV2, PaymentsPreProcessingV2, + PaymentsCompleteAuthorizeV2, PaymentsPostProcessingV2, PaymentsPreProcessingV2, }; use crate::{ core::errors, @@ -172,6 +172,15 @@ pub trait PaymentsPreProcessing: { } +pub trait PaymentsPostProcessing: + api::ConnectorIntegration< + PostProcessing, + types::PaymentsPostProcessingData, + types::PaymentsResponseData, +> +{ +} + pub trait Payment: api_types::ConnectorCommon + api_types::ConnectorValidation @@ -187,6 +196,7 @@ pub trait Payment: + PaymentSession + PaymentToken + PaymentsPreProcessing + + PaymentsPostProcessing + ConnectorCustomer + PaymentIncrementalAuthorization { diff --git a/crates/router/src/types/api/payments_v2.rs b/crates/router/src/types/api/payments_v2.rs index fc490ea3d79..639dc0de5bc 100644 --- a/crates/router/src/types/api/payments_v2.rs +++ b/crates/router/src/types/api/payments_v2.rs @@ -3,7 +3,7 @@ use hyperswitch_domain_models::{ router_flow_types::payments::{ Approve, Authorize, AuthorizeSessionToken, Capture, CompleteAuthorize, CreateConnectorCustomer, IncrementalAuthorization, PSync, PaymentMethodToken, - PreProcessing, Reject, Session, SetupMandate, Void, + PostProcessing, PreProcessing, Reject, Session, SetupMandate, Void, }, }; @@ -152,6 +152,16 @@ pub trait PaymentsPreProcessingV2: { } +pub trait PaymentsPostProcessingV2: + api::ConnectorIntegrationV2< + PostProcessing, + PaymentFlowData, + types::PaymentsPostProcessingData, + types::PaymentsResponseData, +> +{ +} + pub trait PaymentV2: api_types::ConnectorCommon + api_types::ConnectorValidation @@ -167,6 +177,7 @@ pub trait PaymentV2: + PaymentSessionV2 + PaymentTokenV2 + PaymentsPreProcessingV2 + + PaymentsPostProcessingV2 + ConnectorCustomerV2 + PaymentIncrementalAuthorizationV2 { diff --git a/crates/router/src/types/transformers.rs b/crates/router/src/types/transformers.rs index 78c2bf231f2..9a42916f68d 100644 --- a/crates/router/src/types/transformers.rs +++ b/crates/router/src/types/transformers.rs @@ -478,6 +478,7 @@ impl ForeignFrom<api_enums::PaymentMethodType> for api_enums::PaymentMethod { | api_enums::PaymentMethodType::OnlineBankingPoland | api_enums::PaymentMethodType::OnlineBankingSlovakia | api_enums::PaymentMethodType::OpenBankingUk + | api_enums::PaymentMethodType::OpenBankingPIS | api_enums::PaymentMethodType::Przelewy24 | api_enums::PaymentMethodType::Trustly | api_enums::PaymentMethodType::Bizum @@ -556,6 +557,7 @@ impl ForeignTryFrom<payments::PaymentMethodData> for api_enums::PaymentMethod { payments::PaymentMethodData::Voucher(..) => Ok(Self::Voucher), payments::PaymentMethodData::GiftCard(..) => Ok(Self::GiftCard), payments::PaymentMethodData::CardRedirect(..) => Ok(Self::CardRedirect), + payments::PaymentMethodData::OpenBanking(..) => Ok(Self::OpenBanking), payments::PaymentMethodData::MandatePayment => { Err(errors::ApiErrorResponse::InvalidRequestData { message: ("Mandate payments cannot have payment_method_data field".to_string()), diff --git a/crates/router/tests/connectors/cashtocode.rs b/crates/router/tests/connectors/cashtocode.rs index 3e2708fb1f4..3af6e277de9 100644 --- a/crates/router/tests/connectors/cashtocode.rs +++ b/crates/router/tests/connectors/cashtocode.rs @@ -1,4 +1,5 @@ use api_models::payments::{Address, AddressDetails}; +use common_utils::id_type; use router::types::{self, domain, storage::enums}; use crate::{ @@ -41,6 +42,7 @@ impl CashtocodeTest { payment_method_type: Option<enums::PaymentMethodType>, payment_method_data: domain::PaymentMethodData, ) -> Option<types::PaymentsAuthorizeData> { + let cust_id = id_type::CustomerId::from("John Doe".into()); Some(types::PaymentsAuthorizeData { amount: 1000, currency: enums::Currency::EUR, @@ -66,7 +68,7 @@ impl CashtocodeTest { router_return_url: Some(String::from("https://google.com")), webhook_url: None, complete_authorize_url: None, - customer_id: Some("John Doe".to_owned()), + customer_id: if let Ok(id) = cust_id { Some(id) } else { None }, surcharge_details: None, request_incremental_authorization: false, metadata: None, diff --git a/crates/router/tests/connectors/utils.rs b/crates/router/tests/connectors/utils.rs index b03fee739f7..736c9ae6b53 100644 --- a/crates/router/tests/connectors/utils.rs +++ b/crates/router/tests/connectors/utils.rs @@ -560,6 +560,7 @@ pub trait ConnectorActions: Connector { Ok(types::PaymentsResponseData::ThreeDSEnrollmentResponse { .. }) => None, Ok(types::PaymentsResponseData::MultipleCaptureResponse { .. }) => None, Ok(types::PaymentsResponseData::IncrementalAuthorizationResponse { .. }) => None, + Ok(types::PaymentsResponseData::PostProcessingResponse { .. }) => None, Err(_) => None, } } @@ -1069,6 +1070,7 @@ pub fn get_connector_transaction_id( Ok(types::PaymentsResponseData::ThreeDSEnrollmentResponse { .. }) => None, Ok(types::PaymentsResponseData::MultipleCaptureResponse { .. }) => None, Ok(types::PaymentsResponseData::IncrementalAuthorizationResponse { .. }) => None, + Ok(types::PaymentsResponseData::PostProcessingResponse { .. }) => None, Err(_) => None, } }
2024-03-04T13:21:57Z
## 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 Post-Processing flows for Open banking connectors - Traits and and type changes - #3758 needs to go in first ### 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. Add Plaid MCA with `payment_method` as `open_banking` and `payment_method_type` as `open_banking_pis` ``` curl --location --request POST 'http://localhost:8080/account/merchant_1720607250/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": "some_key", "key1": "some_key" }, "test_mode": false, "disabled": false, "payment_methods_enabled": [ { "payment_method": "open_banking", "payment_method_types": [ { "payment_method_type": "open_banking_pis", "recurring_enabled": false, "installment_payment_enabled": false, "accepted_currencies": { "type": "enable_only", "list": [ "EUR", "GBP" ] } } ] } ], "additional_merchant_data": { "open_banking_recipient_data": { "account_data": { "bacs": { "sort_code": "200000", "account_number": "55779911", "name": "merchant_name" } } } }, "metadata": { "city": "NY", "unit": "246" } }' ``` Response - ``` { "connector_type": "payment_processor", "connector_name": "plaid", "connector_label": "plaid3", "merchant_connector_id": "mca_gVM5IWhLHFsW5q8F3uez", "profile_id": "pro_UgP3FfqWGhfPLuUqYtJF", "connector_account_details": { "auth_type": "BodyKey", "api_key": "Some_key", "key1": "Some_key" }, "payment_methods_enabled": [ { "payment_method": "open_banking", "payment_method_types": [ { "payment_method_type": "open_banking_pis", "payment_experience": null, "card_networks": null, "accepted_currencies": { "type": "enable_only", "list": [ "EUR", "GBP" ] }, "accepted_countries": null, "minimum_amount": null, "maximum_amount": null, "recurring_enabled": false, "installment_payment_enabled": false } ] } ], "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": { "bacs": { "account_number": "55779911", "sort_code": "200000", "name": "merchant_name", "connector_recipient_id": "recipient-id-sandbox-45beb880-9e3d-4ae3-927b-052f5610fd74" } } } } } ``` ## 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 - [ ] I added a [CHANGELOG](/CHANGELOG.md) entry if applicable
926dcd3a3c0f3c09d39767e2a2c5721a42272322
1. Add Plaid MCA with `payment_method` as `open_banking` and `payment_method_type` as `open_banking_pis` ``` curl --location --request POST 'http://localhost:8080/account/merchant_1720607250/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": "some_key", "key1": "some_key" }, "test_mode": false, "disabled": false, "payment_methods_enabled": [ { "payment_method": "open_banking", "payment_method_types": [ { "payment_method_type": "open_banking_pis", "recurring_enabled": false, "installment_payment_enabled": false, "accepted_currencies": { "type": "enable_only", "list": [ "EUR", "GBP" ] } } ] } ], "additional_merchant_data": { "open_banking_recipient_data": { "account_data": { "bacs": { "sort_code": "200000", "account_number": "55779911", "name": "merchant_name" } } } }, "metadata": { "city": "NY", "unit": "246" } }' ``` Response - ``` { "connector_type": "payment_processor", "connector_name": "plaid", "connector_label": "plaid3", "merchant_connector_id": "mca_gVM5IWhLHFsW5q8F3uez", "profile_id": "pro_UgP3FfqWGhfPLuUqYtJF", "connector_account_details": { "auth_type": "BodyKey", "api_key": "Some_key", "key1": "Some_key" }, "payment_methods_enabled": [ { "payment_method": "open_banking", "payment_method_types": [ { "payment_method_type": "open_banking_pis", "payment_experience": null, "card_networks": null, "accepted_currencies": { "type": "enable_only", "list": [ "EUR", "GBP" ] }, "accepted_countries": null, "minimum_amount": null, "maximum_amount": null, "recurring_enabled": false, "installment_payment_enabled": false } ] } ], "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": { "bacs": { "account_number": "55779911", "sort_code": "200000", "name": "merchant_name", "connector_recipient_id": "recipient-id-sandbox-45beb880-9e3d-4ae3-927b-052f5610fd74" } } } } } ```
juspay/hyperswitch
juspay__hyperswitch-3585
Bug: refactor: change list roles api to also send inactive merchants
diff --git a/crates/router/src/core/user.rs b/crates/router/src/core/user.rs index 41a407bd670..70c3eb6673b 100644 --- a/crates/router/src/core/user.rs +++ b/crates/router/src/core/user.rs @@ -945,10 +945,13 @@ pub async fn create_merchant_account( pub async fn list_merchant_ids_for_user( state: AppState, - user: auth::UserFromToken, + user_from_token: auth::UserFromToken, ) -> UserResponse<Vec<user_api::UserMerchantAccount>> { - let user_roles = - utils::user_role::get_active_user_roles_for_user(&state, &user.user_id).await?; + let user_roles = state + .store + .list_user_roles_by_user_id(user_from_token.user_id.as_str()) + .await + .change_context(UserErrors::InternalServerError)?; let merchant_accounts = state .store diff --git a/crates/router/src/utils/user_role.rs b/crates/router/src/utils/user_role.rs index 7ca06aeda0d..462d3d01d79 100644 --- a/crates/router/src/utils/user_role.rs +++ b/crates/router/src/utils/user_role.rs @@ -1,11 +1,8 @@ use api_models::user_role as user_role_api; -use diesel_models::{enums::UserStatus, user_role::UserRole}; -use error_stack::ResultExt; use crate::{ consts, core::errors::{UserErrors, UserResult}, - routes::AppState, services::authorization::{ permissions::Permission, predefined_permissions::{self, RoleInfo}, @@ -17,20 +14,6 @@ pub fn is_internal_role(role_id: &str) -> bool { || role_id == consts::user_role::ROLE_ID_INTERNAL_VIEW_ONLY_USER } -pub async fn get_active_user_roles_for_user( - state: &AppState, - user_id: &str, -) -> UserResult<Vec<UserRole>> { - Ok(state - .store - .list_user_roles_by_user_id(user_id) - .await - .change_context(UserErrors::InternalServerError)? - .into_iter() - .filter(|ele| ele.status == UserStatus::Active) - .collect()) -} - pub fn validate_role_id(role_id: &str) -> UserResult<()> { if predefined_permissions::is_role_invitable(role_id) { return Ok(());
2024-02-07T12:48: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 --> Changed switch list api to also send inactive merchants in the 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). --> To use this in this api to get all the merchant details ## 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/switch/list' \ --header 'Authorization: Bearer JWT' ``` This api will send merchants with `is_active`: `false` in the response from now on. ``` [ { "merchant_id": "merchant_1", "merchant_name": null, "is_active": false }, { "merchant_id": "merchant_2", "merchant_name": null, "is_active": 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 - [ ] I added a [CHANGELOG](/CHANGELOG.md) entry if applicable
fbe84b2a334cfb744ae4f27b1eadc892c7f9b164
``` curl --location 'http://localhost:8080/user/switch/list' \ --header 'Authorization: Bearer JWT' ``` This api will send merchants with `is_active`: `false` in the response from now on. ``` [ { "merchant_id": "merchant_1", "merchant_name": null, "is_active": false }, { "merchant_id": "merchant_2", "merchant_name": null, "is_active": true } ] ```
juspay/hyperswitch
juspay__hyperswitch-3577
Bug: [BUG] : store connector mandate id in complete auth ### Bug Description Connector_reference in TransactionResponse of Complete auth call not saved in the DB ### Expected Behavior Store the connector_reference, when it is sent in Complete auth call. ### 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/mandate.rs b/crates/router/src/core/mandate.rs index e564e4a733e..d58eae371e8 100644 --- a/crates/router/src/core/mandate.rs +++ b/crates/router/src/core/mandate.rs @@ -1,7 +1,7 @@ pub mod helpers; pub mod utils; use api_models::payments; -use common_utils::{ext_traits::Encode, pii}; +use common_utils::ext_traits::Encode; use diesel_models::{enums as storage_enums, Mandate}; use error_stack::{report, IntoReport, ResultExt}; use futures::future; @@ -24,7 +24,7 @@ use crate::{ ConnectorData, GetToken, }, domain, storage, - transformers::ForeignTryFrom, + transformers::ForeignFrom, }, utils::OptionExt, }; @@ -154,25 +154,46 @@ pub async fn revoke_mandate( pub async fn update_connector_mandate_id( db: &dyn StorageInterface, merchant_account: String, - mandate_ids_opt: Option<api_models::payments::MandateIds>, + mandate_ids_opt: Option<String>, + payment_method_id: Option<String>, resp: Result<types::PaymentsResponseData, types::ErrorResponse>, ) -> RouterResponse<mandates::MandateResponse> { - let connector_mandate_id = Option::foreign_try_from(resp)?; + let mandate_details = Option::foreign_from(resp); + let connector_mandate_id = mandate_details + .clone() + .map(|md| { + Encode::<types::MandateReference>::encode_to_value(&md) + .change_context(errors::ApiErrorResponse::InternalServerError) + .map(masking::Secret::new) + }) + .transpose()?; + //Ignore updation if the payment_attempt mandate_id or connector_mandate_id is not present - if let Some((mandate_ids, connector_id)) = mandate_ids_opt.zip(connector_mandate_id) { - let mandate_id = &mandate_ids.mandate_id; + if let Some((mandate_id, connector_id)) = mandate_ids_opt.zip(connector_mandate_id) { let mandate = db - .find_mandate_by_merchant_id_mandate_id(&merchant_account, mandate_id) + .find_mandate_by_merchant_id_mandate_id(&merchant_account, &mandate_id) .await .change_context(errors::ApiErrorResponse::MandateNotFound)?; + + let update_mandate_details = match payment_method_id { + Some(pmd_id) => storage::MandateUpdate::ConnectorMandateIdUpdate { + connector_mandate_id: mandate_details + .and_then(|mandate_reference| mandate_reference.connector_mandate_id), + connector_mandate_ids: Some(connector_id), + payment_method_id: pmd_id, + original_payment_id: None, + }, + None => storage::MandateUpdate::ConnectorReferenceUpdate { + connector_mandate_ids: Some(connector_id), + }, + }; + // only update the connector_mandate_id if existing is none if mandate.connector_mandate_id.is_none() { db.update_mandate_by_merchant_id_mandate_id( &merchant_account, - mandate_id, - storage::MandateUpdate::ConnectorReferenceUpdate { - connector_mandate_ids: Some(connector_id), - }, + &mandate_id, + update_mandate_details, ) .await .change_context(errors::ApiErrorResponse::MandateUpdateFailed)?; @@ -454,27 +475,16 @@ pub async fn retrieve_mandates_list( Ok(services::ApplicationResponse::Json(mandates_list)) } -impl ForeignTryFrom<Result<types::PaymentsResponseData, types::ErrorResponse>> - for Option<pii::SecretSerdeValue> +impl ForeignFrom<Result<types::PaymentsResponseData, types::ErrorResponse>> + for Option<types::MandateReference> { - type Error = error_stack::Report<errors::ApiErrorResponse>; - fn foreign_try_from( - resp: Result<types::PaymentsResponseData, types::ErrorResponse>, - ) -> errors::RouterResult<Self> { - let mandate_details = match resp { + fn foreign_from(resp: Result<types::PaymentsResponseData, types::ErrorResponse>) -> Self { + match resp { Ok(types::PaymentsResponseData::TransactionResponse { mandate_reference, .. }) => mandate_reference, _ => None, - }; - - mandate_details - .map(|md| { - Encode::<types::MandateReference>::encode_to_value(&md) - .change_context(errors::ApiErrorResponse::MandateNotFound) - .map(masking::Secret::new) - }) - .transpose() + } } } diff --git a/crates/router/src/core/payments/operations/payment_response.rs b/crates/router/src/core/payments/operations/payment_response.rs index e5552f0d156..0666c921422 100644 --- a/crates/router/src/core/payments/operations/payment_response.rs +++ b/crates/router/src/core/payments/operations/payment_response.rs @@ -819,17 +819,27 @@ async fn payment_response_update_tracker<F: Clone, T: types::Capturable>( .in_current_span(), ); - // When connector requires redirection for mandate creation it can update the connector mandate_id during Psync + // When connector requires redirection for mandate creation it can update the connector mandate_id during Psync and CompleteAuthorize let m_db = state.clone().store; + let m_payment_method_id = payment_data.payment_attempt.payment_method_id.clone(); let m_router_data_merchant_id = router_data.merchant_id.clone(); - let m_payment_data_mandate_id = payment_data.mandate_id.clone(); + let m_payment_data_mandate_id = + payment_data + .payment_attempt + .mandate_id + .clone() + .or(payment_data + .mandate_id + .clone() + .map(|mandate_ids| mandate_ids.mandate_id)); let m_router_data_response = router_data.response.clone(); let mandate_update_fut = tokio::spawn( async move { mandate::update_connector_mandate_id( m_db.as_ref(), - m_router_data_merchant_id, + m_router_data_merchant_id.clone(), m_payment_data_mandate_id, + m_payment_method_id, m_router_data_response, ) .await
2024-02-07T09:46:28Z
## 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 --> In this PR we store the connector_reference, when it is sent in Complete auth call. ## Test Case 1. Make a 3ds mandate payment with Cybersource ``` curl --location 'http://localhost:8080/payments' \ --header 'Content-Type: application/json' \ --header 'Accept: application/json' \ --header 'api-key:{{api_key}}' \ --data-raw '{ "amount": 0, "currency": "PLN", "confirm": true, "business_country": "US", "business_label": "default", "capture_method": "automatic", "customer_id": "abc", "capture_on": "2022-09-10T10:11:12Z", "authentication_type": "three_ds", "return_url": "https://hs-payments-test.netlify.app/payments", "email": "sdh@xyz.in", "name": "John Doe", "phone": "999999999", "phone_country_code": "+65", "description": "Its my first payment request", "statement_descriptor_name": "Juspay", "statement_descriptor_suffix": "Router", "setup_future_usage": "off_session", "payment_method": "card", "payment_method_type": "credit", "payment_type": "setup_mandate", "payment_method_data": { "card": { "card_number": "4622943127013705", "card_exp_month": "12", "card_exp_year": "2030", "card_holder_name": "joseph Doe", "card_cvc": "838" } }, "billing": { "address": { "line1": "1467", "line2": "CA", "line3": "Harrison Street", "city": "San Fransico", "state": "New York", "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" }, "metadata": { "order_details": { "product_name": "Apple iphone 15", "quantity": 1, "amount": 3200, "account_name": "transaction_processing" } }, "mandate_data": { "customer_acceptance": { "acceptance_type": "offline", "accepted_at": "1963-05-03T04:07:52.723Z", "online": { "ip_address": "13.232.74.226", "user_agent": "amet irure esse" } } , "mandate_type": { "multi_use": { "amount": 700, "currency": "USD" } } } }' ``` <img width="1138" alt="Screenshot 2024-02-07 at 3 08 57 PM" src="https://github.com/juspay/hyperswitch/assets/131388445/f25a3624-f6e7-477f-8a1f-28c569a770b9"> mandate id should be stored in the mandate table <img width="1380" alt="Screenshot 2024-02-07 at 3 09 18 PM" src="https://github.com/juspay/hyperswitch/assets/131388445/60033b46-11db-45e9-ad52-84729862b646"> DB Query ``` SELECT * FROM mandate WHERE mandate.original_payment_id = '{payment_id}'; ``` ## Flows Impacted 1. Normal payment 2. Setup mandate 3. Recurring mandate (both customer initiated and merchant initiated) 4. Flows where connector mandate reference is updated in the psync call or after redirection complete (Cybersource 3ds) ## 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 - [ ] I added a [CHANGELOG](/CHANGELOG.md) entry if applicable
5fb3c001b5dc371f81fe1708fd9a6c6978fb726e
juspay/hyperswitch
juspay__hyperswitch-3582
Bug: Logging framework - add connector name for all payment CRUD API calls Add connector name labels for payment CRUD (create/confirm/void/redirect/update/retrieve) API’s to ES
diff --git a/crates/router/src/services/api.rs b/crates/router/src/services/api.rs index 3730c5bf9a4..feaa59485d6 100644 --- a/crates/router/src/services/api.rs +++ b/crates/router/src/services/api.rs @@ -265,7 +265,7 @@ pub enum CaptureSyncMethod { /// Handle the flow by interacting with connector module /// `connector_request` is applicable only in case if the `CallConnectorAction` is `Trigger` /// In other cases, It will be created if required, even if it is not passed -#[instrument(skip_all, fields(payment_method))] +#[instrument(skip_all, fields(connector_name, payment_method))] pub async fn execute_connector_processing_step< 'b, 'a, @@ -285,6 +285,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()); logger::debug!(connector_request=?connector_request); let mut router_data = req.clone();
2024-02-07T12:22:20Z
## 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 --> Adding connector_name from the moment its available into logs for better search on ELS/Loki ### 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. ![image (7)](https://github.com/juspay/hyperswitch/assets/104988143/dcc4d690-124c-4cea-8c2c-80092c0758eb) 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 payment confirm api call check for `connector_name` field in golden_log_line (can search loki with `{golden_log_line="true"}` query and find the log with request_id) Impacted Area -> Application IO level logs ![image](https://github.com/juspay/hyperswitch/assets/21202349/1fe15d2f-187a-4525-8674-eca623da43a6) ## 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 - [ ] I added a [CHANGELOG](/CHANGELOG.md) entry if applicable
c5343dfcc20f1000e319c62fa0341c46701595ff
make a payment confirm api call check for `connector_name` field in golden_log_line (can search loki with `{golden_log_line="true"}` query and find the log with request_id) Impacted Area -> Application IO level logs ![image](https://github.com/juspay/hyperswitch/assets/21202349/1fe15d2f-187a-4525-8674-eca623da43a6)
juspay/hyperswitch
juspay__hyperswitch-3553
Bug: [FIX] dont return true in case health check is not done on the component Whenever a component is disabled we don't have to check for it's health so return false in case if we didn't check it
diff --git a/crates/api_models/src/health_check.rs b/crates/api_models/src/health_check.rs index 6b0297b655f..29a59df397e 100644 --- a/crates/api_models/src/health_check.rs +++ b/crates/api_models/src/health_check.rs @@ -2,7 +2,8 @@ pub struct RouterHealthCheckResponse { pub database: bool, pub redis: bool, - pub locker: bool, + #[serde(skip_serializing_if = "Option::is_none")] + pub vault: Option<bool>, #[cfg(feature = "olap")] pub analytics: bool, pub outgoing_request: bool, @@ -17,4 +18,28 @@ pub struct SchedulerHealthCheckResponse { pub outgoing_request: bool, } +pub enum HealthState { + Running, + Error, + NotApplicable, +} + +impl From<HealthState> for bool { + fn from(value: HealthState) -> Self { + match value { + HealthState::Running => true, + HealthState::Error | HealthState::NotApplicable => false, + } + } +} +impl From<HealthState> for Option<bool> { + fn from(value: HealthState) -> Self { + match value { + HealthState::Running => Some(true), + HealthState::Error => Some(false), + HealthState::NotApplicable => None, + } + } +} + impl common_utils::events::ApiEventMetric for SchedulerHealthCheckResponse {} diff --git a/crates/router/src/core/health_check.rs b/crates/router/src/core/health_check.rs index bc523b4fba6..3be764ef66b 100644 --- a/crates/router/src/core/health_check.rs +++ b/crates/router/src/core/health_check.rs @@ -1,5 +1,6 @@ #[cfg(feature = "olap")] use analytics::health_check::HealthCheck; +use api_models::health_check::HealthState; use error_stack::ResultExt; use router_env::logger; @@ -12,23 +13,27 @@ use crate::{ #[async_trait::async_trait] pub trait HealthCheckInterface { - async fn health_check_db(&self) -> CustomResult<(), errors::HealthCheckDBError>; - async fn health_check_redis(&self) -> CustomResult<(), errors::HealthCheckRedisError>; - async fn health_check_locker(&self) -> CustomResult<(), errors::HealthCheckLockerError>; - async fn health_check_outgoing(&self) -> CustomResult<(), errors::HealthCheckOutGoing>; + async fn health_check_db(&self) -> CustomResult<HealthState, errors::HealthCheckDBError>; + async fn health_check_redis(&self) -> CustomResult<HealthState, errors::HealthCheckRedisError>; + async fn health_check_locker( + &self, + ) -> CustomResult<HealthState, errors::HealthCheckLockerError>; + async fn health_check_outgoing(&self) + -> CustomResult<HealthState, errors::HealthCheckOutGoing>; #[cfg(feature = "olap")] - async fn health_check_analytics(&self) -> CustomResult<(), errors::HealthCheckDBError>; + async fn health_check_analytics(&self) + -> CustomResult<HealthState, errors::HealthCheckDBError>; } #[async_trait::async_trait] impl HealthCheckInterface for app::AppState { - async fn health_check_db(&self) -> CustomResult<(), errors::HealthCheckDBError> { + async fn health_check_db(&self) -> CustomResult<HealthState, errors::HealthCheckDBError> { let db = &*self.store; db.health_check_db().await?; - Ok(()) + Ok(HealthState::Running) } - async fn health_check_redis(&self) -> CustomResult<(), errors::HealthCheckRedisError> { + async fn health_check_redis(&self) -> CustomResult<HealthState, errors::HealthCheckRedisError> { let db = &*self.store; let redis_conn = db .get_redis_conn() @@ -55,10 +60,12 @@ impl HealthCheckInterface for app::AppState { logger::debug!("Redis delete_key was successful"); - Ok(()) + Ok(HealthState::Running) } - async fn health_check_locker(&self) -> CustomResult<(), errors::HealthCheckLockerError> { + async fn health_check_locker( + &self, + ) -> CustomResult<HealthState, errors::HealthCheckLockerError> { let locker = &self.conf.locker; if !locker.mock_locker { let mut url = locker.host_rs.to_owned(); @@ -67,16 +74,19 @@ impl HealthCheckInterface for app::AppState { services::call_connector_api(self, request) .await .change_context(errors::HealthCheckLockerError::FailedToCallLocker)? - .ok(); + .map_err(|_| { + error_stack::report!(errors::HealthCheckLockerError::FailedToCallLocker) + })?; + Ok(HealthState::Running) + } else { + Ok(HealthState::NotApplicable) } - - logger::debug!("Locker call was successful"); - - Ok(()) } #[cfg(feature = "olap")] - async fn health_check_analytics(&self) -> CustomResult<(), errors::HealthCheckDBError> { + async fn health_check_analytics( + &self, + ) -> CustomResult<HealthState, errors::HealthCheckDBError> { let analytics = &self.pool; match analytics { analytics::AnalyticsProvider::Sqlx(client) => client @@ -107,10 +117,14 @@ impl HealthCheckInterface for app::AppState { .await .change_context(errors::HealthCheckDBError::ClickhouseAnalyticsError) } - } + }?; + + Ok(HealthState::Running) } - async fn health_check_outgoing(&self) -> CustomResult<(), errors::HealthCheckOutGoing> { + async fn health_check_outgoing( + &self, + ) -> CustomResult<HealthState, errors::HealthCheckOutGoing> { let request = services::Request::new(services::Method::Get, consts::OUTGOING_CALL_URL); services::call_connector_api(self, request) .await @@ -125,6 +139,6 @@ impl HealthCheckInterface for app::AppState { })?; logger::debug!("Outgoing request successful"); - Ok(()) + Ok(HealthState::Running) } } diff --git a/crates/router/src/routes/health.rs b/crates/router/src/routes/health.rs index 2183ab07fed..a00ba011bff 100644 --- a/crates/router/src/routes/health.rs +++ b/crates/router/src/routes/health.rs @@ -45,7 +45,7 @@ async fn deep_health_check_func(state: app::AppState) -> RouterResponse<RouterHe logger::debug!("Database health check begin"); - let db_status = state.health_check_db().await.map(|_| true).map_err(|err| { + let db_status = state.health_check_db().await.map_err(|err| { error_stack::report!(errors::ApiErrorResponse::HealthCheckError { component: "Database", message: err.to_string() @@ -56,64 +56,48 @@ async fn deep_health_check_func(state: app::AppState) -> RouterResponse<RouterHe logger::debug!("Redis health check begin"); - let redis_status = state - .health_check_redis() - .await - .map(|_| true) - .map_err(|err| { - error_stack::report!(errors::ApiErrorResponse::HealthCheckError { - component: "Redis", - message: err.to_string() - }) - })?; + let redis_status = state.health_check_redis().await.map_err(|err| { + error_stack::report!(errors::ApiErrorResponse::HealthCheckError { + component: "Redis", + message: err.to_string() + }) + })?; logger::debug!("Redis health check end"); logger::debug!("Locker health check begin"); - let locker_status = state - .health_check_locker() - .await - .map(|_| true) - .map_err(|err| { - error_stack::report!(errors::ApiErrorResponse::HealthCheckError { - component: "Locker", - message: err.to_string() - }) - })?; + let locker_status = state.health_check_locker().await.map_err(|err| { + error_stack::report!(errors::ApiErrorResponse::HealthCheckError { + component: "Locker", + message: err.to_string() + }) + })?; #[cfg(feature = "olap")] - let analytics_status = state - .health_check_analytics() - .await - .map(|_| true) - .map_err(|err| { - error_stack::report!(errors::ApiErrorResponse::HealthCheckError { - component: "Analytics", - message: err.to_string() - }) - })?; - - let outgoing_check = state - .health_check_outgoing() - .await - .map(|_| true) - .map_err(|err| { - error_stack::report!(errors::ApiErrorResponse::HealthCheckError { - component: "Outgoing Request", - message: err.to_string() - }) - })?; + let analytics_status = state.health_check_analytics().await.map_err(|err| { + error_stack::report!(errors::ApiErrorResponse::HealthCheckError { + component: "Analytics", + message: err.to_string() + }) + })?; + + let outgoing_check = state.health_check_outgoing().await.map_err(|err| { + error_stack::report!(errors::ApiErrorResponse::HealthCheckError { + component: "Outgoing Request", + message: err.to_string() + }) + })?; logger::debug!("Locker health check end"); let response = RouterHealthCheckResponse { - database: db_status, - redis: redis_status, - locker: locker_status, + database: db_status.into(), + redis: redis_status.into(), + vault: locker_status.into(), #[cfg(feature = "olap")] - analytics: analytics_status, - outgoing_request: outgoing_check, + analytics: analytics_status.into(), + outgoing_request: outgoing_check.into(), }; Ok(api::ApplicationResponse::Json(response))
2024-02-05T11:48:10Z
## Type of Change <!-- Put an `x` in the boxes that apply --> - [x] Bugfix ## Description <!-- Describe your changes in detail --> Don't return true on the places where checks or not applicable ## 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 fixes misconception in health check where it would return true even in case if the case is not checked. ## 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)? --> - Disable locker in config ```bash curl --location 'http://localhost:8080/health/ready' ``` <img width="1305" alt="Screenshot 2024-02-07 at 2 55 21 PM" src="https://github.com/juspay/hyperswitch/assets/43412619/27a2a956-a57a-4a1b-a6cf-d2b0e602017d"> **THIS CANNOT BE TESTED IN SANDBOX** ## 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
d3fb705ed241a216cbe53de1886d18506bff68bc
- Disable locker in config ```bash curl --location 'http://localhost:8080/health/ready' ``` <img width="1305" alt="Screenshot 2024-02-07 at 2 55 21 PM" src="https://github.com/juspay/hyperswitch/assets/43412619/27a2a956-a57a-4a1b-a6cf-d2b0e602017d"> **THIS CANNOT BE TESTED IN SANDBOX**
juspay/hyperswitch
juspay__hyperswitch-3562
Bug: chore(analytics): create a seperate flow for a force sync Currently we use PaymentRetrieve for GET /payment/:id call, for force_sync use cases we should have a separate flow since the underlying execution differs significantly...
diff --git a/crates/router/src/compatibility/stripe/payment_intents.rs b/crates/router/src/compatibility/stripe/payment_intents.rs index d67166c0d04..87560032ea4 100644 --- a/crates/router/src/compatibility/stripe/payment_intents.rs +++ b/crates/router/src/compatibility/stripe/payment_intents.rs @@ -71,7 +71,7 @@ pub async fn payment_intents_create( )) .await } -#[instrument(skip_all, fields(flow = ?Flow::PaymentsRetrieve))] +#[instrument(skip_all, fields(flow = ?Flow::PaymentsRetrieveForceSync))] pub async fn payment_intents_retrieve( state: web::Data<routes::AppState>, req: HttpRequest, @@ -96,7 +96,7 @@ pub async fn payment_intents_retrieve( Err(err) => return api::log_and_return_error_response(report!(err)), }; - let flow = Flow::PaymentsRetrieve; + let flow = Flow::PaymentsRetrieveForceSync; let locking_action = payload.get_locking_input(flow.clone()); Box::pin(wrap::compatibility_api_wrap::< _, @@ -131,7 +131,7 @@ pub async fn payment_intents_retrieve( )) .await } -#[instrument(skip_all, fields(flow = ?Flow::PaymentsRetrieve))] +#[instrument(skip_all, fields(flow))] pub async fn payment_intents_retrieve_with_gateway_creds( state: web::Data<routes::AppState>, qs_config: web::Data<serde_qs::Config>, @@ -160,7 +160,13 @@ pub async fn payment_intents_retrieve_with_gateway_creds( Err(err) => return api::log_and_return_error_response(report!(err)), }; - let flow = Flow::PaymentsRetrieve; + let flow = match json_payload.force_sync { + Some(true) => Flow::PaymentsRetrieveForceSync, + _ => Flow::PaymentsRetrieve, + }; + + tracing::Span::current().record("flow", &flow.to_string()); + let locking_action = payload.get_locking_input(flow.clone()); Box::pin(wrap::compatibility_api_wrap::< _, diff --git a/crates/router/src/compatibility/stripe/refunds.rs b/crates/router/src/compatibility/stripe/refunds.rs index 77c3a61fa78..80ebbc4f84d 100644 --- a/crates/router/src/compatibility/stripe/refunds.rs +++ b/crates/router/src/compatibility/stripe/refunds.rs @@ -57,14 +57,14 @@ pub async fn refund_create( )) .await } -#[instrument(skip_all, fields(flow = ?Flow::RefundsRetrieve))] +#[instrument(skip_all, fields(flow))] pub async fn refund_retrieve_with_gateway_creds( state: web::Data<routes::AppState>, qs_config: web::Data<serde_qs::Config>, req: HttpRequest, form_payload: web::Bytes, ) -> HttpResponse { - let refund_request = match qs_config + let refund_request: refund_types::RefundsRetrieveRequest = match qs_config .deserialize_bytes(&form_payload) .map_err(|err| report!(errors::StripeErrorCode::from(err))) { @@ -72,7 +72,12 @@ pub async fn refund_retrieve_with_gateway_creds( Err(err) => return api::log_and_return_error_response(err), }; - let flow = Flow::RefundsRetrieve; + let flow = match refund_request.force_sync { + Some(true) => Flow::RefundsRetrieveForceSync, + _ => Flow::RefundsRetrieve, + }; + + tracing::Span::current().record("flow", &flow.to_string()); Box::pin(wrap::compatibility_api_wrap::< _, @@ -103,7 +108,7 @@ pub async fn refund_retrieve_with_gateway_creds( )) .await } -#[instrument(skip_all, fields(flow = ?Flow::RefundsRetrieve))] +#[instrument(skip_all, fields(flow = ?Flow::RefundsRetrieveForceSync))] pub async fn refund_retrieve( state: web::Data<routes::AppState>, req: HttpRequest, @@ -115,7 +120,7 @@ pub async fn refund_retrieve( merchant_connector_details: None, }; - let flow = Flow::RefundsRetrieve; + let flow = Flow::RefundsRetrieveForceSync; Box::pin(wrap::compatibility_api_wrap::< _, diff --git a/crates/router/src/compatibility/stripe/setup_intents.rs b/crates/router/src/compatibility/stripe/setup_intents.rs index 515e41ec91f..6522dc4697c 100644 --- a/crates/router/src/compatibility/stripe/setup_intents.rs +++ b/crates/router/src/compatibility/stripe/setup_intents.rs @@ -78,7 +78,7 @@ pub async fn setup_intents_create( )) .await } -#[instrument(skip_all, fields(flow = ?Flow::PaymentsRetrieve))] +#[instrument(skip_all, fields(flow = ?Flow::PaymentsRetrieveForceSync))] pub async fn setup_intents_retrieve( state: web::Data<routes::AppState>, req: HttpRequest, @@ -103,7 +103,7 @@ pub async fn setup_intents_retrieve( Err(err) => return api::log_and_return_error_response(report!(err)), }; - let flow = Flow::PaymentsRetrieve; + let flow = Flow::PaymentsRetrieveForceSync; Box::pin(wrap::compatibility_api_wrap::< _, diff --git a/crates/router/src/routes/lock_utils.rs b/crates/router/src/routes/lock_utils.rs index 9471289a0c8..6b2fa3046a3 100644 --- a/crates/router/src/routes/lock_utils.rs +++ b/crates/router/src/routes/lock_utils.rs @@ -102,6 +102,7 @@ impl From<Flow> for ApiIdentifier { Flow::PaymentsCreate | Flow::PaymentsRetrieve + | Flow::PaymentsRetrieveForceSync | Flow::PaymentsUpdate | Flow::PaymentsConfirm | Flow::PaymentsCapture @@ -123,6 +124,7 @@ impl From<Flow> for ApiIdentifier { Flow::RefundsCreate | Flow::RefundsRetrieve + | Flow::RefundsRetrieveForceSync | Flow::RefundsUpdate | Flow::RefundsList => Self::Refunds, diff --git a/crates/router/src/routes/payments.rs b/crates/router/src/routes/payments.rs index b822e6d4e68..24849d828e2 100644 --- a/crates/router/src/routes/payments.rs +++ b/crates/router/src/routes/payments.rs @@ -229,7 +229,7 @@ pub async fn payments_start( operation_id = "Retrieve a Payment", security(("api_key" = []), ("publishable_key" = [])) )] -#[instrument(skip(state, req), fields(flow = ?Flow::PaymentsRetrieve, payment_id))] +#[instrument(skip(state, req), fields(flow, payment_id))] // #[get("/{payment_id}")] pub async fn payments_retrieve( state: web::Data<app::AppState>, @@ -237,7 +237,10 @@ pub async fn payments_retrieve( path: web::Path<String>, json_payload: web::Query<payment_types::PaymentRetrieveBody>, ) -> impl Responder { - let flow = Flow::PaymentsRetrieve; + let flow = match json_payload.force_sync { + Some(true) => Flow::PaymentsRetrieveForceSync, + _ => Flow::PaymentsRetrieve, + }; let payload = payment_types::PaymentsRetrieveRequest { resource_id: payment_types::PaymentIdType::PaymentIntentId(path.to_string()), merchant_id: json_payload.merchant_id.clone(), @@ -249,6 +252,7 @@ pub async fn payments_retrieve( }; 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) { @@ -300,7 +304,7 @@ pub async fn payments_retrieve( operation_id = "Retrieve a Payment", security(("api_key" = [])) )] -#[instrument(skip(state, req), fields(flow = ?Flow::PaymentsRetrieve, payment_id))] +#[instrument(skip(state, req), fields(flow, payment_id))] // #[post("/sync")] pub async fn payments_retrieve_with_gateway_creds( state: web::Data<app::AppState>, @@ -320,9 +324,13 @@ pub async fn payments_retrieve_with_gateway_creds( merchant_connector_details: json_payload.merchant_connector_details.clone(), ..Default::default() }; - let flow = Flow::PaymentsRetrieve; + let flow = match json_payload.force_sync { + Some(true) => Flow::PaymentsRetrieveForceSync, + _ => Flow::PaymentsRetrieve, + }; tracing::Span::current().record("payment_id", &json_payload.payment_id); + 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 47e9f2bf42a..ef9ffb41124 100644 --- a/crates/router/src/routes/refunds.rs +++ b/crates/router/src/routes/refunds.rs @@ -63,7 +63,7 @@ pub async fn refunds_create( operation_id = "Retrieve a Refund", security(("api_key" = [])) )] -#[instrument(skip_all, fields(flow = ?Flow::RefundsRetrieve))] +#[instrument(skip_all, fields(flow))] // #[get("/{id}")] pub async fn refunds_retrieve( state: web::Data<AppState>, @@ -76,7 +76,12 @@ pub async fn refunds_retrieve( force_sync: query_params.force_sync, merchant_connector_details: None, }; - let flow = Flow::RefundsRetrieve; + let flow = match query_params.force_sync { + Some(true) => Flow::RefundsRetrieveForceSync, + _ => Flow::RefundsRetrieve, + }; + + tracing::Span::current().record("flow", &flow.to_string()); Box::pin(api::server_wrap( flow, @@ -115,14 +120,20 @@ pub async fn refunds_retrieve( operation_id = "Retrieve a Refund", security(("api_key" = [])) )] -#[instrument(skip_all, fields(flow = ?Flow::RefundsRetrieve))] +#[instrument(skip_all, fields(flow))] // #[post("/sync")] pub async fn refunds_retrieve_with_body( state: web::Data<AppState>, req: HttpRequest, json_payload: web::Json<refunds::RefundsRetrieveRequest>, ) -> HttpResponse { - let flow = Flow::RefundsRetrieve; + let flow = match json_payload.force_sync { + Some(true) => Flow::RefundsRetrieveForceSync, + _ => Flow::RefundsRetrieve, + }; + + tracing::Span::current().record("flow", &flow.to_string()); + Box::pin(api::server_wrap( flow, state, diff --git a/crates/router_env/src/logger/types.rs b/crates/router_env/src/logger/types.rs index 62c09c42455..93b1ef6cdce 100644 --- a/crates/router_env/src/logger/types.rs +++ b/crates/router_env/src/logger/types.rs @@ -127,6 +127,8 @@ pub enum Flow { PaymentsCreate, /// Payments Retrieve flow. PaymentsRetrieve, + /// Payments Retrieve force sync flow. + PaymentsRetrieveForceSync, /// Payments update flow. PaymentsUpdate, /// Payments confirm flow. @@ -168,6 +170,8 @@ pub enum Flow { RefundsCreate, /// Refunds retrieve flow. RefundsRetrieve, + /// Refunds retrieve force sync flow. + RefundsRetrieveForceSync, /// Refunds update flow. RefundsUpdate, /// Refunds list flow.
2024-02-06T11:17:50Z
Currently we use PaymentRetrieve for GET /payment/:id call, for force_sync use cases we should have a separate flow since the underlying execution differs significantly... Refs: #3562 ## 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 --> Currently we don't show payment retrieve call logs in the audit logs but we want to display the force retrieve calls so we have created the separate flow when the flow is force retrieve. ### 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)? --> hit a payment/refunds/dispute retrieve call with a force sync flag as true and in the logs u get to see the enum contains force retrieve in it ex- `RefundsRetriveForceSync` when we do a refunds or payment retrive call with the force_sync flag as true , the debugger will display the `RefundsRetriveForceSync` in the flow type ``` curl --location '<url>/refunds/<refund_id>?force_sync=true' \ --header 'Accept: */*' \ --header 'Accept-Language: en-GB,en-US;q=0.9,en;q=0.8' \ --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/121.0.0.0 Safari/537.36' \ --header 'api-key: hyperswitch' \ --header 'authorization: Bearer <token>' \ --header 'sec-ch-ua-mobile: ?0' \ --header 'sec-ch-ua-platform: "macOS"' ``` ![image](https://github.com/juspay/hyperswitch/assets/126486299/1e52a232-1de1-4ce0-b03a-ae33d988795a) ## 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 - [ ] I added a [CHANGELOG](/CHANGELOG.md) entry if applicable
53559c22527dde9536aa493ad7cd3bf353335c1a
hit a payment/refunds/dispute retrieve call with a force sync flag as true and in the logs u get to see the enum contains force retrieve in it ex- `RefundsRetriveForceSync` when we do a refunds or payment retrive call with the force_sync flag as true , the debugger will display the `RefundsRetriveForceSync` in the flow type ``` curl --location '<url>/refunds/<refund_id>?force_sync=true' \ --header 'Accept: */*' \ --header 'Accept-Language: en-GB,en-US;q=0.9,en;q=0.8' \ --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/121.0.0.0 Safari/537.36' \ --header 'api-key: hyperswitch' \ --header 'authorization: Bearer <token>' \ --header 'sec-ch-ua-mobile: ?0' \ --header 'sec-ch-ua-platform: "macOS"' ``` ![image](https://github.com/juspay/hyperswitch/assets/126486299/1e52a232-1de1-4ce0-b03a-ae33d988795a)
juspay/hyperswitch
juspay__hyperswitch-3558
Bug: feat(analytics): refunds and disputes audit rail
diff --git a/crates/analytics/src/api_event/events.rs b/crates/analytics/src/api_event/events.rs index eb9b2d561c5..4be3a3420da 100644 --- a/crates/analytics/src/api_event/events.rs +++ b/crates/analytics/src/api_event/events.rs @@ -33,9 +33,30 @@ where .add_filter_clause("merchant_id", merchant_id) .switch()?; match query_param.query_param { - QueryType::Payment { payment_id } => query_builder - .add_filter_clause("payment_id", payment_id) - .switch()?, + QueryType::Payment { payment_id } => { + query_builder + .add_filter_clause("payment_id", payment_id) + .switch()?; + query_builder + .add_filter_in_range_clause( + "api_flow", + &[ + Flow::PaymentsCancel, + Flow::PaymentsCapture, + Flow::PaymentsConfirm, + Flow::PaymentsCreate, + Flow::PaymentsStart, + Flow::PaymentsUpdate, + Flow::RefundsCreate, + Flow::RefundsUpdate, + Flow::DisputesEvidenceSubmit, + Flow::AttachDisputeEvidence, + Flow::RetrieveDisputeEvidence, + Flow::IncomingWebhookReceive, + ], + ) + .switch()?; + } QueryType::Refund { payment_id, refund_id, @@ -46,28 +67,31 @@ where query_builder .add_filter_clause("refund_id", refund_id) .switch()?; + query_builder + .add_filter_in_range_clause("api_flow", &[Flow::RefundsCreate, Flow::RefundsUpdate]) + .switch()?; + } + QueryType::Dispute { + payment_id, + dispute_id, + } => { + query_builder + .add_filter_clause("payment_id", payment_id) + .switch()?; + query_builder + .add_filter_clause("dispute_id", dispute_id) + .switch()?; + query_builder + .add_filter_in_range_clause( + "api_flow", + &[ + Flow::DisputesEvidenceSubmit, + Flow::AttachDisputeEvidence, + Flow::RetrieveDisputeEvidence, + ], + ) + .switch()?; } - } - if let Some(list_api_name) = query_param.api_name_filter { - query_builder - .add_filter_in_range_clause("api_flow", &list_api_name) - .switch()?; - } else { - query_builder - .add_filter_in_range_clause( - "api_flow", - &[ - Flow::PaymentsCancel, - Flow::PaymentsCapture, - Flow::PaymentsConfirm, - Flow::PaymentsCreate, - Flow::PaymentsStart, - Flow::PaymentsUpdate, - Flow::RefundsCreate, - Flow::IncomingWebhookReceive, - ], - ) - .switch()?; } //TODO!: update the execute_query function to return reports instead of plain errors... query_builder diff --git a/crates/api_models/src/analytics/api_event.rs b/crates/api_models/src/analytics/api_event.rs index 62fe829f01b..5fe8e4ff3a7 100644 --- a/crates/api_models/src/analytics/api_event.rs +++ b/crates/api_models/src/analytics/api_event.rs @@ -8,7 +8,6 @@ use super::{NameDescription, TimeRange}; pub struct ApiLogsRequest { #[serde(flatten)] pub query_param: QueryType, - pub api_name_filter: Option<Vec<String>>, } pub enum FilterType { @@ -27,6 +26,10 @@ pub enum QueryType { payment_id: String, refund_id: String, }, + Dispute { + payment_id: String, + dispute_id: String, + }, } #[derive(
2024-01-31T06:47:14Z
## 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 api_logs for refunds and disputes and same for connector_outgoing_events and webhook_events logs. ### 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). --> ## 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)? --> to test api_events for refunds ```curl curl --location '<base_url>/analytics/v1/api_event_logs?type=Refund&payment_id=<payment_id>&refund_id=<refund_id>' \ --header 'Accept: */*' \ --header 'Accept-Language: en-GB,en-US;q=0.9,en;q=0.8' \ --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/120.0.0.0 Safari/537.36' \ --header 'api-key: hyperswitch' \ --header 'authorization: Bearer <token>"' \ --header 'sec-ch-ua-mobile: ?0' \ --header 'sec-ch-ua-platform: "macOS"'` <img width="1132" alt="Screenshot 2024-01-31 at 1 50 21 PM" src="https://github.com/juspay/hyperswitch/assets/126486299/318b9a07-d350-4741-8c78-8c1922e014db"> ``` for disputes ```curl curl --location '<base_url>/analytics/v1/api_event_logs?type=Dispute&dispute_id=<dispute_id>' \ --header 'Accept: */*' \ --header 'Accept-Language: en-GB,en-US;q=0.9,en;q=0.8' \ --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/120.0.0.0 Safari/537.36' \ --header 'api-key: hyperswitch' \ --header 'authorization: Bearer <token>"' \ --header 'sec-ch-ua-mobile: ?0' \ --header 'sec-ch-ua-platform: "macOS"' ``` ## 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 - [ ] I added a [CHANGELOG](/CHANGELOG.md) entry if applicable
fbe84b2a334cfb744ae4f27b1eadc892c7f9b164
to test api_events for refunds ```curl curl --location '<base_url>/analytics/v1/api_event_logs?type=Refund&payment_id=<payment_id>&refund_id=<refund_id>' \ --header 'Accept: */*' \ --header 'Accept-Language: en-GB,en-US;q=0.9,en;q=0.8' \ --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/120.0.0.0 Safari/537.36' \ --header 'api-key: hyperswitch' \ --header 'authorization: Bearer <token>"' \ --header 'sec-ch-ua-mobile: ?0' \ --header 'sec-ch-ua-platform: "macOS"'` <img width="1132" alt="Screenshot 2024-01-31 at 1 50 21 PM" src="https://github.com/juspay/hyperswitch/assets/126486299/318b9a07-d350-4741-8c78-8c1922e014db"> ``` for disputes ```curl curl --location '<base_url>/analytics/v1/api_event_logs?type=Dispute&dispute_id=<dispute_id>' \ --header 'Accept: */*' \ --header 'Accept-Language: en-GB,en-US;q=0.9,en;q=0.8' \ --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/120.0.0.0 Safari/537.36' \ --header 'api-key: hyperswitch' \ --header 'authorization: Bearer <token>"' \ --header 'sec-ch-ua-mobile: ?0' \ --header 'sec-ch-ua-platform: "macOS"' ```
juspay/hyperswitch
juspay__hyperswitch-3573
Bug: feat: force password for user Support to have a check whether for newly invited users, whether the password has been changed once or not. This will be limited to users with email feature flag disabled.
diff --git a/crates/api_models/src/user/dashboard_metadata.rs b/crates/api_models/src/user/dashboard_metadata.rs index 11588bbfbaf..66831c7aeb8 100644 --- a/crates/api_models/src/user/dashboard_metadata.rs +++ b/crates/api_models/src/user/dashboard_metadata.rs @@ -24,6 +24,8 @@ pub enum SetMetaDataRequest { ConfigureWoocom, SetupWoocomWebhook, IsMultipleConfiguration, + #[serde(skip)] + IsChangePasswordRequired, } #[derive(Debug, serde::Deserialize, serde::Serialize)] @@ -110,6 +112,7 @@ pub enum GetMetaDataRequest { ConfigureWoocom, SetupWoocomWebhook, IsMultipleConfiguration, + IsChangePasswordRequired, } #[derive(Debug, serde::Deserialize, serde::Serialize)] @@ -146,4 +149,5 @@ pub enum GetMetaDataResponse { ConfigureWoocom(bool), SetupWoocomWebhook(bool), IsMultipleConfiguration(bool), + IsChangePasswordRequired(bool), } diff --git a/crates/diesel_models/src/enums.rs b/crates/diesel_models/src/enums.rs index babffdbc4a8..93a98dc824b 100644 --- a/crates/diesel_models/src/enums.rs +++ b/crates/diesel_models/src/enums.rs @@ -511,4 +511,5 @@ pub enum DashboardMetadata { ConfigureWoocom, SetupWoocomWebhook, IsMultipleConfiguration, + IsChangePasswordRequired, } diff --git a/crates/diesel_models/src/query/dashboard_metadata.rs b/crates/diesel_models/src/query/dashboard_metadata.rs index b1cb034eb1f..d91a4078128 100644 --- a/crates/diesel_models/src/query/dashboard_metadata.rs +++ b/crates/diesel_models/src/query/dashboard_metadata.rs @@ -105,7 +105,7 @@ impl DashboardMetadata { .await } - pub async fn delete_user_scoped_dashboard_metadata_by_merchant_id( + pub async fn delete_all_user_scoped_dashboard_metadata_by_merchant_id( conn: &PgPooledConn, user_id: String, merchant_id: String, @@ -118,4 +118,20 @@ impl DashboardMetadata { ) .await } + + pub async fn delete_user_scoped_dashboard_metadata_by_merchant_id_data_key( + conn: &PgPooledConn, + user_id: String, + merchant_id: String, + data_key: enums::DashboardMetadata, + ) -> 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::data_key.eq(data_key)), + ) + .await + } } diff --git a/crates/router/src/core/user.rs b/crates/router/src/core/user.rs index 41a407bd670..58d702cbac1 100644 --- a/crates/router/src/core/user.rs +++ b/crates/router/src/core/user.rs @@ -8,8 +8,9 @@ use error_stack::ResultExt; use masking::ExposeInterface; #[cfg(feature = "email")] use router_env::env; -#[cfg(feature = "email")] use router_env::logger; +#[cfg(not(feature = "email"))] +use user_api::dashboard_metadata::SetMetaDataRequest; use super::errors::{UserErrors, UserResponse, UserResult}; #[cfg(feature = "email")] @@ -308,6 +309,20 @@ pub async fn change_password( .await .change_context(UserErrors::InternalServerError)?; + #[cfg(not(feature = "email"))] + { + state + .store + .delete_user_scoped_dashboard_metadata_by_merchant_id_data_key( + &user_from_token.user_id, + &user_from_token.merchant_id, + diesel_models::enums::DashboardMetadata::IsChangePasswordRequired, + ) + .await + .map_err(|e| logger::error!("Error while deleting dashboard metadata {}", e)) + .ok(); + } + Ok(ApplicationResponse::StatusOk) } @@ -475,8 +490,8 @@ pub async fn invite_user( .insert_user_role(UserRoleNew { user_id: new_user.get_user_id().to_owned(), merchant_id: user_from_token.merchant_id.clone(), - role_id: request.role_id, - org_id: user_from_token.org_id, + role_id: request.role_id.clone(), + org_id: 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, @@ -515,6 +530,20 @@ pub async fn invite_user( #[cfg(not(feature = "email"))] { is_email_sent = false; + let invited_user_token = auth::UserFromToken { + user_id: new_user.get_user_id(), + merchant_id: user_from_token.merchant_id, + org_id: user_from_token.org_id, + role_id: request.role_id, + }; + + let set_metadata_request = SetMetaDataRequest::IsChangePasswordRequired; + dashboard_metadata::set_metadata( + state.clone(), + invited_user_token, + set_metadata_request, + ) + .await?; } Ok(ApplicationResponse::Json(user_api::InviteUserResponse { @@ -692,6 +721,17 @@ async fn handle_new_user_invitation( #[cfg(not(feature = "email"))] { is_email_sent = false; + + let invited_user_token = auth::UserFromToken { + user_id: new_user.get_user_id(), + merchant_id: user_from_token.merchant_id.clone(), + org_id: user_from_token.org_id.clone(), + role_id: request.role_id.clone(), + }; + + let set_metadata_request = SetMetaDataRequest::IsChangePasswordRequired; + dashboard_metadata::set_metadata(state.clone(), invited_user_token, set_metadata_request) + .await?; } Ok(InviteMultipleUserResponse { diff --git a/crates/router/src/core/user/dashboard_metadata.rs b/crates/router/src/core/user/dashboard_metadata.rs index 24ff292870e..82f95564768 100644 --- a/crates/router/src/core/user/dashboard_metadata.rs +++ b/crates/router/src/core/user/dashboard_metadata.rs @@ -105,6 +105,9 @@ fn parse_set_request(data_enum: api::SetMetaDataRequest) -> UserResult<types::Me api::SetMetaDataRequest::IsMultipleConfiguration => { Ok(types::MetaData::IsMultipleConfiguration(true)) } + api::SetMetaDataRequest::IsChangePasswordRequired => { + Ok(types::MetaData::IsChangePasswordRequired(true)) + } } } @@ -131,6 +134,7 @@ fn parse_get_request(data_enum: api::GetMetaDataRequest) -> DBEnum { api::GetMetaDataRequest::ConfigureWoocom => DBEnum::ConfigureWoocom, api::GetMetaDataRequest::SetupWoocomWebhook => DBEnum::SetupWoocomWebhook, api::GetMetaDataRequest::IsMultipleConfiguration => DBEnum::IsMultipleConfiguration, + api::GetMetaDataRequest::IsChangePasswordRequired => DBEnum::IsChangePasswordRequired, } } @@ -207,6 +211,9 @@ fn into_response( DBEnum::IsMultipleConfiguration => Ok(api::GetMetaDataResponse::IsMultipleConfiguration( data.is_some(), )), + DBEnum::IsChangePasswordRequired => Ok(api::GetMetaDataResponse::IsChangePasswordRequired( + data.is_some(), + )), } } @@ -520,6 +527,17 @@ async fn insert_metadata( ) .await } + types::MetaData::IsChangePasswordRequired(data) => { + utils::insert_user_scoped_metadata_to_db( + state, + user.user_id, + user.merchant_id, + user.org_id, + metadata_key, + data, + ) + .await + } } } diff --git a/crates/router/src/db/dashboard_metadata.rs b/crates/router/src/db/dashboard_metadata.rs index 8e2ac0b6ad3..49dd43313c4 100644 --- a/crates/router/src/db/dashboard_metadata.rs +++ b/crates/router/src/db/dashboard_metadata.rs @@ -14,6 +14,7 @@ pub trait DashboardMetadataInterface { &self, metadata: storage::DashboardMetadataNew, ) -> CustomResult<storage::DashboardMetadata, errors::StorageError>; + async fn update_metadata( &self, user_id: Option<String>, @@ -30,6 +31,7 @@ pub trait DashboardMetadataInterface { org_id: &str, data_keys: Vec<enums::DashboardMetadata>, ) -> CustomResult<Vec<storage::DashboardMetadata>, errors::StorageError>; + async fn find_merchant_scoped_dashboard_metadata( &self, merchant_id: &str, @@ -37,11 +39,18 @@ pub trait DashboardMetadataInterface { data_keys: Vec<enums::DashboardMetadata>, ) -> CustomResult<Vec<storage::DashboardMetadata>, errors::StorageError>; - async fn delete_user_scoped_dashboard_metadata_by_merchant_id( + async fn delete_all_user_scoped_dashboard_metadata_by_merchant_id( &self, user_id: &str, merchant_id: &str, ) -> CustomResult<bool, errors::StorageError>; + + async fn delete_user_scoped_dashboard_metadata_by_merchant_id_data_key( + &self, + user_id: &str, + merchant_id: &str, + data_key: enums::DashboardMetadata, + ) -> CustomResult<storage::DashboardMetadata, errors::StorageError>; } #[async_trait::async_trait] @@ -117,16 +126,34 @@ impl DashboardMetadataInterface for Store { .map_err(Into::into) .into_report() } - async fn delete_user_scoped_dashboard_metadata_by_merchant_id( + async fn delete_all_user_scoped_dashboard_metadata_by_merchant_id( &self, user_id: &str, merchant_id: &str, ) -> CustomResult<bool, errors::StorageError> { let conn = connection::pg_connection_write(self).await?; - storage::DashboardMetadata::delete_user_scoped_dashboard_metadata_by_merchant_id( + storage::DashboardMetadata::delete_all_user_scoped_dashboard_metadata_by_merchant_id( + &conn, + user_id.to_owned(), + merchant_id.to_owned(), + ) + .await + .map_err(Into::into) + .into_report() + } + + async fn delete_user_scoped_dashboard_metadata_by_merchant_id_data_key( + &self, + user_id: &str, + merchant_id: &str, + data_key: enums::DashboardMetadata, + ) -> CustomResult<storage::DashboardMetadata, errors::StorageError> { + let conn = connection::pg_connection_write(self).await?; + storage::DashboardMetadata::delete_user_scoped_dashboard_metadata_by_merchant_id_data_key( &conn, user_id.to_owned(), merchant_id.to_owned(), + data_key, ) .await .map_err(Into::into) @@ -267,7 +294,7 @@ impl DashboardMetadataInterface for MockDb { } Ok(query_result) } - async fn delete_user_scoped_dashboard_metadata_by_merchant_id( + async fn delete_all_user_scoped_dashboard_metadata_by_merchant_id( &self, user_id: &str, merchant_id: &str, @@ -294,4 +321,31 @@ impl DashboardMetadataInterface for MockDb { Ok(true) } + + async fn delete_user_scoped_dashboard_metadata_by_merchant_id_data_key( + &self, + user_id: &str, + merchant_id: &str, + data_key: enums::DashboardMetadata, + ) -> CustomResult<storage::DashboardMetadata, errors::StorageError> { + let mut dashboard_metadata = self.dashboard_metadata.lock().await; + + let index_to_remove = dashboard_metadata + .iter() + .position(|metadata_inner| { + metadata_inner + .user_id + .as_deref() + .map_or(false, |user_id_inner| user_id_inner == user_id) + && metadata_inner.merchant_id == merchant_id + && metadata_inner.data_key == data_key + }) + .ok_or(errors::StorageError::ValueNotFound( + "No data found".to_string(), + ))?; + + let deleted_value = dashboard_metadata.swap_remove(index_to_remove); + + Ok(deleted_value) + } } diff --git a/crates/router/src/db/kafka_store.rs b/crates/router/src/db/kafka_store.rs index 0a9030bae29..029b1a57764 100644 --- a/crates/router/src/db/kafka_store.rs +++ b/crates/router/src/db/kafka_store.rs @@ -1964,6 +1964,7 @@ impl UserRoleInterface for KafkaStore { .update_user_role_by_user_id_merchant_id(user_id, merchant_id, update) .await } + async fn delete_user_role_by_user_id_merchant_id( &self, user_id: &str, @@ -2021,6 +2022,7 @@ impl DashboardMetadataInterface for KafkaStore { .find_user_scoped_dashboard_metadata(user_id, merchant_id, org_id, data_keys) .await } + async fn find_merchant_scoped_dashboard_metadata( &self, merchant_id: &str, @@ -2032,13 +2034,28 @@ impl DashboardMetadataInterface for KafkaStore { .await } - async fn delete_user_scoped_dashboard_metadata_by_merchant_id( + async fn delete_all_user_scoped_dashboard_metadata_by_merchant_id( &self, user_id: &str, merchant_id: &str, ) -> CustomResult<bool, errors::StorageError> { self.diesel_store - .delete_user_scoped_dashboard_metadata_by_merchant_id(user_id, merchant_id) + .delete_all_user_scoped_dashboard_metadata_by_merchant_id(user_id, merchant_id) + .await + } + + async fn delete_user_scoped_dashboard_metadata_by_merchant_id_data_key( + &self, + user_id: &str, + merchant_id: &str, + data_key: enums::DashboardMetadata, + ) -> CustomResult<storage::DashboardMetadata, errors::StorageError> { + self.diesel_store + .delete_user_scoped_dashboard_metadata_by_merchant_id_data_key( + user_id, + merchant_id, + data_key, + ) .await } } diff --git a/crates/router/src/types/domain/user/dashboard_metadata.rs b/crates/router/src/types/domain/user/dashboard_metadata.rs index 5e4017a3cb1..9c00809238e 100644 --- a/crates/router/src/types/domain/user/dashboard_metadata.rs +++ b/crates/router/src/types/domain/user/dashboard_metadata.rs @@ -25,6 +25,7 @@ pub enum MetaData { ConfigureWoocom(bool), SetupWoocomWebhook(bool), IsMultipleConfiguration(bool), + IsChangePasswordRequired(bool), } impl From<&MetaData> for DBEnum { @@ -51,6 +52,7 @@ impl From<&MetaData> for DBEnum { MetaData::ConfigureWoocom(_) => Self::ConfigureWoocom, MetaData::SetupWoocomWebhook(_) => Self::SetupWoocomWebhook, MetaData::IsMultipleConfiguration(_) => Self::IsMultipleConfiguration, + MetaData::IsChangePasswordRequired(_) => Self::IsChangePasswordRequired, } } } diff --git a/crates/router/src/utils/user/dashboard_metadata.rs b/crates/router/src/utils/user/dashboard_metadata.rs index bcf270010ea..ac3d918a34f 100644 --- a/crates/router/src/utils/user/dashboard_metadata.rs +++ b/crates/router/src/utils/user/dashboard_metadata.rs @@ -219,7 +219,9 @@ pub fn separate_metadata_type_based_on_scope( | DBEnum::ConfigureWoocom | DBEnum::SetupWoocomWebhook | DBEnum::IsMultipleConfiguration => merchant_scoped.push(key), - DBEnum::Feedback | DBEnum::ProdIntent => user_scoped.push(key), + DBEnum::Feedback | DBEnum::ProdIntent | DBEnum::IsChangePasswordRequired => { + user_scoped.push(key) + } } } (merchant_scoped, user_scoped)
2024-02-07T08:25:39Z
## Type of Change <!-- Put an `x` in the boxes that apply --> - [ ] Bugfix - [x] New feature - [ ] Enhancement - [ ] Refactoring - [ ] Dependency updates - [ ] Documentation - [ ] CI/CD ## Description For newly invited users, add support to have check for whether password has been changed once or not. - Use enum `IsChangePasswordRequired` to have this check. ### 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 For users with email feature flag disabled, there is no support to know whether the newly invited user has change password or not. ## How did you test it? For Test Invite user ``` curl --location 'http://localhost:8080/user/user/invite' \ --header 'Authorization: Bearer JWT' \ --header 'Content-Type: application/json' \ --data-raw '{ "email": "test_force@gmail.com", "name": "test3", "role_id": "merchant_admin" } ' ``` Invited user signin ``` curl --location 'http://localhost:8080/user/signin' \ --header 'Content-Type: application/json' \ --header 'Cookie: token=JWT' \ --data-raw '{ "email": "test_force@gmail.com", "password": "926fc057-df2e-42af-aada-5e403487f3aa" }' ``` Check value of Enum `IsChangePasswordRequired` ``` curl --location --request GET 'http://localhost:8080/user/data?keys=IsChangePasswordRequired' \ --header 'Authorization: Bearer JWT' \ --header 'Content-Type: application/json' \ --data ' ' ``` Response: ``` [ { "IsChangePasswordRequired": true } ] ``` Change Password: ``` curl --location 'http://localhost:8080/user/change_password' \ --header 'Content-Type: application/json' \ --header 'Cookie: token=eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJ1c2VyX2lkIjoiMWZjNzgyOTUtM2JiMy00OGJjLThlZDgtNzFjMzVjMzMxYWU2IiwibWVyY2hhbnRfaWQiOiJtZXJjaGFudF8xNjk3NzE2ODcwIiwicm9sZV9pZCI6Im1lcmNoYW50X2FkbWluIiwiZXhwIjoxNjk3ODg5NjcxLCJvcmdfaWQiOiJvcmdfejQ5ZExMeTdmbllUODN5TDY3clEifQ.CJzEQ2qbhn-qUiiVBSdvCJiLvWp-5wCF9R54gth6QbQ' \ --header 'Authorization: Bearer JWT' \ --data '{ "old_password": "926fc057-df2e-42af-aada-5e403487f3aa", "new_password": "test" } ' ``` Again checking the value of enum after login: ``` curl --location --request GET 'http://localhost:8080/user/data?keys=IsChangePasswordRequired' \ --header 'Authorization: Bearer JWT' \ --header 'Content-Type: application/json' \ --data ' ' ``` Response should be: ``` [ { "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 - [ ] I added a [CHANGELOG](/CHANGELOG.md) entry if applicable
3af6aaf28e92780679eb0314eb3e95803b9c3113
For Test Invite user ``` curl --location 'http://localhost:8080/user/user/invite' \ --header 'Authorization: Bearer JWT' \ --header 'Content-Type: application/json' \ --data-raw '{ "email": "test_force@gmail.com", "name": "test3", "role_id": "merchant_admin" } ' ``` Invited user signin ``` curl --location 'http://localhost:8080/user/signin' \ --header 'Content-Type: application/json' \ --header 'Cookie: token=JWT' \ --data-raw '{ "email": "test_force@gmail.com", "password": "926fc057-df2e-42af-aada-5e403487f3aa" }' ``` Check value of Enum `IsChangePasswordRequired` ``` curl --location --request GET 'http://localhost:8080/user/data?keys=IsChangePasswordRequired' \ --header 'Authorization: Bearer JWT' \ --header 'Content-Type: application/json' \ --data ' ' ``` Response: ``` [ { "IsChangePasswordRequired": true } ] ``` Change Password: ``` curl --location 'http://localhost:8080/user/change_password' \ --header 'Content-Type: application/json' \ --header 'Cookie: token=eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJ1c2VyX2lkIjoiMWZjNzgyOTUtM2JiMy00OGJjLThlZDgtNzFjMzVjMzMxYWU2IiwibWVyY2hhbnRfaWQiOiJtZXJjaGFudF8xNjk3NzE2ODcwIiwicm9sZV9pZCI6Im1lcmNoYW50X2FkbWluIiwiZXhwIjoxNjk3ODg5NjcxLCJvcmdfaWQiOiJvcmdfejQ5ZExMeTdmbllUODN5TDY3clEifQ.CJzEQ2qbhn-qUiiVBSdvCJiLvWp-5wCF9R54gth6QbQ' \ --header 'Authorization: Bearer JWT' \ --data '{ "old_password": "926fc057-df2e-42af-aada-5e403487f3aa", "new_password": "test" } ' ``` Again checking the value of enum after login: ``` curl --location --request GET 'http://localhost:8080/user/data?keys=IsChangePasswordRequired' \ --header 'Authorization: Bearer JWT' \ --header 'Content-Type: application/json' \ --data ' ' ``` Response should be: ``` [ { "IsChangePasswordRequired": false } ] ```
juspay/hyperswitch
juspay__hyperswitch-3588
Bug: [BUG] map error message and connector transaction_id in case connector returns failure status in 2xx response status. ### Bug Description When connector returns failure status in 2xx response, error messages are not persisted for some connectors. ### Expected Behavior When connector returns failure status in 2xx response, error messages should be persisted for all connectors. ### Actual Behavior When connector returns failure status in 2xx response, error messages are not persisted for some connectors. ### Steps To Reproduce Provide an unambiguous set of steps to reproduce this bug. Include code or configuration to reproduce, if relevant. 1. Simulate a failed payment in noon or payme 2. Status will be failed but error message will be null. ### 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/connector/bankofamerica/transformers.rs b/crates/router/src/connector/bankofamerica/transformers.rs index de53b991d89..b2a9f14ccce 100644 --- a/crates/router/src/connector/bankofamerica/transformers.rs +++ b/crates/router/src/connector/bankofamerica/transformers.rs @@ -1446,9 +1446,9 @@ impl<F> resource_id: types::ResponseId::NoResponseId, redirection_data, mandate_reference: None, - connector_metadata: Some( - serde_json::json!({"three_ds_data":three_ds_data}), - ), + connector_metadata: Some(serde_json::json!({ + "three_ds_data": three_ds_data + })), network_txn_id: None, connector_response_reference_id, incremental_authorization_allowed: None, diff --git a/crates/router/src/connector/cryptopay/transformers.rs b/crates/router/src/connector/cryptopay/transformers.rs index fb806fda68f..d4697e3ba14 100644 --- a/crates/router/src/connector/cryptopay/transformers.rs +++ b/crates/router/src/connector/cryptopay/transformers.rs @@ -4,7 +4,8 @@ use reqwest::Url; use serde::{Deserialize, Serialize}; use crate::{ - connector::utils::{self, CryptoData}, + connector::utils::{self, is_payment_failure, CryptoData}, + consts, core::errors, services, types::{self, api, storage::enums}, @@ -155,14 +156,30 @@ impl<F, T> types::PaymentsResponseData, >, ) -> Result<Self, Self::Error> { - let redirection_data = item - .response - .data - .hosted_page_url - .map(|x| services::RedirectForm::from((x, services::Method::Get))); - Ok(Self { - status: enums::AttemptStatus::from(item.response.data.status), - response: Ok(types::PaymentsResponseData::TransactionResponse { + let status = enums::AttemptStatus::from(item.response.data.status.clone()); + let response = if is_payment_failure(status) { + let payment_response = &item.response.data; + Err(types::ErrorResponse { + code: payment_response + .name + .clone() + .unwrap_or(consts::NO_ERROR_CODE.to_string()), + message: payment_response + .status_context + .clone() + .unwrap_or(consts::NO_ERROR_MESSAGE.to_string()), + reason: payment_response.status_context.clone(), + status_code: item.http_code, + attempt_status: None, + connector_transaction_id: Some(payment_response.id.clone()), + }) + } else { + let redirection_data = item + .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(), ), @@ -176,7 +193,11 @@ impl<F, T> .custom_id .or(Some(item.response.data.id)), incremental_authorization_allowed: None, - }), + }) + }; + Ok(Self { + status, + response, ..item.data }) } diff --git a/crates/router/src/connector/noon/transformers.rs b/crates/router/src/connector/noon/transformers.rs index 2f5f342d7ae..bbd7da234b6 100644 --- a/crates/router/src/connector/noon/transformers.rs +++ b/crates/router/src/connector/noon/transformers.rs @@ -5,8 +5,8 @@ use serde::{Deserialize, Serialize}; use crate::{ connector::utils::{ - self as conn_utils, CardData, PaymentsAuthorizeRequestData, RevokeMandateRequestData, - RouterData, WalletData, + self as conn_utils, is_refund_failure, CardData, PaymentsAuthorizeRequestData, + RevokeMandateRequestData, RouterData, WalletData, }, core::{errors, mandate::MandateBehaviour}, services, @@ -555,6 +555,8 @@ impl<F, T> fn try_from( item: types::ResponseRouterData<F, NoonPaymentsResponse, T, types::PaymentsResponseData>, ) -> Result<Self, Self::Error> { + let order = item.response.result.order; + let status = enums::AttemptStatus::foreign_from((order.status, item.data.status)); let redirection_data = item.response.result.checkout_data.map(|redirection_data| { services::RedirectForm::Form { endpoint: redirection_data.post_url.to_string(), @@ -570,17 +572,16 @@ impl<F, T> connector_mandate_id: Some(subscription_data.identifier), payment_method_id: None, }); - let order = item.response.result.order; Ok(Self { - status: enums::AttemptStatus::foreign_from((order.status, item.data.status)), + status, response: match order.error_message { Some(error_message) => Err(ErrorResponse { code: order.error_code.to_string(), message: error_message.clone(), reason: Some(error_message), status_code: item.http_code, - attempt_status: None, - connector_transaction_id: None, + attempt_status: Some(status), + connector_transaction_id: Some(order.id.to_string()), }), _ => { let connector_response_reference_id = @@ -784,13 +785,18 @@ pub struct NoonPaymentsTransactionResponse { } #[derive(Default, Debug, Deserialize, Serialize)] +#[serde(rename_all = "camelCase")] pub struct NoonRefundResponseResult { transaction: NoonPaymentsTransactionResponse, } #[derive(Default, Debug, Deserialize, Serialize)] +#[serde(rename_all = "camelCase")] pub struct RefundResponse { result: NoonRefundResponseResult, + result_code: u32, + class_description: String, + message: String, } impl TryFrom<types::RefundsResponseRouterData<api::Execute, RefundResponse>> @@ -800,11 +806,26 @@ impl TryFrom<types::RefundsResponseRouterData<api::Execute, RefundResponse>> fn try_from( item: types::RefundsResponseRouterData<api::Execute, RefundResponse>, ) -> Result<Self, Self::Error> { - Ok(Self { - response: Ok(types::RefundsResponseData { + let response = &item.response; + let refund_status = + enums::RefundStatus::from(response.result.transaction.status.to_owned()); + let response = if is_refund_failure(refund_status) { + Err(ErrorResponse { + status_code: item.http_code, + code: response.result_code.to_string(), + message: response.class_description.clone(), + reason: Some(response.message.clone()), + attempt_status: None, + connector_transaction_id: Some(response.result.transaction.id.clone()), + }) + } else { + Ok(types::RefundsResponseData { connector_refund_id: item.response.result.transaction.id, - refund_status: enums::RefundStatus::from(item.response.result.transaction.status), - }), + refund_status, + }) + }; + Ok(Self { + response, ..item.data }) } @@ -819,13 +840,18 @@ pub struct NoonRefundResponseTransactions { } #[derive(Default, Debug, Deserialize, Serialize)] +#[serde(rename_all = "camelCase")] pub struct NoonRefundSyncResponseResult { transactions: Vec<NoonRefundResponseTransactions>, } #[derive(Default, Debug, Deserialize, Serialize)] +#[serde(rename_all = "camelCase")] pub struct RefundSyncResponse { result: NoonRefundSyncResponseResult, + result_code: u32, + class_description: String, + message: String, } impl TryFrom<types::RefundsResponseRouterData<api::RSync, RefundSyncResponse>> @@ -849,12 +875,25 @@ impl TryFrom<types::RefundsResponseRouterData<api::RSync, RefundSyncResponse>> }) }) .ok_or(errors::ConnectorError::ResponseHandlingFailed)?; - - Ok(Self { - response: Ok(types::RefundsResponseData { + let refund_status = enums::RefundStatus::from(noon_transaction.status.to_owned()); + let response = if is_refund_failure(refund_status) { + let response = &item.response; + Err(ErrorResponse { + status_code: item.http_code, + code: response.result_code.to_string(), + message: response.class_description.clone(), + reason: Some(response.message.clone()), + attempt_status: None, + connector_transaction_id: Some(noon_transaction.id.clone()), + }) + } else { + Ok(types::RefundsResponseData { connector_refund_id: noon_transaction.id.to_owned(), - refund_status: enums::RefundStatus::from(noon_transaction.status.to_owned()), - }), + refund_status, + }) + }; + Ok(Self { + response, ..item.data }) } diff --git a/crates/router/src/connector/payme/transformers.rs b/crates/router/src/connector/payme/transformers.rs index 77dcb6429c9..e0f13741b64 100644 --- a/crates/router/src/connector/payme/transformers.rs +++ b/crates/router/src/connector/payme/transformers.rs @@ -12,9 +12,9 @@ use url::Url; use crate::{ connector::utils::{ - self, missing_field_err, AddressDetailsData, CardData, PaymentsAuthorizeRequestData, - PaymentsCompleteAuthorizeRequestData, PaymentsPreProcessingData, PaymentsSyncRequestData, - RouterData, + self, is_payment_failure, is_refund_failure, missing_field_err, AddressDetailsData, + CardData, PaymentsAuthorizeRequestData, PaymentsCompleteAuthorizeRequestData, + PaymentsPreProcessingData, PaymentsSyncRequestData, RouterData, }, consts, core::errors, @@ -198,14 +198,15 @@ impl<F, T> fn try_from( item: types::ResponseRouterData<F, PaymePaySaleResponse, T, types::PaymentsResponseData>, ) -> Result<Self, Self::Error> { - let response = if item.response.sale_status == SaleStatus::Failed { + let status = enums::AttemptStatus::from(item.response.sale_status.clone()); + let response = if is_payment_failure(status) { // To populate error message in case of failure Err(types::ErrorResponse::from((&item.response, item.http_code))) } else { Ok(types::PaymentsResponseData::try_from(&item.response)?) }; Ok(Self { - status: enums::AttemptStatus::from(item.response.sale_status), + status, response, ..item.data }) @@ -227,7 +228,7 @@ impl From<(&PaymePaySaleResponse, u16)> for types::ErrorResponse { reason: pay_sale_response.status_error_details.to_owned(), status_code: http_code, attempt_status: None, - connector_transaction_id: None, + connector_transaction_id: Some(pay_sale_response.payme_sale_id.clone()), } } } @@ -281,7 +282,8 @@ impl<F, T> TryFrom<types::ResponseRouterData<F, SaleQueryResponse, T, types::Pay .first() .cloned() .ok_or(errors::ConnectorError::ResponseHandlingFailed)?; - let response = if transaction_response.sale_status == SaleStatus::Failed { + let status = enums::AttemptStatus::from(transaction_response.sale_status.clone()); + let response = if is_payment_failure(status) { // To populate error message in case of failure Err(types::ErrorResponse::from(( &transaction_response, @@ -291,7 +293,7 @@ impl<F, T> TryFrom<types::ResponseRouterData<F, SaleQueryResponse, T, types::Pay Ok(types::PaymentsResponseData::from(&transaction_response)) }; Ok(Self { - status: enums::AttemptStatus::from(transaction_response.sale_status), + status, response, ..item.data }) @@ -312,7 +314,7 @@ impl From<(&SaleQuery, u16)> for types::ErrorResponse { reason: sale_query_response.sale_error_text.clone(), status_code: http_code, attempt_status: None, - connector_transaction_id: None, + connector_transaction_id: Some(sale_query_response.sale_payme_id.clone()), } } } @@ -982,6 +984,7 @@ impl TryFrom<SaleStatus> for enums::RefundStatus { pub struct PaymeRefundResponse { sale_status: SaleStatus, payme_transaction_id: String, + status_error_code: i64, } impl TryFrom<types::RefundsResponseRouterData<api::Execute, PaymeRefundResponse>> @@ -991,11 +994,25 @@ impl TryFrom<types::RefundsResponseRouterData<api::Execute, PaymeRefundResponse> fn try_from( item: types::RefundsResponseRouterData<api::Execute, PaymeRefundResponse>, ) -> Result<Self, Self::Error> { - Ok(Self { - response: Ok(types::RefundsResponseData { + let refund_status = enums::RefundStatus::try_from(item.response.sale_status.clone())?; + let response = if is_refund_failure(refund_status) { + let payme_response = &item.response; + Err(types::ErrorResponse { + code: payme_response.status_error_code.to_string(), + message: payme_response.status_error_code.to_string(), + reason: Some(payme_response.status_error_code.to_string()), + status_code: item.http_code, + attempt_status: None, + connector_transaction_id: Some(payme_response.payme_transaction_id.clone()), + }) + } else { + Ok(types::RefundsResponseData { connector_refund_id: item.response.payme_transaction_id, - refund_status: enums::RefundStatus::try_from(item.response.sale_status)?, - }), + refund_status, + }) + }; + Ok(Self { + response, ..item.data }) } @@ -1031,13 +1048,24 @@ impl<F, T> .items .first() .ok_or(errors::ConnectorError::ResponseHandlingFailed)?; - Ok(Self { - response: Ok(types::RefundsResponseData { - refund_status: enums::RefundStatus::try_from( - pay_sale_response.sale_status.clone(), - )?, + let refund_status = enums::RefundStatus::try_from(pay_sale_response.sale_status.clone())?; + let response = if is_refund_failure(refund_status) { + Err(types::ErrorResponse { + code: consts::NO_ERROR_CODE.to_string(), + message: consts::NO_ERROR_CODE.to_string(), + reason: None, + status_code: item.http_code, + attempt_status: None, + connector_transaction_id: Some(pay_sale_response.payme_transaction_id.clone()), + }) + } else { + Ok(types::RefundsResponseData { + refund_status, connector_refund_id: pay_sale_response.payme_transaction_id.clone(), - }), + }) + }; + Ok(Self { + response, ..item.data }) } diff --git a/crates/router/src/connector/utils.rs b/crates/router/src/connector/utils.rs index 87d50bb68a2..7951246790f 100644 --- a/crates/router/src/connector/utils.rs +++ b/crates/router/src/connector/utils.rs @@ -1786,6 +1786,7 @@ pub fn is_refund_failure(status: enums::RefundStatus) -> bool { | common_enums::RefundStatus::Success => false, } } + #[cfg(test)] mod error_code_error_message_tests { #![allow(clippy::unwrap_used)]
2024-01-06T08:14:41Z
## 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 --> Store payment_id and refund_id and error_details in case connector returns 2xx for a failed 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)? --> Manual Noon: <img width="1310" alt="noon error mapping" src="https://github.com/juspay/hyperswitch/assets/61539176/84877c5e-ea00-45c9-b32b-fc514859512d"> Payme: <img width="1347" alt="payme error mapping" src="https://github.com/juspay/hyperswitch/assets/61539176/18e9fb84-bba8-48b7-8859-ce1eabe1aef8"> Refund: Noon: Refund create <img width="1728" alt="Noon refund creat" src="https://github.com/juspay/hyperswitch/assets/61539176/c199585a-ed3a-428c-9d44-228f39dc93e9"> Noon: Refund force sync <img width="1728" alt="Noon refund force sync" src="https://github.com/juspay/hyperswitch/assets/61539176/571dc7ae-d1de-4155-8f7e-523476c32b7a"> Payme: refund create: <img width="1728" alt="payme refund create" src="https://github.com/juspay/hyperswitch/assets/61539176/ff640556-e23a-4a54-b327-a8e2f34dfd77"> Payme: refund Force sync <img width="1728" alt="payme refund force sync" src="https://github.com/juspay/hyperswitch/assets/61539176/f93bcd2e-50c2-46f5-b117-e41c669a5639"> ## 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 - [ ] I added a [CHANGELOG](/CHANGELOG.md) entry if applicable
5fb3c001b5dc371f81fe1708fd9a6c6978fb726e
Manual Noon: <img width="1310" alt="noon error mapping" src="https://github.com/juspay/hyperswitch/assets/61539176/84877c5e-ea00-45c9-b32b-fc514859512d"> Payme: <img width="1347" alt="payme error mapping" src="https://github.com/juspay/hyperswitch/assets/61539176/18e9fb84-bba8-48b7-8859-ce1eabe1aef8"> Refund: Noon: Refund create <img width="1728" alt="Noon refund creat" src="https://github.com/juspay/hyperswitch/assets/61539176/c199585a-ed3a-428c-9d44-228f39dc93e9"> Noon: Refund force sync <img width="1728" alt="Noon refund force sync" src="https://github.com/juspay/hyperswitch/assets/61539176/571dc7ae-d1de-4155-8f7e-523476c32b7a"> Payme: refund create: <img width="1728" alt="payme refund create" src="https://github.com/juspay/hyperswitch/assets/61539176/ff640556-e23a-4a54-b327-a8e2f34dfd77"> Payme: refund Force sync <img width="1728" alt="payme refund force sync" src="https://github.com/juspay/hyperswitch/assets/61539176/f93bcd2e-50c2-46f5-b117-e41c669a5639">
juspay/hyperswitch
juspay__hyperswitch-3552
Bug: feat(analytics): adding kafka dispute events
diff --git a/config/config.example.toml b/config/config.example.toml index 3f1e789dd50..611c581a3df 100644 --- a/config/config.example.toml +++ b/config/config.example.toml @@ -559,6 +559,7 @@ refund_analytics_topic = "topic" # Kafka topic to be used for Refund events api_logs_topic = "topic" # Kafka topic to be used for incoming api events connector_logs_topic = "topic" # Kafka topic to be used for connector api events outgoing_webhook_logs_topic = "topic" # Kafka topic to be used for outgoing webhook events +dispute_analytics_topic = "topic" # Kafka topic to be used for Dispute events # File storage configuration [file_storage] diff --git a/config/development.toml b/config/development.toml index 3a3540da5b6..5eef33eafd9 100644 --- a/config/development.toml +++ b/config/development.toml @@ -542,6 +542,7 @@ refund_analytics_topic = "hyperswitch-refund-events" api_logs_topic = "hyperswitch-api-log-events" connector_logs_topic = "hyperswitch-connector-api-events" outgoing_webhook_logs_topic = "hyperswitch-outgoing-webhook-events" +dispute_analytics_topic = "hyperswitch-dispute-events" [analytics] source = "sqlx" diff --git a/config/docker_compose.toml b/config/docker_compose.toml index 9728497aaf6..178788677e5 100644 --- a/config/docker_compose.toml +++ b/config/docker_compose.toml @@ -383,6 +383,7 @@ refund_analytics_topic = "hyperswitch-refund-events" api_logs_topic = "hyperswitch-api-log-events" connector_logs_topic = "hyperswitch-connector-api-events" outgoing_webhook_logs_topic = "hyperswitch-outgoing-webhook-events" +dispute_analytics_topic = "hyperswitch-dispute-events" [analytics] source = "sqlx" diff --git a/crates/analytics/docs/clickhouse/cluster_setup/scripts/dispute_analytics.sql b/crates/analytics/docs/clickhouse/cluster_setup/scripts/dispute_analytics.sql new file mode 100644 index 00000000000..92a748ff489 --- /dev/null +++ b/crates/analytics/docs/clickhouse/cluster_setup/scripts/dispute_analytics.sql @@ -0,0 +1,142 @@ +CREATE TABLE hyperswitch.dispute_queue on cluster '{cluster}' ( + `dispute_id` String, + `amount` String, + `currency` String, + `dispute_stage` LowCardinality(String), + `dispute_status` LowCardinality(String), + `payment_id` String, + `attempt_id` String, + `merchant_id` String, + `connector_status` String, + `connector_dispute_id` String, + `connector_reason` Nullable(String), + `connector_reason_code` Nullable(String), + `challenge_required_by` Nullable(DateTime) CODEC(T64, LZ4), + `connector_created_at` Nullable(DateTime) CODEC(T64, LZ4), + `connector_updated_at` Nullable(DateTime) CODEC(T64, LZ4), + `created_at` DateTime CODEC(T64, LZ4), + `modified_at` DateTime CODEC(T64, LZ4), + `connector` LowCardinality(String), + `evidence` Nullable(String), + `profile_id` Nullable(String), + `merchant_connector_id` Nullable(String), + `sign_flag` Int8 +) ENGINE = Kafka SETTINGS kafka_broker_list = 'kafka0:29092', +kafka_topic_list = 'hyperswitch-dispute-events', +kafka_group_name = 'hyper-c1', +kafka_format = 'JSONEachRow', +kafka_handle_error_mode = 'stream'; + + +CREATE MATERIALIZED VIEW hyperswitch.dispute_mv on cluster '{cluster}' TO hyperswitch.dispute ( + `dispute_id` String, + `amount` String, + `currency` String, + `dispute_stage` LowCardinality(String), + `dispute_status` LowCardinality(String), + `payment_id` String, + `attempt_id` String, + `merchant_id` String, + `connector_status` String, + `connector_dispute_id` String, + `connector_reason` Nullable(String), + `connector_reason_code` Nullable(String), + `challenge_required_by` Nullable(DateTime64(3)), + `connector_created_at` Nullable(DateTime64(3)), + `connector_updated_at` Nullable(DateTime64(3)), + `created_at` DateTime64(3), + `modified_at` DateTime64(3), + `connector` LowCardinality(String), + `evidence` Nullable(String), + `profile_id` Nullable(String), + `merchant_connector_id` Nullable(String), + `inserted_at` DateTime64(3), + `sign_flag` Int8 +) AS +SELECT + dispute_id, + amount, + currency, + dispute_stage, + dispute_status, + payment_id, + attempt_id, + merchant_id, + connector_status, + connector_dispute_id, + connector_reason, + connector_reason_code, + challenge_required_by, + connector_created_at, + connector_updated_at, + created_at, + modified_at, + connector, + evidence, + profile_id, + merchant_connector_id, + now() as inserted_at, + sign_flag +FROM + hyperswitch.dispute_queue +WHERE length(_error) = 0; + + +CREATE TABLE hyperswitch.dispute_clustered on cluster '{cluster}' ( + `dispute_id` String, + `amount` String, + `currency` String, + `dispute_stage` LowCardinality(String), + `dispute_status` LowCardinality(String), + `payment_id` String, + `attempt_id` String, + `merchant_id` String, + `connector_status` String, + `connector_dispute_id` String, + `connector_reason` Nullable(String), + `connector_reason_code` Nullable(String), + `challenge_required_by` Nullable(DateTime) CODEC(T64, LZ4), + `connector_created_at` Nullable(DateTime) CODEC(T64, LZ4), + `connector_updated_at` Nullable(DateTime) CODEC(T64, LZ4), + `created_at` DateTime DEFAULT now() CODEC(T64, LZ4), + `modified_at` DateTime DEFAULT now() CODEC(T64, LZ4), + `connector` LowCardinality(String), + `evidence` String DEFAULT '{}' CODEC(T64, LZ4), + `profile_id` Nullable(String), + `merchant_connector_id` Nullable(String), + `inserted_at` DateTime DEFAULT now() CODEC(T64, LZ4), + `sign_flag` Int8 + INDEX connectorIndex connector TYPE bloom_filter GRANULARITY 1, + INDEX disputeStatusIndex dispute_status TYPE bloom_filter GRANULARITY 1, + INDEX disputeStageIndex dispute_stage TYPE bloom_filter GRANULARITY 1 +) ENGINE = ReplicatedCollapsingMergeTree( + '/clickhouse/{installation}/{cluster}/tables/{shard}/hyperswitch/dispute_clustered', + '{replica}', + dispute_status +) +PARTITION BY toStartOfDay(created_at) +ORDER BY + (created_at, merchant_id, dispute_id) +TTL created_at + toIntervalMonth(6); + + +CREATE MATERIALIZED VIEW hyperswitch.dispute_parse_errors on cluster '{cluster}' +( + `topic` String, + `partition` Int64, + `offset` Int64, + `raw` String, + `error` String +) +ENGINE = MergeTree +ORDER BY (topic, partition, offset) +SETTINGS index_granularity = 8192 AS +SELECT + _topic AS topic, + _partition AS partition, + _offset AS offset, + _raw_message AS raw, + _error AS error +FROM hyperswitch.dispute_queue +WHERE length(_error) > 0 +; \ No newline at end of file diff --git a/crates/analytics/docs/clickhouse/scripts/disputes.sql b/crates/analytics/docs/clickhouse/scripts/disputes.sql new file mode 100644 index 00000000000..3f700bc06d3 --- /dev/null +++ b/crates/analytics/docs/clickhouse/scripts/disputes.sql @@ -0,0 +1,117 @@ +CREATE TABLE dispute_queue ( + `dispute_id` String, + `amount` String, + `currency` String, + `dispute_stage` LowCardinality(String), + `dispute_status` LowCardinality(String), + `payment_id` String, + `attempt_id` String, + `merchant_id` String, + `connector_status` String, + `connector_dispute_id` String, + `connector_reason` Nullable(String), + `connector_reason_code` Nullable(String), + `challenge_required_by` Nullable(DateTime) CODEC(T64, LZ4), + `connector_created_at` Nullable(DateTime) CODEC(T64, LZ4), + `connector_updated_at` Nullable(DateTime) CODEC(T64, LZ4), + `created_at` DateTime CODEC(T64, LZ4), + `modified_at` DateTime CODEC(T64, LZ4), + `connector` LowCardinality(String), + `evidence` Nullable(String), + `profile_id` Nullable(String), + `merchant_connector_id` Nullable(String), + `sign_flag` Int8 +) ENGINE = Kafka SETTINGS kafka_broker_list = 'kafka0:29092', +kafka_topic_list = 'hyperswitch-dispute-events', +kafka_group_name = 'hyper-c1', +kafka_format = 'JSONEachRow', +kafka_handle_error_mode = 'stream'; + + +CREATE TABLE dispute ( + `dispute_id` String, + `amount` String, + `currency` String, + `dispute_stage` LowCardinality(String), + `dispute_status` LowCardinality(String), + `payment_id` String, + `attempt_id` String, + `merchant_id` String, + `connector_status` String, + `connector_dispute_id` String, + `connector_reason` Nullable(String), + `connector_reason_code` Nullable(String), + `challenge_required_by` Nullable(DateTime) CODEC(T64, LZ4), + `connector_created_at` Nullable(DateTime) CODEC(T64, LZ4), + `connector_updated_at` Nullable(DateTime) CODEC(T64, LZ4), + `created_at` DateTime DEFAULT now() CODEC(T64, LZ4), + `modified_at` DateTime DEFAULT now() CODEC(T64, LZ4), + `connector` LowCardinality(String), + `evidence` String DEFAULT '{}' CODEC(T64, LZ4), + `profile_id` Nullable(String), + `merchant_connector_id` Nullable(String), + `inserted_at` DateTime DEFAULT now() CODEC(T64, LZ4), + `sign_flag` Int8 + INDEX connectorIndex connector TYPE bloom_filter GRANULARITY 1, + INDEX disputeStatusIndex dispute_status TYPE bloom_filter GRANULARITY 1, + INDEX disputeStageIndex dispute_stage TYPE bloom_filter GRANULARITY 1 +) ENGINE = CollapsingMergeTree( + sign_flag +) +PARTITION BY toStartOfDay(created_at) +ORDER BY + (created_at, merchant_id, dispute_id) +TTL created_at + toIntervalMonth(6) +; + +CREATE MATERIALIZED VIEW kafka_parse_dispute TO dispute ( + `dispute_id` String, + `amount` String, + `currency` String, + `dispute_stage` LowCardinality(String), + `dispute_status` LowCardinality(String), + `payment_id` String, + `attempt_id` String, + `merchant_id` String, + `connector_status` String, + `connector_dispute_id` String, + `connector_reason` Nullable(String), + `connector_reason_code` Nullable(String), + `challenge_required_by` Nullable(DateTime64(3)), + `connector_created_at` Nullable(DateTime64(3)), + `connector_updated_at` Nullable(DateTime64(3)), + `created_at` DateTime64(3), + `modified_at` DateTime64(3), + `connector` LowCardinality(String), + `evidence` Nullable(String), + `profile_id` Nullable(String), + `merchant_connector_id` Nullable(String), + `inserted_at` DateTime64(3), + `sign_flag` Int8 +) AS +SELECT + dispute_id, + amount, + currency, + dispute_stage, + dispute_status, + payment_id, + attempt_id, + merchant_id, + connector_status, + connector_dispute_id, + connector_reason, + connector_reason_code, + challenge_required_by, + connector_created_at, + connector_updated_at, + created_at, + modified_at, + connector, + evidence, + profile_id, + merchant_connector_id, + now() as inserted_at, + sign_flag +FROM + dispute_queue; diff --git a/crates/router/src/db/kafka_store.rs b/crates/router/src/db/kafka_store.rs index a5e5f216a8b..0078f030c5a 100644 --- a/crates/router/src/db/kafka_store.rs +++ b/crates/router/src/db/kafka_store.rs @@ -374,9 +374,15 @@ impl CustomerInterface for KafkaStore { impl DisputeInterface for KafkaStore { async fn insert_dispute( &self, - dispute: storage::DisputeNew, + dispute_new: storage::DisputeNew, ) -> CustomResult<storage::Dispute, errors::StorageError> { - self.diesel_store.insert_dispute(dispute).await + let dispute = self.diesel_store.insert_dispute(dispute_new).await?; + + if let Err(er) = self.kafka_producer.log_dispute(&dispute, None).await { + logger::error!(message="Failed to add analytics entry for Dispute {dispute:?}", error_message=?er); + }; + + Ok(dispute) } async fn find_by_merchant_id_payment_id_connector_dispute_id( @@ -419,7 +425,19 @@ impl DisputeInterface for KafkaStore { this: storage::Dispute, dispute: storage::DisputeUpdate, ) -> CustomResult<storage::Dispute, errors::StorageError> { - self.diesel_store.update_dispute(this, dispute).await + let dispute_new = self + .diesel_store + .update_dispute(this.clone(), dispute) + .await?; + if let Err(er) = self + .kafka_producer + .log_dispute(&dispute_new, Some(this)) + .await + { + logger::error!(message="Failed to add analytics entry for Dispute {dispute_new:?}", error_message=?er); + }; + + Ok(dispute_new) } async fn find_disputes_by_merchant_id_payment_id( diff --git a/crates/router/src/services/kafka.rs b/crates/router/src/services/kafka.rs index 2bcfcfe974f..ef9352e55b4 100644 --- a/crates/router/src/services/kafka.rs +++ b/crates/router/src/services/kafka.rs @@ -8,6 +8,7 @@ use rdkafka::{ }; use crate::events::EventType; +mod dispute; mod payment_attempt; mod payment_intent; mod refund; @@ -17,8 +18,10 @@ use serde::Serialize; use time::OffsetDateTime; use self::{ - payment_attempt::KafkaPaymentAttempt, payment_intent::KafkaPaymentIntent, refund::KafkaRefund, + dispute::KafkaDispute, payment_attempt::KafkaPaymentAttempt, + payment_intent::KafkaPaymentIntent, refund::KafkaRefund, }; +use crate::types::storage::Dispute; // Using message queue result here to avoid confusion with Kafka result provided by library pub type MQResult<T> = CustomResult<T, KafkaError>; @@ -82,6 +85,7 @@ pub struct KafkaSettings { api_logs_topic: String, connector_logs_topic: String, outgoing_webhook_logs_topic: String, + dispute_analytics_topic: String, } impl KafkaSettings { @@ -135,6 +139,12 @@ impl KafkaSettings { }, )?; + common_utils::fp_utils::when(self.dispute_analytics_topic.is_default_or_empty(), || { + Err(ApplicationError::InvalidConfigurationValueError( + "Kafka Dispute Logs topic must not be empty".into(), + )) + })?; + Ok(()) } } @@ -148,6 +158,7 @@ pub struct KafkaProducer { api_logs_topic: String, connector_logs_topic: String, outgoing_webhook_logs_topic: String, + dispute_analytics_topic: String, } struct RdKafkaProducer(ThreadedProducer<DefaultProducerContext>); @@ -186,6 +197,7 @@ impl KafkaProducer { api_logs_topic: conf.api_logs_topic.clone(), connector_logs_topic: conf.connector_logs_topic.clone(), outgoing_webhook_logs_topic: conf.outgoing_webhook_logs_topic.clone(), + dispute_analytics_topic: conf.dispute_analytics_topic.clone(), }) } @@ -306,6 +318,27 @@ impl KafkaProducer { }) } + pub async fn log_dispute( + &self, + dispute: &Dispute, + old_dispute: Option<Dispute>, + ) -> MQResult<()> { + if let Some(negative_event) = old_dispute { + self.log_kafka_event( + &self.dispute_analytics_topic, + &KafkaEvent::old(&KafkaDispute::from_storage(&negative_event)), + ) + .attach_printable_lazy(|| { + format!("Failed to add negative dispute event {negative_event:?}") + })?; + }; + self.log_kafka_event( + &self.dispute_analytics_topic, + &KafkaEvent::new(&KafkaDispute::from_storage(dispute)), + ) + .attach_printable_lazy(|| format!("Failed to add positive dispute event {dispute:?}")) + } + pub fn get_topic(&self, event: EventType) -> &str { match event { EventType::ApiLogs => &self.api_logs_topic, diff --git a/crates/router/src/services/kafka/dispute.rs b/crates/router/src/services/kafka/dispute.rs new file mode 100644 index 00000000000..3ccdbe53cb1 --- /dev/null +++ b/crates/router/src/services/kafka/dispute.rs @@ -0,0 +1,76 @@ +use diesel_models::enums as storage_enums; +use masking::Secret; +use time::OffsetDateTime; + +use crate::types::storage::dispute::Dispute; + +#[derive(serde::Serialize, Debug)] +pub struct KafkaDispute<'a> { + pub dispute_id: &'a String, + pub amount: &'a String, + pub currency: &'a String, + pub dispute_stage: &'a storage_enums::DisputeStage, + pub dispute_status: &'a storage_enums::DisputeStatus, + pub payment_id: &'a String, + pub attempt_id: &'a String, + pub merchant_id: &'a String, + pub connector_status: &'a String, + pub connector_dispute_id: &'a String, + pub connector_reason: Option<&'a String>, + pub connector_reason_code: Option<&'a String>, + #[serde(default, with = "time::serde::timestamp::option")] + pub challenge_required_by: Option<OffsetDateTime>, + #[serde(default, with = "time::serde::timestamp::option")] + pub connector_created_at: Option<OffsetDateTime>, + #[serde(default, with = "time::serde::timestamp::option")] + pub connector_updated_at: Option<OffsetDateTime>, + #[serde(default, with = "time::serde::timestamp")] + pub created_at: OffsetDateTime, + #[serde(default, with = "time::serde::timestamp")] + pub modified_at: OffsetDateTime, + pub connector: &'a String, + pub evidence: &'a Secret<serde_json::Value>, + pub profile_id: Option<&'a String>, + pub merchant_connector_id: Option<&'a String>, +} + +impl<'a> KafkaDispute<'a> { + pub fn from_storage(dispute: &'a Dispute) -> Self { + Self { + dispute_id: &dispute.dispute_id, + amount: &dispute.amount, + currency: &dispute.currency, + dispute_stage: &dispute.dispute_stage, + dispute_status: &dispute.dispute_status, + payment_id: &dispute.payment_id, + attempt_id: &dispute.attempt_id, + merchant_id: &dispute.merchant_id, + connector_status: &dispute.connector_status, + connector_dispute_id: &dispute.connector_dispute_id, + connector_reason: dispute.connector_reason.as_ref(), + connector_reason_code: dispute.connector_reason_code.as_ref(), + challenge_required_by: dispute.challenge_required_by.map(|i| i.assume_utc()), + connector_created_at: dispute.connector_created_at.map(|i| i.assume_utc()), + connector_updated_at: dispute.connector_updated_at.map(|i| i.assume_utc()), + created_at: dispute.created_at.assume_utc(), + modified_at: dispute.modified_at.assume_utc(), + connector: &dispute.connector, + evidence: &dispute.evidence, + profile_id: dispute.profile_id.as_ref(), + merchant_connector_id: dispute.merchant_connector_id.as_ref(), + } + } +} + +impl<'a> super::KafkaMessage for KafkaDispute<'a> { + fn key(&self) -> String { + format!( + "{}_{}_{}", + self.merchant_id, self.payment_id, self.dispute_id + ) + } + + fn creation_timestamp(&self) -> Option<i64> { + Some(self.modified_at.unix_timestamp()) + } +}
2024-02-05T11:31:41Z
## Type of Change <!-- Put an `x` in the boxes that apply --> - [ ] Bugfix - [x] New feature - [ ] Enhancement - [ ] Refactoring - [ ] Dependency updates - [ ] Documentation - [ ] CI/CD ## Description adding dispute events to kafka ### 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 payment curl commented below, I used checkout connector to create dispute and check on grafana in explore section, select loki and query as ```{app="bach"} |= dispute_id``` I added SS of local console log in the comment below ## 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 - [ ] I added a [CHANGELOG](/CHANGELOG.md) entry if applicable
fb254b8924808e6a2b2a9a31dbed78749836e8d3
Create a payment curl commented below, I used checkout connector to create dispute and check on grafana in explore section, select loki and query as ```{app="bach"} |= dispute_id``` I added SS of local console log in the comment below
juspay/hyperswitch
juspay__hyperswitch-3538
Bug: [FEATURE] Decide Flow based on setup_future_usage param ### Feature Description The setup_future_usage has two fields on_session and off_session. The flow, i.e. either SaveCard/Mandate, will be decided on the basis of these fields. ### Possible Implementation In our current flow there's no specific SaveCard Flow implementation based on the setup_future_usage. So to have specific implementation and distinction between different flows, there would be appropriate usage of the fields of setup_future_usage as: - If the field is on_session, there would be a normal save card flow - if the field is off_session and customer_acceptance field is passed , there would be a mandate flow - If the field is off_session and no customer_acceptance field is passed, there would be a One Time Payment ### 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/mandates.rs b/crates/api_models/src/mandates.rs index b29f4e0d0c3..7c20a902d28 100644 --- a/crates/api_models/src/mandates.rs +++ b/crates/api_models/src/mandates.rs @@ -77,6 +77,9 @@ pub struct MandateCardDetails { pub card_network: Option<api_enums::CardNetwork>, /// The type of the payment card pub card_type: Option<String>, + /// The nick_name of the card holder + #[schema(value_type = Option<String>)] + pub nick_name: Option<Secret<String>>, } #[derive(Clone, Debug, Deserialize, ToSchema, Serialize)] diff --git a/crates/router/src/core/payments/flows/authorize_flow.rs b/crates/router/src/core/payments/flows/authorize_flow.rs index c6de222f7d8..c64912195ed 100644 --- a/crates/router/src/core/payments/flows/authorize_flow.rs +++ b/crates/router/src/core/payments/flows/authorize_flow.rs @@ -103,6 +103,7 @@ impl Feature<api::Authorize, types::PaymentsAuthorizeData> for types::PaymentsAu merchant_account, self.request.payment_method_type, key_store, + is_mandate, )) .await?; Ok(mandate::mandate_procedure( @@ -134,6 +135,7 @@ impl Feature<api::Authorize, types::PaymentsAuthorizeData> for types::PaymentsAu &merchant_account, self.request.payment_method_type, &key_store, + is_mandate, )) .await; diff --git a/crates/router/src/core/payments/flows/setup_mandate_flow.rs b/crates/router/src/core/payments/flows/setup_mandate_flow.rs index 8b0b54158fd..712184308dd 100644 --- a/crates/router/src/core/payments/flows/setup_mandate_flow.rs +++ b/crates/router/src/core/payments/flows/setup_mandate_flow.rs @@ -76,6 +76,9 @@ impl Feature<api::SetupMandate, types::SetupMandateRequestData> for types::Setup ) .await .to_setup_mandate_failed_response()?; + + let is_mandate = resp.request.setup_mandate_details.is_some(); + let pm_id = Box::pin(tokenization::save_payment_method( state, connector, @@ -84,6 +87,7 @@ impl Feature<api::SetupMandate, types::SetupMandateRequestData> for types::Setup merchant_account, self.request.payment_method_type, key_store, + is_mandate, )) .await?; @@ -280,6 +284,8 @@ impl types::SetupMandateRouterData { let payment_method_type = self.request.payment_method_type; + let is_mandate = resp.request.setup_mandate_details.is_some(); + let pm_id = Box::pin(tokenization::save_payment_method( state, connector, @@ -288,6 +294,7 @@ impl types::SetupMandateRouterData { merchant_account, payment_method_type, key_store, + is_mandate, )) .await?; diff --git a/crates/router/src/core/payments/operations/payment_create.rs b/crates/router/src/core/payments/operations/payment_create.rs index 378cbb25467..9117dcb9966 100644 --- a/crates/router/src/core/payments/operations/payment_create.rs +++ b/crates/router/src/core/payments/operations/payment_create.rs @@ -8,7 +8,7 @@ use data_models::{ payments::payment_attempt::PaymentAttempt, }; use diesel_models::ephemeral_key; -use error_stack::{self, ResultExt}; +use error_stack::{self, report, ResultExt}; use masking::PeekInterface; use router_derive::PaymentOperation; use router_env::{instrument, tracing}; @@ -619,6 +619,17 @@ impl<F: Send + Clone, Ctx: PaymentMethodRetrieve> ValidateRequest<F, api::Paymen helpers::validate_payment_method_fields_present(request)?; + if request.mandate_data.is_none() + && request + .setup_future_usage + .map(|fut_usage| fut_usage == enums::FutureUsage::OffSession) + .unwrap_or(false) + { + Err(report!(errors::ApiErrorResponse::PreconditionFailed { + message: "`setup_future_usage` cannot be `off_session` for normal payments".into() + }))? + } + let mandate_type = helpers::validate_mandate(request, payments::is_operation_confirm(self))?; diff --git a/crates/router/src/core/payments/operations/payment_update.rs b/crates/router/src/core/payments/operations/payment_update.rs index 664fce820a0..b29696a2f10 100644 --- a/crates/router/src/core/payments/operations/payment_update.rs +++ b/crates/router/src/core/payments/operations/payment_update.rs @@ -672,6 +672,17 @@ impl<F: Send + Clone, Ctx: PaymentMethodRetrieve> ValidateRequest<F, api::Paymen helpers::validate_payment_method_fields_present(request)?; + if request.mandate_data.is_none() + && request + .setup_future_usage + .map(|fut_usage| fut_usage == storage_enums::FutureUsage::OffSession) + .unwrap_or(false) + { + Err(report!(errors::ApiErrorResponse::PreconditionFailed { + message: "`setup_future_usage` cannot be `off_session` for normal payments".into() + }))? + } + let mandate_type = helpers::validate_mandate(request, false)?; Ok(( diff --git a/crates/router/src/core/payments/tokenization.rs b/crates/router/src/core/payments/tokenization.rs index f52bce46d8e..1b9f512d842 100644 --- a/crates/router/src/core/payments/tokenization.rs +++ b/crates/router/src/core/payments/tokenization.rs @@ -22,6 +22,7 @@ use crate::{ }; #[instrument(skip_all)] +#[allow(clippy::too_many_arguments)] pub async fn save_payment_method<F: Clone, FData>( state: &AppState, connector: &api::ConnectorData, @@ -30,6 +31,7 @@ pub async fn save_payment_method<F: Clone, FData>( merchant_account: &domain::MerchantAccount, payment_method_type: Option<storage_enums::PaymentMethodType>, key_store: &domain::MerchantKeyStore, + is_mandate: bool, ) -> RouterResult<Option<String>> where FData: mandate::MandateBehaviour, @@ -62,8 +64,16 @@ where } else { None }; + let future_usage_validation = resp + .request + .get_setup_future_usage() + .map(|future_usage| { + (future_usage == storage_enums::FutureUsage::OffSession && is_mandate) + || (future_usage == storage_enums::FutureUsage::OnSession && !is_mandate) + }) + .unwrap_or(false); - let pm_id = if resp.request.get_setup_future_usage().is_some() { + let pm_id = if future_usage_validation { let customer = maybe_customer.to_owned().get_required_value("customer")?; let payment_method_create_request = helpers::get_payment_method_create_request( Some(&resp.request.get_payment_method_data()), diff --git a/crates/router/src/types/api/mandates.rs b/crates/router/src/types/api/mandates.rs index f6b2d7bba93..051547dfa92 100644 --- a/crates/router/src/types/api/mandates.rs +++ b/crates/router/src/types/api/mandates.rs @@ -112,6 +112,7 @@ impl From<api::payment_methods::CardDetailFromLocker> for MandateCardDetails { card_issuer: card_details_from_locker.card_issuer, card_network: card_details_from_locker.card_network, card_type: card_details_from_locker.card_type, + nick_name: card_details_from_locker.nick_name, } .into() } diff --git a/openapi/openapi_spec.json b/openapi/openapi_spec.json index 98cfaecf6b8..9627d32ef9e 100644 --- a/openapi/openapi_spec.json +++ b/openapi/openapi_spec.json @@ -9059,6 +9059,11 @@ "type": "string", "description": "The type of the payment card", "nullable": true + }, + "nick_name": { + "type": "string", + "description": "The nick_name of the card holder", + "nullable": true } } }, diff --git a/postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario23- Update Amount/Payments - Confirm/request.json b/postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario23- Update Amount/Payments - Confirm/request.json index 4d4486b1d43..5b0c090f2be 100644 --- a/postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario23- Update Amount/Payments - Confirm/request.json +++ b/postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario23- Update Amount/Payments - Confirm/request.json @@ -62,7 +62,7 @@ "card_cvc": "737" } }, - "setup_future_usage": "off_session", + "setup_future_usage": "on_session", "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", @@ -79,14 +79,8 @@ }, "url": { "raw": "{{baseUrl}}/payments/:id/confirm", - "host": [ - "{{baseUrl}}" - ], - "path": [ - "payments", - ":id", - "confirm" - ], + "host": ["{{baseUrl}}"], + "path": ["payments", ":id", "confirm"], "variable": [ { "key": "id",
2024-02-06T18:00:28Z
## Type of Change <!-- Put an `x` in the boxes that apply --> - [ ] Bugfix - [x] New feature - [ ] Enhancement - [ ] Refactoring - [ ] Dependency updates - [ ] Documentation - [ ] CI/CD ## Description decide flow based on setup_future_usage ### 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 an MA and MCA - Change the setup future usage field on the basis of following cases : > If the field is on_session, there would be a normal save card flow > if the field is off_session and customer_acceptance field is passed , there would be a mandate flow > If the field is off_session and no customer_acceptance field is passed, there would be a One Time Payment > If the field is null it'll be a one Time Payment ## 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 - [ ] I added a [CHANGELOG](/CHANGELOG.md) entry if applicable
0a97a1eb6382a1aa465ac5a1dc792ea4e763511a
- Create an MA and MCA - Change the setup future usage field on the basis of following cases : > If the field is on_session, there would be a normal save card flow > if the field is off_session and customer_acceptance field is passed , there would be a mandate flow > If the field is off_session and no customer_acceptance field is passed, there would be a One Time Payment > If the field is null it'll be a one Time Payment
juspay/hyperswitch
juspay__hyperswitch-3537
Bug: [BUG] Nuvei recurring MIT payment is not handled in Authorize flow ### Bug Description In the Nuvei Authorize flow implementation, the `get_request_body` method currently utilizes `TryFrom` to construct a `NuveiPaymentsRequest` using `RouterData`. To accommodate `NuveiPaymentsRequest` for each payment method, we have a match statement where `payments::PaymentMethodData::MandatePayment` needs to implement `TryFrom` for building `NuveiPaymentsRequest` specifically for recurring mandates. The logic already present in the `get_card_info` method should be relocated inside the new `TryFrom` implementation for `payments::PaymentMethodData::MandatePayment` ### Expected Behavior Recurring MIT payments should work with connector_mandate_id for Nuvei connector. ### Actual Behavior Recurring MIT payment with mandate id through Nuvei is failing saying "Selected payment method through nuvei is not implemented". ### Steps To Reproduce 1. Create CIT payment with nuvei connector. 2. Use mandate_id from the previous CIT payment and create MIT payment 3. Hyperswitch throws 501 http status code in the response ### 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)
diff --git a/crates/router/src/connector/nuvei/transformers.rs b/crates/router/src/connector/nuvei/transformers.rs index d5dd6e813ae..fe17fae8770 100644 --- a/crates/router/src/connector/nuvei/transformers.rs +++ b/crates/router/src/connector/nuvei/transformers.rs @@ -20,7 +20,7 @@ use crate::{ consts, core::errors, services, - types::{self, api, storage::enums, transformers::ForeignTryFrom}, + types::{self, api, storage::enums, transformers::ForeignTryFrom, BrowserInformation}, utils::OptionExt, }; @@ -75,6 +75,7 @@ pub struct NuveiPaymentsRequest { pub transaction_type: TransactionType, pub is_rebilling: Option<String>, pub payment_option: PaymentOption, + pub device_details: Option<DeviceDetails>, pub checksum: String, pub billing_address: Option<BillingAddress>, pub related_transaction_id: Option<String>, @@ -135,7 +136,6 @@ pub struct PaymentOption { pub card: Option<Card>, pub redirect_url: Option<Url>, pub user_payment_option_id: Option<String>, - pub device_details: Option<DeviceDetails>, pub alternative_payment_method: Option<AlternativePaymentMethod>, pub billing_address: Option<BillingAddress>, } @@ -315,7 +315,7 @@ pub struct V2AdditionalParams { #[derive(Debug, Clone, Default, Serialize, Deserialize)] #[serde(rename_all = "camelCase")] pub struct DeviceDetails { - pub ip_address: String, + pub ip_address: Secret<String, pii::IpAddress>, } impl From<enums::CaptureMethod> for TransactionType { @@ -746,6 +746,7 @@ impl<F> let item = data.0; let request_data = match item.request.payment_method_data.clone() { api::PaymentMethodData::Card(card) => get_card_info(item, &card), + api::PaymentMethodData::MandatePayment => Self::try_from(item), api::PaymentMethodData::Wallet(wallet) => match wallet { payments::WalletData::GooglePay(gpay_data) => Self::try_from(gpay_data), payments::WalletData::ApplePay(apple_pay_data) => Ok(Self::from(apple_pay_data)), @@ -845,7 +846,6 @@ impl<F> payments::PaymentMethodData::BankDebit(_) | payments::PaymentMethodData::BankTransfer(_) | payments::PaymentMethodData::Crypto(_) - | payments::PaymentMethodData::MandatePayment | payments::PaymentMethodData::Reward | payments::PaymentMethodData::Upi(_) | payments::PaymentMethodData::Voucher(_) @@ -874,6 +874,7 @@ impl<F> related_transaction_id: request_data.related_transaction_id, payment_option: request_data.payment_option, billing_address: request_data.billing_address, + device_details: request_data.device_details, url_details: Some(UrlDetails { success_url: return_url.clone(), failure_url: return_url.clone(), @@ -888,104 +889,110 @@ fn get_card_info<F>( item: &types::RouterData<F, types::PaymentsAuthorizeData, types::PaymentsResponseData>, card_details: &payments::Card, ) -> Result<NuveiPaymentsRequest, error_stack::Report<errors::ConnectorError>> { - let browser_info = item.request.get_browser_info()?; + let browser_information = item.request.browser_info.clone(); let related_transaction_id = if item.is_three_ds() { item.request.related_transaction_id.clone() } else { None }; - let connector_mandate_id = &item.request.connector_mandate_id(); - if connector_mandate_id.is_some() { - Ok(NuveiPaymentsRequest { - related_transaction_id, - is_rebilling: Some("1".to_string()), // In case of second installment, rebilling should be 1 - user_token_id: Some(item.request.get_email()?), - payment_option: PaymentOption { - user_payment_option_id: connector_mandate_id.clone(), - ..Default::default() - }, - ..Default::default() - }) - } else { - let (is_rebilling, additional_params, user_token_id) = - match item.request.setup_mandate_details.clone() { - Some(mandate_data) => { - let details = match mandate_data - .mandate_type - .get_required_value("mandate_type") - .change_context(errors::ConnectorError::MissingRequiredField { - field_name: "mandate_type", - })? { - MandateDataType::SingleUse(details) => details, - MandateDataType::MultiUse(details) => { - details.ok_or(errors::ConnectorError::MissingRequiredField { - field_name: "mandate_data.mandate_type.multi_use", - })? - } - }; - let mandate_meta: NuveiMandateMeta = utils::to_connector_meta_from_secret( - Some(details.get_metadata().ok_or_else(utils::missing_field_err( - "mandate_data.mandate_type.{multi_use|single_use}.metadata", - ))?), - )?; - ( - Some("0".to_string()), // In case of first installment, rebilling should be 0 - Some(V2AdditionalParams { - rebill_expiry: Some( - details - .get_end_date(date_time::DateFormat::YYYYMMDD) - .change_context(errors::ConnectorError::DateFormattingFailed)? - .ok_or_else(utils::missing_field_err( - "mandate_data.mandate_type.{multi_use|single_use}.end_date", - ))?, - ), - rebill_frequency: Some(mandate_meta.frequency), - challenge_window_size: None, - }), - Some(item.request.get_email()?), - ) - } - _ => (None, None, None), - }; - let three_d = if item.is_three_ds() { - Some(ThreeD { - browser_details: Some(BrowserDetails { - accept_header: browser_info.get_accept_header()?, - ip: browser_info.get_ip_address()?, - java_enabled: browser_info.get_java_enabled()?.to_string().to_uppercase(), - java_script_enabled: browser_info - .get_java_script_enabled()? - .to_string() - .to_uppercase(), - language: browser_info.get_language()?, - screen_height: browser_info.get_screen_height()?, - screen_width: browser_info.get_screen_width()?, - color_depth: browser_info.get_color_depth()?, - user_agent: browser_info.get_user_agent()?, - time_zone: browser_info.get_time_zone()?, - }), - v2_additional_params: additional_params, - notification_url: item.request.complete_authorize_url.clone(), - merchant_url: item.return_url.clone(), - platform_type: Some(PlatformType::Browser), - method_completion_ind: Some(MethodCompletion::Unavailable), - ..Default::default() - }) - } else { - None - }; - Ok(NuveiPaymentsRequest { - related_transaction_id, - is_rebilling, - user_token_id, - payment_option: PaymentOption::from(NuveiCardDetails { - card: card_details.clone(), - three_d, + let address = item.get_billing_address_details_as_optional(); + + let billing_address = match address { + Some(address) => Some(BillingAddress { + first_name: Some(address.get_first_name()?.clone()), + last_name: Some(address.get_last_name()?.clone()), + email: item.request.get_email()?, + country: item.get_billing_country()?, + }), + None => None, + }; + let (is_rebilling, additional_params, user_token_id) = + match item.request.setup_mandate_details.clone() { + Some(mandate_data) => { + let details = match mandate_data + .mandate_type + .get_required_value("mandate_type") + .change_context(errors::ConnectorError::MissingRequiredField { + field_name: "mandate_type", + })? { + MandateDataType::SingleUse(details) => details, + MandateDataType::MultiUse(details) => { + details.ok_or(errors::ConnectorError::MissingRequiredField { + field_name: "mandate_data.mandate_type.multi_use", + })? + } + }; + let mandate_meta: NuveiMandateMeta = utils::to_connector_meta_from_secret(Some( + details.get_metadata().ok_or_else(utils::missing_field_err( + "mandate_data.mandate_type.{multi_use|single_use}.metadata", + ))?, + ))?; + ( + Some("0".to_string()), // In case of first installment, rebilling should be 0 + Some(V2AdditionalParams { + rebill_expiry: Some( + details + .get_end_date(date_time::DateFormat::YYYYMMDD) + .change_context(errors::ConnectorError::DateFormattingFailed)? + .ok_or_else(utils::missing_field_err( + "mandate_data.mandate_type.{multi_use|single_use}.end_date", + ))?, + ), + rebill_frequency: Some(mandate_meta.frequency), + challenge_window_size: None, + }), + Some(item.request.get_email()?), + ) + } + _ => (None, None, None), + }; + let three_d = if item.is_three_ds() { + let browser_details = match &browser_information { + Some(browser_info) => Some(BrowserDetails { + accept_header: browser_info.get_accept_header()?, + ip: browser_info.get_ip_address()?, + java_enabled: browser_info.get_java_enabled()?.to_string().to_uppercase(), + java_script_enabled: browser_info + .get_java_script_enabled()? + .to_string() + .to_uppercase(), + language: browser_info.get_language()?, + screen_height: browser_info.get_screen_height()?, + screen_width: browser_info.get_screen_width()?, + color_depth: browser_info.get_color_depth()?, + user_agent: browser_info.get_user_agent()?, + time_zone: browser_info.get_time_zone()?, }), + None => None, + }; + Some(ThreeD { + browser_details, + v2_additional_params: additional_params, + notification_url: item.request.complete_authorize_url.clone(), + merchant_url: item.return_url.clone(), + platform_type: Some(PlatformType::Browser), + method_completion_ind: Some(MethodCompletion::Unavailable), ..Default::default() }) - } + } else { + None + }; + + Ok(NuveiPaymentsRequest { + related_transaction_id, + is_rebilling, + user_token_id, + device_details: Option::<DeviceDetails>::foreign_try_from( + &item.request.browser_info.clone(), + )?, + payment_option: PaymentOption::from(NuveiCardDetails { + card: card_details.clone(), + three_d, + }), + billing_address, + ..Default::default() + }) } impl From<NuveiCardDetails> for PaymentOption { fn from(card_details: NuveiCardDetails) -> Self { @@ -1532,6 +1539,51 @@ impl TryFrom<types::RefundsResponseRouterData<api::RSync, NuveiPaymentsResponse> } } +impl<F> TryFrom<&types::RouterData<F, types::PaymentsAuthorizeData, types::PaymentsResponseData>> + for NuveiPaymentsRequest +{ + type Error = error_stack::Report<errors::ConnectorError>; + fn try_from( + data: &types::RouterData<F, types::PaymentsAuthorizeData, types::PaymentsResponseData>, + ) -> Result<Self, Self::Error> { + { + let item = data; + let connector_mandate_id = &item.request.connector_mandate_id(); + let related_transaction_id = if item.is_three_ds() { + item.request.related_transaction_id.clone() + } else { + None + }; + Ok(Self { + related_transaction_id, + device_details: Option::<DeviceDetails>::foreign_try_from( + &item.request.browser_info.clone(), + )?, + is_rebilling: Some("1".to_string()), // In case of second installment, rebilling should be 1 + user_token_id: Some(item.request.get_email()?), + payment_option: PaymentOption { + user_payment_option_id: connector_mandate_id.clone(), + ..Default::default() + }, + ..Default::default() + }) + } + } +} + +impl ForeignTryFrom<&Option<BrowserInformation>> for Option<DeviceDetails> { + type Error = error_stack::Report<errors::ConnectorError>; + fn foreign_try_from(browser_info: &Option<BrowserInformation>) -> Result<Self, Self::Error> { + let device_details = match browser_info { + Some(browser_info) => Some(DeviceDetails { + ip_address: browser_info.get_ip_address()?, + }), + None => None, + }; + Ok(device_details) + } +} + fn get_refund_response( response: NuveiPaymentsResponse, http_code: u16, diff --git a/crates/router/src/connector/utils.rs b/crates/router/src/connector/utils.rs index 7951246790f..1e4552d6577 100644 --- a/crates/router/src/connector/utils.rs +++ b/crates/router/src/connector/utils.rs @@ -86,6 +86,7 @@ pub trait RouterData { fn get_payout_method_data(&self) -> Result<api::PayoutMethodData, Error>; #[cfg(feature = "payouts")] fn get_quote_id(&self) -> Result<String, Error>; + fn get_billing_address_details_as_optional(&self) -> Option<api::AddressDetails>; } pub trait PaymentResponseRouterData { @@ -182,6 +183,14 @@ impl<Flow, Request, Response> RouterData for types::RouterData<Flow, Request, Re .ok_or_else(missing_field_err("billing.address")) } + fn get_billing_address_details_as_optional(&self) -> Option<api::AddressDetails> { + self.address + .billing + .as_ref() + .and_then(|a| a.address.as_ref()) + .cloned() + } + fn get_billing_address_with_phone_number(&self) -> Result<&api::Address, Error> { self.address .billing
2024-02-08T13:05:43Z
## Type of Change <!-- Put an `x` in the boxes that apply --> - [X] Bugfix - [ ] New feature - [X] Enhancement - [ ] Refactoring - [ ] Dependency updates - [ ] Documentation - [ ] CI/CD ## Description - Moved mandate logic outside card_info to MandatePayment - Included Device detail to send IP address to nuvei (mandatory) for both card_info and mandate flow , Ip address is taken from browser info - Billing address for rawcard payment flow - Moved broswer info inside three_ds request construction, since its optional for non-3ds card_info flow https://github.com/juspay/hyperswitch/issues/3537 https://github.com/juspay/hyperswitch/issues/3511 ### 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). --> Open Issues : https://github.com/juspay/hyperswitch/issues/3537 https://github.com/juspay/hyperswitch/issues/3511 Changes done to support Recurring mandate payments flow for Nuvei and included fix for mandatory detail population, like device_details, billing address and browser_info ## 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)? --> Added screenshots from testing Recurring pay with mandate <img width="1127" alt="Screenshot 2024-02-08 at 6 49 58 PM" src="https://github.com/juspay/hyperswitch/assets/97145230/a6c7997d-c98e-4eb1-b5d3-27a71c26f1c4"> Payment With and without IP address <img width="1400" alt="Screenshot 2024-02-08 at 6 49 08 PM" src="https://github.com/juspay/hyperswitch/assets/97145230/cab36f5e-2a5d-4a42-8ef2-25e737ae8c7e"> <img width="1417" alt="Screenshot 2024-02-08 at 6 48 30 PM" src="https://github.com/juspay/hyperswitch/assets/97145230/46953001-166e-40b7-ab97-8ed08573d2b9"> ## 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 - [ ] I added a [CHANGELOG](/CHANGELOG.md) entry if applicable
df739a302b062277647afe5c3888015272fdc2cf
Added screenshots from testing Recurring pay with mandate <img width="1127" alt="Screenshot 2024-02-08 at 6 49 58 PM" src="https://github.com/juspay/hyperswitch/assets/97145230/a6c7997d-c98e-4eb1-b5d3-27a71c26f1c4"> Payment With and without IP address <img width="1400" alt="Screenshot 2024-02-08 at 6 49 08 PM" src="https://github.com/juspay/hyperswitch/assets/97145230/cab36f5e-2a5d-4a42-8ef2-25e737ae8c7e"> <img width="1417" alt="Screenshot 2024-02-08 at 6 48 30 PM" src="https://github.com/juspay/hyperswitch/assets/97145230/46953001-166e-40b7-ab97-8ed08573d2b9">
juspay/hyperswitch
juspay__hyperswitch-3534
Bug: feat(user_role): Update role API - test and finalise
diff --git a/crates/api_models/src/user.rs b/crates/api_models/src/user.rs index b29ce811be3..c3e6908c733 100644 --- a/crates/api_models/src/user.rs +++ b/crates/api_models/src/user.rs @@ -142,7 +142,6 @@ pub struct GetUsersResponse(pub Vec<UserDetails>); #[derive(Debug, serde::Serialize)] pub struct UserDetails { - pub user_id: String, pub email: pii::Email, pub name: Secret<String>, pub role_id: String, diff --git a/crates/api_models/src/user_role.rs b/crates/api_models/src/user_role.rs index e8c9b777c7f..2672293390e 100644 --- a/crates/api_models/src/user_role.rs +++ b/crates/api_models/src/user_role.rs @@ -86,7 +86,7 @@ pub struct PermissionInfo { #[derive(Debug, serde::Deserialize, serde::Serialize)] pub struct UpdateUserRoleRequest { - pub user_id: String, + pub email: pii::Email, pub role_id: String, } diff --git a/crates/router/src/core/errors/user.rs b/crates/router/src/core/errors/user.rs index d3b1679378e..c837fd7c20f 100644 --- a/crates/router/src/core/errors/user.rs +++ b/crates/router/src/core/errors/user.rs @@ -60,6 +60,8 @@ pub enum UserErrors { MaxInvitationsError, #[error("RoleNotFound")] RoleNotFound, + #[error("InvalidRoleOperationWithMessage")] + InvalidRoleOperationWithMessage(String), } impl common_utils::errors::ErrorSwitch<api_models::errors::types::ApiErrorResponse> for UserErrors { @@ -103,9 +105,12 @@ impl common_utils::errors::ErrorSwitch<api_models::errors::types::ApiErrorRespon Self::CompanyNameParsingError => { AER::BadRequest(ApiError::new(sub_code, 14, self.get_error_message(), None)) } - Self::MerchantAccountCreationError(error_message) => { - AER::InternalServerError(ApiError::new(sub_code, 15, error_message, None)) - } + Self::MerchantAccountCreationError(_) => AER::InternalServerError(ApiError::new( + sub_code, + 15, + self.get_error_message(), + None, + )), Self::InvalidEmailError => { AER::BadRequest(ApiError::new(sub_code, 16, self.get_error_message(), None)) } @@ -151,6 +156,9 @@ impl common_utils::errors::ErrorSwitch<api_models::errors::types::ApiErrorRespon Self::RoleNotFound => { AER::BadRequest(ApiError::new(sub_code, 32, self.get_error_message(), None)) } + Self::InvalidRoleOperationWithMessage(_) => { + AER::BadRequest(ApiError::new(sub_code, 33, self.get_error_message(), None)) + } } } } @@ -184,6 +192,7 @@ impl UserErrors { Self::InvalidDeleteOperation => "Delete Operation Not Supported", Self::MaxInvitationsError => "Maximum invite count per request exceeded", Self::RoleNotFound => "Role Not Found", + Self::InvalidRoleOperationWithMessage(error_message) => error_message, } } } diff --git a/crates/router/src/core/errors/utils.rs b/crates/router/src/core/errors/utils.rs index a54dae1c035..1f82132a45f 100644 --- a/crates/router/src/core/errors/utils.rs +++ b/crates/router/src/core/errors/utils.rs @@ -509,3 +509,34 @@ impl RedisErrorExt for error_stack::Report<errors::RedisError> { } } } + +#[cfg(feature = "olap")] +impl<T> StorageErrorExt<T, errors::UserErrors> for error_stack::Result<T, errors::StorageError> { + #[track_caller] + fn to_not_found_response( + self, + not_found_response: errors::UserErrors, + ) -> error_stack::Result<T, errors::UserErrors> { + self.map_err(|e| { + if e.current_context().is_db_not_found() { + e.change_context(not_found_response) + } else { + e.change_context(errors::UserErrors::InternalServerError) + } + }) + } + + #[track_caller] + fn to_duplicate_response( + self, + duplicate_response: errors::UserErrors, + ) -> error_stack::Result<T, errors::UserErrors> { + self.map_err(|e| { + if e.current_context().is_db_unique_violation() { + e.change_context(duplicate_response) + } else { + e.change_context(errors::UserErrors::InternalServerError) + } + }) + } +} diff --git a/crates/router/src/core/user.rs b/crates/router/src/core/user.rs index 70c3eb6673b..7b37f529f83 100644 --- a/crates/router/src/core/user.rs +++ b/crates/router/src/core/user.rs @@ -11,13 +11,15 @@ use router_env::env; #[cfg(feature = "email")] use router_env::logger; -use super::errors::{UserErrors, UserResponse, UserResult}; +use super::errors::{StorageErrorExt, UserErrors, UserResponse, UserResult}; #[cfg(feature = "email")] use crate::services::email::types as email_types; use crate::{ consts, routes::AppState, - services::{authentication as auth, ApplicationResponse}, + services::{ + authentication as auth, authorization::predefined_permissions, ApplicationResponse, + }, types::domain, utils, }; @@ -150,7 +152,7 @@ pub async fn signin( let preferred_role = user_from_db .get_role_from_db_by_merchant_id(&state, preferred_merchant_id.as_str()) .await - .change_context(UserErrors::InternalServerError) + .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, @@ -408,11 +410,17 @@ pub async fn invite_user( .change_context(UserErrors::InternalServerError)?; if inviter_user.email == request.email { - return Err(UserErrors::InvalidRoleOperation.into()) - .attach_printable("User Inviting themself"); + return Err(UserErrors::InvalidRoleOperationWithMessage( + "User Inviting themselves".to_string(), + ) + .into()); + } + + if !predefined_permissions::is_role_invitable(request.role_id.as_str())? { + return Err(UserErrors::InvalidRoleId.into()) + .attach_printable(format!("role_id = {} is not invitable", request.role_id)); } - utils::user_role::validate_role_id(request.role_id.as_str())?; let invitee_email = domain::UserEmail::from_pii_email(request.email.clone())?; let invitee_user = state @@ -561,14 +569,20 @@ async fn handle_invitation( user_from_token: &auth::UserFromToken, request: &user_api::InviteUserRequest, ) -> UserResult<InviteMultipleUserResponse> { - let inviter_user = user_from_token.get_user(state.clone()).await?; + let inviter_user = user_from_token.get_user(state).await?; if inviter_user.email == request.email { - return Err(UserErrors::InvalidRoleOperation.into()) - .attach_printable("User Inviting themself"); + return Err(UserErrors::InvalidRoleOperationWithMessage( + "User Inviting themselves".to_string(), + ) + .into()); + } + + if !predefined_permissions::is_role_invitable(request.role_id.as_str())? { + return Err(UserErrors::InvalidRoleId.into()) + .attach_printable(format!("role_id = {} is not invitable", request.role_id)); } - utils::user_role::validate_role_id(request.role_id.as_str())?; let invitee_email = domain::UserEmail::from_pii_email(request.email.clone())?; let invitee_user = state .store @@ -733,7 +747,11 @@ pub async fn resend_invite( .map_err(|e| { if e.current_context().is_db_not_found() { e.change_context(UserErrors::InvalidRoleOperation) - .attach_printable("User role with given UserId MerchantId not found") + .attach_printable(format!( + "User role with user_id = {} and org_id = {} is not found", + user.get_user_id(), + user_from_token.merchant_id + )) } else { e.change_context(UserErrors::InternalServerError) } @@ -741,7 +759,7 @@ pub async fn resend_invite( if !matches!(user_role.status, UserStatus::InvitationSent) { return Err(UserErrors::InvalidRoleOperation.into()) - .attach_printable("Invalid Status for Reinvitation"); + .attach_printable("User status is not InvitationSent".to_string()); } let email_contents = email_types::InviteUser { @@ -832,8 +850,10 @@ pub async fn switch_merchant_id( user_from_token: auth::UserFromToken, ) -> UserResponse<user_api::SwitchMerchantResponse> { if user_from_token.merchant_id == request.merchant_id { - return Err(UserErrors::InvalidRoleOperation.into()) - .attach_printable("User switch to same merchant id."); + return Err(UserErrors::InvalidRoleOperationWithMessage( + "User switching to same merchant id".to_string(), + ) + .into()); } let user_roles = state @@ -847,7 +867,7 @@ pub async fn switch_merchant_id( .filter(|role| role.status == UserStatus::Active) .collect::<Vec<_>>(); - let user = user_from_token.get_user(state.clone()).await?.into(); + let user = user_from_token.get_user(&state).await?.into(); let (token, role_id) = if utils::user_role::is_internal_role(&user_from_token.role_id) { let key_store = state @@ -916,8 +936,7 @@ pub async fn create_merchant_account( user_from_token: auth::UserFromToken, req: user_api::UserMerchantCreate, ) -> UserResponse<()> { - let user_from_db: domain::UserFromStorage = - user_from_token.get_user(state.clone()).await?.into(); + let user_from_db: domain::UserFromStorage = user_from_token.get_user(&state).await?.into(); let new_user = domain::NewUser::try_from((user_from_db, req, user_from_token))?; let new_merchant = new_user.get_new_merchant(); diff --git a/crates/router/src/core/user_role.rs b/crates/router/src/core/user_role.rs index 742c281b89a..b48b39eea14 100644 --- a/crates/router/src/core/user_role.rs +++ b/crates/router/src/core/user_role.rs @@ -5,7 +5,7 @@ use masking::ExposeInterface; use router_env::logger; use crate::{ - core::errors::{UserErrors, UserResponse}, + core::errors::{StorageErrorExt, UserErrors, UserResponse}, routes::AppState, services::{ authentication::{self as auth}, @@ -33,6 +33,7 @@ pub async fn list_roles(_state: AppState) -> UserResponse<user_role_api::ListRol Ok(ApplicationResponse::Json(user_role_api::ListRolesResponse( predefined_permissions::PREDEFINED_PERMISSIONS .iter() + .filter(|(_, role_info)| role_info.is_invitable()) .filter_map(|(role_id, role_info)| { utils::user_role::get_role_name_and_permission_response(role_info).map( |(permissions, role_name)| user_role_api::RoleInfoResponse { @@ -87,34 +88,49 @@ pub async fn update_user_role( user_from_token: auth::UserFromToken, req: user_role_api::UpdateUserRoleRequest, ) -> UserResponse<()> { - let merchant_id = user_from_token.merchant_id; - let role_id = req.role_id.clone(); - utils::user_role::validate_role_id(role_id.as_str())?; + if !predefined_permissions::is_role_updatable(&req.role_id)? { + return Err(UserErrors::InvalidRoleOperation.into()) + .attach_printable(format!("User role cannot be updated to {}", req.role_id)); + } + + let user_to_be_updated = + utils::user::get_user_from_db_by_email(&state, domain::UserEmail::try_from(req.email)?) + .await + .to_not_found_response(UserErrors::InvalidRoleOperation) + .attach_printable("User not found in our records".to_string())?; - if user_from_token.user_id == req.user_id { + if user_from_token.user_id == user_to_be_updated.get_user_id() { return Err(UserErrors::InvalidRoleOperation.into()) - .attach_printable("Admin User Changing their 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)?; + + if !predefined_permissions::is_role_updatable(&user_role_to_be_updated.role_id)? { + return Err(UserErrors::InvalidRoleOperation.into()).attach_printable(format!( + "User role cannot be updated from {}", + user_role_to_be_updated.role_id + )); } state .store .update_user_role_by_user_id_merchant_id( - req.user_id.as_str(), - merchant_id.as_str(), + user_to_be_updated.get_user_id(), + user_role_to_be_updated.merchant_id.as_str(), UserRoleUpdate::UpdateRole { - role_id, + role_id: req.role_id.clone(), modified_by: user_from_token.user_id, }, ) .await - .map_err(|e| { - if e.current_context().is_db_not_found() { - return e - .change_context(UserErrors::InvalidRoleOperation) - .attach_printable("UserId MerchantId not found"); - } - e.change_context(UserErrors::InternalServerError) - })?; + .to_not_found_response(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) } @@ -181,7 +197,7 @@ pub async fn delete_user_role( .map_err(|e| { if e.current_context().is_db_not_found() { e.change_context(UserErrors::InvalidRoleOperation) - .attach_printable("User not found in records") + .attach_printable("User not found in our records") } else { e.change_context(UserErrors::InternalServerError) } @@ -204,9 +220,9 @@ pub async fn delete_user_role( .find(|&role| role.merchant_id == user_from_token.merchant_id.as_str()) { Some(user_role) => { - if !predefined_permissions::is_role_deletable(&user_role.role_id) { - return Err(UserErrors::InvalidRoleId.into()) - .attach_printable("Deletion not allowed for users with specific role id"); + if !predefined_permissions::is_role_deletable(&user_role.role_id)? { + return Err(UserErrors::InvalidDeleteOperation.into()) + .attach_printable(format!("role_id = {} is not deletable", user_role.role_id)); } } None => { diff --git a/crates/router/src/services/authorization/predefined_permissions.rs b/crates/router/src/services/authorization/predefined_permissions.rs index 6fe0ddcc360..fd98d90c191 100644 --- a/crates/router/src/services/authorization/predefined_permissions.rs +++ b/crates/router/src/services/authorization/predefined_permissions.rs @@ -1,15 +1,21 @@ 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 { @@ -65,6 +71,7 @@ pub static PREDEFINED_PERMISSIONS: Lazy<HashMap<&'static str, RoleInfo>> = Lazy: name: None, is_invitable: false, is_deletable: false, + is_updatable: false, }, ); roles.insert( @@ -90,6 +97,7 @@ pub static PREDEFINED_PERMISSIONS: Lazy<HashMap<&'static str, RoleInfo>> = Lazy: name: None, is_invitable: false, is_deletable: false, + is_updatable: false, }, ); @@ -130,6 +138,7 @@ pub static PREDEFINED_PERMISSIONS: Lazy<HashMap<&'static str, RoleInfo>> = Lazy: name: Some("Organization Admin"), is_invitable: false, is_deletable: false, + is_updatable: false, }, ); @@ -170,6 +179,7 @@ pub static PREDEFINED_PERMISSIONS: Lazy<HashMap<&'static str, RoleInfo>> = Lazy: name: Some("Admin"), is_invitable: true, is_deletable: true, + is_updatable: true, }, ); roles.insert( @@ -195,6 +205,7 @@ pub static PREDEFINED_PERMISSIONS: Lazy<HashMap<&'static str, RoleInfo>> = Lazy: name: Some("View Only"), is_invitable: true, is_deletable: true, + is_updatable: true, }, ); roles.insert( @@ -221,6 +232,7 @@ pub static PREDEFINED_PERMISSIONS: Lazy<HashMap<&'static str, RoleInfo>> = Lazy: name: Some("IAM"), is_invitable: true, is_deletable: true, + is_updatable: true, }, ); roles.insert( @@ -247,6 +259,7 @@ pub static PREDEFINED_PERMISSIONS: Lazy<HashMap<&'static str, RoleInfo>> = Lazy: name: Some("Developer"), is_invitable: true, is_deletable: true, + is_updatable: true, }, ); roles.insert( @@ -278,6 +291,7 @@ pub static PREDEFINED_PERMISSIONS: Lazy<HashMap<&'static str, RoleInfo>> = Lazy: name: Some("Operator"), is_invitable: true, is_deletable: true, + is_updatable: true, }, ); roles.insert( @@ -301,6 +315,7 @@ pub static PREDEFINED_PERMISSIONS: Lazy<HashMap<&'static str, RoleInfo>> = Lazy: name: Some("Customer Support"), is_invitable: true, is_deletable: true, + is_updatable: true, }, ); roles @@ -312,14 +327,29 @@ pub fn get_role_name_from_id(role_id: &str) -> Option<&'static str> { .and_then(|role_info| role_info.name) } -pub fn is_role_invitable(role_id: &str) -> bool { +#[cfg(feature = "olap")] +pub fn is_role_invitable(role_id: &str) -> UserResult<bool> { PREDEFINED_PERMISSIONS .get(role_id) - .map_or(false, |role_info| role_info.is_invitable) + .map(|role_info| role_info.is_invitable) + .ok_or(UserErrors::InvalidRoleId.into()) + .attach_printable(format!("role_id = {} doesn't exist", role_id)) } -pub fn is_role_deletable(role_id: &str) -> bool { +#[cfg(feature = "olap")] +pub fn is_role_deletable(role_id: &str) -> UserResult<bool> { PREDEFINED_PERMISSIONS .get(role_id) - .map_or(false, |role_info| role_info.is_deletable) + .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 d3ea69ecd86..468fa8e4cd2 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_utils::pii; +use common_utils::{errors::CustomResult, pii}; use diesel_models::{ enums::UserStatus, organization as diesel_org, @@ -21,7 +21,7 @@ use crate::{ consts, core::{ admin, - errors::{UserErrors, UserResult}, + errors::{self, UserErrors, UserResult}, }, db::StorageInterface, routes::AppState, @@ -778,19 +778,11 @@ impl UserFromStorage { &self, state: &AppState, merchant_id: &str, - ) -> UserResult<UserRole> { + ) -> CustomResult<UserRole, errors::StorageError> { state .store .find_user_role_by_user_id_merchant_id(self.get_user_id(), merchant_id) .await - .map_err(|e| { - if e.current_context().is_db_not_found() { - UserErrors::RoleNotFound - } else { - UserErrors::InternalServerError - } - }) - .into_report() } } @@ -850,7 +842,6 @@ impl TryFrom<UserAndRoleJoined> for user_api::UserDetails { .to_string(); Ok(Self { - user_id: user_and_role.0.user_id, email: user_and_role.0.email, name: user_and_role.0.name, role_id, diff --git a/crates/router/src/utils/user.rs b/crates/router/src/utils/user.rs index 697d10f772e..9c2d2c1fd3f 100644 --- a/crates/router/src/utils/user.rs +++ b/crates/router/src/utils/user.rs @@ -1,15 +1,16 @@ use std::collections::HashMap; use api_models::user as user_api; +use common_utils::errors::CustomResult; use diesel_models::{enums::UserStatus, user_role::UserRole}; use error_stack::ResultExt; -use masking::Secret; +use masking::{ExposeInterface, Secret}; use crate::{ - core::errors::{UserErrors, UserResult}, + core::errors::{StorageError, UserErrors, UserResult}, routes::AppState, services::authentication::{AuthToken, UserFromToken}, - types::domain::{MerchantAccount, UserFromStorage}, + types::domain::{self, MerchantAccount, UserFromStorage}, }; pub mod dashboard_metadata; @@ -47,7 +48,7 @@ impl UserFromToken { Ok(merchant_account) } - pub async fn get_user(&self, state: AppState) -> UserResult<diesel_models::user::User> { + pub async fn get_user(&self, state: &AppState) -> UserResult<diesel_models::user::User> { let user = state .store .find_user_by_id(&self.user_id) @@ -146,3 +147,14 @@ pub fn get_multiple_merchant_details_with_status( }) .collect() } + +pub async fn get_user_from_db_by_email( + state: &AppState, + email: domain::UserEmail, +) -> CustomResult<UserFromStorage, StorageError> { + state + .store + .find_user_by_email(email.get_secret().expose().as_str()) + .await + .map(UserFromStorage::from) +} diff --git a/crates/router/src/utils/user_role.rs b/crates/router/src/utils/user_role.rs index 462d3d01d79..9c7150c08da 100644 --- a/crates/router/src/utils/user_role.rs +++ b/crates/router/src/utils/user_role.rs @@ -2,11 +2,7 @@ use api_models::user_role as user_role_api; use crate::{ consts, - core::errors::{UserErrors, UserResult}, - services::authorization::{ - permissions::Permission, - predefined_permissions::{self, RoleInfo}, - }, + services::authorization::{permissions::Permission, predefined_permissions::RoleInfo}, }; pub fn is_internal_role(role_id: &str) -> bool { @@ -14,13 +10,6 @@ pub fn is_internal_role(role_id: &str) -> bool { || role_id == consts::user_role::ROLE_ID_INTERNAL_VIEW_ONLY_USER } -pub fn validate_role_id(role_id: &str) -> UserResult<()> { - if predefined_permissions::is_role_invitable(role_id) { - return Ok(()); - } - Err(UserErrors::InvalidRoleId.into()) -} - pub fn get_role_name_and_permission_response( role_info: &RoleInfo, ) -> Option<(Vec<user_role_api::Permission>, &'static str)> {
2024-02-01T14:05:34Z
## 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 changes update user role api and the list users api. And fixes a bug in list roles api. ### 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). --> To allow roles to be updated. ## 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. Update user role api ``` curl --location 'http://localhost:8080/user/user/update_role' \ --header 'Content-Type: application/json' \ --header 'Authorization: Bearer JWT' \ --data '{ "email": "user_email", "role_id": "merchant_admin" }' ``` If api is success, it will respond with 200 OK. 2. List users api ``` curl --location 'http://localhost:8080/user/user/list' \ --header 'Authorization: Bearer JWT' ``` If api is success, response will be like this. Previously this response used to have `user_id` field, now it is removed. ``` [ { "email": "email", "name": "name", "role_id": "merchant_iam_admin", "role_name": "IAM", "status": "InvitationSent", "last_modified_at": "2024-01-22T11:16:42.283Z" }, { "email": "email", "name": "name", "role_id": "org_admin", "role_name": "Organization Admin", "status": "Active", "last_modified_at": "2024-01-22T11:15:26.260Z" }, ] ``` 3. List roles api ``` curl --location 'http://localhost:8080/user/role/list' \ --header 'Authorization: Bearer JWT' ``` This api will no longer return org_admin role in the response and the response will be identical to this. ``` [ { "role_id": "merchant_admin", "permissions": [ "PaymentRead", "PaymentWrite", "RefundRead", "RefundWrite", "ApiKeyRead", "ApiKeyWrite", "MerchantAccountRead", "MerchantAccountWrite", "MerchantConnectorAccountRead", "ForexRead", "MerchantConnectorAccountWrite", "RoutingRead", "RoutingWrite", "ThreeDsDecisionManagerWrite", "ThreeDsDecisionManagerRead", "SurchargeDecisionManagerWrite", "SurchargeDecisionManagerRead", "DisputeRead", "DisputeWrite", "MandateRead", "MandateWrite", "CustomerRead", "CustomerWrite", "FileRead", "FileWrite", "Analytics", "UsersRead", "UsersWrite" ], "role_name": "Admin" }, { "role_id": "merchant_operator", "permissions": [ "PaymentRead", "PaymentWrite", "RefundRead", "RefundWrite", "ApiKeyRead", "MerchantAccountRead", "ForexRead", "MerchantConnectorAccountRead", "MerchantConnectorAccountWrite", "RoutingRead", "RoutingWrite", "ThreeDsDecisionManagerRead", "ThreeDsDecisionManagerWrite", "SurchargeDecisionManagerRead", "SurchargeDecisionManagerWrite", "DisputeRead", "MandateRead", "CustomerRead", "FileRead", "Analytics", "UsersRead" ], "role_name": "Operator" }, { "role_id": "merchant_customer_support", "permissions": [ "PaymentRead", "RefundRead", "RefundWrite", "ForexRead", "DisputeRead", "DisputeWrite", "MerchantAccountRead", "MerchantConnectorAccountRead", "MandateRead", "CustomerRead", "FileRead", "FileWrite", "Analytics" ], "role_name": "Customer Support" }, { "role_id": "merchant_developer", "permissions": [ "PaymentRead", "RefundRead", "ApiKeyRead", "ApiKeyWrite", "MerchantAccountRead", "ForexRead", "MerchantConnectorAccountRead", "RoutingRead", "ThreeDsDecisionManagerRead", "SurchargeDecisionManagerRead", "DisputeRead", "MandateRead", "CustomerRead", "FileRead", "Analytics", "UsersRead" ], "role_name": "Developer" }, { "role_id": "merchant_iam_admin", "permissions": [ "PaymentRead", "RefundRead", "ApiKeyRead", "MerchantAccountRead", "ForexRead", "MerchantConnectorAccountRead", "RoutingRead", "ThreeDsDecisionManagerRead", "SurchargeDecisionManagerRead", "DisputeRead", "MandateRead", "CustomerRead", "FileRead", "Analytics", "UsersRead", "UsersWrite" ], "role_name": "IAM" }, { "role_id": "merchant_view_only", "permissions": [ "PaymentRead", "RefundRead", "ApiKeyRead", "MerchantAccountRead", "ForexRead", "MerchantConnectorAccountRead", "RoutingRead", "ThreeDsDecisionManagerRead", "SurchargeDecisionManagerRead", "DisputeRead", "MandateRead", "CustomerRead", "FileRead", "Analytics", "UsersRead" ], "role_name": "View Only" } ] ``` ## 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 - [ ] I added a [CHANGELOG](/CHANGELOG.md) entry if applicable
014c2d5f555633bc04baca9b4a8c30b9c3534350
1. Update user role api ``` curl --location 'http://localhost:8080/user/user/update_role' \ --header 'Content-Type: application/json' \ --header 'Authorization: Bearer JWT' \ --data '{ "email": "user_email", "role_id": "merchant_admin" }' ``` If api is success, it will respond with 200 OK. 2. List users api ``` curl --location 'http://localhost:8080/user/user/list' \ --header 'Authorization: Bearer JWT' ``` If api is success, response will be like this. Previously this response used to have `user_id` field, now it is removed. ``` [ { "email": "email", "name": "name", "role_id": "merchant_iam_admin", "role_name": "IAM", "status": "InvitationSent", "last_modified_at": "2024-01-22T11:16:42.283Z" }, { "email": "email", "name": "name", "role_id": "org_admin", "role_name": "Organization Admin", "status": "Active", "last_modified_at": "2024-01-22T11:15:26.260Z" }, ] ``` 3. List roles api ``` curl --location 'http://localhost:8080/user/role/list' \ --header 'Authorization: Bearer JWT' ``` This api will no longer return org_admin role in the response and the response will be identical to this. ``` [ { "role_id": "merchant_admin", "permissions": [ "PaymentRead", "PaymentWrite", "RefundRead", "RefundWrite", "ApiKeyRead", "ApiKeyWrite", "MerchantAccountRead", "MerchantAccountWrite", "MerchantConnectorAccountRead", "ForexRead", "MerchantConnectorAccountWrite", "RoutingRead", "RoutingWrite", "ThreeDsDecisionManagerWrite", "ThreeDsDecisionManagerRead", "SurchargeDecisionManagerWrite", "SurchargeDecisionManagerRead", "DisputeRead", "DisputeWrite", "MandateRead", "MandateWrite", "CustomerRead", "CustomerWrite", "FileRead", "FileWrite", "Analytics", "UsersRead", "UsersWrite" ], "role_name": "Admin" }, { "role_id": "merchant_operator", "permissions": [ "PaymentRead", "PaymentWrite", "RefundRead", "RefundWrite", "ApiKeyRead", "MerchantAccountRead", "ForexRead", "MerchantConnectorAccountRead", "MerchantConnectorAccountWrite", "RoutingRead", "RoutingWrite", "ThreeDsDecisionManagerRead", "ThreeDsDecisionManagerWrite", "SurchargeDecisionManagerRead", "SurchargeDecisionManagerWrite", "DisputeRead", "MandateRead", "CustomerRead", "FileRead", "Analytics", "UsersRead" ], "role_name": "Operator" }, { "role_id": "merchant_customer_support", "permissions": [ "PaymentRead", "RefundRead", "RefundWrite", "ForexRead", "DisputeRead", "DisputeWrite", "MerchantAccountRead", "MerchantConnectorAccountRead", "MandateRead", "CustomerRead", "FileRead", "FileWrite", "Analytics" ], "role_name": "Customer Support" }, { "role_id": "merchant_developer", "permissions": [ "PaymentRead", "RefundRead", "ApiKeyRead", "ApiKeyWrite", "MerchantAccountRead", "ForexRead", "MerchantConnectorAccountRead", "RoutingRead", "ThreeDsDecisionManagerRead", "SurchargeDecisionManagerRead", "DisputeRead", "MandateRead", "CustomerRead", "FileRead", "Analytics", "UsersRead" ], "role_name": "Developer" }, { "role_id": "merchant_iam_admin", "permissions": [ "PaymentRead", "RefundRead", "ApiKeyRead", "MerchantAccountRead", "ForexRead", "MerchantConnectorAccountRead", "RoutingRead", "ThreeDsDecisionManagerRead", "SurchargeDecisionManagerRead", "DisputeRead", "MandateRead", "CustomerRead", "FileRead", "Analytics", "UsersRead", "UsersWrite" ], "role_name": "IAM" }, { "role_id": "merchant_view_only", "permissions": [ "PaymentRead", "RefundRead", "ApiKeyRead", "MerchantAccountRead", "ForexRead", "MerchantConnectorAccountRead", "RoutingRead", "ThreeDsDecisionManagerRead", "SurchargeDecisionManagerRead", "DisputeRead", "MandateRead", "CustomerRead", "FileRead", "Analytics", "UsersRead" ], "role_name": "View Only" } ] ```
juspay/hyperswitch
juspay__hyperswitch-3524
Bug: Deep health check for outgoing request in scheduler
diff --git a/crates/api_models/src/health_check.rs b/crates/api_models/src/health_check.rs index e4611f43bcf..2c65c7b6d50 100644 --- a/crates/api_models/src/health_check.rs +++ b/crates/api_models/src/health_check.rs @@ -13,6 +13,7 @@ impl common_utils::events::ApiEventMetric for RouterHealthCheckResponse {} pub struct SchedulerHealthCheckResponse { pub database: bool, pub redis: bool, + pub outgoing_request: bool, } impl common_utils::events::ApiEventMetric for SchedulerHealthCheckResponse {} diff --git a/crates/router/src/bin/scheduler.rs b/crates/router/src/bin/scheduler.rs index 5f98cd88014..59a108ef5e6 100644 --- a/crates/router/src/bin/scheduler.rs +++ b/crates/router/src/bin/scheduler.rs @@ -187,11 +187,23 @@ pub async fn deep_health_check_func( }) })?; + let outgoing_req_check = state + .health_check_outgoing() + .await + .map(|_| true) + .map_err(|err| { + error_stack::report!(errors::ApiErrorResponse::HealthCheckError { + component: "Outgoing Request", + message: err.to_string() + }) + })?; + logger::debug!("Redis health check end"); let response = SchedulerHealthCheckResponse { database: db_status, redis: redis_status, + outgoing_request: outgoing_req_check, }; Ok(response)
2024-02-01T12:37:02Z
## Type of Change <!-- Put an `x` in the boxes that apply --> - [x] Bugfix ## Description <!-- Describe your changes in detail --> Closes #3524 . Add an outgoing request check for scheduler. ## 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). --> Added a check in scheduler for checking the outgoing requests ## 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:3000/health/ready'` - <img width="1305" alt="Screenshot 2024-02-01 at 6 06 36 PM" src="https://github.com/juspay/hyperswitch/assets/43412619/5d1e1525-a408-484f-9749-6affbad3758c"> **This cannot be tested in sandbox as it's not exposed externally in sandbox** ## 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
54fb61eeebec503f599774fe9e97f6b6ce3f1458
- `curl --location 'http://localhost:3000/health/ready'` - <img width="1305" alt="Screenshot 2024-02-01 at 6 06 36 PM" src="https://github.com/juspay/hyperswitch/assets/43412619/5d1e1525-a408-484f-9749-6affbad3758c"> **This cannot be tested in sandbox as it's not exposed externally in sandbox**
juspay/hyperswitch
juspay__hyperswitch-3527
Bug: [BUG] ListPaymentMethods For Merchant has an empty array of payment_methods_enabled ### Bug Description While doing a, ListPaymentMethods For Merchant it has an empty array of payment_methods_enabled. ### Expected Behavior ListPaymentMethods For Merchant should have the payment_methods that has been enabled for that merchant ### Actual Behavior ListPaymentMethods For Merchant it has an empty array ### Steps To Reproduce Provide an unambiguous set of steps to reproduce this bug. Include code or configuration to reproduce, if relevant. 1.Create MA and MCA 2. while making payments do a confirm as false 3. List PaymentMethods For Merchants , the list would be empty for non-card transactions , also the payment_type would be new_mandate/setup_mandate ### 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/payment_methods/cards.rs b/crates/router/src/core/payment_methods/cards.rs index e08dbc61f5e..5797fd60da0 100644 --- a/crates/router/src/core/payment_methods/cards.rs +++ b/crates/router/src/core/payment_methods/cards.rs @@ -1823,7 +1823,6 @@ pub async fn list_payment_methods( } else { api_surcharge_decision_configs::MerchantSurchargeConfigs::default() }; - print!("PAMT{:?}", payment_attempt); Ok(services::ApplicationResponse::Json( api::PaymentMethodListResponse { redirect_url: merchant_account.return_url, @@ -2070,13 +2069,30 @@ pub async fn filter_payment_methods( })?; let filter7 = payment_attempt .and_then(|attempt| attempt.mandate_details.as_ref()) - .map(|_mandate_details| { - filter_pm_based_on_supported_payments_for_mandate( - supported_payment_methods_for_mandate, - &payment_method, - &payment_method_object.payment_method_type, - connector_variant, - ) + .map(|mandate_details| { + let (mandate_type_present, update_mandate_id_present) = + match mandate_details { + data_models::mandates::MandateTypeDetails::MandateType(_) => { + (true, false) + } + data_models::mandates::MandateTypeDetails::MandateDetails( + mand_details, + ) => ( + mand_details.mandate_type.is_some(), + mand_details.update_mandate_id.is_some(), + ), + }; + + if mandate_type_present || update_mandate_id_present { + filter_pm_based_on_supported_payments_for_mandate( + supported_payment_methods_for_mandate, + &payment_method, + &payment_method_object.payment_method_type, + connector_variant, + ) + } else { + true + } }) .unwrap_or(true); diff --git a/crates/router/src/core/payments/operations/payment_create.rs b/crates/router/src/core/payments/operations/payment_create.rs index 381f0265976..378cbb25467 100644 --- a/crates/router/src/core/payments/operations/payment_create.rs +++ b/crates/router/src/core/payments/operations/payment_create.rs @@ -712,7 +712,9 @@ impl PaymentCreate { Err(errors::ApiErrorResponse::InvalidRequestData {message:"Only one field out of 'mandate_type' and 'update_mandate_id' was expected, found both".to_string()})? } - let mandate_dets = if let Some(update_id) = request + let mandate_details = if request.mandate_data.is_none() { + None + } else if let Some(update_id) = request .mandate_data .as_ref() .and_then(|inner| inner.update_mandate_id.clone()) @@ -723,8 +725,6 @@ impl PaymentCreate { }; Some(MandateTypeDetails::MandateDetails(mandate_data)) } else { - // let mandate_type: data_models::mandates::MandateDataType = - let mandate_data = MandateDetails { update_mandate_id: None, mandate_type: request @@ -761,7 +761,7 @@ impl PaymentCreate { business_sub_label: request.business_sub_label.clone(), surcharge_amount, tax_amount, - mandate_details: mandate_dets, + mandate_details, ..storage::PaymentAttemptNew::default() }, additional_pm_data,
2024-02-01T12:34:32Z
## Type of Change <!-- Put an `x` in the boxes that apply --> - [x] Bugfix - [ ] New feature - [ ] Enhancement - [ ] Refactoring - [ ] Dependency updates - [ ] Documentation - [ ] CI/CD ## Description ListPaymentMethodsForMerchant was unable to list the payment methods enabled as it was always taking mandate to have Some value even though its respective fields were None. So added a check that, if there's mandate_data present then only any data should be stored in the database ### 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 MA and MCA - Do a payment with confirm as false and then ListPaymentMethodsForMerchnats > Earlier ![Screenshot 2024-02-01 at 6 15 04 PM](https://github.com/juspay/hyperswitch/assets/55580080/d0b10a50-5694-49e1-93c4-80511fda964c) > After fix ![Screenshot 2024-02-01 at 6 25 21 PM](https://github.com/juspay/hyperswitch/assets/55580080/685dec2a-061b-4f6a-af93-ba35b9751f60) ## 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 - [ ] I added a [CHANGELOG](/CHANGELOG.md) entry if applicable
54fb61eeebec503f599774fe9e97f6b6ce3f1458
- Create MA and MCA - Do a payment with confirm as false and then ListPaymentMethodsForMerchnats > Earlier ![Screenshot 2024-02-01 at 6 15 04 PM](https://github.com/juspay/hyperswitch/assets/55580080/d0b10a50-5694-49e1-93c4-80511fda964c) > After fix ![Screenshot 2024-02-01 at 6 25 21 PM](https://github.com/juspay/hyperswitch/assets/55580080/685dec2a-061b-4f6a-af93-ba35b9751f60)
juspay/hyperswitch
juspay__hyperswitch-3522
Bug: feat: resend user invite Add support to resend invites to users. Currently we can invite the user or multiple users, but there is no support to invite the same user again. The invitation mail will be send to user and user will be able to accept the invitation.
diff --git a/crates/api_models/src/events/user.rs b/crates/api_models/src/events/user.rs index 04aabc071ae..d7150af9bc7 100644 --- a/crates/api_models/src/events/user.rs +++ b/crates/api_models/src/events/user.rs @@ -12,8 +12,8 @@ use crate::user::{ }, AuthorizeResponse, ChangePasswordRequest, ConnectAccountRequest, CreateInternalUserRequest, DashboardEntryResponse, ForgotPasswordRequest, GetUsersResponse, InviteUserRequest, - InviteUserResponse, ResetPasswordRequest, SendVerifyEmailRequest, SignInResponse, - SignUpRequest, SignUpWithMerchantIdRequest, SwitchMerchantIdRequest, + InviteUserResponse, ReInviteUserRequest, ResetPasswordRequest, SendVerifyEmailRequest, + SignInResponse, SignUpRequest, SignUpWithMerchantIdRequest, SwitchMerchantIdRequest, UpdateUserAccountDetailsRequest, UserMerchantCreate, VerifyEmailRequest, }; @@ -54,6 +54,7 @@ common_utils::impl_misc_api_event_type!( ResetPasswordRequest, InviteUserRequest, InviteUserResponse, + ReInviteUserRequest, VerifyEmailRequest, SendVerifyEmailRequest, SignInResponse, diff --git a/crates/api_models/src/user.rs b/crates/api_models/src/user.rs index 89f42f58c39..b29ce811be3 100644 --- a/crates/api_models/src/user.rs +++ b/crates/api_models/src/user.rs @@ -113,6 +113,11 @@ pub struct InviteMultipleUserResponse { pub error: Option<String>, } +#[derive(Debug, serde::Deserialize, serde::Serialize, Clone)] +pub struct ReInviteUserRequest { + pub email: pii::Email, +} + #[derive(Debug, serde::Deserialize, serde::Serialize)] pub struct SwitchMerchantIdRequest { pub merchant_id: String, diff --git a/crates/router/src/core/user.rs b/crates/router/src/core/user.rs index 7050c9f0024..41a407bd670 100644 --- a/crates/router/src/core/user.rs +++ b/crates/router/src/core/user.rs @@ -706,6 +706,63 @@ async fn handle_new_user_invitation( }) } +#[cfg(feature = "email")] +pub async fn resend_invite( + state: AppState, + user_from_token: auth::UserFromToken, + request: user_api::ReInviteUserRequest, +) -> UserResponse<()> { + let invitee_email = domain::UserEmail::from_pii_email(request.email)?; + let user: domain::UserFromStorage = state + .store + .find_user_by_email(invitee_email.clone().get_secret().expose().as_str()) + .await + .map_err(|e| { + if e.current_context().is_db_not_found() { + e.change_context(UserErrors::InvalidRoleOperation) + .attach_printable("User not found in the records") + } else { + e.change_context(UserErrors::InternalServerError) + } + })? + .into(); + let user_role = state + .store + .find_user_role_by_user_id_merchant_id(user.get_user_id(), &user_from_token.merchant_id) + .await + .map_err(|e| { + if e.current_context().is_db_not_found() { + e.change_context(UserErrors::InvalidRoleOperation) + .attach_printable("User role with given UserId MerchantId not found") + } else { + e.change_context(UserErrors::InternalServerError) + } + })?; + + if !matches!(user_role.status, UserStatus::InvitationSent) { + return Err(UserErrors::InvalidRoleOperation.into()) + .attach_printable("Invalid Status for Reinvitation"); + } + + 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, + }; + state + .email_client + .compose_and_send_email( + Box::new(email_contents), + state.conf.proxy.https_url.as_ref(), + ) + .await + .change_context(UserErrors::InternalServerError)?; + + Ok(ApplicationResponse::StatusOk) +} + pub async fn create_internal_user( state: AppState, request: user_api::CreateInternalUserRequest, diff --git a/crates/router/src/routes/app.rs b/crates/router/src/routes/app.rs index 9e8bee73c28..c130da8dbb4 100644 --- a/crates/router/src/routes/app.rs +++ b/crates/router/src/routes/app.rs @@ -976,41 +976,12 @@ impl User { .service(web::resource("/switch/list").route(web::get().to(list_merchant_ids_for_user))) .service(web::resource("/permission_info").route(web::get().to(get_authorization_info))) .service(web::resource("/update").route(web::post().to(update_user_account_details))) - .service( - web::resource("/user/invite_multiple").route(web::post().to(invite_multiple_user)), - ) .service( web::resource("/data") .route(web::get().to(get_multiple_dashboard_metadata)) .route(web::post().to(set_dashboard_metadata)), - ) - .service(web::resource("/user/delete").route(web::delete().to(delete_user_role))); - - // User management - route = route.service( - web::scope("/user") - .service(web::resource("/list").route(web::get().to(get_user_details))) - .service(web::resource("/invite").route(web::post().to(invite_user))) - .service(web::resource("/invite/accept").route(web::post().to(accept_invitation))) - .service(web::resource("/update_role").route(web::post().to(update_user_role))), - ); - - // Role information - route = route.service( - web::scope("/role") - .service(web::resource("").route(web::get().to(get_role_from_token))) - .service(web::resource("/list").route(web::get().to(list_all_roles))) - .service(web::resource("/{role_id}").route(web::get().to(get_role))), - ); + ); - #[cfg(feature = "dummy_connector")] - { - route = route.service( - web::resource("/sample_data") - .route(web::post().to(generate_sample_data)) - .route(web::delete().to(delete_sample_data)), - ) - } #[cfg(feature = "email")] { route = route @@ -1031,12 +1002,43 @@ impl User { .service( web::resource("/verify_email_request") .route(web::post().to(verify_email_request)), - ); + ) + .service(web::resource("/user/resend_invite").route(web::post().to(resend_invite))); } #[cfg(not(feature = "email"))] { route = route.service(web::resource("/signup").route(web::post().to(user_signup))) } + + // User management + route = route.service( + web::scope("/user") + .service(web::resource("/list").route(web::get().to(get_user_details))) + .service(web::resource("/invite").route(web::post().to(invite_user))) + .service( + web::resource("/invite_multiple").route(web::post().to(invite_multiple_user)), + ) + .service(web::resource("/invite/accept").route(web::post().to(accept_invitation))) + .service(web::resource("/update_role").route(web::post().to(update_user_role))) + .service(web::resource("/delete").route(web::delete().to(delete_user_role))), + ); + + // Role information + route = route.service( + web::scope("/role") + .service(web::resource("").route(web::get().to(get_role_from_token))) + .service(web::resource("/list").route(web::get().to(list_all_roles))) + .service(web::resource("/{role_id}").route(web::get().to(get_role))), + ); + + #[cfg(feature = "dummy_connector")] + { + route = route.service( + web::resource("/sample_data") + .route(web::post().to(generate_sample_data)) + .route(web::delete().to(delete_sample_data)), + ) + } route } } diff --git a/crates/router/src/routes/lock_utils.rs b/crates/router/src/routes/lock_utils.rs index 0dfc3b1b339..042e89fdd52 100644 --- a/crates/router/src/routes/lock_utils.rs +++ b/crates/router/src/routes/lock_utils.rs @@ -182,6 +182,7 @@ impl From<Flow> for ApiIdentifier { | Flow::ResetPassword | Flow::InviteUser | Flow::InviteMultipleUser + | Flow::ReInviteUser | Flow::UserSignUpWithMerchantId | Flow::VerifyEmailWithoutInviteChecks | Flow::VerifyEmail diff --git a/crates/router/src/routes/user.rs b/crates/router/src/routes/user.rs index 0c2694dc70f..a863bc2b662 100644 --- a/crates/router/src/routes/user.rs +++ b/crates/router/src/routes/user.rs @@ -401,6 +401,25 @@ pub async fn invite_multiple_user( .await } +#[cfg(feature = "email")] +pub async fn resend_invite( + state: web::Data<AppState>, + req: HttpRequest, + payload: web::Json<user_api::ReInviteUserRequest>, +) -> HttpResponse { + let flow = Flow::ReInviteUser; + Box::pin(api::server_wrap( + flow, + state.clone(), + &req, + payload.into_inner(), + user_core::resend_invite, + &auth::JWTAuth(Permission::UsersWrite), + api_locking::LockAction::NotApplicable, + )) + .await +} + #[cfg(feature = "email")] pub async fn verify_email_without_invite_checks( state: web::Data<AppState>, diff --git a/crates/router_env/src/logger/types.rs b/crates/router_env/src/logger/types.rs index 55e7bafd8e0..11e6f9c0ed8 100644 --- a/crates/router_env/src/logger/types.rs +++ b/crates/router_env/src/logger/types.rs @@ -331,6 +331,8 @@ pub enum Flow { InviteUser, /// Invite multiple users InviteMultipleUser, + /// Reinvite user + ReInviteUser, /// Delete user role DeleteUserRole, /// Incremental Authorization flow
2024-02-01T12:20:14Z
## Type of Change <!-- Put an `x` in the boxes that apply --> - [ ] Bugfix - [x] New feature - [ ] Enhancement - [ ] Refactoring - [ ] Dependency updates - [ ] Documentation - [ ] CI/CD ## Description The new endpoint `/resend_invite`, add supports to send invitation to user again. ### 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 invite user: ``` curl --location 'http://localhost:8080/user/user/invite' \ --header 'Authorization: Bearer JWT' \ --header 'Content-Type: application/json' \ --data-raw '{ "email": "test_2@juspay.in", "name": "test2", "role_id": "merchant_admin" } ' ``` For resend invite: ``` curl --location 'http://localhost:8080/user/user/resend_invite' \ --header 'Authorization: Bearer JWT' \ --header 'Content-Type: application/json' \ --data-raw '{ "email": "test_2@juspay.in" }' ``` <img width="1259" alt="Screenshot 2024-02-01 at 5 39 38 PM" src="https://github.com/juspay/hyperswitch/assets/64925866/0fd7df5d-4db6-4e5f-ba6e-0635cbfe9e18"> ## 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 - [ ] I added a [CHANGELOG](/CHANGELOG.md) entry if applicable
54fb61eeebec503f599774fe9e97f6b6ce3f1458
To invite user: ``` curl --location 'http://localhost:8080/user/user/invite' \ --header 'Authorization: Bearer JWT' \ --header 'Content-Type: application/json' \ --data-raw '{ "email": "test_2@juspay.in", "name": "test2", "role_id": "merchant_admin" } ' ``` For resend invite: ``` curl --location 'http://localhost:8080/user/user/resend_invite' \ --header 'Authorization: Bearer JWT' \ --header 'Content-Type: application/json' \ --data-raw '{ "email": "test_2@juspay.in" }' ``` <img width="1259" alt="Screenshot 2024-02-01 at 5 39 38 PM" src="https://github.com/juspay/hyperswitch/assets/64925866/0fd7df5d-4db6-4e5f-ba6e-0635cbfe9e18">
juspay/hyperswitch
juspay__hyperswitch-3520
Bug: feat(logging-framework): Add a end log line to print the accumulated log values Instead of relying on the exit & entry points of root spans, we should add an explicit log entry at the end of root span
diff --git a/crates/router/src/middleware.rs b/crates/router/src/middleware.rs index 702c3c70e6c..9205f53a04b 100644 --- a/crates/router/src/middleware.rs +++ b/crates/router/src/middleware.rs @@ -141,9 +141,14 @@ where let response_fut = self.service.call(req); Box::pin( - response_fut.instrument( + async move { + let response = response_fut.await; + logger::info!(golden_log_line = true); + response + } + .instrument( router_env::tracing::info_span!( - "golden_log_line", + "ROOT_SPAN", payment_id = Empty, merchant_id = Empty, connector_name = Empty, diff --git a/crates/router/src/routes/customers.rs b/crates/router/src/routes/customers.rs index 012030df6be..a20d2dd026b 100644 --- a/crates/router/src/routes/customers.rs +++ b/crates/router/src/routes/customers.rs @@ -147,7 +147,7 @@ pub async fn get_customer_mandates( customer_id: path.into_inner(), }; - api::server_wrap( + Box::pin(api::server_wrap( flow, state, &req, @@ -166,6 +166,6 @@ pub async fn get_customer_mandates( req.headers(), ), api_locking::LockAction::NotApplicable, - ) + )) .await } diff --git a/crates/router/src/routes/mandates.rs b/crates/router/src/routes/mandates.rs index eafd61dcded..1203b766cbb 100644 --- a/crates/router/src/routes/mandates.rs +++ b/crates/router/src/routes/mandates.rs @@ -118,7 +118,7 @@ pub async fn retrieve_mandates_list( ) -> HttpResponse { let flow = Flow::MandatesList; let payload = payload.into_inner(); - api::server_wrap( + Box::pin(api::server_wrap( flow, state, &req, @@ -132,6 +132,6 @@ pub async fn retrieve_mandates_list( req.headers(), ), api_locking::LockAction::NotApplicable, - ) + )) .await }
2024-02-01T13:06:05Z
## 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 --> - Add an end request log line for logging keys ### 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). --> - Since we no longer log enter & exit spans we need an explicit log line to mark end of request ## 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 health API call & check for the following log line ```json { "message": "[ROOT_SPAN - EVENT] router::middleware", "hostname": "sampraslopes-SERIAL.local", "pid": 78236, "env": "development", "level": "INFO", "target": "router::middleware", "service": "router", "line": 146, "file": "crates/router/src/middleware.rs", "fn": "ROOT_SPAN", "full_name": "router::middleware::ROOT_SPAN", "time": "2024-02-01T11:54:29.607859000Z", "flow": "UNKNOWN", "request_id": "018d6485-3b65-7902-8983-fc57988d7e7a", "extra": { "golden_log_line": true, "otel.kind": "server", "http.scheme": "http", "trace_id": "00000000000000000000000000000000", "http.method": "GET", "http.host": "localhost:8080", "http.user_agent": "Mozilla/5.0 (Macintosh; Intel Mac OS X 10.15; rv:123.0) Gecko/20100101 Firefox/123.0", "otel.name": "HTTP GET default", "http.flavor": "1.1", "http.route": "default", "http.target": "/favicon.ico", "http.client_ip": "127.0.0.1" } } ``` ## 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 - [ ] I added a [CHANGELOG](/CHANGELOG.md) entry if applicable
54fb61eeebec503f599774fe9e97f6b6ce3f1458
make a health API call & check for the following log line ```json { "message": "[ROOT_SPAN - EVENT] router::middleware", "hostname": "sampraslopes-SERIAL.local", "pid": 78236, "env": "development", "level": "INFO", "target": "router::middleware", "service": "router", "line": 146, "file": "crates/router/src/middleware.rs", "fn": "ROOT_SPAN", "full_name": "router::middleware::ROOT_SPAN", "time": "2024-02-01T11:54:29.607859000Z", "flow": "UNKNOWN", "request_id": "018d6485-3b65-7902-8983-fc57988d7e7a", "extra": { "golden_log_line": true, "otel.kind": "server", "http.scheme": "http", "trace_id": "00000000000000000000000000000000", "http.method": "GET", "http.host": "localhost:8080", "http.user_agent": "Mozilla/5.0 (Macintosh; Intel Mac OS X 10.15; rv:123.0) Gecko/20100101 Firefox/123.0", "otel.name": "HTTP GET default", "http.flavor": "1.1", "http.route": "default", "http.target": "/favicon.ico", "http.client_ip": "127.0.0.1" } } ```
juspay/hyperswitch
juspay__hyperswitch-3518
Bug: Deep health check for outgoing request
diff --git a/crates/api_models/src/health_check.rs b/crates/api_models/src/health_check.rs index 8323f135134..c1ab2a2d757 100644 --- a/crates/api_models/src/health_check.rs +++ b/crates/api_models/src/health_check.rs @@ -5,6 +5,7 @@ pub struct RouterHealthCheckResponse { pub locker: bool, #[cfg(feature = "olap")] pub analytics: bool, + pub outgoing_request: bool, } impl common_utils::events::ApiEventMetric for RouterHealthCheckResponse {} diff --git a/crates/router/src/consts.rs b/crates/router/src/consts.rs index 12b688e3d3a..3c3f01dc5f9 100644 --- a/crates/router/src/consts.rs +++ b/crates/router/src/consts.rs @@ -91,3 +91,6 @@ pub const MAX_SESSION_EXPIRY: u32 = 7890000; pub const MIN_SESSION_EXPIRY: u32 = 60; pub const LOCKER_HEALTH_CALL_PATH: &str = "/health"; + +// URL for checking the outgoing call +pub const OUTGOING_CALL_URL: &str = "https://api.stripe.com/healthcheck"; diff --git a/crates/router/src/core/errors.rs b/crates/router/src/core/errors.rs index cbc4290f63b..9052893d4a9 100644 --- a/crates/router/src/core/errors.rs +++ b/crates/router/src/core/errors.rs @@ -186,6 +186,12 @@ pub enum ConnectorError { InvalidConnectorConfig { config: &'static str }, } +#[derive(Debug, thiserror::Error)] +pub enum HealthCheckOutGoing { + #[error("Outgoing call failed with error: {message}")] + OutGoingFailed { message: String }, +} + #[derive(Debug, thiserror::Error)] pub enum VaultError { #[error("Failed to save card in card vault")] diff --git a/crates/router/src/core/health_check.rs b/crates/router/src/core/health_check.rs index 6fc038b82e9..bc523b4fba6 100644 --- a/crates/router/src/core/health_check.rs +++ b/crates/router/src/core/health_check.rs @@ -4,7 +4,7 @@ use error_stack::ResultExt; use router_env::logger; use crate::{ - consts::LOCKER_HEALTH_CALL_PATH, + consts, core::errors::{self, CustomResult}, routes::app, services::api as services, @@ -15,6 +15,7 @@ pub trait HealthCheckInterface { async fn health_check_db(&self) -> CustomResult<(), errors::HealthCheckDBError>; async fn health_check_redis(&self) -> CustomResult<(), errors::HealthCheckRedisError>; async fn health_check_locker(&self) -> CustomResult<(), errors::HealthCheckLockerError>; + async fn health_check_outgoing(&self) -> CustomResult<(), errors::HealthCheckOutGoing>; #[cfg(feature = "olap")] async fn health_check_analytics(&self) -> CustomResult<(), errors::HealthCheckDBError>; } @@ -61,7 +62,7 @@ impl HealthCheckInterface for app::AppState { let locker = &self.conf.locker; if !locker.mock_locker { let mut url = locker.host_rs.to_owned(); - url.push_str(LOCKER_HEALTH_CALL_PATH); + url.push_str(consts::LOCKER_HEALTH_CALL_PATH); let request = services::Request::new(services::Method::Get, &url); services::call_connector_api(self, request) .await @@ -108,4 +109,22 @@ impl HealthCheckInterface for app::AppState { } } } + + async fn health_check_outgoing(&self) -> CustomResult<(), errors::HealthCheckOutGoing> { + let request = services::Request::new(services::Method::Get, consts::OUTGOING_CALL_URL); + services::call_connector_api(self, request) + .await + .map_err(|err| errors::HealthCheckOutGoing::OutGoingFailed { + message: err.to_string(), + })? + .map_err(|err| errors::HealthCheckOutGoing::OutGoingFailed { + message: format!( + "Got a non 200 status while making outgoing request. Error {:?}", + err.response + ), + })?; + + logger::debug!("Outgoing request successful"); + Ok(()) + } } diff --git a/crates/router/src/routes/health.rs b/crates/router/src/routes/health.rs index 89132c3319b..2183ab07fed 100644 --- a/crates/router/src/routes/health.rs +++ b/crates/router/src/routes/health.rs @@ -94,6 +94,17 @@ async fn deep_health_check_func(state: app::AppState) -> RouterResponse<RouterHe }) })?; + let outgoing_check = state + .health_check_outgoing() + .await + .map(|_| true) + .map_err(|err| { + error_stack::report!(errors::ApiErrorResponse::HealthCheckError { + component: "Outgoing Request", + message: err.to_string() + }) + })?; + logger::debug!("Locker health check end"); let response = RouterHealthCheckResponse { @@ -102,6 +113,7 @@ async fn deep_health_check_func(state: app::AppState) -> RouterResponse<RouterHe locker: locker_status, #[cfg(feature = "olap")] analytics: analytics_status, + outgoing_request: outgoing_check, }; Ok(api::ApplicationResponse::Json(response))
2024-02-01T06:29:21Z
## Type of Change <!-- Put an `x` in the boxes that apply --> - [x] New feature ## Description <!-- Describe your changes in detail --> Closes #3518. Add healthcheck for outgoing calls ## 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). --> Added a check for outgoing requests ## 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/health/ready'` <img width="907" alt="Screenshot 2024-02-01 at 11 58 57 AM" src="https://github.com/juspay/hyperswitch/assets/43412619/79ebea8f-4ab2-4d35-893d-60974f64b39f"> ## 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
20efc3020ac389199eed13154f070685417ef82a
- `curl --location 'http://localhost:8080/health/ready'` <img width="907" alt="Screenshot 2024-02-01 at 11 58 57 AM" src="https://github.com/juspay/hyperswitch/assets/43412619/79ebea8f-4ab2-4d35-893d-60974f64b39f">
juspay/hyperswitch
juspay__hyperswitch-3514
Bug: [FEATURE] send metadata field in authentication request for nmi, noon and cryptopay ### Feature Description Send metadata in the authorize request for noon, nmi and cryptopay. ### Possible Implementation metadata field is being sent in routerData.request for Authorize request. This needs to be mapped to connector request body. ### 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/payment_methods.rs b/crates/api_models/src/payment_methods.rs index 0540d470a94..ef1812acf11 100644 --- a/crates/api_models/src/payment_methods.rs +++ b/crates/api_models/src/payment_methods.rs @@ -642,7 +642,7 @@ pub struct PaymentMethodListResponse { pub redirect_url: Option<String>, /// currency of the Payment to be done - #[schema(example = "USD")] + #[schema(example = "USD", value_type = Currency)] pub currency: Option<api_enums::Currency>, /// Information about the payment method diff --git a/crates/router/src/connector/cryptopay/transformers.rs b/crates/router/src/connector/cryptopay/transformers.rs index 4102945b201..fb806fda68f 100644 --- a/crates/router/src/connector/cryptopay/transformers.rs +++ b/crates/router/src/connector/cryptopay/transformers.rs @@ -1,3 +1,4 @@ +use common_utils::pii; use masking::Secret; use reqwest::Url; use serde::{Deserialize, Serialize}; @@ -47,6 +48,7 @@ pub struct CryptopayPaymentsRequest { pay_currency: String, success_redirect_url: Option<String>, unsuccess_redirect_url: Option<String>, + metadata: Option<pii::SecretSerdeValue>, custom_id: String, } @@ -66,6 +68,7 @@ impl TryFrom<&CryptopayRouterData<&types::PaymentsAuthorizeRouterData>> pay_currency, success_redirect_url: item.router_data.request.router_return_url.clone(), unsuccess_redirect_url: item.router_data.request.router_return_url.clone(), + metadata: item.router_data.request.metadata.clone(), custom_id: item.router_data.connector_request_reference_id.clone(), }) } diff --git a/crates/router/src/connector/nmi/transformers.rs b/crates/router/src/connector/nmi/transformers.rs index 5b486aae600..395781cc516 100644 --- a/crates/router/src/connector/nmi/transformers.rs +++ b/crates/router/src/connector/nmi/transformers.rs @@ -1,8 +1,8 @@ use api_models::webhooks; use cards::CardNumber; -use common_utils::{errors::CustomResult, ext_traits::XmlExt}; +use common_utils::{errors::CustomResult, ext_traits::XmlExt, pii}; use error_stack::{IntoReport, Report, ResultExt}; -use masking::{ExposeInterface, Secret}; +use masking::{ExposeInterface, PeekInterface, Secret}; use serde::{Deserialize, Serialize}; use crate::{ @@ -403,9 +403,35 @@ pub struct NmiPaymentsRequest { currency: enums::Currency, #[serde(flatten)] payment_method: PaymentMethod, + #[serde(flatten)] + merchant_defined_field: Option<NmiMerchantDefinedField>, orderid: String, } +#[derive(Debug, Serialize)] +pub struct NmiMerchantDefinedField { + #[serde(flatten)] + inner: std::collections::BTreeMap<String, Secret<String>>, +} + +impl NmiMerchantDefinedField { + pub fn new(metadata: &pii::SecretSerdeValue) -> Self { + let metadata_as_string = metadata.peek().to_string(); + let hash_map: std::collections::BTreeMap<String, serde_json::Value> = + serde_json::from_str(&metadata_as_string).unwrap_or(std::collections::BTreeMap::new()); + let inner = hash_map + .into_iter() + .enumerate() + .map(|(index, (hs_key, hs_value))| { + let nmi_key = format!("merchant_defined_field_{}", index + 1); + let nmi_value = format!("{hs_key}={hs_value}"); + (nmi_key, Secret::new(nmi_value)) + }) + .collect(); + Self { inner } + } +} + #[derive(Debug, Serialize)] #[serde(untagged)] pub enum PaymentMethod { @@ -451,6 +477,12 @@ impl TryFrom<&NmiRouterData<&types::PaymentsAuthorizeRouterData>> for NmiPayment amount, currency: item.router_data.request.currency, payment_method, + merchant_defined_field: item + .router_data + .request + .metadata + .as_ref() + .map(NmiMerchantDefinedField::new), orderid: item.router_data.connector_request_reference_id.clone(), }) } @@ -564,6 +596,7 @@ impl TryFrom<&types::SetupMandateRouterData> for NmiPaymentsRequest { amount: 0.0, currency: item.request.currency, payment_method, + merchant_defined_field: None, orderid: item.connector_request_reference_id.clone(), }) } diff --git a/crates/router/src/connector/noon.rs b/crates/router/src/connector/noon.rs index 6c98a307637..6e1959b46d0 100644 --- a/crates/router/src/connector/noon.rs +++ b/crates/router/src/connector/noon.rs @@ -5,8 +5,9 @@ use std::fmt::Debug; use base64::Engine; use common_utils::{crypto, ext_traits::ByteSliceExt, request::RequestContent}; use diesel_models::enums; -use error_stack::{IntoReport, ResultExt}; +use error_stack::{IntoReport, Report, ResultExt}; use masking::PeekInterface; +use router_env::logger; use transformers as noon; use crate::{ @@ -28,7 +29,7 @@ use crate::{ api::{self, ConnectorCommon, ConnectorCommonExt}, ErrorResponse, Response, }, - utils::BytesExt, + utils::{self, BytesExt}, }; #[derive(Debug, Clone)] @@ -127,19 +128,23 @@ impl ConnectorCommon for Noon { &self, res: Response, ) -> CustomResult<ErrorResponse, errors::ConnectorError> { - let response: noon::NoonErrorResponse = res - .response - .parse_struct("NoonErrorResponse") - .change_context(errors::ConnectorError::ResponseDeserializationFailed)?; - - Ok(ErrorResponse { - status_code: res.status_code, - code: response.result_code.to_string(), - message: response.class_description, - reason: Some(response.message), - attempt_status: None, - connector_transaction_id: None, - }) + let response: Result<noon::NoonErrorResponse, Report<common_utils::errors::ParsingError>> = + res.response.parse_struct("NoonErrorResponse"); + + match response { + Ok(noon_error_response) => Ok(ErrorResponse { + status_code: res.status_code, + code: consts::NO_ERROR_CODE.to_string(), + message: noon_error_response.class_description, + reason: Some(noon_error_response.message), + attempt_status: None, + connector_transaction_id: None, + }), + Err(error_message) => { + logger::error!(deserialization_error =? error_message); + utils::handle_json_response_deserialization_failure(res, "noon".to_owned()) + } + } } } diff --git a/crates/router/src/connector/noon/transformers.rs b/crates/router/src/connector/noon/transformers.rs index 8bb3a96a3ca..9a6490c5756 100644 --- a/crates/router/src/connector/noon/transformers.rs +++ b/crates/router/src/connector/noon/transformers.rs @@ -1,6 +1,6 @@ use common_utils::pii; use error_stack::ResultExt; -use masking::Secret; +use masking::{PeekInterface, Secret}; use serde::{Deserialize, Serialize}; use crate::{ @@ -67,9 +67,46 @@ pub struct NoonOrder { reference: String, //Short description of the order. name: String, + nvp: Option<NoonOrderNvp>, ip_address: Option<Secret<String, pii::IpAddress>>, } +#[derive(Debug, Serialize)] +pub struct NoonOrderNvp { + #[serde(flatten)] + inner: std::collections::BTreeMap<String, Secret<String>>, +} + +fn get_value_as_string(value: &serde_json::Value) -> String { + match value { + serde_json::Value::String(string) => string.to_owned(), + serde_json::Value::Null + | serde_json::Value::Bool(_) + | serde_json::Value::Number(_) + | serde_json::Value::Array(_) + | serde_json::Value::Object(_) => value.to_string(), + } +} + +impl NoonOrderNvp { + pub fn new(metadata: &pii::SecretSerdeValue) -> Self { + let metadata_as_string = metadata.peek().to_string(); + let hash_map: std::collections::BTreeMap<String, serde_json::Value> = + serde_json::from_str(&metadata_as_string).unwrap_or(std::collections::BTreeMap::new()); + let inner = hash_map + .into_iter() + .enumerate() + .map(|(index, (hs_key, hs_value))| { + let noon_key = format!("{}", index + 1); + // to_string() function on serde_json::Value returns a string with "" quotes. Noon doesn't allow this. Hence get_value_as_string function + let noon_value = format!("{hs_key}={}", get_value_as_string(&hs_value)); + (noon_key, Secret::new(noon_value)) + }) + .collect(); + Self { inner } + } +} + #[derive(Debug, Serialize)] #[serde(rename_all = "UPPERCASE")] pub enum NoonPaymentActions { @@ -365,6 +402,7 @@ impl TryFrom<&types::PaymentsAuthorizeRouterData> for NoonPaymentsRequest { category, reference: item.connector_request_reference_id.clone(), name, + nvp: item.request.metadata.as_ref().map(NoonOrderNvp::new), ip_address, }; let payment_action = if item.request.is_auto_capture()? { diff --git a/openapi/openapi_spec.json b/openapi/openapi_spec.json index 98cfaecf6b8..9992360723e 100644 --- a/openapi/openapi_spec.json +++ b/openapi/openapi_spec.json @@ -11637,6 +11637,7 @@ "PaymentMethodListResponse": { "type": "object", "required": [ + "currency", "payment_methods", "mandate_payment", "show_surcharge_breakup_screen" @@ -11648,6 +11649,9 @@ "example": "https://www.google.com", "nullable": true }, + "currency": { + "$ref": "#/components/schemas/Currency" + }, "payment_methods": { "type": "array", "items": {
2024-01-11T09:59:47Z
## 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 --> Send metadata in the authorize request for noon, nmi and cryptopay. ### 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)? --> Manual. 1. CryptoPay (connector force sync response) <img width="1728" alt="Cryptopay log" src="https://github.com/juspay/hyperswitch/assets/61539176/1975c066-bcb1-4ae8-ad91-c200d92d28fa"> 2. NMI (connector force sync response) Authomatic capture (auth+capture) <img width="1728" alt="Screenshot 2024-02-06 at 12 36 19 PM" src="https://github.com/juspay/hyperswitch/assets/61539176/1d512585-1211-4fae-a7ed-d79f4f30f718"> Manual Capture(auth and then capture) <img width="1728" alt="Screenshot 2024-02-06 at 1 16 28 PM" src="https://github.com/juspay/hyperswitch/assets/61539176/6c9c5401-0bad-4b6f-b419-2d2bddf729ab"> 4. Noon (connector dashboard) <img width="1728" alt="Screenshot 2024-01-31 at 8 25 10 PM" src="https://github.com/juspay/hyperswitch/assets/61539176/6b2b759a-b97d-4acf-894b-2b179f7bbbdc"> ## 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 - [ ] I added a [CHANGELOG](/CHANGELOG.md) entry if applicable
a9c0d0c55492c14a4a10283ffd8deae04c8ea853
Manual. 1. CryptoPay (connector force sync response) <img width="1728" alt="Cryptopay log" src="https://github.com/juspay/hyperswitch/assets/61539176/1975c066-bcb1-4ae8-ad91-c200d92d28fa"> 2. NMI (connector force sync response) Authomatic capture (auth+capture) <img width="1728" alt="Screenshot 2024-02-06 at 12 36 19 PM" src="https://github.com/juspay/hyperswitch/assets/61539176/1d512585-1211-4fae-a7ed-d79f4f30f718"> Manual Capture(auth and then capture) <img width="1728" alt="Screenshot 2024-02-06 at 1 16 28 PM" src="https://github.com/juspay/hyperswitch/assets/61539176/6c9c5401-0bad-4b6f-b419-2d2bddf729ab"> 4. Noon (connector dashboard) <img width="1728" alt="Screenshot 2024-01-31 at 8 25 10 PM" src="https://github.com/juspay/hyperswitch/assets/61539176/6b2b759a-b97d-4acf-894b-2b179f7bbbdc">
juspay/hyperswitch
juspay__hyperswitch-3513
Bug: [CHORE] Add file storage config in env_specific toml ### Feature Description Add file storage config in env_specific.toml ### Possible Implementation Add file storage config in env_specific.toml ### 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/deployments/env_specific.toml b/config/deployments/env_specific.toml index 354c320e8f5..04831376050 100644 --- a/config/deployments/env_specific.toml +++ b/config/deployments/env_specific.toml @@ -70,9 +70,13 @@ api_logs_topic = "topic" # Kafka topic to be used for incoming api connector_logs_topic = "topic" # Kafka topic to be used for connector api events outgoing_webhook_logs_topic = "topic" # Kafka topic to be used for outgoing webhook events -[file_upload_config] -bucket_name = "bucket" -region = "bucket_region" +# File storage configuration +[file_storage] +file_storage_backend = "aws_s3" # File storage backend to be used + +[file_storage.aws_s3] +region = "bucket_region" # The AWS region used by AWS S3 for file storage +bucket_name = "bucket" # The AWS S3 bucket name for file storage # This section provides configs for currency conversion api [forex_api]
2024-01-31T16:03:36Z
## 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 adds file storage config in `env_specific.toml` ### 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)? --> Cannot be tested as this is just a config addition ## 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 - [ ] I added a [CHANGELOG](/CHANGELOG.md) entry if applicable
7251f6474fdac3575202971e55638c435ca5c4c8
Cannot be tested as this is just a config addition
juspay/hyperswitch
juspay__hyperswitch-3511
Bug: [BUG] Nuvei Payment request validation issues ### Bug Description nuvei payments - browser_info is validated for both non-3ds and 3ds flows, as per nuvei docs browser_info is mandatory only for 3ds flows. The validation should be thrown by gateway instead - IP address and billing address not sent to Nuvei, which is mandatory by default, hyperswitch is currently not passing these fields. we were not able to use any other nuvei account due to this, These fields can be controlled at nuvei gateway account level, but by default they are mandatory and nuvei recommends these info to be sent. ### Expected Behavior - browser_info : Gateway should validate if browser info is not provided, payment request should go through even without browser_info for non-3ds - IP address and billing address should forward these details to nuvei ### Actual Behavior - browser_info is validated by hyperswitch when not provided, even in cases where its not mandatory - IP address and billing address is not sent from hyperswitch to nuvei ### Steps To Reproduce Payment request to reproduce the issue : ``` `curl --location 'http://localhost:8090/payments' \ --header 'Content-Type: application/json' \ --header 'Accept: application/json' \ --header 'api-key: dev_GHrXsmnL5N4eGiw363ZF6qfzWxjk2UqwQHlkvaE4B03lGV9Vb4ESpCK6aKjYdN9V' \ --data-raw '{ "amount": 1000, "currency": "USD", "confirm": true, "capture_method": "automatic", "customer_id": "futurebilling", "email": "guest@example.com", "name": "John Doe", "phone": "999999999", "phone_country_code": "+65", "description": "testing", "authentication_type": "three_ds", "return_url": "https://google.com", "payment_method": "card", "payment_method_type": "credit", "setup_future_usage": "off_session", "payment_method_data": { "card": { "card_number": "4000027891380961", "card_exp_month": "12", "card_exp_year": "2030", "card_holder_name": "joseph Doe", "card_cvc": "123" } }, "mandate_data": { "customer_acceptance": { "acceptance_type": "offline", "accepted_at": "1963-05-03T04:07:52.723Z", "online": { "ip_address": "127.0.0.1", "user_agent": "amet irure esse" } }, "mandate_type": { "multi_use": { "amount": 7000, "currency": "USD", "metadata": { "frequency": "1" }, "end_date": "2025-05-03T04:07:52.723Z" } } }, "billing": { "address": { "line1": "1467", "line2": "Harrison Street", "line3": "Harrison Street", "city": "San Fransico", "state": "California", "zip": "94122", "country": "BR", "first_name": "joseph", "last_name": "Doe" } }, "shipping": { "address": { "line1": "1467", "line2": "Harrison Street", "line3": "Harrison Street", "city": "San Fransico", "zip": "94122", "country": "BR", "first_name": "joseph", "last_name": "Doe" }, "phone": { "number": "8056594427", "country_code": "+91" } }, "statement_descriptor_name": "joseph", "metadata": { "udf1": "value1", "new_customer": "true", "login_date": "2019-09-10T10:11:12Z" } }'` ``` ### 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. x-request-id : 018d6035-8137-75c6-8088-4754d80e0701 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/connector/nuvei/transformers.rs b/crates/router/src/connector/nuvei/transformers.rs index d5dd6e813ae..fe17fae8770 100644 --- a/crates/router/src/connector/nuvei/transformers.rs +++ b/crates/router/src/connector/nuvei/transformers.rs @@ -20,7 +20,7 @@ use crate::{ consts, core::errors, services, - types::{self, api, storage::enums, transformers::ForeignTryFrom}, + types::{self, api, storage::enums, transformers::ForeignTryFrom, BrowserInformation}, utils::OptionExt, }; @@ -75,6 +75,7 @@ pub struct NuveiPaymentsRequest { pub transaction_type: TransactionType, pub is_rebilling: Option<String>, pub payment_option: PaymentOption, + pub device_details: Option<DeviceDetails>, pub checksum: String, pub billing_address: Option<BillingAddress>, pub related_transaction_id: Option<String>, @@ -135,7 +136,6 @@ pub struct PaymentOption { pub card: Option<Card>, pub redirect_url: Option<Url>, pub user_payment_option_id: Option<String>, - pub device_details: Option<DeviceDetails>, pub alternative_payment_method: Option<AlternativePaymentMethod>, pub billing_address: Option<BillingAddress>, } @@ -315,7 +315,7 @@ pub struct V2AdditionalParams { #[derive(Debug, Clone, Default, Serialize, Deserialize)] #[serde(rename_all = "camelCase")] pub struct DeviceDetails { - pub ip_address: String, + pub ip_address: Secret<String, pii::IpAddress>, } impl From<enums::CaptureMethod> for TransactionType { @@ -746,6 +746,7 @@ impl<F> let item = data.0; let request_data = match item.request.payment_method_data.clone() { api::PaymentMethodData::Card(card) => get_card_info(item, &card), + api::PaymentMethodData::MandatePayment => Self::try_from(item), api::PaymentMethodData::Wallet(wallet) => match wallet { payments::WalletData::GooglePay(gpay_data) => Self::try_from(gpay_data), payments::WalletData::ApplePay(apple_pay_data) => Ok(Self::from(apple_pay_data)), @@ -845,7 +846,6 @@ impl<F> payments::PaymentMethodData::BankDebit(_) | payments::PaymentMethodData::BankTransfer(_) | payments::PaymentMethodData::Crypto(_) - | payments::PaymentMethodData::MandatePayment | payments::PaymentMethodData::Reward | payments::PaymentMethodData::Upi(_) | payments::PaymentMethodData::Voucher(_) @@ -874,6 +874,7 @@ impl<F> related_transaction_id: request_data.related_transaction_id, payment_option: request_data.payment_option, billing_address: request_data.billing_address, + device_details: request_data.device_details, url_details: Some(UrlDetails { success_url: return_url.clone(), failure_url: return_url.clone(), @@ -888,104 +889,110 @@ fn get_card_info<F>( item: &types::RouterData<F, types::PaymentsAuthorizeData, types::PaymentsResponseData>, card_details: &payments::Card, ) -> Result<NuveiPaymentsRequest, error_stack::Report<errors::ConnectorError>> { - let browser_info = item.request.get_browser_info()?; + let browser_information = item.request.browser_info.clone(); let related_transaction_id = if item.is_three_ds() { item.request.related_transaction_id.clone() } else { None }; - let connector_mandate_id = &item.request.connector_mandate_id(); - if connector_mandate_id.is_some() { - Ok(NuveiPaymentsRequest { - related_transaction_id, - is_rebilling: Some("1".to_string()), // In case of second installment, rebilling should be 1 - user_token_id: Some(item.request.get_email()?), - payment_option: PaymentOption { - user_payment_option_id: connector_mandate_id.clone(), - ..Default::default() - }, - ..Default::default() - }) - } else { - let (is_rebilling, additional_params, user_token_id) = - match item.request.setup_mandate_details.clone() { - Some(mandate_data) => { - let details = match mandate_data - .mandate_type - .get_required_value("mandate_type") - .change_context(errors::ConnectorError::MissingRequiredField { - field_name: "mandate_type", - })? { - MandateDataType::SingleUse(details) => details, - MandateDataType::MultiUse(details) => { - details.ok_or(errors::ConnectorError::MissingRequiredField { - field_name: "mandate_data.mandate_type.multi_use", - })? - } - }; - let mandate_meta: NuveiMandateMeta = utils::to_connector_meta_from_secret( - Some(details.get_metadata().ok_or_else(utils::missing_field_err( - "mandate_data.mandate_type.{multi_use|single_use}.metadata", - ))?), - )?; - ( - Some("0".to_string()), // In case of first installment, rebilling should be 0 - Some(V2AdditionalParams { - rebill_expiry: Some( - details - .get_end_date(date_time::DateFormat::YYYYMMDD) - .change_context(errors::ConnectorError::DateFormattingFailed)? - .ok_or_else(utils::missing_field_err( - "mandate_data.mandate_type.{multi_use|single_use}.end_date", - ))?, - ), - rebill_frequency: Some(mandate_meta.frequency), - challenge_window_size: None, - }), - Some(item.request.get_email()?), - ) - } - _ => (None, None, None), - }; - let three_d = if item.is_three_ds() { - Some(ThreeD { - browser_details: Some(BrowserDetails { - accept_header: browser_info.get_accept_header()?, - ip: browser_info.get_ip_address()?, - java_enabled: browser_info.get_java_enabled()?.to_string().to_uppercase(), - java_script_enabled: browser_info - .get_java_script_enabled()? - .to_string() - .to_uppercase(), - language: browser_info.get_language()?, - screen_height: browser_info.get_screen_height()?, - screen_width: browser_info.get_screen_width()?, - color_depth: browser_info.get_color_depth()?, - user_agent: browser_info.get_user_agent()?, - time_zone: browser_info.get_time_zone()?, - }), - v2_additional_params: additional_params, - notification_url: item.request.complete_authorize_url.clone(), - merchant_url: item.return_url.clone(), - platform_type: Some(PlatformType::Browser), - method_completion_ind: Some(MethodCompletion::Unavailable), - ..Default::default() - }) - } else { - None - }; - Ok(NuveiPaymentsRequest { - related_transaction_id, - is_rebilling, - user_token_id, - payment_option: PaymentOption::from(NuveiCardDetails { - card: card_details.clone(), - three_d, + let address = item.get_billing_address_details_as_optional(); + + let billing_address = match address { + Some(address) => Some(BillingAddress { + first_name: Some(address.get_first_name()?.clone()), + last_name: Some(address.get_last_name()?.clone()), + email: item.request.get_email()?, + country: item.get_billing_country()?, + }), + None => None, + }; + let (is_rebilling, additional_params, user_token_id) = + match item.request.setup_mandate_details.clone() { + Some(mandate_data) => { + let details = match mandate_data + .mandate_type + .get_required_value("mandate_type") + .change_context(errors::ConnectorError::MissingRequiredField { + field_name: "mandate_type", + })? { + MandateDataType::SingleUse(details) => details, + MandateDataType::MultiUse(details) => { + details.ok_or(errors::ConnectorError::MissingRequiredField { + field_name: "mandate_data.mandate_type.multi_use", + })? + } + }; + let mandate_meta: NuveiMandateMeta = utils::to_connector_meta_from_secret(Some( + details.get_metadata().ok_or_else(utils::missing_field_err( + "mandate_data.mandate_type.{multi_use|single_use}.metadata", + ))?, + ))?; + ( + Some("0".to_string()), // In case of first installment, rebilling should be 0 + Some(V2AdditionalParams { + rebill_expiry: Some( + details + .get_end_date(date_time::DateFormat::YYYYMMDD) + .change_context(errors::ConnectorError::DateFormattingFailed)? + .ok_or_else(utils::missing_field_err( + "mandate_data.mandate_type.{multi_use|single_use}.end_date", + ))?, + ), + rebill_frequency: Some(mandate_meta.frequency), + challenge_window_size: None, + }), + Some(item.request.get_email()?), + ) + } + _ => (None, None, None), + }; + let three_d = if item.is_three_ds() { + let browser_details = match &browser_information { + Some(browser_info) => Some(BrowserDetails { + accept_header: browser_info.get_accept_header()?, + ip: browser_info.get_ip_address()?, + java_enabled: browser_info.get_java_enabled()?.to_string().to_uppercase(), + java_script_enabled: browser_info + .get_java_script_enabled()? + .to_string() + .to_uppercase(), + language: browser_info.get_language()?, + screen_height: browser_info.get_screen_height()?, + screen_width: browser_info.get_screen_width()?, + color_depth: browser_info.get_color_depth()?, + user_agent: browser_info.get_user_agent()?, + time_zone: browser_info.get_time_zone()?, }), + None => None, + }; + Some(ThreeD { + browser_details, + v2_additional_params: additional_params, + notification_url: item.request.complete_authorize_url.clone(), + merchant_url: item.return_url.clone(), + platform_type: Some(PlatformType::Browser), + method_completion_ind: Some(MethodCompletion::Unavailable), ..Default::default() }) - } + } else { + None + }; + + Ok(NuveiPaymentsRequest { + related_transaction_id, + is_rebilling, + user_token_id, + device_details: Option::<DeviceDetails>::foreign_try_from( + &item.request.browser_info.clone(), + )?, + payment_option: PaymentOption::from(NuveiCardDetails { + card: card_details.clone(), + three_d, + }), + billing_address, + ..Default::default() + }) } impl From<NuveiCardDetails> for PaymentOption { fn from(card_details: NuveiCardDetails) -> Self { @@ -1532,6 +1539,51 @@ impl TryFrom<types::RefundsResponseRouterData<api::RSync, NuveiPaymentsResponse> } } +impl<F> TryFrom<&types::RouterData<F, types::PaymentsAuthorizeData, types::PaymentsResponseData>> + for NuveiPaymentsRequest +{ + type Error = error_stack::Report<errors::ConnectorError>; + fn try_from( + data: &types::RouterData<F, types::PaymentsAuthorizeData, types::PaymentsResponseData>, + ) -> Result<Self, Self::Error> { + { + let item = data; + let connector_mandate_id = &item.request.connector_mandate_id(); + let related_transaction_id = if item.is_three_ds() { + item.request.related_transaction_id.clone() + } else { + None + }; + Ok(Self { + related_transaction_id, + device_details: Option::<DeviceDetails>::foreign_try_from( + &item.request.browser_info.clone(), + )?, + is_rebilling: Some("1".to_string()), // In case of second installment, rebilling should be 1 + user_token_id: Some(item.request.get_email()?), + payment_option: PaymentOption { + user_payment_option_id: connector_mandate_id.clone(), + ..Default::default() + }, + ..Default::default() + }) + } + } +} + +impl ForeignTryFrom<&Option<BrowserInformation>> for Option<DeviceDetails> { + type Error = error_stack::Report<errors::ConnectorError>; + fn foreign_try_from(browser_info: &Option<BrowserInformation>) -> Result<Self, Self::Error> { + let device_details = match browser_info { + Some(browser_info) => Some(DeviceDetails { + ip_address: browser_info.get_ip_address()?, + }), + None => None, + }; + Ok(device_details) + } +} + fn get_refund_response( response: NuveiPaymentsResponse, http_code: u16, diff --git a/crates/router/src/connector/utils.rs b/crates/router/src/connector/utils.rs index 7951246790f..1e4552d6577 100644 --- a/crates/router/src/connector/utils.rs +++ b/crates/router/src/connector/utils.rs @@ -86,6 +86,7 @@ pub trait RouterData { fn get_payout_method_data(&self) -> Result<api::PayoutMethodData, Error>; #[cfg(feature = "payouts")] fn get_quote_id(&self) -> Result<String, Error>; + fn get_billing_address_details_as_optional(&self) -> Option<api::AddressDetails>; } pub trait PaymentResponseRouterData { @@ -182,6 +183,14 @@ impl<Flow, Request, Response> RouterData for types::RouterData<Flow, Request, Re .ok_or_else(missing_field_err("billing.address")) } + fn get_billing_address_details_as_optional(&self) -> Option<api::AddressDetails> { + self.address + .billing + .as_ref() + .and_then(|a| a.address.as_ref()) + .cloned() + } + fn get_billing_address_with_phone_number(&self) -> Result<&api::Address, Error> { self.address .billing
2024-02-08T13:05:43Z
## Type of Change <!-- Put an `x` in the boxes that apply --> - [X] Bugfix - [ ] New feature - [X] Enhancement - [ ] Refactoring - [ ] Dependency updates - [ ] Documentation - [ ] CI/CD ## Description - Moved mandate logic outside card_info to MandatePayment - Included Device detail to send IP address to nuvei (mandatory) for both card_info and mandate flow , Ip address is taken from browser info - Billing address for rawcard payment flow - Moved broswer info inside three_ds request construction, since its optional for non-3ds card_info flow https://github.com/juspay/hyperswitch/issues/3537 https://github.com/juspay/hyperswitch/issues/3511 ### 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). --> Open Issues : https://github.com/juspay/hyperswitch/issues/3537 https://github.com/juspay/hyperswitch/issues/3511 Changes done to support Recurring mandate payments flow for Nuvei and included fix for mandatory detail population, like device_details, billing address and browser_info ## 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)? --> Added screenshots from testing Recurring pay with mandate <img width="1127" alt="Screenshot 2024-02-08 at 6 49 58 PM" src="https://github.com/juspay/hyperswitch/assets/97145230/a6c7997d-c98e-4eb1-b5d3-27a71c26f1c4"> Payment With and without IP address <img width="1400" alt="Screenshot 2024-02-08 at 6 49 08 PM" src="https://github.com/juspay/hyperswitch/assets/97145230/cab36f5e-2a5d-4a42-8ef2-25e737ae8c7e"> <img width="1417" alt="Screenshot 2024-02-08 at 6 48 30 PM" src="https://github.com/juspay/hyperswitch/assets/97145230/46953001-166e-40b7-ab97-8ed08573d2b9"> ## 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 - [ ] I added a [CHANGELOG](/CHANGELOG.md) entry if applicable
df739a302b062277647afe5c3888015272fdc2cf
Added screenshots from testing Recurring pay with mandate <img width="1127" alt="Screenshot 2024-02-08 at 6 49 58 PM" src="https://github.com/juspay/hyperswitch/assets/97145230/a6c7997d-c98e-4eb1-b5d3-27a71c26f1c4"> Payment With and without IP address <img width="1400" alt="Screenshot 2024-02-08 at 6 49 08 PM" src="https://github.com/juspay/hyperswitch/assets/97145230/cab36f5e-2a5d-4a42-8ef2-25e737ae8c7e"> <img width="1417" alt="Screenshot 2024-02-08 at 6 48 30 PM" src="https://github.com/juspay/hyperswitch/assets/97145230/46953001-166e-40b7-ab97-8ed08573d2b9">
juspay/hyperswitch
juspay__hyperswitch-3509
Bug: [BUG] : Add noon applepay mandate configs ### Bug Description Add noon Applepay mandate configs ### 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/config/config.example.toml b/config/config.example.toml index f7e9fa70f6e..007c671e9e4 100644 --- a/config/config.example.toml +++ b/config/config.example.toml @@ -383,6 +383,7 @@ bank_debit.becs = { connector_list = "gocardless" } # Mandate supported payment bank_debit.sepa = { connector_list = "gocardless" } # Mandate supported payment method type and connector for bank_debit bank_redirect.ideal = {connector_list = "stripe,adyen,globalpay"} # Mandate supported payment method type and connector for bank_redirect bank_redirect.sofort = {connector_list = "stripe,adyen,globalpay"} +wallet.apple_pay = { connector_list = "stripe,adyen,cybersource,noon" } # Required fields info used while listing the payment_method_data diff --git a/config/deployments/integration_test.toml b/config/deployments/integration_test.toml index b84546eff34..2c5d16e3e3c 100644 --- a/config/deployments/integration_test.toml +++ b/config/deployments/integration_test.toml @@ -114,7 +114,7 @@ bank_debit.sepa.connector_list = "gocardless" card.credit.connector_list = "stripe,adyen,authorizedotnet,cybersource,globalpay,worldpay,multisafepay,nmi,nexinets,noon" card.debit.connector_list = "stripe,adyen,authorizedotnet,cybersource,globalpay,worldpay,multisafepay,nmi,nexinets,noon" pay_later.klarna.connector_list = "adyen" -wallet.apple_pay.connector_list = "stripe,adyen,cybersource" +wallet.apple_pay.connector_list = "stripe,adyen,cybersource,noon" wallet.google_pay.connector_list = "stripe,adyen,cybersource" wallet.paypal.connector_list = "adyen" bank_redirect.ideal = {connector_list = "stripe,adyen,globalpay"} diff --git a/config/deployments/production.toml b/config/deployments/production.toml index d5479b4f02c..964281c52bb 100644 --- a/config/deployments/production.toml +++ b/config/deployments/production.toml @@ -114,7 +114,7 @@ bank_debit.sepa.connector_list = "gocardless" card.credit.connector_list = "stripe,adyen,authorizedotnet,cybersource,globalpay,worldpay,multisafepay,nmi,nexinets,noon" card.debit.connector_list = "stripe,adyen,authorizedotnet,cybersource,globalpay,worldpay,multisafepay,nmi,nexinets,noon" pay_later.klarna.connector_list = "adyen" -wallet.apple_pay.connector_list = "stripe,adyen,cybersource" +wallet.apple_pay.connector_list = "stripe,adyen,cybersource,noon" wallet.google_pay.connector_list = "stripe,adyen,cybersource" wallet.paypal.connector_list = "adyen" bank_redirect.ideal = {connector_list = "stripe,adyen,globalpay"} diff --git a/config/deployments/sandbox.toml b/config/deployments/sandbox.toml index 14f49e01caf..aa2377cf8a0 100644 --- a/config/deployments/sandbox.toml +++ b/config/deployments/sandbox.toml @@ -114,7 +114,7 @@ bank_debit.sepa.connector_list = "gocardless" card.credit.connector_list = "stripe,adyen,authorizedotnet,cybersource,globalpay,worldpay,multisafepay,nmi,nexinets,noon" card.debit.connector_list = "stripe,adyen,authorizedotnet,cybersource,globalpay,worldpay,multisafepay,nmi,nexinets,noon" pay_later.klarna.connector_list = "adyen" -wallet.apple_pay.connector_list = "stripe,adyen,cybersource" +wallet.apple_pay.connector_list = "stripe,adyen,cybersource,noon" wallet.google_pay.connector_list = "stripe,adyen,cybersource" wallet.paypal.connector_list = "adyen" bank_redirect.ideal = {connector_list = "stripe,adyen,globalpay"} diff --git a/config/docker_compose.toml b/config/docker_compose.toml index 67fca85929d..fba91dc1254 100644 --- a/config/docker_compose.toml +++ b/config/docker_compose.toml @@ -334,7 +334,7 @@ adyen = { banks = "aib,bank_of_scotland,danske_bank,first_direct,first_trust,hal [mandates.supported_payment_methods] pay_later.klarna = {connector_list = "adyen"} wallet.google_pay = {connector_list = "stripe,adyen"} -wallet.apple_pay = {connector_list = "stripe,adyen"} +wallet.apple_pay = {connector_list = "stripe,adyen,cybersource,noon"} wallet.paypal = {connector_list = "adyen"} card.credit = {connector_list = "stripe,adyen,authorizedotnet,cybersource,globalpay,worldpay,multisafepay,nmi,nexinets,noon"} card.debit = {connector_list = "stripe,adyen,authorizedotnet,cybersource,globalpay,worldpay,multisafepay,nmi,nexinets,noon"}
2024-01-31T13:46:33Z
## Type of Change <!-- Put an `x` in the boxes that apply --> - [x] Bugfix - [ ] New feature - [ ] Enhancement - [ ] Refactoring - [ ] Dependency updates - [ ] Documentation - [ ] CI/CD ##Description Add Applepay Mandate configs for noon in all environments. ## Test Case Applepay should appear in the payment method list ## 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 - [ ] I added a [CHANGELOG](/CHANGELOG.md) entry if applicable
20efc3020ac389199eed13154f070685417ef82a
juspay/hyperswitch
juspay__hyperswitch-3510
Bug: [FIX] add a configuration validation for workers We don't have a validation check [number of workers in our config](https://github.com/juspay/hyperswitch/blob/94cd7b689758a71e13a3eaa655335e658d13afc8/crates/router/src/configs/settings.rs#L422) . But if the number of workers is zero actix straight out panics. Ref: https://docs.rs/actix-web/latest/actix_web/struct.HttpServer.html#method.workers
diff --git a/crates/router/src/configs/validations.rs b/crates/router/src/configs/validations.rs index 910ae754347..69d0274d704 100644 --- a/crates/router/src/configs/validations.rs +++ b/crates/router/src/configs/validations.rs @@ -68,10 +68,18 @@ impl super::settings::Locker { impl super::settings::Server { pub fn validate(&self) -> Result<(), ApplicationError> { - common_utils::fp_utils::when(self.host.is_default_or_empty(), || { + use common_utils::fp_utils::when; + + when(self.host.is_default_or_empty(), || { Err(ApplicationError::InvalidConfigurationValueError( "server host must not be empty".into(), )) + })?; + + when(self.workers == 0, || { + Err(ApplicationError::InvalidConfigurationValueError( + "number of workers must be greater than 0".into(), + )) }) } }
2024-02-02T09:54:18Z
## 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 validation check on number workers ### 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). --> It fixes #3510 ## 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)? --> Nothing to test in this PR ## 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 - [ ] I added a [CHANGELOG](/CHANGELOG.md) entry if applicable
cf0e0b330e4c62860f645bcb61d96b07c9f4fb7b
Nothing to test in this PR
juspay/hyperswitch
juspay__hyperswitch-3497
Bug: [FIX] add a metric while pushing data to drainer stream
diff --git a/crates/storage_impl/src/lib.rs b/crates/storage_impl/src/lib.rs index 7e2c7f2fc3c..d31f05b4979 100644 --- a/crates/storage_impl/src/lib.rs +++ b/crates/storage_impl/src/lib.rs @@ -225,6 +225,11 @@ impl<T: DatabaseStore> KVRouterStore<T> { .change_context(RedisError::JsonSerializationFailed)?, ) .await + .map(|_| metrics::KV_PUSHED_TO_DRAINER.add(&metrics::CONTEXT, 1, &[])) + .map_err(|err| { + metrics::KV_FAILED_TO_PUSH_TO_DRAINER.add(&metrics::CONTEXT, 1, &[]); + err + }) .change_context(RedisError::StreamAppendFailed) } } diff --git a/crates/storage_impl/src/metrics.rs b/crates/storage_impl/src/metrics.rs index 3310e458879..29bca2a007b 100644 --- a/crates/storage_impl/src/metrics.rs +++ b/crates/storage_impl/src/metrics.rs @@ -8,3 +8,5 @@ counter_metric!(KV_MISS, GLOBAL_METER); // No. of KV misses // Metrics for KV counter_metric!(KV_OPERATION_SUCCESSFUL, GLOBAL_METER); counter_metric!(KV_OPERATION_FAILED, GLOBAL_METER); +counter_metric!(KV_PUSHED_TO_DRAINER, GLOBAL_METER); +counter_metric!(KV_FAILED_TO_PUSH_TO_DRAINER, GLOBAL_METER);
2024-01-17T05:25:30Z
## Type of Change <!-- Put an `x` in the boxes that apply --> - [x] Enhancement ## Description <!-- Describe your changes in detail --> Add a metric to indicate data was pushed to drainer ## 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). --> Add a proper metrics to indicate data was pushed/failed while pushing to drainer ## 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)? --> - Do a transaction through KV merchant - Check `KV_PUSHED_TO_DRAINER` on grafana keeping data source as `vm-single` ![Screenshot 2024-01-30 at 4 10 56 PM](https://github.com/juspay/hyperswitch/assets/43412619/5c7dbfdc-253f-4895-985a-5bc674a56de4) ## 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
398c5ed51e0547504c3dfbd1d7c23568337e7d1c
- Do a transaction through KV merchant - Check `KV_PUSHED_TO_DRAINER` on grafana keeping data source as `vm-single` ![Screenshot 2024-01-30 at 4 10 56 PM](https://github.com/juspay/hyperswitch/assets/43412619/5c7dbfdc-253f-4895-985a-5bc674a56de4)
juspay/hyperswitch
juspay__hyperswitch-3494
Bug: [FEATURE]: [Noon] Implement Revoke Mandate ### Feature Description When revoke mandate api is triggered, revoke the existing connector mandate with noon also ### Possible Implementation Implement Revoke Mandate for Noon ### 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/noon.rs b/crates/router/src/connector/noon.rs index 180b4b1485f..6c98a307637 100644 --- a/crates/router/src/connector/noon.rs +++ b/crates/router/src/connector/noon.rs @@ -46,6 +46,7 @@ impl api::Refund for Noon {} impl api::RefundExecute for Noon {} impl api::RefundSync for Noon {} impl api::PaymentToken for Noon {} +impl api::ConnectorMandateRevoke for Noon {} impl ConnectorIntegration< @@ -492,6 +493,81 @@ impl ConnectorIntegration<api::Void, types::PaymentsCancelData, types::PaymentsR } } +impl + ConnectorIntegration< + api::MandateRevoke, + types::MandateRevokeRequestData, + types::MandateRevokeResponseData, + > for Noon +{ + fn get_headers( + &self, + req: &types::MandateRevokeRouterData, + 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::MandateRevokeRouterData, + connectors: &settings::Connectors, + ) -> CustomResult<String, errors::ConnectorError> { + Ok(format!("{}payment/v1/order", self.base_url(connectors))) + } + fn build_request( + &self, + req: &types::MandateRevokeRouterData, + connectors: &settings::Connectors, + ) -> CustomResult<Option<services::Request>, errors::ConnectorError> { + Ok(Some( + services::RequestBuilder::new() + .method(services::Method::Post) + .url(&types::MandateRevokeType::get_url(self, req, connectors)?) + .attach_default_headers() + .headers(types::MandateRevokeType::get_headers( + self, req, connectors, + )?) + .set_body(types::MandateRevokeType::get_request_body( + self, req, connectors, + )?) + .build(), + )) + } + fn get_request_body( + &self, + req: &types::MandateRevokeRouterData, + _connectors: &settings::Connectors, + ) -> CustomResult<RequestContent, errors::ConnectorError> { + let connector_req = noon::NoonRevokeMandateRequest::try_from(req)?; + Ok(RequestContent::Json(Box::new(connector_req))) + } + + fn handle_response( + &self, + data: &types::MandateRevokeRouterData, + res: Response, + ) -> CustomResult<types::MandateRevokeRouterData, errors::ConnectorError> { + let response: noon::NoonRevokeMandateResponse = res + .response + .parse_struct("Noon NoonRevokeMandateResponse") + .change_context(errors::ConnectorError::ResponseDeserializationFailed)?; + types::RouterData::try_from(types::ResponseRouterData { + response, + data: data.clone(), + http_code: res.status_code, + }) + } + fn get_error_response( + &self, + res: Response, + ) -> CustomResult<ErrorResponse, errors::ConnectorError> { + self.build_error_response(res) + } +} + impl ConnectorIntegration<api::Execute, types::RefundsData, types::RefundsResponseData> for Noon { fn get_headers( &self, diff --git a/crates/router/src/connector/noon/transformers.rs b/crates/router/src/connector/noon/transformers.rs index bbf284848b5..ee06cd064be 100644 --- a/crates/router/src/connector/noon/transformers.rs +++ b/crates/router/src/connector/noon/transformers.rs @@ -5,7 +5,8 @@ use serde::{Deserialize, Serialize}; use crate::{ connector::utils::{ - self as conn_utils, CardData, PaymentsAuthorizeRequestData, RouterData, WalletData, + self as conn_utils, CardData, PaymentsAuthorizeRequestData, RevokeMandateRequestData, + RouterData, WalletData, }, core::errors, services, @@ -30,11 +31,13 @@ pub enum NoonSubscriptionType { } #[derive(Debug, Serialize)] +#[serde(rename_all = "camelCase")] pub struct NoonSubscriptionData { #[serde(rename = "type")] subscription_type: NoonSubscriptionType, //Short description about the subscription. name: String, + max_amount: Option<String>, } #[derive(Debug, Serialize)] @@ -168,12 +171,13 @@ pub enum NoonPaymentData { } #[derive(Debug, Serialize)] -#[serde(rename_all = "UPPERCASE")] +#[serde(rename_all = "SCREAMING_SNAKE_CASE")] pub enum NoonApiOperations { Initiate, Capture, Reverse, Refund, + CancelSubscription, } #[derive(Debug, Serialize)] #[serde(rename_all = "camelCase")] @@ -335,6 +339,21 @@ impl TryFrom<&types::PaymentsAuthorizeRouterData> for NoonPaymentsRequest { NoonSubscriptionData { subscription_type: NoonSubscriptionType::Unscheduled, name: name.clone(), + max_amount: item + .request + .setup_mandate_details + .clone() + .and_then(|mandate_details| match mandate_details.mandate_type { + Some(data_models::mandates::MandateDataType::SingleUse(mandate)) + | Some(data_models::mandates::MandateDataType::MultiUse(Some( + mandate, + ))) => Some( + conn_utils::to_currency_base_unit(mandate.amount, mandate.currency) + .ok(), + ), + _ => None, + }) + .flatten(), }, true, )) { @@ -450,7 +469,7 @@ impl ForeignFrom<(NoonPaymentStatus, Self)> for enums::AttemptStatus { } #[derive(Debug, Serialize, Deserialize)] -pub struct NoonSubscriptionResponse { +pub struct NoonSubscriptionObject { identifier: String, } @@ -475,7 +494,7 @@ pub struct NoonCheckoutData { pub struct NoonPaymentsResponseResult { order: NoonPaymentsOrderResponse, checkout_data: Option<NoonCheckoutData>, - subscription: Option<NoonSubscriptionResponse>, + subscription: Option<NoonSubscriptionObject>, } #[derive(Debug, Serialize, Deserialize)] @@ -603,6 +622,25 @@ impl TryFrom<&types::PaymentsCancelRouterData> for NoonPaymentsCancelRequest { } } +#[derive(Debug, Serialize)] +#[serde(rename_all = "camelCase")] +pub struct NoonRevokeMandateRequest { + api_operation: NoonApiOperations, + subscription: NoonSubscriptionObject, +} + +impl TryFrom<&types::MandateRevokeRouterData> for NoonRevokeMandateRequest { + type Error = error_stack::Report<errors::ConnectorError>; + fn try_from(item: &types::MandateRevokeRouterData) -> Result<Self, Self::Error> { + Ok(Self { + api_operation: NoonApiOperations::CancelSubscription, + subscription: NoonSubscriptionObject { + identifier: item.request.get_connector_mandate_id()?, + }, + }) + } +} + impl<F> TryFrom<&types::RefundsRouterData<F>> for NoonPaymentsActionRequest { type Error = error_stack::Report<errors::ConnectorError>; fn try_from(item: &types::RefundsRouterData<F>) -> Result<Self, Self::Error> { @@ -624,6 +662,55 @@ impl<F> TryFrom<&types::RefundsRouterData<F>> for NoonPaymentsActionRequest { }) } } +#[derive(Debug, Deserialize)] +pub enum NoonRevokeStatus { + Cancelled, +} + +#[derive(Debug, Deserialize)] +pub struct NoonCancelSubscriptionObject { + status: NoonRevokeStatus, +} + +#[derive(Debug, Deserialize)] +pub struct NoonRevokeMandateResult { + subscription: NoonCancelSubscriptionObject, +} + +#[derive(Debug, Deserialize)] +pub struct NoonRevokeMandateResponse { + result: NoonRevokeMandateResult, +} + +impl<F> + TryFrom< + types::ResponseRouterData< + F, + NoonRevokeMandateResponse, + types::MandateRevokeRequestData, + types::MandateRevokeResponseData, + >, + > for types::RouterData<F, types::MandateRevokeRequestData, types::MandateRevokeResponseData> +{ + type Error = error_stack::Report<errors::ConnectorError>; + fn try_from( + item: types::ResponseRouterData< + F, + NoonRevokeMandateResponse, + types::MandateRevokeRequestData, + types::MandateRevokeResponseData, + >, + ) -> Result<Self, Self::Error> { + match item.response.result.subscription.status { + NoonRevokeStatus::Cancelled => Ok(Self { + response: Ok(types::MandateRevokeResponseData { + mandate_status: common_enums::MandateStatus::Revoked, + }), + ..item.data + }), + } + } +} #[derive(Debug, Default, Deserialize, Clone)] #[serde(rename_all = "UPPERCASE")] diff --git a/crates/router/src/core/payments/flows.rs b/crates/router/src/core/payments/flows.rs index c9f9d6d87f5..ebc0cf3664a 100644 --- a/crates/router/src/core/payments/flows.rs +++ b/crates/router/src/core/payments/flows.rs @@ -2247,7 +2247,6 @@ default_imp_for_revoking_mandates!( connector::Multisafepay, connector::Nexinets, connector::Nmi, - connector::Noon, connector::Nuvei, connector::Opayo, connector::Opennode,
2024-01-30T07:57:22Z
## 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 --> Implement revoke mandate flow for Noon ### 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). --> #3494 ## 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 Mandate with the Noon - Test Recurring Payment using mandate_id - Revoke the mandate and check at connector if it is revoked or not. <img width="928" alt="Screenshot 2024-01-30 at 12 40 51 PM" src="https://github.com/juspay/hyperswitch/assets/55536657/365fd0a3-5992-44ec-a43f-ce2616ad40ba"> <img width="877" alt="Screenshot 2024-01-30 at 12 39 25 PM" src="https://github.com/juspay/hyperswitch/assets/55536657/1170ecc7-0a7b-43ba-95d7-758cb92da3d4"> <img width="1029" alt="Screenshot 2024-01-30 at 12 39 15 PM" src="https://github.com/juspay/hyperswitch/assets/55536657/75b40aea-c29a-41a7-be42-d72409a86f06"> <img width="884" alt="Screenshot 2024-01-30 at 5 12 52 PM" src="https://github.com/juspay/hyperswitch/assets/55536657/386d12c1-3c69-4107-93d5-5b101a7ba4ff"> ## 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 - [ ] I added a [CHANGELOG](/CHANGELOG.md) entry if applicable
937aea906e759e6e8a76a424db99ed052d46b7d2
- Create Mandate with the Noon - Test Recurring Payment using mandate_id - Revoke the mandate and check at connector if it is revoked or not. <img width="928" alt="Screenshot 2024-01-30 at 12 40 51 PM" src="https://github.com/juspay/hyperswitch/assets/55536657/365fd0a3-5992-44ec-a43f-ce2616ad40ba"> <img width="877" alt="Screenshot 2024-01-30 at 12 39 25 PM" src="https://github.com/juspay/hyperswitch/assets/55536657/1170ecc7-0a7b-43ba-95d7-758cb92da3d4"> <img width="1029" alt="Screenshot 2024-01-30 at 12 39 15 PM" src="https://github.com/juspay/hyperswitch/assets/55536657/75b40aea-c29a-41a7-be42-d72409a86f06"> <img width="884" alt="Screenshot 2024-01-30 at 5 12 52 PM" src="https://github.com/juspay/hyperswitch/assets/55536657/386d12c1-3c69-4107-93d5-5b101a7ba4ff">
juspay/hyperswitch
juspay__hyperswitch-3493
Bug: [BUG] : Add iDEAL and Sofort mandate configs to env files ### Expected Behavior payment method list includes iDeal and Sofort for a mandate payment ### Actual Behavior payment method list don't include iDeal and Sofort for a mandate payment. ### 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/config/deployments/integration_test.toml b/config/deployments/integration_test.toml index d377b3359c9..b84546eff34 100644 --- a/config/deployments/integration_test.toml +++ b/config/deployments/integration_test.toml @@ -117,6 +117,8 @@ pay_later.klarna.connector_list = "adyen" wallet.apple_pay.connector_list = "stripe,adyen,cybersource" wallet.google_pay.connector_list = "stripe,adyen,cybersource" wallet.paypal.connector_list = "adyen" +bank_redirect.ideal = {connector_list = "stripe,adyen,globalpay"} +bank_redirect.sofort = {connector_list = "stripe,adyen,globalpay"} [multiple_api_version_supported_connectors] supported_connectors = "braintree" diff --git a/config/deployments/production.toml b/config/deployments/production.toml index d4671d3a99d..d5479b4f02c 100644 --- a/config/deployments/production.toml +++ b/config/deployments/production.toml @@ -117,6 +117,8 @@ pay_later.klarna.connector_list = "adyen" wallet.apple_pay.connector_list = "stripe,adyen,cybersource" wallet.google_pay.connector_list = "stripe,adyen,cybersource" wallet.paypal.connector_list = "adyen" +bank_redirect.ideal = {connector_list = "stripe,adyen,globalpay"} +bank_redirect.sofort = {connector_list = "stripe,adyen,globalpay"} [multiple_api_version_supported_connectors] supported_connectors = "braintree" diff --git a/config/deployments/sandbox.toml b/config/deployments/sandbox.toml index abacd3ba5a1..c58eff29edb 100644 --- a/config/deployments/sandbox.toml +++ b/config/deployments/sandbox.toml @@ -117,6 +117,8 @@ pay_later.klarna.connector_list = "adyen" wallet.apple_pay.connector_list = "stripe,adyen,cybersource" wallet.google_pay.connector_list = "stripe,adyen,cybersource" wallet.paypal.connector_list = "adyen" +bank_redirect.ideal = {connector_list = "stripe,adyen,globalpay"} +bank_redirect.sofort = {connector_list = "stripe,adyen,globalpay"} [multiple_api_version_supported_connectors] supported_connectors = "braintree"
2024-01-30T09:20:44Z
## Type of Change <!-- Put an `x` in the boxes that apply --> - [x] Bugfix - [ ] New feature - [ ] Enhancement - [ ] Refactoring - [ ] Dependency updates - [ ] Documentation - [ ] CI/CD ## 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 - [x] I added unit tests for my changes where possible - [ ] I added a [CHANGELOG](/CHANGELOG.md) entry if applicable
87191d687cd66bf096bfb98ffe51a805b4b76a03
juspay/hyperswitch
juspay__hyperswitch-3490
Bug: Send Email to biz@hyperswitch.io at every prod intent
diff --git a/crates/router/src/consts/user.rs b/crates/router/src/consts/user.rs index c570aca7603..1cda969f780 100644 --- a/crates/router/src/consts/user.rs +++ b/crates/router/src/consts/user.rs @@ -1,2 +1,3 @@ pub const MAX_NAME_LENGTH: usize = 70; pub const MAX_COMPANY_NAME_LENGTH: usize = 70; +pub const BUSINESS_EMAIL: &str = "biz@hyperswitch.io"; diff --git a/crates/router/src/core/user/dashboard_metadata.rs b/crates/router/src/core/user/dashboard_metadata.rs index b537aa3ec73..24ff292870e 100644 --- a/crates/router/src/core/user/dashboard_metadata.rs +++ b/crates/router/src/core/user/dashboard_metadata.rs @@ -3,7 +3,11 @@ use diesel_models::{ enums::DashboardMetadata as DBEnum, user::dashboard_metadata::DashboardMetadata, }; use error_stack::ResultExt; +#[cfg(feature = "email")] +use router_env::logger; +#[cfg(feature = "email")] +use crate::services::email::types as email_types; use crate::{ core::errors::{UserErrors, UserResponse, UserResult}, routes::AppState, @@ -434,15 +438,31 @@ async fn insert_metadata( if utils::is_update_required(&metadata) { metadata = utils::update_user_scoped_metadata( state, - user.user_id, + user.user_id.clone(), user.merchant_id, user.org_id, metadata_key, - data, + data.clone(), ) .await .change_context(UserErrors::InternalServerError); } + + #[cfg(feature = "email")] + { + if utils::is_prod_email_required(&data) { + let email_contents = email_types::BizEmailProd::new(state, data)?; + let send_email_result = state + .email_client + .compose_and_send_email( + Box::new(email_contents), + state.conf.proxy.https_url.as_ref(), + ) + .await; + logger::info!(?send_email_result); + } + } + metadata } types::MetaData::SPTestPayment(data) => { diff --git a/crates/router/src/services/email/assets/bizemailprod.html b/crates/router/src/services/email/assets/bizemailprod.html new file mode 100644 index 00000000000..c705608ec72 --- /dev/null +++ b/crates/router/src/services/email/assets/bizemailprod.html @@ -0,0 +1,138 @@ +<meta content="text/html; charset=UTF-8" http-equiv="Content-Type" /> +<title>Welcome to HyperSwitch!</title> +<body style="background-color: #ececec"> + <div + id="wrapper" + style=" + background-color: none; + margin: 0 auto; + text-align: center; + width: 90%; + -premailer-height: 200; + " + > + <table + align="center" + class="main-table" + style=" + -premailer-cellpadding: 0; + -premailer-cellspacing: 0; + background-color: #fff; + border: 0; + border-top: 5px solid #0165ef; + margin: 0 auto; + mso-table-lspace: 0; + mso-table-rspace: 0; + padding: 0 40; + text-align: center; + width: 100%; + " + bgcolor="#ffffff" + cellpadding="0" + cellspacing="0" + > + <tr> + <td + class="spacer-sm" + style=" + -premailer-height: 20; + -premailer-width: 80%; + line-height: 10px; + margin: 0 auto; + padding: 0; + " + width="100%" + ></td> + </tr> + <tr> + <td + class="spacer-sm" + style=" + -premailer-height: 20; + -premailer-width: 80%; + line-height: 10px; + margin: 0 auto; + padding: 0; + " + width="100%" + ></td> + </tr> + <tr> + <td + class="copy" + style=" + color: #666; + font-family: Roboto, Helvetica, Arial, san-serif; + font-size: 14px; + text-align: left; + line-height: 20px; + margin-top: 20px; + padding: 15px; + " + > + <br /> + <p>Hi Team,</p> + <p> + A Production Account Intent has been initiated by {username} - + please find more details below: + </p> + <ol> + <li><strong>Name:</strong> {username}</li> + <li><strong>Point of Contact Email (POC):</strong> {poc_email}</li> + <li><strong>Legal Business Name:</strong> {legal_business_name}</li> + <li><strong>Business Location:</strong> {business_location}</li> + <li><strong>Business Website:</strong> {business_website}</li> + </ol> + <br /> + </td> + </tr> + <tr> + <td + class="spacer-sm" + style=" + -premailer-height: 20; + -premailer-width: 80%; + line-height: 10px; + margin: 0 auto; + padding: 0; + " + width="100%" + ></td> + </tr> + + <tr> + <td + class="headline" + style=" + color: #444; + font-family: Roboto, Helvetica, Arial, san-serif; + font-size: 18px; + font-weight: 100; + line-height: 36px; + margin: 0 auto; + padding: 0; + text-align: center; + " + align="center" + > + Regards,<br /> + Hyperswitch Dashboard Team + </td> + </tr> + <tr> + <td + class="spacer-lg" + style=" + -premailer-height: 75; + -premailer-width: 100%; + line-height: 30px; + margin: 0 auto; + padding: 0; + " + height="75" + width="100%" + ></td> + </tr> + </table> + </div> +</body> diff --git a/crates/router/src/services/email/types.rs b/crates/router/src/services/email/types.rs index c68907c2846..6ad1a0eb99a 100644 --- a/crates/router/src/services/email/types.rs +++ b/crates/router/src/services/email/types.rs @@ -1,11 +1,16 @@ +use api_models::user::dashboard_metadata::ProdIntent; use common_utils::errors::CustomResult; use error_stack::ResultExt; use external_services::email::{EmailContents, EmailData, EmailError}; -use masking::{ExposeInterface, PeekInterface}; +use masking::{ExposeInterface, PeekInterface, Secret}; -use crate::{configs, consts}; +use crate::{configs, consts, routes::AppState}; #[cfg(feature = "olap")] -use crate::{core::errors::UserErrors, services::jwt, types::domain}; +use crate::{ + core::errors::{UserErrors, UserResult}, + services::jwt, + types::domain, +}; pub enum EmailBody { Verify { @@ -23,6 +28,13 @@ pub enum EmailBody { link: String, user_name: String, }, + BizEmailProd { + user_name: String, + poc_email: String, + legal_business_name: String, + business_location: String, + business_website: String, + }, ReconActivation { user_name: String, }, @@ -69,6 +81,22 @@ pub mod html { username = user_name, ) } + EmailBody::BizEmailProd { + user_name, + poc_email, + legal_business_name, + business_location, + business_website, + } => { + format!( + include_str!("assets/bizemailprod.html"), + poc_email = poc_email, + legal_business_name = legal_business_name, + business_location = business_location, + business_website = business_website, + username = user_name, + ) + } EmailBody::ProFeatureRequest { feature_name, merchant_id, @@ -275,6 +303,56 @@ impl EmailData for ReconActivation { } } +pub struct BizEmailProd { + pub recipient_email: domain::UserEmail, + pub user_name: Secret<String>, + pub poc_email: Secret<String>, + pub legal_business_name: String, + pub business_location: String, + pub business_website: String, + pub settings: std::sync::Arc<configs::settings::Settings>, + pub subject: &'static str, +} + +impl BizEmailProd { + pub fn new(state: &AppState, data: ProdIntent) -> UserResult<Self> { + Ok(Self { + recipient_email: (domain::UserEmail::new( + consts::user::BUSINESS_EMAIL.to_string().into(), + ))?, + settings: state.conf.clone(), + subject: "New Prod Intent", + user_name: data.poc_name.unwrap_or_default().into(), + poc_email: data.poc_email.unwrap_or_default().into(), + legal_business_name: data.legal_business_name.unwrap_or_default(), + business_location: data + .business_location + .unwrap_or(common_enums::CountryAlpha2::AD) + .to_string(), + business_website: data.business_website.unwrap_or_default(), + }) + } +} + +#[async_trait::async_trait] +impl EmailData for BizEmailProd { + async fn get_email_data(&self) -> CustomResult<EmailContents, EmailError> { + let body = html::get_html_body(EmailBody::BizEmailProd { + user_name: self.user_name.clone().expose(), + poc_email: self.poc_email.clone().expose(), + legal_business_name: self.legal_business_name.clone(), + business_location: self.business_location.clone(), + business_website: self.business_website.clone(), + }); + + Ok(EmailContents { + subject: self.subject.to_string(), + body: external_services::email::IntermediateString::new(body), + recipient: self.recipient_email.clone().into_inner(), + }) + } +} + pub struct ProFeatureRequest { pub recipient_email: domain::UserEmail, pub feature_name: String, diff --git a/crates/router/src/utils/user/dashboard_metadata.rs b/crates/router/src/utils/user/dashboard_metadata.rs index 09fb5ccd24b..bcf270010ea 100644 --- a/crates/router/src/utils/user/dashboard_metadata.rs +++ b/crates/router/src/utils/user/dashboard_metadata.rs @@ -2,7 +2,7 @@ use std::{net::IpAddr, str::FromStr}; use actix_web::http::header::HeaderMap; use api_models::user::dashboard_metadata::{ - GetMetaDataRequest, GetMultipleMetaDataPayload, SetMetaDataRequest, + GetMetaDataRequest, GetMultipleMetaDataPayload, ProdIntent, SetMetaDataRequest, }; use diesel_models::{ enums::DashboardMetadata as DBEnum, @@ -276,3 +276,10 @@ pub fn parse_string_to_enums(query: String) -> UserResult<GetMultipleMetaDataPay .attach_printable("Error Parsing to DashboardMetadata enums")?, }) } + +pub fn is_prod_email_required(data: &ProdIntent) -> bool { + !(data + .poc_email + .as_ref() + .map_or(true, |mail| mail.contains("juspay"))) +}
2024-01-29T15:48:48Z
## Type of Change <!-- Put an `x` in the boxes that apply --> - [ ] Bugfix - [x] New feature - [ ] Enhancement - [ ] Refactoring - [ ] Dependency updates - [ ] Documentation - [ ] CI/CD ## Description Sending an email to biz@hyperswitch.io whenever a new Prod Intent will be filled. ### 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 regularly update the biz@hyperswitch.io regarding the Prod Intent. ## 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/data' \ --header 'api-key: hyperswitch' \ --header 'Content-Type: text/plain' \ --header 'Authorization: Bearer JWT' \ --data-raw '{ "ProdIntent": { "poc_email": "---", "is_completed": true, "legal_business_name": "---", "business_location": "AX", "business_website": "---", "poc_name": "---", "comments": "---" } }' ``` When we hit this curl the email will be sent to biz@hyperswitch.io ## 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 - [ ] I added a [CHANGELOG](/CHANGELOG.md) entry if applicable
58771b8985a53c83185805f770fee26c5836c645
``` curl --location 'http://localhost:8080/user/data' \ --header 'api-key: hyperswitch' \ --header 'Content-Type: text/plain' \ --header 'Authorization: Bearer JWT' \ --data-raw '{ "ProdIntent": { "poc_email": "---", "is_completed": true, "legal_business_name": "---", "business_location": "AX", "business_website": "---", "poc_name": "---", "comments": "---" } }' ``` When we hit this curl the email will be sent to biz@hyperswitch.io
juspay/hyperswitch
juspay__hyperswitch-3491
Bug: feat(logging): add flow field to logging framework Add API Flow field to the root span & persistent keys
diff --git a/crates/router/src/middleware.rs b/crates/router/src/middleware.rs index 587a15693f2..702c3c70e6c 100644 --- a/crates/router/src/middleware.rs +++ b/crates/router/src/middleware.rs @@ -58,7 +58,7 @@ where let request_id = request_id_fut.await?; let request_id = request_id.as_hyphenated().to_string(); if let Some(upstream_request_id) = old_x_request_id { - router_env::logger::info!(?request_id, ?upstream_request_id); + router_env::logger::info!(?upstream_request_id); } let mut response = response_fut.await?; response.headers_mut().append( @@ -146,7 +146,8 @@ where "golden_log_line", payment_id = Empty, merchant_id = Empty, - connector_name = Empty + connector_name = Empty, + flow = "UNKNOWN" ) .or_current(), ), diff --git a/crates/router_env/src/logger/storage.rs b/crates/router_env/src/logger/storage.rs index 961a77c65aa..036a73cf874 100644 --- a/crates/router_env/src/logger/storage.rs +++ b/crates/router_env/src/logger/storage.rs @@ -92,7 +92,7 @@ impl Visit for Storage<'_> { } } -const PERSISTENT_KEYS: [&str; 3] = ["payment_id", "connector_name", "merchant_id"]; +const PERSISTENT_KEYS: [&str; 4] = ["payment_id", "connector_name", "merchant_id", "flow"]; impl<S: Subscriber + for<'a> tracing_subscriber::registry::LookupSpan<'a>> Layer<S> for StorageSubscription
2024-01-29T11:50:23Z
## 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 --> - Adding flow to the persistent keys in subscriber layer - Adding flow to the middle ware log ### 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 flow to the persistent keys in api's ## 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)? --> run the application locally all api requests should have the following log line at the end of request - the fields should be populated when available - These log line will be generated even for health & non-existent paths (e.g `/` or `/favicon.ico`) ```json { "message": "[GOLDEN_LOG_LINE - EVENT] REQUEST MIDDLEWARE END", "hostname": "<MY_MACHINE>.local", "pid": 62901, "env": "development", "level": "INFO", "target": "router::middleware", "service": "router", "line": 61, "file": "crates/router/src/middleware.rs", "fn": "golden_log_line", "full_name": "router::middleware::golden_log_line", "flow": "PaymentsCreate", "time": "2024-01-24T06:35:06.771569000Z", "merchant_id": "merchant_1706060159", "request_id": "018d3a2d-e583-7581-8992-8596b3052995", "extra": { "trace_id": "00000000000000000000000000000000", "http.method": "POST", "http.route": "/payments", "http.flavor": "1.1", "http.user_agent": "PostmanRuntime/7.33.0", "payment_id": "payment_intent_id = \"pay_y8XHx5whOaWTdoGrgAAf\"", "otel.name": "HTTP POST /payments", "http.client_ip": "::1", "http.host": "localhost:8080", "http.target": "/payments", "http.scheme": "http", "otel.kind": "server" } } ``` ## 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 - [ ] I added a [CHANGELOG](/CHANGELOG.md) entry if applicable
a9638d118e0b68653fef3bec2ce8aa3c47feedd3
run the application locally all api requests should have the following log line at the end of request - the fields should be populated when available - These log line will be generated even for health & non-existent paths (e.g `/` or `/favicon.ico`) ```json { "message": "[GOLDEN_LOG_LINE - EVENT] REQUEST MIDDLEWARE END", "hostname": "<MY_MACHINE>.local", "pid": 62901, "env": "development", "level": "INFO", "target": "router::middleware", "service": "router", "line": 61, "file": "crates/router/src/middleware.rs", "fn": "golden_log_line", "full_name": "router::middleware::golden_log_line", "flow": "PaymentsCreate", "time": "2024-01-24T06:35:06.771569000Z", "merchant_id": "merchant_1706060159", "request_id": "018d3a2d-e583-7581-8992-8596b3052995", "extra": { "trace_id": "00000000000000000000000000000000", "http.method": "POST", "http.route": "/payments", "http.flavor": "1.1", "http.user_agent": "PostmanRuntime/7.33.0", "payment_id": "payment_intent_id = \"pay_y8XHx5whOaWTdoGrgAAf\"", "otel.name": "HTTP POST /payments", "http.client_ip": "::1", "http.host": "localhost:8080", "http.target": "/payments", "http.scheme": "http", "otel.kind": "server" } } ```
juspay/hyperswitch
juspay__hyperswitch-3535
Bug: [REFACTOR] introducing `hyperswitch_interface` crates Create a new crate `Hyperswitch-interface` containing below modules for now: `secrets_interface`: Module used for application config `encryption` and `decryption` during startup which will contain its own trait and error types `encryption_interface`: Module used for user value `encryption` and `decryption` during runtime which will contain its own trait and error types
diff --git a/Cargo.lock b/Cargo.lock index 49ccfc2c645..4bee1804f4c 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -2495,6 +2495,7 @@ dependencies = [ "hex", "hyper", "hyper-proxy", + "hyperswitch_interfaces", "masking", "once_cell", "router_env", @@ -3214,6 +3215,18 @@ dependencies = [ "tokio-native-tls", ] +[[package]] +name = "hyperswitch_interfaces" +version = "0.1.0" +dependencies = [ + "async-trait", + "common_utils", + "dyn-clone", + "masking", + "serde", + "thiserror", +] + [[package]] name = "iana-time-zone" version = "0.1.58" @@ -5186,6 +5199,7 @@ dependencies = [ "hex", "http", "hyper", + "hyperswitch_interfaces", "image", "infer 0.13.0", "josekit", diff --git a/crates/drainer/src/connection.rs b/crates/drainer/src/connection.rs index 788ff1456e2..e01b72150c5 100644 --- a/crates/drainer/src/connection.rs +++ b/crates/drainer/src/connection.rs @@ -3,7 +3,10 @@ use diesel::PgConnection; #[cfg(feature = "aws_kms")] use external_services::aws_kms::{self, decrypt::AwsKmsDecrypt}; #[cfg(feature = "hashicorp-vault")] -use external_services::hashicorp_vault::{self, decrypt::VaultFetch, Kv2}; +use external_services::hashicorp_vault::{ + core::{HashiCorpVault, Kv2}, + decrypt::VaultFetch, +}; #[cfg(not(feature = "aws_kms"))] use masking::PeekInterface; @@ -28,8 +31,8 @@ pub async fn redis_connection( pub async fn diesel_make_pg_pool( database: &Database, _test_transaction: bool, - #[cfg(feature = "aws_kms")] aws_kms_client: &'static aws_kms::AwsKmsClient, - #[cfg(feature = "hashicorp-vault")] hashicorp_client: &'static hashicorp_vault::HashiCorpVault, + #[cfg(feature = "aws_kms")] aws_kms_client: &'static aws_kms::core::AwsKmsClient, + #[cfg(feature = "hashicorp-vault")] hashicorp_client: &'static HashiCorpVault, ) -> PgPool { let password = database.password.clone(); #[cfg(feature = "hashicorp-vault")] diff --git a/crates/drainer/src/services.rs b/crates/drainer/src/services.rs index e6ca8d023a0..3918c756c10 100644 --- a/crates/drainer/src/services.rs +++ b/crates/drainer/src/services.rs @@ -34,10 +34,10 @@ impl Store { &config.master_database, test_transaction, #[cfg(feature = "aws_kms")] - external_services::aws_kms::get_aws_kms_client(&config.kms).await, + external_services::aws_kms::core::get_aws_kms_client(&config.kms).await, #[cfg(feature = "hashicorp-vault")] #[allow(clippy::expect_used)] - external_services::hashicorp_vault::get_hashicorp_client(&config.hc_vault) + external_services::hashicorp_vault::core::get_hashicorp_client(&config.hc_vault) .await .expect("Failed while getting hashicorp client"), ) diff --git a/crates/drainer/src/settings.rs b/crates/drainer/src/settings.rs index 17b0b68b324..de5af654540 100644 --- a/crates/drainer/src/settings.rs +++ b/crates/drainer/src/settings.rs @@ -14,7 +14,7 @@ use serde::Deserialize; use crate::errors; #[cfg(feature = "aws_kms")] -pub type Password = aws_kms::AwsKmsValue; +pub type Password = aws_kms::core::AwsKmsValue; #[cfg(not(feature = "aws_kms"))] pub type Password = masking::Secret<String>; @@ -36,9 +36,9 @@ pub struct Settings { pub log: Log, pub drainer: DrainerSettings, #[cfg(feature = "aws_kms")] - pub kms: aws_kms::AwsKmsConfig, + pub kms: aws_kms::core::AwsKmsConfig, #[cfg(feature = "hashicorp-vault")] - pub hc_vault: hashicorp_vault::HashiCorpVaultConfig, + pub hc_vault: hashicorp_vault::core::HashiCorpVaultConfig, } #[derive(Debug, Deserialize, Clone)] diff --git a/crates/external_services/Cargo.toml b/crates/external_services/Cargo.toml index 2b6bc22b2e9..58c81946017 100644 --- a/crates/external_services/Cargo.toml +++ b/crates/external_services/Cargo.toml @@ -35,5 +35,6 @@ hex = "0.4.3" # First party crates common_utils = { version = "0.1.0", path = "../common_utils" } +hyperswitch_interfaces = { version = "0.1.0", path = "../hyperswitch_interfaces" } 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"] } diff --git a/crates/external_services/src/aws_kms.rs b/crates/external_services/src/aws_kms.rs index cf21f36f22b..3e5353fd9e3 100644 --- a/crates/external_services/src/aws_kms.rs +++ b/crates/external_services/src/aws_kms.rs @@ -1,284 +1,7 @@ //! Interactions with the AWS KMS SDK -use std::time::Instant; +pub mod core; -use aws_config::meta::region::RegionProviderChain; -use aws_sdk_kms::{config::Region, primitives::Blob, Client}; -use base64::Engine; -use common_utils::errors::CustomResult; -use error_stack::{IntoReport, ResultExt}; -use masking::{PeekInterface, Secret}; -use router_env::logger; -/// decrypting data using the AWS KMS SDK. pub mod decrypt; -use crate::{consts, metrics}; - -static AWS_KMS_CLIENT: tokio::sync::OnceCell<AwsKmsClient> = tokio::sync::OnceCell::const_new(); - -/// Returns a shared AWS KMS client, or initializes a new one if not previously initialized. -#[inline] -pub async fn get_aws_kms_client(config: &AwsKmsConfig) -> &'static AwsKmsClient { - AWS_KMS_CLIENT - .get_or_init(|| AwsKmsClient::new(config)) - .await -} - -/// Configuration parameters required for constructing a [`AwsKmsClient`]. -#[derive(Clone, Debug, Default, serde::Deserialize)] -#[serde(default)] -pub struct AwsKmsConfig { - /// The AWS key identifier of the KMS key used to encrypt or decrypt data. - pub key_id: String, - - /// The AWS region to send KMS requests to. - pub region: String, -} - -/// Client for AWS KMS operations. -#[derive(Debug)] -pub struct AwsKmsClient { - inner_client: Client, - key_id: String, -} - -impl AwsKmsClient { - /// Constructs a new AWS KMS client. - pub async fn new(config: &AwsKmsConfig) -> Self { - let region_provider = RegionProviderChain::first_try(Region::new(config.region.clone())); - let sdk_config = aws_config::from_env().region(region_provider).load().await; - - Self { - inner_client: Client::new(&sdk_config), - key_id: config.key_id.clone(), - } - } - - /// Decrypts the provided base64-encoded encrypted data using the AWS KMS SDK. We assume that - /// the SDK has the values required to interact with the AWS KMS APIs (`AWS_ACCESS_KEY_ID` and - /// `AWS_SECRET_ACCESS_KEY`) either set in environment variables, or that the SDK is running in - /// a machine that is able to assume an IAM role. - pub async fn decrypt(&self, data: impl AsRef<[u8]>) -> CustomResult<String, AwsKmsError> { - let start = Instant::now(); - let data = consts::BASE64_ENGINE - .decode(data) - .into_report() - .change_context(AwsKmsError::Base64DecodingFailed)?; - let ciphertext_blob = Blob::new(data); - - let decrypt_output = self - .inner_client - .decrypt() - .key_id(&self.key_id) - .ciphertext_blob(ciphertext_blob) - .send() - .await - .map_err(|error| { - // Logging using `Debug` representation of the error as the `Display` - // representation does not hold sufficient information. - logger::error!(aws_kms_sdk_error=?error, "Failed to AWS KMS decrypt data"); - metrics::AWS_KMS_DECRYPTION_FAILURES.add(&metrics::CONTEXT, 1, &[]); - error - }) - .into_report() - .change_context(AwsKmsError::DecryptionFailed)?; - - let output = decrypt_output - .plaintext - .ok_or(AwsKmsError::MissingPlaintextDecryptionOutput) - .into_report() - .and_then(|blob| { - String::from_utf8(blob.into_inner()) - .into_report() - .change_context(AwsKmsError::Utf8DecodingFailed) - })?; - - let time_taken = start.elapsed(); - metrics::AWS_KMS_DECRYPT_TIME.record(&metrics::CONTEXT, time_taken.as_secs_f64(), &[]); - - Ok(output) - } - - /// Encrypts the provided String data using the AWS KMS SDK. We assume that - /// the SDK has the values required to interact with the AWS KMS APIs (`AWS_ACCESS_KEY_ID` and - /// `AWS_SECRET_ACCESS_KEY`) either set in environment variables, or that the SDK is running in - /// a machine that is able to assume an IAM role. - pub async fn encrypt(&self, data: impl AsRef<[u8]>) -> CustomResult<String, AwsKmsError> { - let start = Instant::now(); - let plaintext_blob = Blob::new(data.as_ref()); - - let encrypted_output = self - .inner_client - .encrypt() - .key_id(&self.key_id) - .plaintext(plaintext_blob) - .send() - .await - .map_err(|error| { - // Logging using `Debug` representation of the error as the `Display` - // representation does not hold sufficient information. - logger::error!(aws_kms_sdk_error=?error, "Failed to AWS KMS encrypt data"); - metrics::AWS_KMS_ENCRYPTION_FAILURES.add(&metrics::CONTEXT, 1, &[]); - error - }) - .into_report() - .change_context(AwsKmsError::EncryptionFailed)?; - - let output = encrypted_output - .ciphertext_blob - .ok_or(AwsKmsError::MissingCiphertextEncryptionOutput) - .into_report() - .map(|blob| consts::BASE64_ENGINE.encode(blob.into_inner()))?; - let time_taken = start.elapsed(); - metrics::AWS_KMS_ENCRYPT_TIME.record(&metrics::CONTEXT, time_taken.as_secs_f64(), &[]); - - Ok(output) - } -} - -/// Errors that could occur during AWS KMS operations. -#[derive(Debug, thiserror::Error)] -pub enum AwsKmsError { - /// An error occurred when base64 encoding input data. - #[error("Failed to base64 encode input data")] - Base64EncodingFailed, - - /// An error occurred when base64 decoding input data. - #[error("Failed to base64 decode input data")] - Base64DecodingFailed, - - /// An error occurred when AWS KMS decrypting input data. - #[error("Failed to AWS KMS decrypt input data")] - DecryptionFailed, - - /// An error occurred when AWS KMS encrypting input data. - #[error("Failed to AWS KMS encrypt input data")] - EncryptionFailed, - - /// The AWS KMS decrypted output does not include a plaintext output. - #[error("Missing plaintext AWS KMS decryption output")] - MissingPlaintextDecryptionOutput, - - /// The AWS KMS encrypted output does not include a ciphertext output. - #[error("Missing ciphertext AWS KMS encryption output")] - MissingCiphertextEncryptionOutput, - - /// An error occurred UTF-8 decoding AWS KMS decrypted output. - #[error("Failed to UTF-8 decode decryption output")] - Utf8DecodingFailed, - - /// The AWS KMS client has not been initialized. - #[error("The AWS KMS client has not been initialized")] - AwsKmsClientNotInitialized, -} - -impl AwsKmsConfig { - /// Verifies that the [`AwsKmsClient`] configuration is usable. - pub fn validate(&self) -> Result<(), &'static str> { - use common_utils::{ext_traits::ConfigExt, fp_utils::when}; - - when(self.key_id.is_default_or_empty(), || { - Err("KMS AWS key ID must not be empty") - })?; - - when(self.region.is_default_or_empty(), || { - Err("KMS AWS region must not be empty") - }) - } -} - -/// A wrapper around a AWS KMS value that can be decrypted. -#[derive(Clone, Debug, Default, serde::Deserialize, Eq, PartialEq)] -#[serde(transparent)] -pub struct AwsKmsValue(Secret<String>); - -impl common_utils::ext_traits::ConfigExt for AwsKmsValue { - fn is_empty_after_trim(&self) -> bool { - self.0.peek().is_empty_after_trim() - } -} - -impl From<String> for AwsKmsValue { - fn from(value: String) -> Self { - Self(Secret::new(value)) - } -} - -impl From<Secret<String>> for AwsKmsValue { - fn from(value: Secret<String>) -> Self { - Self(value) - } -} - -#[cfg(feature = "hashicorp-vault")] -#[async_trait::async_trait] -impl super::hashicorp_vault::decrypt::VaultFetch for AwsKmsValue { - async fn fetch_inner<En>( - self, - client: &super::hashicorp_vault::HashiCorpVault, - ) -> error_stack::Result<Self, super::hashicorp_vault::HashiCorpError> - where - for<'a> En: super::hashicorp_vault::Engine< - ReturnType<'a, String> = std::pin::Pin< - Box< - dyn std::future::Future< - Output = error_stack::Result< - String, - super::hashicorp_vault::HashiCorpError, - >, - > + Send - + 'a, - >, - >, - > + 'a, - { - self.0.fetch_inner::<En>(client).await.map(AwsKmsValue) - } -} - -#[cfg(test)] -mod tests { - #![allow(clippy::expect_used)] - #[tokio::test] - async fn check_aws_kms_encryption() { - std::env::set_var("AWS_SECRET_ACCESS_KEY", "YOUR SECRET ACCESS KEY"); - std::env::set_var("AWS_ACCESS_KEY_ID", "YOUR AWS ACCESS KEY ID"); - use super::*; - let config = AwsKmsConfig { - key_id: "YOUR AWS KMS KEY ID".to_string(), - region: "AWS REGION".to_string(), - }; - - let data = "hello".to_string(); - let binding = data.as_bytes(); - let kms_encrypted_fingerprint = AwsKmsClient::new(&config) - .await - .encrypt(binding) - .await - .expect("aws kms encryption failed"); - - println!("{}", kms_encrypted_fingerprint); - } - - #[tokio::test] - async fn check_aws_kms_decrypt() { - std::env::set_var("AWS_SECRET_ACCESS_KEY", "YOUR SECRET ACCESS KEY"); - std::env::set_var("AWS_ACCESS_KEY_ID", "YOUR AWS ACCESS KEY ID"); - use super::*; - let config = AwsKmsConfig { - key_id: "YOUR AWS KMS KEY ID".to_string(), - region: "AWS REGION".to_string(), - }; - - // Should decrypt to hello - let data = "AWS KMS ENCRYPTED CIPHER".to_string(); - let binding = data.as_bytes(); - let kms_encrypted_fingerprint = AwsKmsClient::new(&config) - .await - .decrypt(binding) - .await - .expect("aws kms decryption failed"); - - println!("{}", kms_encrypted_fingerprint); - } -} +pub mod implementers; diff --git a/crates/external_services/src/aws_kms/core.rs b/crates/external_services/src/aws_kms/core.rs new file mode 100644 index 00000000000..c01bcbfb094 --- /dev/null +++ b/crates/external_services/src/aws_kms/core.rs @@ -0,0 +1,299 @@ +//! Interactions with the AWS KMS SDK + +use std::time::Instant; + +use aws_config::meta::region::RegionProviderChain; +use aws_sdk_kms::{config::Region, primitives::Blob, Client}; +use base64::Engine; +use common_utils::errors::CustomResult; +use error_stack::{IntoReport, ResultExt}; +use masking::{PeekInterface, Secret}; +use router_env::logger; + +#[cfg(feature = "hashicorp-vault")] +use crate::hashicorp_vault; +use crate::{aws_kms::decrypt::AwsKmsDecrypt, consts, metrics}; + +pub(crate) static AWS_KMS_CLIENT: tokio::sync::OnceCell<AwsKmsClient> = + tokio::sync::OnceCell::const_new(); + +/// Returns a shared AWS KMS client, or initializes a new one if not previously initialized. +#[inline] +pub async fn get_aws_kms_client(config: &AwsKmsConfig) -> &'static AwsKmsClient { + AWS_KMS_CLIENT + .get_or_init(|| AwsKmsClient::new(config)) + .await +} + +/// Configuration parameters required for constructing a [`AwsKmsClient`]. +#[derive(Clone, Debug, Default, serde::Deserialize)] +#[serde(default)] +pub struct AwsKmsConfig { + /// The AWS key identifier of the KMS key used to encrypt or decrypt data. + pub key_id: String, + + /// The AWS region to send KMS requests to. + pub region: String, +} + +/// Client for AWS KMS operations. +#[derive(Debug, Clone)] +pub struct AwsKmsClient { + inner_client: Client, + key_id: String, +} + +impl AwsKmsClient { + /// Constructs a new AWS KMS client. + pub async fn new(config: &AwsKmsConfig) -> Self { + let region_provider = RegionProviderChain::first_try(Region::new(config.region.clone())); + let sdk_config = aws_config::from_env().region(region_provider).load().await; + + Self { + inner_client: Client::new(&sdk_config), + key_id: config.key_id.clone(), + } + } + + /// Decrypts the provided base64-encoded encrypted data using the AWS KMS SDK. We assume that + /// the SDK has the values required to interact with the AWS KMS APIs (`AWS_ACCESS_KEY_ID` and + /// `AWS_SECRET_ACCESS_KEY`) either set in environment variables, or that the SDK is running in + /// a machine that is able to assume an IAM role. + pub async fn decrypt(&self, data: impl AsRef<[u8]>) -> CustomResult<String, AwsKmsError> { + let start = Instant::now(); + let data = consts::BASE64_ENGINE + .decode(data) + .into_report() + .change_context(AwsKmsError::Base64DecodingFailed)?; + let ciphertext_blob = Blob::new(data); + + let decrypt_output = self + .inner_client + .decrypt() + .key_id(&self.key_id) + .ciphertext_blob(ciphertext_blob) + .send() + .await + .map_err(|error| { + // Logging using `Debug` representation of the error as the `Display` + // representation does not hold sufficient information. + logger::error!(aws_kms_sdk_error=?error, "Failed to AWS KMS decrypt data"); + metrics::AWS_KMS_DECRYPTION_FAILURES.add(&metrics::CONTEXT, 1, &[]); + error + }) + .into_report() + .change_context(AwsKmsError::DecryptionFailed)?; + + let output = decrypt_output + .plaintext + .ok_or(AwsKmsError::MissingPlaintextDecryptionOutput) + .into_report() + .and_then(|blob| { + String::from_utf8(blob.into_inner()) + .into_report() + .change_context(AwsKmsError::Utf8DecodingFailed) + })?; + + let time_taken = start.elapsed(); + metrics::AWS_KMS_DECRYPT_TIME.record(&metrics::CONTEXT, time_taken.as_secs_f64(), &[]); + + Ok(output) + } + + /// Encrypts the provided String data using the AWS KMS SDK. We assume that + /// the SDK has the values required to interact with the AWS KMS APIs (`AWS_ACCESS_KEY_ID` and + /// `AWS_SECRET_ACCESS_KEY`) either set in environment variables, or that the SDK is running in + /// a machine that is able to assume an IAM role. + pub async fn encrypt(&self, data: impl AsRef<[u8]>) -> CustomResult<String, AwsKmsError> { + let start = Instant::now(); + let plaintext_blob = Blob::new(data.as_ref()); + + let encrypted_output = self + .inner_client + .encrypt() + .key_id(&self.key_id) + .plaintext(plaintext_blob) + .send() + .await + .map_err(|error| { + // Logging using `Debug` representation of the error as the `Display` + // representation does not hold sufficient information. + logger::error!(aws_kms_sdk_error=?error, "Failed to AWS KMS encrypt data"); + metrics::AWS_KMS_ENCRYPTION_FAILURES.add(&metrics::CONTEXT, 1, &[]); + error + }) + .into_report() + .change_context(AwsKmsError::EncryptionFailed)?; + + let output = encrypted_output + .ciphertext_blob + .ok_or(AwsKmsError::MissingCiphertextEncryptionOutput) + .into_report() + .map(|blob| consts::BASE64_ENGINE.encode(blob.into_inner()))?; + let time_taken = start.elapsed(); + metrics::AWS_KMS_ENCRYPT_TIME.record(&metrics::CONTEXT, time_taken.as_secs_f64(), &[]); + + Ok(output) + } +} + +/// Errors that could occur during KMS operations. +#[derive(Debug, thiserror::Error)] +pub enum AwsKmsError { + /// An error occurred when base64 encoding input data. + #[error("Failed to base64 encode input data")] + Base64EncodingFailed, + + /// An error occurred when base64 decoding input data. + #[error("Failed to base64 decode input data")] + Base64DecodingFailed, + + /// An error occurred when AWS KMS decrypting input data. + #[error("Failed to AWS KMS decrypt input data")] + DecryptionFailed, + + /// An error occurred when AWS KMS encrypting input data. + #[error("Failed to AWS KMS encrypt input data")] + EncryptionFailed, + + /// The AWS KMS decrypted output does not include a plaintext output. + #[error("Missing plaintext AWS KMS decryption output")] + MissingPlaintextDecryptionOutput, + + /// The AWS KMS encrypted output does not include a ciphertext output. + #[error("Missing ciphertext AWS KMS encryption output")] + MissingCiphertextEncryptionOutput, + + /// An error occurred UTF-8 decoding AWS KMS decrypted output. + #[error("Failed to UTF-8 decode decryption output")] + Utf8DecodingFailed, + + /// The AWS KMS client has not been initialized. + #[error("The AWS KMS client has not been initialized")] + AwsKmsClientNotInitialized, +} + +impl AwsKmsConfig { + /// Verifies that the [`AwsKmsClient`] configuration is usable. + pub fn validate(&self) -> Result<(), &'static str> { + use common_utils::{ext_traits::ConfigExt, fp_utils::when}; + + when(self.key_id.is_default_or_empty(), || { + Err("KMS AWS key ID must not be empty") + })?; + + when(self.region.is_default_or_empty(), || { + Err("KMS AWS region must not be empty") + }) + } +} + +/// A wrapper around a AWS KMS value that can be decrypted. +#[derive(Clone, Debug, Default, serde::Deserialize, Eq, PartialEq)] +#[serde(transparent)] +pub struct AwsKmsValue(Secret<String>); + +impl common_utils::ext_traits::ConfigExt for AwsKmsValue { + fn is_empty_after_trim(&self) -> bool { + self.0.peek().is_empty_after_trim() + } +} + +impl From<String> for AwsKmsValue { + fn from(value: String) -> Self { + Self(Secret::new(value)) + } +} + +impl From<Secret<String>> for AwsKmsValue { + fn from(value: Secret<String>) -> Self { + Self(value) + } +} + +#[cfg(feature = "hashicorp-vault")] +#[async_trait::async_trait] +impl hashicorp_vault::decrypt::VaultFetch for AwsKmsValue { + async fn fetch_inner<En>( + self, + client: &hashicorp_vault::core::HashiCorpVault, + ) -> error_stack::Result<Self, hashicorp_vault::core::HashiCorpError> + where + for<'a> En: hashicorp_vault::core::Engine< + ReturnType<'a, String> = std::pin::Pin< + Box< + dyn std::future::Future< + Output = error_stack::Result< + String, + hashicorp_vault::core::HashiCorpError, + >, + > + Send + + 'a, + >, + >, + > + 'a, + { + self.0.fetch_inner::<En>(client).await.map(AwsKmsValue) + } +} + +#[async_trait::async_trait] +impl AwsKmsDecrypt for &AwsKmsValue { + type Output = String; + async fn decrypt_inner( + self, + aws_kms_client: &AwsKmsClient, + ) -> CustomResult<Self::Output, AwsKmsError> { + aws_kms_client + .decrypt(self.0.peek()) + .await + .attach_printable("Failed to decrypt AWS KMS value") + } +} + +#[cfg(test)] +mod tests { + #![allow(clippy::expect_used)] + #[tokio::test] + async fn check_aws_kms_encryption() { + std::env::set_var("AWS_SECRET_ACCESS_KEY", "YOUR SECRET ACCESS KEY"); + std::env::set_var("AWS_ACCESS_KEY_ID", "YOUR AWS ACCESS KEY ID"); + use super::*; + let config = AwsKmsConfig { + key_id: "YOUR AWS KMS KEY ID".to_string(), + region: "AWS REGION".to_string(), + }; + + let data = "hello".to_string(); + let binding = data.as_bytes(); + let kms_encrypted_fingerprint = AwsKmsClient::new(&config) + .await + .encrypt(binding) + .await + .expect("aws kms encryption failed"); + + println!("{}", kms_encrypted_fingerprint); + } + + #[tokio::test] + async fn check_aws_kms_decrypt() { + std::env::set_var("AWS_SECRET_ACCESS_KEY", "YOUR SECRET ACCESS KEY"); + std::env::set_var("AWS_ACCESS_KEY_ID", "YOUR AWS ACCESS KEY ID"); + use super::*; + let config = AwsKmsConfig { + key_id: "YOUR AWS KMS KEY ID".to_string(), + region: "AWS REGION".to_string(), + }; + + // Should decrypt to hello + let data = "AWS KMS ENCRYPTED CIPHER".to_string(); + let binding = data.as_bytes(); + let kms_encrypted_fingerprint = AwsKmsClient::new(&config) + .await + .decrypt(binding) + .await + .expect("aws kms decryption failed"); + + println!("{}", kms_encrypted_fingerprint); + } +} diff --git a/crates/external_services/src/aws_kms/decrypt.rs b/crates/external_services/src/aws_kms/decrypt.rs index 9abd4fefbef..47edb8f958f 100644 --- a/crates/external_services/src/aws_kms/decrypt.rs +++ b/crates/external_services/src/aws_kms/decrypt.rs @@ -1,6 +1,7 @@ +//! Decrypting data using the AWS KMS SDK. use common_utils::errors::CustomResult; -use super::*; +use crate::aws_kms::core::{AwsKmsClient, AwsKmsError, AWS_KMS_CLIENT}; #[async_trait::async_trait] /// This trait performs in place decryption of the structure on which this is implemented @@ -26,17 +27,3 @@ pub trait AwsKmsDecrypt { self.decrypt_inner(client).await } } - -#[async_trait::async_trait] -impl AwsKmsDecrypt for &AwsKmsValue { - type Output = String; - async fn decrypt_inner( - self, - aws_kms_client: &AwsKmsClient, - ) -> CustomResult<Self::Output, AwsKmsError> { - aws_kms_client - .decrypt(self.0.peek()) - .await - .attach_printable("Failed to decrypt AWS KMS value") - } -} diff --git a/crates/external_services/src/aws_kms/implementers.rs b/crates/external_services/src/aws_kms/implementers.rs new file mode 100644 index 00000000000..cc00dbf3468 --- /dev/null +++ b/crates/external_services/src/aws_kms/implementers.rs @@ -0,0 +1,41 @@ +//! Trait implementations for aws kms client + +use common_utils::errors::CustomResult; +use error_stack::ResultExt; +use hyperswitch_interfaces::{ + encryption_interface::{EncryptionError, EncryptionManagementInterface}, + secrets_interface::{SecretManagementInterface, SecretsManagementError}, +}; +use masking::{PeekInterface, Secret}; + +use crate::aws_kms::core::AwsKmsClient; + +#[async_trait::async_trait] +impl EncryptionManagementInterface for AwsKmsClient { + async fn encrypt(&self, input: &[u8]) -> CustomResult<Vec<u8>, EncryptionError> { + self.encrypt(input) + .await + .change_context(EncryptionError::EncryptionFailed) + .map(|val| val.into_bytes()) + } + + async fn decrypt(&self, input: &[u8]) -> CustomResult<Vec<u8>, EncryptionError> { + self.decrypt(input) + .await + .change_context(EncryptionError::DecryptionFailed) + .map(|val| val.into_bytes()) + } +} + +#[async_trait::async_trait] +impl SecretManagementInterface for AwsKmsClient { + async fn get_secret( + &self, + input: Secret<String>, + ) -> CustomResult<Secret<String>, SecretsManagementError> { + self.decrypt(input.peek()) + .await + .change_context(SecretsManagementError::FetchSecretFailed) + .map(Into::into) + } +} diff --git a/crates/external_services/src/hashicorp_vault.rs b/crates/external_services/src/hashicorp_vault.rs index e31c8f01392..5a3ba539689 100644 --- a/crates/external_services/src/hashicorp_vault.rs +++ b/crates/external_services/src/hashicorp_vault.rs @@ -1,215 +1,7 @@ //! Interactions with the HashiCorp Vault -use std::{collections::HashMap, future::Future, pin::Pin}; +pub mod core; -use error_stack::{Report, ResultExt}; -use vaultrs::client::{VaultClient, VaultClientSettingsBuilder}; - -/// Utilities for supporting decryption of data pub mod decrypt; -static HC_CLIENT: tokio::sync::OnceCell<HashiCorpVault> = tokio::sync::OnceCell::const_new(); - -#[allow(missing_debug_implementations)] -/// A struct representing a connection to HashiCorp Vault. -pub struct HashiCorpVault { - /// The underlying client used for interacting with HashiCorp Vault. - client: VaultClient, -} - -/// Configuration for connecting to HashiCorp Vault. -#[derive(Clone, Debug, Default, serde::Deserialize)] -#[serde(default)] -pub struct HashiCorpVaultConfig { - /// The URL of the HashiCorp Vault server. - pub url: String, - /// The authentication token used to access HashiCorp Vault. - pub token: String, -} - -/// Asynchronously retrieves a HashiCorp Vault client based on the provided configuration. -/// -/// # Parameters -/// -/// - `config`: A reference to a `HashiCorpVaultConfig` containing the configuration details. -pub async fn get_hashicorp_client( - config: &HashiCorpVaultConfig, -) -> error_stack::Result<&'static HashiCorpVault, HashiCorpError> { - HC_CLIENT - .get_or_try_init(|| async { HashiCorpVault::new(config) }) - .await -} - -/// A trait defining an engine for interacting with HashiCorp Vault. -pub trait Engine: Sized { - /// The associated type representing the return type of the engine's operations. - type ReturnType<'b, T> - where - T: 'b, - Self: 'b; - /// Reads data from HashiCorp Vault at the specified location. - /// - /// # Parameters - /// - /// - `client`: A reference to the HashiCorpVault client. - /// - `location`: The location in HashiCorp Vault to read data from. - /// - /// # Returns - /// - /// A future representing the result of the read operation. - fn read(client: &HashiCorpVault, location: String) -> Self::ReturnType<'_, String>; -} - -/// An implementation of the `Engine` trait for the Key-Value version 2 (Kv2) engine. -#[derive(Debug)] -pub enum Kv2 {} - -impl Engine for Kv2 { - type ReturnType<'b, T: 'b> = - Pin<Box<dyn Future<Output = error_stack::Result<T, HashiCorpError>> + Send + 'b>>; - fn read(client: &HashiCorpVault, location: String) -> Self::ReturnType<'_, String> { - Box::pin(async move { - let mut split = location.split(':'); - let mount = split.next().ok_or(HashiCorpError::IncompleteData)?; - let path = split.next().ok_or(HashiCorpError::IncompleteData)?; - let key = split.next().unwrap_or("value"); - - let mut output = - vaultrs::kv2::read::<HashMap<String, String>>(&client.client, mount, path) - .await - .map_err(Into::<Report<_>>::into) - .change_context(HashiCorpError::FetchFailed)?; - - Ok(output.remove(key).ok_or(HashiCorpError::ParseError)?) - }) - } -} - -impl HashiCorpVault { - /// Creates a new instance of HashiCorpVault based on the provided configuration. - /// - /// # Parameters - /// - /// - `config`: A reference to a `HashiCorpVaultConfig` containing the configuration details. - /// - pub fn new(config: &HashiCorpVaultConfig) -> error_stack::Result<Self, HashiCorpError> { - VaultClient::new( - VaultClientSettingsBuilder::default() - .address(&config.url) - .token(&config.token) - .build() - .map_err(Into::<Report<_>>::into) - .change_context(HashiCorpError::ClientCreationFailed) - .attach_printable("Failed while building vault settings")?, - ) - .map_err(Into::<Report<_>>::into) - .change_context(HashiCorpError::ClientCreationFailed) - .map(|client| Self { client }) - } - - /// Asynchronously fetches data from HashiCorp Vault using the specified engine. - /// - /// # Parameters - /// - /// - `data`: A String representing the location or identifier of the data in HashiCorp Vault. - /// - /// # Type Parameters - /// - /// - `En`: The engine type that implements the `Engine` trait. - /// - `I`: The type that can be constructed from the retrieved encoded data. - /// - pub async fn fetch<En, I>(&self, data: String) -> error_stack::Result<I, HashiCorpError> - where - for<'a> En: Engine< - ReturnType<'a, String> = Pin< - Box< - dyn Future<Output = error_stack::Result<String, HashiCorpError>> - + Send - + 'a, - >, - >, - > + 'a, - I: FromEncoded, - { - let output = En::read(self, data).await?; - I::from_encoded(output).ok_or(error_stack::report!(HashiCorpError::HexDecodingFailed)) - } -} - -/// A trait for types that can be constructed from encoded data in the form of a String. -pub trait FromEncoded: Sized { - /// Constructs an instance of the type from the provided encoded input. - /// - /// # Parameters - /// - /// - `input`: A String containing the encoded data. - /// - /// # Returns - /// - /// An `Option<Self>` representing the constructed instance if successful, or `None` otherwise. - /// - /// # Example - /// - /// ```rust - /// # use your_module::{FromEncoded, masking::Secret, Vec}; - /// let secret_instance = Secret::<String>::from_encoded("encoded_secret_string".to_string()); - /// let vec_instance = Vec::<u8>::from_encoded("68656c6c6f".to_string()); - /// ``` - fn from_encoded(input: String) -> Option<Self>; -} - -impl FromEncoded for masking::Secret<String> { - fn from_encoded(input: String) -> Option<Self> { - Some(input.into()) - } -} - -impl FromEncoded for Vec<u8> { - fn from_encoded(input: String) -> Option<Self> { - hex::decode(input).ok() - } -} - -/// An enumeration representing various errors that can occur in interactions with HashiCorp Vault. -#[derive(Debug, thiserror::Error)] -pub enum HashiCorpError { - /// Failed while creating hashicorp client - #[error("Failed while creating a new client")] - ClientCreationFailed, - - /// Failed while building configurations for hashicorp client - #[error("Failed while building configuration")] - ConfigurationBuildFailed, - - /// Failed while decoding data to hex format - #[error("Failed while decoding hex data")] - HexDecodingFailed, - - /// An error occurred when base64 decoding input data. - #[error("Failed to base64 decode input data")] - Base64DecodingFailed, - - /// An error occurred when KMS decrypting input data. - #[error("Failed to KMS decrypt input data")] - DecryptionFailed, - - /// The KMS decrypted output does not include a plaintext output. - #[error("Missing plaintext KMS decryption output")] - MissingPlaintextDecryptionOutput, - - /// An error occurred UTF-8 decoding KMS decrypted output. - #[error("Failed to UTF-8 decode decryption output")] - Utf8DecodingFailed, - - /// Incomplete data provided to fetch data from hasicorp - #[error("Provided information about the value is incomplete")] - IncompleteData, - - /// Failed while fetching data from vault - #[error("Failed while fetching data from the server")] - FetchFailed, - - /// Failed while parsing received data - #[error("Failed while parsing the response")] - ParseError, -} +pub mod implementers; diff --git a/crates/external_services/src/hashicorp_vault/core.rs b/crates/external_services/src/hashicorp_vault/core.rs new file mode 100644 index 00000000000..86908b9d3d6 --- /dev/null +++ b/crates/external_services/src/hashicorp_vault/core.rs @@ -0,0 +1,227 @@ +//! Interactions with the HashiCorp Vault + +use std::{collections::HashMap, future::Future, pin::Pin}; + +use common_utils::{ext_traits::ConfigExt, fp_utils::when}; +use error_stack::{Report, ResultExt}; +use masking::{PeekInterface, Secret}; +use vaultrs::client::{VaultClient, VaultClientSettingsBuilder}; + +static HC_CLIENT: tokio::sync::OnceCell<HashiCorpVault> = tokio::sync::OnceCell::const_new(); + +#[allow(missing_debug_implementations)] +/// A struct representing a connection to HashiCorp Vault. +pub struct HashiCorpVault { + /// The underlying client used for interacting with HashiCorp Vault. + client: VaultClient, +} + +/// Configuration for connecting to HashiCorp Vault. +#[derive(Clone, Debug, Default, serde::Deserialize)] +#[serde(default)] +pub struct HashiCorpVaultConfig { + /// The URL of the HashiCorp Vault server. + pub url: String, + /// The authentication token used to access HashiCorp Vault. + pub token: Secret<String>, +} + +impl HashiCorpVaultConfig { + /// Verifies that the [`HashiCorpVault`] configuration is usable. + pub fn validate(&self) -> Result<(), &'static str> { + when(self.url.is_default_or_empty(), || { + Err("HashiCorp vault url must not be empty") + })?; + + when(self.token.is_default_or_empty(), || { + Err("HashiCorp vault token must not be empty") + }) + } +} + +/// Asynchronously retrieves a HashiCorp Vault client based on the provided configuration. +/// +/// # Parameters +/// +/// - `config`: A reference to a `HashiCorpVaultConfig` containing the configuration details. +pub async fn get_hashicorp_client( + config: &HashiCorpVaultConfig, +) -> error_stack::Result<&'static HashiCorpVault, HashiCorpError> { + HC_CLIENT + .get_or_try_init(|| async { HashiCorpVault::new(config) }) + .await +} + +/// A trait defining an engine for interacting with HashiCorp Vault. +pub trait Engine: Sized { + /// The associated type representing the return type of the engine's operations. + type ReturnType<'b, T> + where + T: 'b, + Self: 'b; + /// Reads data from HashiCorp Vault at the specified location. + /// + /// # Parameters + /// + /// - `client`: A reference to the HashiCorpVault client. + /// - `location`: The location in HashiCorp Vault to read data from. + /// + /// # Returns + /// + /// A future representing the result of the read operation. + fn read(client: &HashiCorpVault, location: String) -> Self::ReturnType<'_, String>; +} + +/// An implementation of the `Engine` trait for the Key-Value version 2 (Kv2) engine. +#[derive(Debug)] +pub enum Kv2 {} + +impl Engine for Kv2 { + type ReturnType<'b, T: 'b> = + Pin<Box<dyn Future<Output = error_stack::Result<T, HashiCorpError>> + Send + 'b>>; + fn read(client: &HashiCorpVault, location: String) -> Self::ReturnType<'_, String> { + Box::pin(async move { + let mut split = location.split(':'); + let mount = split.next().ok_or(HashiCorpError::IncompleteData)?; + let path = split.next().ok_or(HashiCorpError::IncompleteData)?; + let key = split.next().unwrap_or("value"); + + let mut output = + vaultrs::kv2::read::<HashMap<String, String>>(&client.client, mount, path) + .await + .map_err(Into::<Report<_>>::into) + .change_context(HashiCorpError::FetchFailed)?; + + Ok(output.remove(key).ok_or(HashiCorpError::ParseError)?) + }) + } +} + +impl HashiCorpVault { + /// Creates a new instance of HashiCorpVault based on the provided configuration. + /// + /// # Parameters + /// + /// - `config`: A reference to a `HashiCorpVaultConfig` containing the configuration details. + /// + pub fn new(config: &HashiCorpVaultConfig) -> error_stack::Result<Self, HashiCorpError> { + VaultClient::new( + VaultClientSettingsBuilder::default() + .address(&config.url) + .token(config.token.peek()) + .build() + .map_err(Into::<Report<_>>::into) + .change_context(HashiCorpError::ClientCreationFailed) + .attach_printable("Failed while building vault settings")?, + ) + .map_err(Into::<Report<_>>::into) + .change_context(HashiCorpError::ClientCreationFailed) + .map(|client| Self { client }) + } + + /// Asynchronously fetches data from HashiCorp Vault using the specified engine. + /// + /// # Parameters + /// + /// - `data`: A String representing the location or identifier of the data in HashiCorp Vault. + /// + /// # Type Parameters + /// + /// - `En`: The engine type that implements the `Engine` trait. + /// - `I`: The type that can be constructed from the retrieved encoded data. + /// + pub async fn fetch<En, I>(&self, data: String) -> error_stack::Result<I, HashiCorpError> + where + for<'a> En: Engine< + ReturnType<'a, String> = Pin< + Box< + dyn Future<Output = error_stack::Result<String, HashiCorpError>> + + Send + + 'a, + >, + >, + > + 'a, + I: FromEncoded, + { + let output = En::read(self, data).await?; + I::from_encoded(output).ok_or(error_stack::report!(HashiCorpError::HexDecodingFailed)) + } +} + +/// A trait for types that can be constructed from encoded data in the form of a String. +pub trait FromEncoded: Sized { + /// Constructs an instance of the type from the provided encoded input. + /// + /// # Parameters + /// + /// - `input`: A String containing the encoded data. + /// + /// # Returns + /// + /// An `Option<Self>` representing the constructed instance if successful, or `None` otherwise. + /// + /// # Example + /// + /// ```rust + /// # use your_module::{FromEncoded, masking::Secret, Vec}; + /// let secret_instance = Secret::<String>::from_encoded("encoded_secret_string".to_string()); + /// let vec_instance = Vec::<u8>::from_encoded("68656c6c6f".to_string()); + /// ``` + fn from_encoded(input: String) -> Option<Self>; +} + +impl FromEncoded for Secret<String> { + fn from_encoded(input: String) -> Option<Self> { + Some(input.into()) + } +} + +impl FromEncoded for Vec<u8> { + fn from_encoded(input: String) -> Option<Self> { + hex::decode(input).ok() + } +} + +/// An enumeration representing various errors that can occur in interactions with HashiCorp Vault. +#[derive(Debug, thiserror::Error)] +pub enum HashiCorpError { + /// Failed while creating hashicorp client + #[error("Failed while creating a new client")] + ClientCreationFailed, + + /// Failed while building configurations for hashicorp client + #[error("Failed while building configuration")] + ConfigurationBuildFailed, + + /// Failed while decoding data to hex format + #[error("Failed while decoding hex data")] + HexDecodingFailed, + + /// An error occurred when base64 decoding input data. + #[error("Failed to base64 decode input data")] + Base64DecodingFailed, + + /// An error occurred when KMS decrypting input data. + #[error("Failed to KMS decrypt input data")] + DecryptionFailed, + + /// The KMS decrypted output does not include a plaintext output. + #[error("Missing plaintext KMS decryption output")] + MissingPlaintextDecryptionOutput, + + /// An error occurred UTF-8 decoding KMS decrypted output. + #[error("Failed to UTF-8 decode decryption output")] + Utf8DecodingFailed, + + /// Incomplete data provided to fetch data from hasicorp + #[error("Provided information about the value is incomplete")] + IncompleteData, + + /// Failed while fetching data from vault + #[error("Failed while fetching data from the server")] + FetchFailed, + + /// Failed while parsing received data + #[error("Failed while parsing the response")] + ParseError, +} diff --git a/crates/external_services/src/hashicorp_vault/decrypt.rs b/crates/external_services/src/hashicorp_vault/decrypt.rs index 1bc1b6ffa16..650b219841f 100644 --- a/crates/external_services/src/hashicorp_vault/decrypt.rs +++ b/crates/external_services/src/hashicorp_vault/decrypt.rs @@ -1,7 +1,11 @@ +//! Utilities for supporting decryption of data + use std::{future::Future, pin::Pin}; use masking::ExposeInterface; +use crate::hashicorp_vault::core::{Engine, HashiCorpError, HashiCorpVault}; + /// A trait for types that can be asynchronously fetched and decrypted from HashiCorp Vault. #[async_trait::async_trait] pub trait VaultFetch: Sized { @@ -14,13 +18,13 @@ pub trait VaultFetch: Sized { /// async fn fetch_inner<En>( self, - client: &super::HashiCorpVault, - ) -> error_stack::Result<Self, super::HashiCorpError> + client: &HashiCorpVault, + ) -> error_stack::Result<Self, HashiCorpError> where - for<'a> En: super::Engine< + for<'a> En: Engine< ReturnType<'a, String> = Pin< Box< - dyn Future<Output = error_stack::Result<String, super::HashiCorpError>> + dyn Future<Output = error_stack::Result<String, HashiCorpError>> + Send + 'a, >, @@ -32,13 +36,13 @@ pub trait VaultFetch: Sized { impl VaultFetch for masking::Secret<String> { async fn fetch_inner<En>( self, - client: &super::HashiCorpVault, - ) -> error_stack::Result<Self, super::HashiCorpError> + client: &HashiCorpVault, + ) -> error_stack::Result<Self, HashiCorpError> where - for<'a> En: super::Engine< + for<'a> En: Engine< ReturnType<'a, String> = Pin< Box< - dyn Future<Output = error_stack::Result<String, super::HashiCorpError>> + dyn Future<Output = error_stack::Result<String, HashiCorpError>> + Send + 'a, >, diff --git a/crates/external_services/src/hashicorp_vault/implementers.rs b/crates/external_services/src/hashicorp_vault/implementers.rs new file mode 100644 index 00000000000..52fec2bd8d3 --- /dev/null +++ b/crates/external_services/src/hashicorp_vault/implementers.rs @@ -0,0 +1,24 @@ +//! Trait implementations for Hashicorp vault client + +use common_utils::errors::CustomResult; +use error_stack::ResultExt; +use hyperswitch_interfaces::secrets_interface::{ + SecretManagementInterface, SecretsManagementError, +}; +use masking::{ExposeInterface, Secret}; + +use crate::hashicorp_vault::core::{HashiCorpVault, Kv2}; + +#[async_trait::async_trait] +impl SecretManagementInterface for HashiCorpVault { + async fn get_secret( + &self, + input: Secret<String>, + ) -> CustomResult<Secret<String>, SecretsManagementError> { + self.fetch::<Kv2, Secret<String>>(input.expose()) + .await + .map(|val| val.expose().to_owned()) + .change_context(SecretsManagementError::FetchSecretFailed) + .map(Into::into) + } +} diff --git a/crates/external_services/src/lib.rs b/crates/external_services/src/lib.rs index cdabdeb49ae..33ab7541974 100644 --- a/crates/external_services/src/lib.rs +++ b/crates/external_services/src/lib.rs @@ -13,6 +13,10 @@ pub mod file_storage; #[cfg(feature = "hashicorp-vault")] pub mod hashicorp_vault; +pub mod no_encryption; + +pub mod managers; + /// Crate specific constants #[cfg(feature = "aws_kms")] pub mod consts { diff --git a/crates/external_services/src/managers.rs b/crates/external_services/src/managers.rs new file mode 100644 index 00000000000..cb33d7bbf38 --- /dev/null +++ b/crates/external_services/src/managers.rs @@ -0,0 +1,5 @@ +//! Config and client managers + +pub mod encryption_management; + +pub mod secrets_management; diff --git a/crates/external_services/src/managers/encryption_management.rs b/crates/external_services/src/managers/encryption_management.rs new file mode 100644 index 00000000000..4612190926c --- /dev/null +++ b/crates/external_services/src/managers/encryption_management.rs @@ -0,0 +1,53 @@ +//! +//! Encryption management util module +//! + +use common_utils::errors::CustomResult; +use hyperswitch_interfaces::encryption_interface::{ + EncryptionError, EncryptionManagementInterface, +}; + +#[cfg(feature = "aws_kms")] +use crate::aws_kms; +use crate::no_encryption::core::NoEncryption; + +/// Enum representing configuration options for encryption management. +#[derive(Debug, Clone, Default, serde::Deserialize)] +#[serde(tag = "encryption_manager")] +#[serde(rename_all = "snake_case")] +pub enum EncryptionManagementConfig { + /// AWS KMS configuration + #[cfg(feature = "aws_kms")] + AwsKms { + /// AWS KMS config + aws_kms: aws_kms::core::AwsKmsConfig, + }, + + /// Variant representing no encryption + #[default] + NoEncryption, +} + +impl EncryptionManagementConfig { + /// Verifies that the client configuration is usable + pub fn validate(&self) -> Result<(), &'static str> { + match self { + #[cfg(feature = "aws_kms")] + Self::AwsKms { aws_kms } => aws_kms.validate(), + + Self::NoEncryption => Ok(()), + } + } + + /// Retrieves the appropriate encryption client based on the configuration. + pub async fn get_encryption_management_client( + &self, + ) -> CustomResult<Box<dyn EncryptionManagementInterface>, EncryptionError> { + Ok(match self { + #[cfg(feature = "aws_kms")] + Self::AwsKms { aws_kms } => Box::new(aws_kms::core::AwsKmsClient::new(aws_kms).await), + + Self::NoEncryption => Box::new(NoEncryption), + }) + } +} diff --git a/crates/external_services/src/managers/secrets_management.rs b/crates/external_services/src/managers/secrets_management.rs new file mode 100644 index 00000000000..b79046b4c75 --- /dev/null +++ b/crates/external_services/src/managers/secrets_management.rs @@ -0,0 +1,72 @@ +//! +//! Secrets management util module +//! + +use common_utils::errors::CustomResult; +#[cfg(feature = "hashicorp-vault")] +use error_stack::ResultExt; +use hyperswitch_interfaces::secrets_interface::{ + SecretManagementInterface, SecretsManagementError, +}; + +#[cfg(feature = "aws_kms")] +use crate::aws_kms; +#[cfg(feature = "hashicorp-vault")] +use crate::hashicorp_vault; +use crate::no_encryption::core::NoEncryption; + +/// Enum representing configuration options for secrets management. +#[derive(Debug, Clone, Default, serde::Deserialize)] +#[serde(tag = "secrets_manager")] +#[serde(rename_all = "snake_case")] +pub enum SecretsManagementConfig { + /// AWS KMS configuration + #[cfg(feature = "aws_kms")] + AwsKms { + /// AWS KMS config + aws_kms: aws_kms::core::AwsKmsConfig, + }, + + /// HashiCorp-Vault configuration + #[cfg(feature = "hashicorp-vault")] + HashiCorpVault { + /// HC-Vault config + hc_vault: hashicorp_vault::core::HashiCorpVaultConfig, + }, + + /// Variant representing no encryption + #[default] + NoEncryption, +} + +impl SecretsManagementConfig { + /// Verifies that the client configuration is usable + pub fn validate(&self) -> Result<(), &'static str> { + match self { + #[cfg(feature = "aws_kms")] + Self::AwsKms { aws_kms } => aws_kms.validate(), + #[cfg(feature = "hashicorp-vault")] + Self::HashiCorpVault { hc_vault } => hc_vault.validate(), + Self::NoEncryption => Ok(()), + } + } + + /// Retrieves the appropriate secret management client based on the configuration. + pub async fn get_secret_management_client( + &self, + ) -> CustomResult<Box<dyn SecretManagementInterface>, SecretsManagementError> { + match self { + #[cfg(feature = "aws_kms")] + Self::AwsKms { aws_kms } => { + Ok(Box::new(aws_kms::core::AwsKmsClient::new(aws_kms).await)) + } + #[cfg(feature = "hashicorp-vault")] + Self::HashiCorpVault { hc_vault } => { + hashicorp_vault::core::HashiCorpVault::new(hc_vault) + .change_context(SecretsManagementError::ClientCreationFailed) + .map(|inner| -> Box<dyn SecretManagementInterface> { Box::new(inner) }) + } + Self::NoEncryption => Ok(Box::new(NoEncryption)), + } + } +} diff --git a/crates/external_services/src/no_encryption.rs b/crates/external_services/src/no_encryption.rs new file mode 100644 index 00000000000..17c29618f89 --- /dev/null +++ b/crates/external_services/src/no_encryption.rs @@ -0,0 +1,7 @@ +//! +//! No encryption functionalities +//! + +pub mod core; + +pub mod implementers; diff --git a/crates/external_services/src/no_encryption/core.rs b/crates/external_services/src/no_encryption/core.rs new file mode 100644 index 00000000000..a55815c03f9 --- /dev/null +++ b/crates/external_services/src/no_encryption/core.rs @@ -0,0 +1,17 @@ +//! No encryption core functionalities + +/// No encryption type +#[derive(Debug, Clone)] +pub struct NoEncryption; + +impl NoEncryption { + /// Encryption functionality + pub fn encrypt(&self, data: impl AsRef<[u8]>) -> Vec<u8> { + data.as_ref().into() + } + + /// Decryption functionality + pub fn decrypt(&self, data: impl AsRef<[u8]>) -> Vec<u8> { + data.as_ref().into() + } +} diff --git a/crates/external_services/src/no_encryption/implementers.rs b/crates/external_services/src/no_encryption/implementers.rs new file mode 100644 index 00000000000..f67c7c85fd5 --- /dev/null +++ b/crates/external_services/src/no_encryption/implementers.rs @@ -0,0 +1,36 @@ +//! Trait implementations for No encryption client + +use common_utils::errors::CustomResult; +use error_stack::{IntoReport, ResultExt}; +use hyperswitch_interfaces::{ + encryption_interface::{EncryptionError, EncryptionManagementInterface}, + secrets_interface::{SecretManagementInterface, SecretsManagementError}, +}; +use masking::{ExposeInterface, Secret}; + +use crate::no_encryption::core::NoEncryption; + +#[async_trait::async_trait] +impl EncryptionManagementInterface for NoEncryption { + async fn encrypt(&self, input: &[u8]) -> CustomResult<Vec<u8>, EncryptionError> { + Ok(self.encrypt(input)) + } + + async fn decrypt(&self, input: &[u8]) -> CustomResult<Vec<u8>, EncryptionError> { + Ok(self.decrypt(input)) + } +} + +#[async_trait::async_trait] +impl SecretManagementInterface for NoEncryption { + async fn get_secret( + &self, + input: Secret<String>, + ) -> CustomResult<Secret<String>, SecretsManagementError> { + String::from_utf8(self.decrypt(input.expose())) + .map(Into::into) + .into_report() + .change_context(SecretsManagementError::FetchSecretFailed) + .attach_printable("Failed to convert decrypted value to UTF-8") + } +} diff --git a/crates/hyperswitch_interfaces/Cargo.toml b/crates/hyperswitch_interfaces/Cargo.toml new file mode 100644 index 00000000000..855cf63917f --- /dev/null +++ b/crates/hyperswitch_interfaces/Cargo.toml @@ -0,0 +1,17 @@ +[package] +name = "hyperswitch_interfaces" +version = "0.1.0" +edition.workspace = true +rust-version.workspace = true +readme = "README.md" +license.workspace = true + +[dependencies] +async-trait = "0.1.68" +dyn-clone = "1.0.11" +serde = { version = "1.0.193", features = ["derive"] } +thiserror = "1.0.40" + +# First party crates +common_utils = { version = "0.1.0", path = "../common_utils" } +masking = { version = "0.1.0", path = "../masking" } diff --git a/crates/hyperswitch_interfaces/README.md b/crates/hyperswitch_interfaces/README.md new file mode 100644 index 00000000000..e96e3eabe2a --- /dev/null +++ b/crates/hyperswitch_interfaces/README.md @@ -0,0 +1,3 @@ +# Hyperswitch Interfaces + +This crate includes interfaces and its error types diff --git a/crates/hyperswitch_interfaces/src/encryption_interface.rs b/crates/hyperswitch_interfaces/src/encryption_interface.rs new file mode 100644 index 00000000000..1993019a213 --- /dev/null +++ b/crates/hyperswitch_interfaces/src/encryption_interface.rs @@ -0,0 +1,29 @@ +//! Encryption related interface and error types + +#![warn(missing_docs, missing_debug_implementations)] + +use common_utils::errors::CustomResult; + +/// Trait defining the interface for encryption management +#[async_trait::async_trait] +pub trait EncryptionManagementInterface: Sync + Send + dyn_clone::DynClone { + /// Encrypt the given input data + async fn encrypt(&self, input: &[u8]) -> CustomResult<Vec<u8>, EncryptionError>; + + /// Decrypt the given input data + async fn decrypt(&self, input: &[u8]) -> CustomResult<Vec<u8>, EncryptionError>; +} + +dyn_clone::clone_trait_object!(EncryptionManagementInterface); + +/// Errors that may occur during above encryption functionalities +#[derive(Debug, thiserror::Error)] +pub enum EncryptionError { + /// An error occurred when encrypting input data. + #[error("Failed to encrypt input data")] + EncryptionFailed, + + /// An error occurred when decrypting input data. + #[error("Failed to decrypt input data")] + DecryptionFailed, +} diff --git a/crates/hyperswitch_interfaces/src/lib.rs b/crates/hyperswitch_interfaces/src/lib.rs new file mode 100644 index 00000000000..3f7b8d41c3e --- /dev/null +++ b/crates/hyperswitch_interfaces/src/lib.rs @@ -0,0 +1,7 @@ +//! Hyperswitch interface + +#![warn(missing_docs, missing_debug_implementations)] + +pub mod secrets_interface; + +pub mod encryption_interface; diff --git a/crates/hyperswitch_interfaces/src/secrets_interface.rs b/crates/hyperswitch_interfaces/src/secrets_interface.rs new file mode 100644 index 00000000000..761981bedda --- /dev/null +++ b/crates/hyperswitch_interfaces/src/secrets_interface.rs @@ -0,0 +1,36 @@ +//! Secrets management interface + +pub mod secret_handler; + +pub mod secret_state; + +use common_utils::errors::CustomResult; +use masking::Secret; + +/// Trait defining the interface for managing application secrets +#[async_trait::async_trait] +pub trait SecretManagementInterface: Send + Sync { + /// Given an input, encrypt/store the secret + // async fn store_secret( + // &self, + // input: Secret<String>, + // ) -> CustomResult<String, SecretsManagementError>; + + /// Given an input, decrypt/retrieve the secret + async fn get_secret( + &self, + input: Secret<String>, + ) -> CustomResult<Secret<String>, SecretsManagementError>; +} + +/// Errors that may occur during secret management +#[derive(Debug, thiserror::Error)] +pub enum SecretsManagementError { + /// An error occurred when retrieving raw data. + #[error("Failed to fetch the raw data")] + FetchSecretFailed, + + /// Failed while creating kms client + #[error("Failed while creating a secrets management client")] + ClientCreationFailed, +} diff --git a/crates/hyperswitch_interfaces/src/secrets_interface/secret_handler.rs b/crates/hyperswitch_interfaces/src/secrets_interface/secret_handler.rs new file mode 100644 index 00000000000..a0915b8de69 --- /dev/null +++ b/crates/hyperswitch_interfaces/src/secrets_interface/secret_handler.rs @@ -0,0 +1,21 @@ +//! Module containing trait for raw secret retrieval + +use common_utils::errors::CustomResult; + +use crate::secrets_interface::{ + secret_state::{RawSecret, SecretStateContainer, SecuredSecret}, + SecretManagementInterface, SecretsManagementError, +}; + +/// Trait defining the interface for retrieving a raw secret value, given a secured value +#[async_trait::async_trait] +pub trait SecretsHandler +where + Self: Sized, +{ + /// Construct `Self` with raw secret value and transitions its type from `SecuredSecret` to `RawSecret` + async fn convert_to_raw_secret( + value: SecretStateContainer<Self, SecuredSecret>, + kms_client: Box<dyn SecretManagementInterface>, + ) -> CustomResult<SecretStateContainer<Self, RawSecret>, SecretsManagementError>; +} diff --git a/crates/hyperswitch_interfaces/src/secrets_interface/secret_state.rs b/crates/hyperswitch_interfaces/src/secrets_interface/secret_state.rs new file mode 100644 index 00000000000..6d3f75500af --- /dev/null +++ b/crates/hyperswitch_interfaces/src/secrets_interface/secret_state.rs @@ -0,0 +1,71 @@ +//! Module to manage encrypted and decrypted states for a given type. + +use std::marker::PhantomData; + +use serde::{Deserialize, Deserializer}; + +/// Trait defining the states of a secret +pub trait SecretState {} + +/// Decrypted state +#[derive(Debug, Clone, Deserialize)] +pub enum RawSecret {} + +/// Encrypted state +#[derive(Debug, Clone, Deserialize)] +pub enum SecuredSecret {} + +impl SecretState for RawSecret {} +impl SecretState for SecuredSecret {} + +/// Struct for managing the encrypted and decrypted states of a given type +#[derive(Debug, Clone, Default)] +pub struct SecretStateContainer<T, S: SecretState> { + inner: T, + marker: PhantomData<S>, +} + +impl<T: Clone, S: SecretState> SecretStateContainer<T, S> { + /// + /// Get the inner data while consuming self + /// + #[inline] + pub fn into_inner(self) -> T { + self.inner + } + + /// + /// Get the reference to inner value + /// + #[inline] + pub fn get_inner(&self) -> &T { + &self.inner + } +} + +impl<'de, T: Deserialize<'de>, S: SecretState> Deserialize<'de> for SecretStateContainer<T, S> { + fn deserialize<D>(deserializer: D) -> Result<Self, D::Error> + where + D: Deserializer<'de>, + { + let val = Deserialize::deserialize(deserializer)?; + Ok(Self { + inner: val, + marker: PhantomData, + }) + } +} + +impl<T> SecretStateContainer<T, SecuredSecret> { + /// Transition the secret state from `SecuredSecret` to `RawSecret` + pub fn transition_state( + mut self, + decryptor_fn: impl FnOnce(T) -> T, + ) -> SecretStateContainer<T, RawSecret> { + self.inner = decryptor_fn(self.inner); + SecretStateContainer { + inner: self.inner, + marker: PhantomData, + } + } +} diff --git a/crates/router/Cargo.toml b/crates/router/Cargo.toml index 9b345217bb5..690a0676fa6 100644 --- a/crates/router/Cargo.toml +++ b/crates/router/Cargo.toml @@ -111,6 +111,7 @@ diesel_models = { version = "0.1.0", path = "../diesel_models", features = ["kv_ euclid = { version = "0.1.0", path = "../euclid", features = ["valued_jit"] } pm_auth = { version = "0.1.0", path = "../pm_auth", package = "pm_auth" } external_services = { version = "0.1.0", path = "../external_services" } +hyperswitch_interfaces = { version = "0.1.0", path = "../hyperswitch_interfaces" } kgraph_utils = { version = "0.1.0", path = "../kgraph_utils" } masking = { version = "0.1.0", path = "../masking" } redis_interface = { version = "0.1.0", path = "../redis_interface" } diff --git a/crates/router/src/configs/aws_kms.rs b/crates/router/src/configs/aws_kms.rs index 5e37f2a4dd6..9bb5fcc6f20 100644 --- a/crates/router/src/configs/aws_kms.rs +++ b/crates/router/src/configs/aws_kms.rs @@ -1,5 +1,8 @@ use common_utils::errors::CustomResult; -use external_services::aws_kms::{decrypt::AwsKmsDecrypt, AwsKmsClient, AwsKmsError}; +use external_services::aws_kms::{ + core::{AwsKmsClient, AwsKmsError}, + decrypt::AwsKmsDecrypt, +}; use masking::ExposeInterface; use crate::configs::settings; diff --git a/crates/router/src/configs/defaults.rs b/crates/router/src/configs/defaults.rs index 71cd61ffa80..82237e7a887 100644 --- a/crates/router/src/configs/defaults.rs +++ b/crates/router/src/configs/defaults.rs @@ -2,7 +2,7 @@ use std::collections::{HashMap, HashSet}; use api_models::{enums, payment_methods::RequiredFieldInfo}; #[cfg(feature = "aws_kms")] -use external_services::aws_kms::AwsKmsValue; +use external_services::aws_kms::core::AwsKmsValue; use super::settings::{ConnectorFields, Password, PaymentMethodType, RequiredFieldFinal}; diff --git a/crates/router/src/configs/hc_vault.rs b/crates/router/src/configs/hc_vault.rs index f20d8e79ed8..fa6596f7494 100644 --- a/crates/router/src/configs/hc_vault.rs +++ b/crates/router/src/configs/hc_vault.rs @@ -1,5 +1,6 @@ use external_services::hashicorp_vault::{ - decrypt::VaultFetch, Engine, HashiCorpError, HashiCorpVault, + core::{Engine, HashiCorpError, HashiCorpVault}, + decrypt::VaultFetch, }; use masking::ExposeInterface; diff --git a/crates/router/src/configs/settings.rs b/crates/router/src/configs/settings.rs index 2572d764d06..13c3ba23e1d 100644 --- a/crates/router/src/configs/settings.rs +++ b/crates/router/src/configs/settings.rs @@ -12,9 +12,15 @@ use config::{Environment, File}; use external_services::aws_kms; #[cfg(feature = "email")] use external_services::email::EmailSettings; -use external_services::file_storage::FileStorageConfig; #[cfg(feature = "hashicorp-vault")] use external_services::hashicorp_vault; +use external_services::{ + file_storage::FileStorageConfig, + managers::{ + encryption_management::EncryptionManagementConfig, + secrets_management::SecretsManagementConfig, + }, +}; use redis_interface::RedisSettings; pub use router_env::config::{Log, LogConsole, LogFile, LogTelemetry}; use rust_decimal::Decimal; @@ -30,7 +36,7 @@ use crate::{ events::EventsConfig, }; #[cfg(feature = "aws_kms")] -pub type Password = aws_kms::AwsKmsValue; +pub type Password = aws_kms::core::AwsKmsValue; #[cfg(not(feature = "aws_kms"))] pub type Password = masking::Secret<String>; @@ -89,10 +95,12 @@ pub struct Settings { pub bank_config: BankRedirectConfig, pub api_keys: ApiKeys, #[cfg(feature = "aws_kms")] - pub kms: aws_kms::AwsKmsConfig, + pub kms: aws_kms::core::AwsKmsConfig, pub file_storage: FileStorageConfig, + pub encryption_management: EncryptionManagementConfig, + pub secrets_management: SecretsManagementConfig, #[cfg(feature = "hashicorp-vault")] - pub hc_vault: hashicorp_vault::HashiCorpVaultConfig, + pub hc_vault: hashicorp_vault::core::HashiCorpVaultConfig, pub tokenization: TokenizationConfig, pub connector_customer: ConnectorCustomer, #[cfg(feature = "dummy_connector")] @@ -368,11 +376,11 @@ pub struct Secrets { pub recon_admin_api_key: String, pub master_enc_key: Password, #[cfg(feature = "aws_kms")] - pub kms_encrypted_jwt_secret: aws_kms::AwsKmsValue, + pub kms_encrypted_jwt_secret: aws_kms::core::AwsKmsValue, #[cfg(feature = "aws_kms")] - pub kms_encrypted_admin_api_key: aws_kms::AwsKmsValue, + pub kms_encrypted_admin_api_key: aws_kms::core::AwsKmsValue, #[cfg(feature = "aws_kms")] - pub kms_encrypted_recon_admin_api_key: aws_kms::AwsKmsValue, + pub kms_encrypted_recon_admin_api_key: aws_kms::core::AwsKmsValue, } #[derive(Debug, Deserialize, Clone)] @@ -598,7 +606,7 @@ pub struct ApiKeys { /// Base64-encoded (KMS encrypted) ciphertext of the key used for calculating hashes of API /// keys #[cfg(feature = "aws_kms")] - pub kms_encrypted_hash_key: aws_kms::AwsKmsValue, + pub kms_encrypted_hash_key: aws_kms::core::AwsKmsValue, /// Hex-encoded 32-byte long (64 characters long when hex-encoded) key used for calculating /// hashes of API keys @@ -724,6 +732,14 @@ impl Settings { self.lock_settings.validate()?; self.events.validate()?; + + self.encryption_management + .validate() + .map_err(|err| ApplicationError::InvalidConfigurationValueError(err.into()))?; + + self.secrets_management + .validate() + .map_err(|err| ApplicationError::InvalidConfigurationValueError(err.into()))?; Ok(()) } } diff --git a/crates/router/src/core/api_keys.rs b/crates/router/src/core/api_keys.rs index 162f8bed0f8..b694d1291a8 100644 --- a/crates/router/src/core/api_keys.rs +++ b/crates/router/src/core/api_keys.rs @@ -38,9 +38,9 @@ static HASH_KEY: tokio::sync::OnceCell<StrongSecret<[u8; PlaintextApiKey::HASH_K pub async fn get_hash_key( api_key_config: &settings::ApiKeys, - #[cfg(feature = "aws_kms")] aws_kms_client: &aws_kms::AwsKmsClient, + #[cfg(feature = "aws_kms")] aws_kms_client: &aws_kms::core::AwsKmsClient, #[cfg(feature = "hashicorp-vault")] - hc_client: &external_services::hashicorp_vault::HashiCorpVault, + hc_client: &external_services::hashicorp_vault::core::HashiCorpVault, ) -> errors::RouterResult<&'static StrongSecret<[u8; PlaintextApiKey::HASH_KEY_LEN]>> { HASH_KEY .get_or_try_init(|| async { @@ -57,7 +57,7 @@ pub async fn get_hash_key( #[cfg(feature = "hashicorp-vault")] let hash_key = hash_key - .fetch_inner::<external_services::hashicorp_vault::Kv2>(hc_client) + .fetch_inner::<external_services::hashicorp_vault::core::Kv2>(hc_client) .await .change_context(errors::ApiErrorResponse::InternalServerError)?; @@ -153,9 +153,9 @@ impl PlaintextApiKey { #[instrument(skip_all)] pub async fn create_api_key( state: AppState, - #[cfg(feature = "aws_kms")] aws_kms_client: &aws_kms::AwsKmsClient, + #[cfg(feature = "aws_kms")] aws_kms_client: &aws_kms::core::AwsKmsClient, #[cfg(feature = "hashicorp-vault")] - hc_client: &external_services::hashicorp_vault::HashiCorpVault, + hc_client: &external_services::hashicorp_vault::core::HashiCorpVault, api_key: api::CreateApiKeyRequest, merchant_id: String, ) -> RouterResponse<api::CreateApiKeyResponse> { @@ -590,9 +590,9 @@ mod tests { let hash_key = get_hash_key( &settings.api_keys, #[cfg(feature = "aws_kms")] - external_services::aws_kms::get_aws_kms_client(&settings.kms).await, + external_services::aws_kms::core::get_aws_kms_client(&settings.kms).await, #[cfg(feature = "hashicorp-vault")] - external_services::hashicorp_vault::get_hashicorp_client(&settings.hc_vault) + external_services::hashicorp_vault::core::get_hashicorp_client(&settings.hc_vault) .await .unwrap(), ) diff --git a/crates/router/src/core/blocklist/utils.rs b/crates/router/src/core/blocklist/utils.rs index 43701c80786..733b565beed 100644 --- a/crates/router/src/core/blocklist/utils.rs +++ b/crates/router/src/core/blocklist/utils.rs @@ -48,7 +48,7 @@ pub async fn delete_entry_from_blocklist( })?; #[cfg(feature = "aws_kms")] - let decrypted_fingerprint = aws_kms::get_aws_kms_client(&state.conf.kms) + let decrypted_fingerprint = aws_kms::core::get_aws_kms_client(&state.conf.kms) .await .decrypt(blocklist_fingerprint.encrypted_fingerprint) .await @@ -244,7 +244,7 @@ pub async fn insert_entry_into_blocklist( })?; #[cfg(feature = "aws_kms")] - let decrypted_fingerprint = aws_kms::get_aws_kms_client(&state.conf.kms) + let decrypted_fingerprint = aws_kms::core::get_aws_kms_client(&state.conf.kms) .await .decrypt(blocklist_fingerprint.encrypted_fingerprint) .await diff --git a/crates/router/src/core/payments/flows/session_flow.rs b/crates/router/src/core/payments/flows/session_flow.rs index 062c58e056c..479a0685a97 100644 --- a/crates/router/src/core/payments/flows/session_flow.rs +++ b/crates/router/src/core/payments/flows/session_flow.rs @@ -189,12 +189,13 @@ async fn create_applepay_session_token( common_merchant_identifier, ) = async { #[cfg(feature = "hashicorp-vault")] - let client = external_services::hashicorp_vault::get_hashicorp_client( - &state.conf.hc_vault, - ) - .await - .change_context(errors::ApiErrorResponse::InternalServerError) - .attach_printable("Failed while building hashicorp client")?; + let client = + external_services::hashicorp_vault::core::get_hashicorp_client( + &state.conf.hc_vault, + ) + .await + .change_context(errors::ApiErrorResponse::InternalServerError) + .attach_printable("Failed while building hashicorp client")?; #[cfg(feature = "hashicorp-vault")] { @@ -206,7 +207,7 @@ async fn create_applepay_session_token( .apple_pay_merchant_cert .clone(), ) - .fetch_inner::<hashicorp_vault::Kv2>(client) + .fetch_inner::<hashicorp_vault::core::Kv2>(client) .await .change_context(errors::ApiErrorResponse::InternalServerError)? .expose(), @@ -217,7 +218,7 @@ async fn create_applepay_session_token( .apple_pay_merchant_cert_key .clone(), ) - .fetch_inner::<hashicorp_vault::Kv2>(client) + .fetch_inner::<hashicorp_vault::core::Kv2>(client) .await .change_context(errors::ApiErrorResponse::InternalServerError)? .expose(), @@ -228,7 +229,7 @@ async fn create_applepay_session_token( .common_merchant_identifier .clone(), ) - .fetch_inner::<hashicorp_vault::Kv2>(client) + .fetch_inner::<hashicorp_vault::core::Kv2>(client) .await .change_context(errors::ApiErrorResponse::InternalServerError)? .expose(), @@ -260,7 +261,7 @@ async fn create_applepay_session_token( #[cfg(feature = "aws_kms")] let decrypted_apple_pay_merchant_cert = - aws_kms::get_aws_kms_client(&state.conf.kms) + aws_kms::core::get_aws_kms_client(&state.conf.kms) .await .decrypt(apple_pay_merchant_cert) .await @@ -269,7 +270,7 @@ async fn create_applepay_session_token( #[cfg(feature = "aws_kms")] let decrypted_apple_pay_merchant_cert_key = - aws_kms::get_aws_kms_client(&state.conf.kms) + aws_kms::core::get_aws_kms_client(&state.conf.kms) .await .decrypt(apple_pay_merchant_cert_key) .await @@ -280,7 +281,7 @@ async fn create_applepay_session_token( #[cfg(feature = "aws_kms")] let decrypted_merchant_identifier = - aws_kms::get_aws_kms_client(&state.conf.kms) + aws_kms::core::get_aws_kms_client(&state.conf.kms) .await .decrypt(common_merchant_identifier) .await diff --git a/crates/router/src/core/payments/helpers.rs b/crates/router/src/core/payments/helpers.rs index 7ec1f5e9213..b93d959eb8d 100644 --- a/crates/router/src/core/payments/helpers.rs +++ b/crates/router/src/core/payments/helpers.rs @@ -3537,16 +3537,17 @@ impl ApplePayData { ) -> CustomResult<String, errors::ApplePayDecryptionError> { let apple_pay_ppc = async { #[cfg(feature = "hashicorp-vault")] - let client = - external_services::hashicorp_vault::get_hashicorp_client(&state.conf.hc_vault) - .await - .change_context(errors::ApplePayDecryptionError::DecryptionFailed) - .attach_printable("Failed while creating client")?; + let client = external_services::hashicorp_vault::core::get_hashicorp_client( + &state.conf.hc_vault, + ) + .await + .change_context(errors::ApplePayDecryptionError::DecryptionFailed) + .attach_printable("Failed while creating client")?; #[cfg(feature = "hashicorp-vault")] let output = masking::Secret::new(state.conf.applepay_decrypt_keys.apple_pay_ppc.clone()) - .fetch_inner::<hashicorp_vault::Kv2>(client) + .fetch_inner::<hashicorp_vault::core::Kv2>(client) .await .change_context(errors::ApplePayDecryptionError::DecryptionFailed)? .expose(); @@ -3559,7 +3560,7 @@ impl ApplePayData { .await?; #[cfg(feature = "aws_kms")] - let cert_data = aws_kms::get_aws_kms_client(&state.conf.kms) + let cert_data = aws_kms::core::get_aws_kms_client(&state.conf.kms) .await .decrypt(&apple_pay_ppc) .await @@ -3620,16 +3621,17 @@ impl ApplePayData { let apple_pay_ppc_key = async { #[cfg(feature = "hashicorp-vault")] - let client = - external_services::hashicorp_vault::get_hashicorp_client(&state.conf.hc_vault) - .await - .change_context(errors::ApplePayDecryptionError::DecryptionFailed) - .attach_printable("Failed while creating client")?; + let client = external_services::hashicorp_vault::core::get_hashicorp_client( + &state.conf.hc_vault, + ) + .await + .change_context(errors::ApplePayDecryptionError::DecryptionFailed) + .attach_printable("Failed while creating client")?; #[cfg(feature = "hashicorp-vault")] let output = masking::Secret::new(state.conf.applepay_decrypt_keys.apple_pay_ppc_key.clone()) - .fetch_inner::<hashicorp_vault::Kv2>(client) + .fetch_inner::<hashicorp_vault::core::Kv2>(client) .await .change_context(errors::ApplePayDecryptionError::DecryptionFailed) .attach_printable("Failed while creating client")? @@ -3643,7 +3645,7 @@ impl ApplePayData { .await?; #[cfg(feature = "aws_kms")] - let decrypted_apple_pay_ppc_key = aws_kms::get_aws_kms_client(&state.conf.kms) + let decrypted_apple_pay_ppc_key = aws_kms::core::get_aws_kms_client(&state.conf.kms) .await .decrypt(&apple_pay_ppc_key) .await diff --git a/crates/router/src/core/pm_auth.rs b/crates/router/src/core/pm_auth.rs index f77d5120812..f00c452f3ea 100644 --- a/crates/router/src/core/pm_auth.rs +++ b/crates/router/src/core/pm_auth.rs @@ -349,14 +349,15 @@ async fn store_bank_details_in_payment_methods( let pm_auth_key = async { #[cfg(feature = "hashicorp-vault")] - let client = external_services::hashicorp_vault::get_hashicorp_client(&state.conf.hc_vault) - .await - .change_context(ApiErrorResponse::InternalServerError) - .attach_printable("Failed while creating client")?; + let client = + external_services::hashicorp_vault::core::get_hashicorp_client(&state.conf.hc_vault) + .await + .change_context(ApiErrorResponse::InternalServerError) + .attach_printable("Failed while creating client")?; #[cfg(feature = "hashicorp-vault")] let output = masking::Secret::new(state.conf.payment_method_auth.pm_auth_key.clone()) - .fetch_inner::<hashicorp_vault::Kv2>(client) + .fetch_inner::<hashicorp_vault::core::Kv2>(client) .await .change_context(ApiErrorResponse::InternalServerError)? .expose(); @@ -369,7 +370,7 @@ async fn store_bank_details_in_payment_methods( .await?; #[cfg(feature = "aws_kms")] - let pm_auth_key = aws_kms::get_aws_kms_client(&state.conf.kms) + let pm_auth_key = aws_kms::core::get_aws_kms_client(&state.conf.kms) .await .decrypt(pm_auth_key) .await diff --git a/crates/router/src/core/verification.rs b/crates/router/src/core/verification.rs index 0ed70e6e0c6..79513bfb308 100644 --- a/crates/router/src/core/verification.rs +++ b/crates/router/src/core/verification.rs @@ -13,7 +13,7 @@ pub async fn verify_merchant_creds_for_applepay( state: AppState, _req: &actix_web::HttpRequest, body: verifications::ApplepayMerchantVerificationRequest, - kms_config: &aws_kms::AwsKmsConfig, + kms_config: &aws_kms::core::AwsKmsConfig, merchant_id: String, ) -> CustomResult< services::ApplicationResponse<ApplepayMerchantResponse>, @@ -27,19 +27,19 @@ pub async fn verify_merchant_creds_for_applepay( let encrypted_key = &state.conf.applepay_merchant_configs.merchant_cert_key; let applepay_endpoint = &state.conf.applepay_merchant_configs.applepay_endpoint; - let applepay_internal_merchant_identifier = aws_kms::get_aws_kms_client(kms_config) + let applepay_internal_merchant_identifier = aws_kms::core::get_aws_kms_client(kms_config) .await .decrypt(encrypted_merchant_identifier) .await .change_context(api_error_response::ApiErrorResponse::InternalServerError)?; - let cert_data = aws_kms::get_aws_kms_client(kms_config) + let cert_data = aws_kms::core::get_aws_kms_client(kms_config) .await .decrypt(encrypted_cert) .await .change_context(api_error_response::ApiErrorResponse::InternalServerError)?; - let key_data = aws_kms::get_aws_kms_client(kms_config) + let key_data = aws_kms::core::get_aws_kms_client(kms_config) .await .decrypt(encrypted_key) .await diff --git a/crates/router/src/routes/api_keys.rs b/crates/router/src/routes/api_keys.rs index cf859d048dd..cf0f009a0b1 100644 --- a/crates/router/src/routes/api_keys.rs +++ b/crates/router/src/routes/api_keys.rs @@ -46,10 +46,10 @@ pub async fn api_key_create( |state, _, payload| async { #[cfg(feature = "aws_kms")] let aws_kms_client = - external_services::aws_kms::get_aws_kms_client(&state.clone().conf.kms).await; + external_services::aws_kms::core::get_aws_kms_client(&state.clone().conf.kms).await; #[cfg(feature = "hashicorp-vault")] - let hc_client = external_services::hashicorp_vault::get_hashicorp_client( + let hc_client = external_services::hashicorp_vault::core::get_hashicorp_client( &state.clone().conf.hc_vault, ) .await diff --git a/crates/router/src/routes/app.rs b/crates/router/src/routes/app.rs index 651d3c0026f..84f8b62b57d 100644 --- a/crates/router/src/routes/app.rs +++ b/crates/router/src/routes/app.rs @@ -13,6 +13,7 @@ use external_services::email::{ses::AwsSes, EmailService}; use external_services::file_storage::FileStorageInterface; #[cfg(all(feature = "olap", feature = "hashicorp-vault"))] use external_services::hashicorp_vault::decrypt::VaultFetch; +use hyperswitch_interfaces::encryption_interface::EncryptionManagementInterface; #[cfg(all(feature = "olap", feature = "aws_kms"))] use masking::PeekInterface; use router_env::tracing_actix_web::RequestId; @@ -73,6 +74,7 @@ pub struct AppState { pub pool: crate::analytics::AnalyticsProvider, pub request_id: Option<RequestId>, pub file_storage_client: Box<dyn FileStorageInterface>, + pub encryption_client: Box<dyn EncryptionManagementInterface>, } impl scheduler::SchedulerAppState for AppState { @@ -150,13 +152,20 @@ impl AppState { shut_down_signal: oneshot::Sender<()>, api_client: Box<dyn crate::services::ApiClient>, ) -> Self { + #[allow(clippy::expect_used)] + let encryption_client = conf + .encryption_management + .get_encryption_management_client() + .await + .expect("Failed to create encryption client"); + Box::pin(async move { #[cfg(feature = "aws_kms")] - let aws_kms_client = aws_kms::get_aws_kms_client(&conf.kms).await; + let aws_kms_client = aws_kms::core::get_aws_kms_client(&conf.kms).await; #[cfg(all(feature = "hashicorp-vault", feature = "olap"))] #[allow(clippy::expect_used)] let hc_client = - external_services::hashicorp_vault::get_hashicorp_client(&conf.hc_vault) + external_services::hashicorp_vault::core::get_hashicorp_client(&conf.hc_vault) .await .expect("Failed while creating hashicorp_client"); let testable = storage_impl == StorageImpl::PostgresqlTest; @@ -204,7 +213,7 @@ impl AppState { sqlx.password = sqlx .password .clone() - .fetch_inner::<external_services::hashicorp_vault::Kv2>(hc_client) + .fetch_inner::<external_services::hashicorp_vault::core::Kv2>(hc_client) .await .expect("Failed while fetching from hashicorp vault"); } @@ -230,7 +239,7 @@ impl AppState { { conf.connector_onboarding = conf .connector_onboarding - .fetch_inner::<external_services::hashicorp_vault::Kv2>(hc_client) + .fetch_inner::<external_services::hashicorp_vault::core::Kv2>(hc_client) .await .expect("Failed to decrypt connector onboarding credentials"); } @@ -254,7 +263,7 @@ impl AppState { conf.jwekey = conf .jwekey .clone() - .fetch_inner::<external_services::hashicorp_vault::Kv2>(hc_client) + .fetch_inner::<external_services::hashicorp_vault::core::Kv2>(hc_client) .await .expect("Failed to decrypt connector onboarding credentials"); } @@ -287,6 +296,7 @@ impl AppState { pool, request_id: None, file_storage_client, + encryption_client, } }) .await diff --git a/crates/router/src/services.rs b/crates/router/src/services.rs index 220fde4631f..dc7bf14fecf 100644 --- a/crates/router/src/services.rs +++ b/crates/router/src/services.rs @@ -46,18 +46,19 @@ pub async fn get_store( test_transaction: bool, ) -> StorageResult<Store> { #[cfg(feature = "aws_kms")] - let aws_kms_client = aws_kms::get_aws_kms_client(&config.kms).await; + let aws_kms_client = aws_kms::core::get_aws_kms_client(&config.kms).await; #[cfg(feature = "hashicorp-vault")] - let hc_client = external_services::hashicorp_vault::get_hashicorp_client(&config.hc_vault) - .await - .change_context(StorageError::InitializationError)?; + let hc_client = + external_services::hashicorp_vault::core::get_hashicorp_client(&config.hc_vault) + .await + .change_context(StorageError::InitializationError)?; let master_config = config.master_database.clone(); #[cfg(feature = "hashicorp-vault")] let master_config = master_config - .fetch_inner::<external_services::hashicorp_vault::Kv2>(hc_client) + .fetch_inner::<external_services::hashicorp_vault::core::Kv2>(hc_client) .await .change_context(StorageError::InitializationError) .attach_printable("Failed to fetch data from hashicorp vault")?; @@ -74,7 +75,7 @@ pub async fn get_store( #[cfg(all(feature = "olap", feature = "hashicorp-vault"))] let replica_config = replica_config - .fetch_inner::<external_services::hashicorp_vault::Kv2>(hc_client) + .fetch_inner::<external_services::hashicorp_vault::core::Kv2>(hc_client) .await .change_context(StorageError::InitializationError) .attach_printable("Failed to fetch data from hashicorp vault")?; @@ -128,15 +129,15 @@ pub async fn get_store( #[allow(clippy::expect_used)] async fn get_master_enc_key( conf: &crate::configs::settings::Settings, - #[cfg(feature = "aws_kms")] aws_kms_client: &aws_kms::AwsKmsClient, + #[cfg(feature = "aws_kms")] aws_kms_client: &aws_kms::core::AwsKmsClient, #[cfg(feature = "hashicorp-vault")] - hc_client: &external_services::hashicorp_vault::HashiCorpVault, + hc_client: &external_services::hashicorp_vault::core::HashiCorpVault, ) -> StrongSecret<Vec<u8>> { let master_enc_key = conf.secrets.master_enc_key.clone(); #[cfg(feature = "hashicorp-vault")] let master_enc_key = master_enc_key - .fetch_inner::<external_services::hashicorp_vault::Kv2>(hc_client) + .fetch_inner::<external_services::hashicorp_vault::core::Kv2>(hc_client) .await .expect("Failed to fetch master enc key"); diff --git a/crates/router/src/services/authentication.rs b/crates/router/src/services/authentication.rs index 308ceb2672b..990e0785306 100644 --- a/crates/router/src/services/authentication.rs +++ b/crates/router/src/services/authentication.rs @@ -226,9 +226,9 @@ where api_keys::get_hash_key( &config.api_keys, #[cfg(feature = "aws_kms")] - aws_kms::get_aws_kms_client(&config.kms).await, + aws_kms::core::get_aws_kms_client(&config.kms).await, #[cfg(feature = "hashicorp-vault")] - external_services::hashicorp_vault::get_hashicorp_client(&config.hc_vault) + external_services::hashicorp_vault::core::get_hashicorp_client(&config.hc_vault) .await .change_context(errors::ApiErrorResponse::InternalServerError)?, ) @@ -289,9 +289,9 @@ static ADMIN_API_KEY: tokio::sync::OnceCell<StrongSecret<String>> = pub async fn get_admin_api_key( secrets: &settings::Secrets, - #[cfg(feature = "aws_kms")] aws_kms_client: &aws_kms::AwsKmsClient, + #[cfg(feature = "aws_kms")] aws_kms_client: &aws_kms::core::AwsKmsClient, #[cfg(feature = "hashicorp-vault")] - hc_client: &external_services::hashicorp_vault::HashiCorpVault, + hc_client: &external_services::hashicorp_vault::core::HashiCorpVault, ) -> RouterResult<&'static StrongSecret<String>> { ADMIN_API_KEY .get_or_try_init(|| async { @@ -308,7 +308,7 @@ pub async fn get_admin_api_key( #[cfg(feature = "hashicorp-vault")] let admin_api_key = masking::Secret::new(admin_api_key) - .fetch_inner::<external_services::hashicorp_vault::Kv2>(hc_client) + .fetch_inner::<external_services::hashicorp_vault::core::Kv2>(hc_client) .await .change_context(errors::ApiErrorResponse::InternalServerError) .attach_printable("Failed to KMS decrypt admin API key")? @@ -369,9 +369,9 @@ where let admin_api_key = get_admin_api_key( &conf.secrets, #[cfg(feature = "aws_kms")] - aws_kms::get_aws_kms_client(&conf.kms).await, + aws_kms::core::get_aws_kms_client(&conf.kms).await, #[cfg(feature = "hashicorp-vault")] - external_services::hashicorp_vault::get_hashicorp_client(&conf.hc_vault) + external_services::hashicorp_vault::core::get_hashicorp_client(&conf.hc_vault) .await .change_context(errors::ApiErrorResponse::InternalServerError) .attach_printable("Failed while getting admin api key")?, @@ -873,7 +873,7 @@ static JWT_SECRET: tokio::sync::OnceCell<StrongSecret<String>> = tokio::sync::On pub async fn get_jwt_secret( secrets: &settings::Secrets, - #[cfg(feature = "aws_kms")] aws_kms_client: &aws_kms::AwsKmsClient, + #[cfg(feature = "aws_kms")] aws_kms_client: &aws_kms::core::AwsKmsClient, ) -> RouterResult<&'static StrongSecret<String>> { JWT_SECRET .get_or_try_init(|| async { @@ -901,7 +901,7 @@ where let secret = get_jwt_secret( &conf.secrets, #[cfg(feature = "aws_kms")] - aws_kms::get_aws_kms_client(&conf.kms).await, + aws_kms::core::get_aws_kms_client(&conf.kms).await, ) .await? .peek() @@ -972,7 +972,7 @@ static RECON_API_KEY: tokio::sync::OnceCell<StrongSecret<String>> = #[cfg(feature = "recon")] pub async fn get_recon_admin_api_key( secrets: &settings::Secrets, - #[cfg(feature = "aws_kms")] kms_client: &aws_kms::AwsKmsClient, + #[cfg(feature = "aws_kms")] kms_client: &aws_kms::core::AwsKmsClient, ) -> RouterResult<&'static StrongSecret<String>> { RECON_API_KEY .get_or_try_init(|| async { @@ -1013,7 +1013,7 @@ where let admin_api_key = get_recon_admin_api_key( &conf.secrets, #[cfg(feature = "aws_kms")] - aws_kms::get_aws_kms_client(&conf.kms).await, + aws_kms::core::get_aws_kms_client(&conf.kms).await, ) .await?; diff --git a/crates/router/src/services/jwt.rs b/crates/router/src/services/jwt.rs index 08db52e4020..05de1b4e11e 100644 --- a/crates/router/src/services/jwt.rs +++ b/crates/router/src/services/jwt.rs @@ -27,7 +27,7 @@ where let jwt_secret = authentication::get_jwt_secret( &settings.secrets, #[cfg(feature = "aws_kms")] - external_services::aws_kms::get_aws_kms_client(&settings.kms).await, + external_services::aws_kms::core::get_aws_kms_client(&settings.kms).await, ) .await .change_context(UserErrors::InternalServerError) diff --git a/crates/router/src/utils/currency.rs b/crates/router/src/utils/currency.rs index 057805a76f0..30ac4815efb 100644 --- a/crates/router/src/utils/currency.rs +++ b/crates/router/src/utils/currency.rs @@ -128,9 +128,9 @@ async fn waited_fetch_and_update_caches( state: &AppState, local_fetch_retry_delay: u64, local_fetch_retry_count: u64, - #[cfg(feature = "aws_kms")] aws_kms_config: &aws_kms::AwsKmsConfig, + #[cfg(feature = "aws_kms")] aws_kms_config: &aws_kms::core::AwsKmsConfig, #[cfg(feature = "hashicorp-vault")] - hc_config: &external_services::hashicorp_vault::HashiCorpVaultConfig, + hc_config: &external_services::hashicorp_vault::core::HashiCorpVaultConfig, ) -> CustomResult<FxExchangeRatesCacheEntry, ForexCacheError> { for _n in 1..local_fetch_retry_count { sleep(Duration::from_millis(local_fetch_retry_delay)).await; @@ -192,9 +192,9 @@ pub async fn get_forex_rates( call_delay: i64, local_fetch_retry_delay: u64, local_fetch_retry_count: u64, - #[cfg(feature = "aws_kms")] aws_kms_config: &aws_kms::AwsKmsConfig, + #[cfg(feature = "aws_kms")] aws_kms_config: &aws_kms::core::AwsKmsConfig, #[cfg(feature = "hashicorp-vault")] - hc_config: &external_services::hashicorp_vault::HashiCorpVaultConfig, + hc_config: &external_services::hashicorp_vault::core::HashiCorpVaultConfig, ) -> CustomResult<FxExchangeRatesCacheEntry, ForexCacheError> { if let Some(local_rates) = retrieve_forex_from_local().await { if local_rates.is_expired(call_delay) { @@ -234,9 +234,9 @@ async fn handler_local_no_data( call_delay: i64, _local_fetch_retry_delay: u64, _local_fetch_retry_count: u64, - #[cfg(feature = "aws_kms")] aws_kms_config: &aws_kms::AwsKmsConfig, + #[cfg(feature = "aws_kms")] aws_kms_config: &aws_kms::core::AwsKmsConfig, #[cfg(feature = "hashicorp-vault")] - hc_config: &external_services::hashicorp_vault::HashiCorpVaultConfig, + hc_config: &external_services::hashicorp_vault::core::HashiCorpVaultConfig, ) -> CustomResult<FxExchangeRatesCacheEntry, ForexCacheError> { match retrieve_forex_from_redis(state).await { Ok(Some(data)) => { @@ -281,9 +281,9 @@ async fn handler_local_no_data( async fn successive_fetch_and_save_forex( state: &AppState, stale_redis_data: Option<FxExchangeRatesCacheEntry>, - #[cfg(feature = "aws_kms")] aws_kms_config: &aws_kms::AwsKmsConfig, + #[cfg(feature = "aws_kms")] aws_kms_config: &aws_kms::core::AwsKmsConfig, #[cfg(feature = "hashicorp-vault")] - hc_config: &external_services::hashicorp_vault::HashiCorpVaultConfig, + hc_config: &external_services::hashicorp_vault::core::HashiCorpVaultConfig, ) -> CustomResult<FxExchangeRatesCacheEntry, ForexCacheError> { match acquire_redis_lock(state).await { Ok(lock_acquired) => { @@ -351,9 +351,9 @@ async fn fallback_forex_redis_check( state: &AppState, redis_data: FxExchangeRatesCacheEntry, call_delay: i64, - #[cfg(feature = "aws_kms")] aws_kms_config: &aws_kms::AwsKmsConfig, + #[cfg(feature = "aws_kms")] aws_kms_config: &aws_kms::core::AwsKmsConfig, #[cfg(feature = "hashicorp-vault")] - hc_config: &external_services::hashicorp_vault::HashiCorpVaultConfig, + hc_config: &external_services::hashicorp_vault::core::HashiCorpVaultConfig, ) -> CustomResult<FxExchangeRatesCacheEntry, ForexCacheError> { match is_redis_expired(Some(redis_data.clone()).as_ref(), call_delay).await { Some(redis_forex) => { @@ -381,9 +381,9 @@ async fn handler_local_expired( state: &AppState, call_delay: i64, local_rates: FxExchangeRatesCacheEntry, - #[cfg(feature = "aws_kms")] aws_kms_config: &aws_kms::AwsKmsConfig, + #[cfg(feature = "aws_kms")] aws_kms_config: &aws_kms::core::AwsKmsConfig, #[cfg(feature = "hashicorp-vault")] - hc_config: &external_services::hashicorp_vault::HashiCorpVaultConfig, + hc_config: &external_services::hashicorp_vault::core::HashiCorpVaultConfig, ) -> CustomResult<FxExchangeRatesCacheEntry, ForexCacheError> { match retrieve_forex_from_redis(state).await { Ok(redis_data) => { @@ -427,14 +427,14 @@ async fn handler_local_expired( async fn fetch_forex_rates( state: &AppState, - #[cfg(feature = "aws_kms")] aws_kms_config: &aws_kms::AwsKmsConfig, + #[cfg(feature = "aws_kms")] aws_kms_config: &aws_kms::core::AwsKmsConfig, #[cfg(feature = "hashicorp-vault")] - hc_config: &external_services::hashicorp_vault::HashiCorpVaultConfig, + hc_config: &external_services::hashicorp_vault::core::HashiCorpVaultConfig, ) -> Result<FxExchangeRatesCacheEntry, error_stack::Report<ForexCacheError>> { let forex_api_key = async { #[cfg(feature = "hashicorp-vault")] - let client = hashicorp_vault::get_hashicorp_client(hc_config) + let client = hashicorp_vault::core::get_hashicorp_client(hc_config) .await .change_context(ForexCacheError::AwsKmsDecryptionFailed)?; @@ -446,7 +446,7 @@ async fn fetch_forex_rates( .forex_api .api_key .clone() - .fetch_inner::<hashicorp_vault::Kv2>(client) + .fetch_inner::<hashicorp_vault::core::Kv2>(client) .await .change_context(ForexCacheError::AwsKmsDecryptionFailed)?; @@ -454,7 +454,7 @@ async fn fetch_forex_rates( } .await?; #[cfg(feature = "aws_kms")] - let forex_api_key = aws_kms::get_aws_kms_client(aws_kms_config) + let forex_api_key = aws_kms::core::get_aws_kms_client(aws_kms_config) .await .decrypt(forex_api_key.peek()) .await @@ -516,13 +516,13 @@ async fn fetch_forex_rates( pub async fn fallback_fetch_forex_rates( state: &AppState, - #[cfg(feature = "aws_kms")] aws_kms_config: &aws_kms::AwsKmsConfig, + #[cfg(feature = "aws_kms")] aws_kms_config: &aws_kms::core::AwsKmsConfig, #[cfg(feature = "hashicorp-vault")] - hc_config: &external_services::hashicorp_vault::HashiCorpVaultConfig, + hc_config: &external_services::hashicorp_vault::core::HashiCorpVaultConfig, ) -> CustomResult<FxExchangeRatesCacheEntry, ForexCacheError> { let fallback_api_key = async { #[cfg(feature = "hashicorp-vault")] - let client = hashicorp_vault::get_hashicorp_client(hc_config) + let client = hashicorp_vault::core::get_hashicorp_client(hc_config) .await .change_context(ForexCacheError::AwsKmsDecryptionFailed)?; @@ -534,7 +534,7 @@ pub async fn fallback_fetch_forex_rates( .forex_api .fallback_api_key .clone() - .fetch_inner::<hashicorp_vault::Kv2>(client) + .fetch_inner::<hashicorp_vault::core::Kv2>(client) .await .change_context(ForexCacheError::AwsKmsDecryptionFailed)?; @@ -542,7 +542,7 @@ pub async fn fallback_fetch_forex_rates( } .await?; #[cfg(feature = "aws_kms")] - let fallback_forex_api_key = aws_kms::get_aws_kms_client(aws_kms_config) + let fallback_forex_api_key = aws_kms::core::get_aws_kms_client(aws_kms_config) .await .decrypt(fallback_api_key.peek()) .await @@ -691,9 +691,9 @@ pub async fn convert_currency( amount: i64, to_currency: String, from_currency: String, - #[cfg(feature = "aws_kms")] aws_kms_config: &aws_kms::AwsKmsConfig, + #[cfg(feature = "aws_kms")] aws_kms_config: &aws_kms::core::AwsKmsConfig, #[cfg(feature = "hashicorp-vault")] - hc_config: &external_services::hashicorp_vault::HashiCorpVaultConfig, + hc_config: &external_services::hashicorp_vault::core::HashiCorpVaultConfig, ) -> CustomResult<api_models::currency::CurrencyConversionResponse, ForexCacheError> { let rates = get_forex_rates( &state,
2024-02-02T13:02:25Z
## 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 --> Create a new crate `Hyperswitch-interface` containing below modules for now: `secrets_interface`: Module used for application config `encryption` and `decryption` during startup which will contain its own trait and error types `encryption_interface`: Module used for user value `encryption` and `decryption` during runtime which will contain its own trait and error types This PR only adds the above crate with the addition of `secret_management_config` and `encryption_management_config` in the `router` ### 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)? --> New crates addition which doesn't integrate with other existing crates yet. So 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 - [ ] I added a [CHANGELOG](/CHANGELOG.md) entry if applicable
cfa10aa60ef16d2302787f7ecf7c129228fc0549
New crates addition which doesn't integrate with other existing crates yet. So basic sanity testing should suffice
juspay/hyperswitch
juspay__hyperswitch-3488
Bug: [FEATURE] Create a delete endpoint for Config Table ### Feature Description Add an API for deleting data from config table. ### Possible Implementation Add the endpoint DELETE `config/{key}` for deleting the config key. ### 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/diesel_models/src/query/configs.rs b/crates/diesel_models/src/query/configs.rs index 62ed60e3b0a..306fb5e3353 100644 --- a/crates/diesel_models/src/query/configs.rs +++ b/crates/diesel_models/src/query/configs.rs @@ -50,8 +50,11 @@ impl Config { } #[instrument(skip(conn))] - pub async fn delete_by_key(conn: &PgPooledConn, key: &str) -> StorageResult<bool> { - generics::generic_delete::<<Self as HasTable>::Table, _>(conn, dsl::key.eq(key.to_owned())) - .await + pub async fn delete_by_key(conn: &PgPooledConn, key: &str) -> StorageResult<Self> { + generics::generic_delete_one_with_result::<<Self as HasTable>::Table, _, _>( + conn, + dsl::key.eq(key.to_owned()), + ) + .await } } diff --git a/crates/router/src/core/configs.rs b/crates/router/src/core/configs.rs index 8aa2310416e..ba2303167d7 100644 --- a/crates/router/src/core/configs.rs +++ b/crates/router/src/core/configs.rs @@ -41,3 +41,12 @@ pub async fn update_config( .to_not_found_response(errors::ApiErrorResponse::ConfigNotFound)?; Ok(ApplicationResponse::Json(config.foreign_into())) } + +pub async fn config_delete(state: AppState, key: String) -> RouterResponse<api::Config> { + let store = state.store.as_ref(); + let config = store + .delete_config_by_key(&key) + .await + .to_not_found_response(errors::ApiErrorResponse::ConfigNotFound)?; + Ok(ApplicationResponse::Json(config.foreign_into())) +} diff --git a/crates/router/src/db/configs.rs b/crates/router/src/db/configs.rs index f3e85ba5d23..1d472c1fb66 100644 --- a/crates/router/src/db/configs.rs +++ b/crates/router/src/db/configs.rs @@ -51,7 +51,10 @@ pub trait ConfigInterface { config_update: storage::ConfigUpdate, ) -> CustomResult<storage::Config, errors::StorageError>; - async fn delete_config_by_key(&self, key: &str) -> CustomResult<bool, errors::StorageError>; + async fn delete_config_by_key( + &self, + key: &str, + ) -> CustomResult<storage::Config, errors::StorageError>; } #[async_trait::async_trait] @@ -154,7 +157,10 @@ impl ConfigInterface for Store { cache::get_or_populate_in_memory(self, key, find_else_unwrap_or, &CONFIG_CACHE).await } - async fn delete_config_by_key(&self, key: &str) -> CustomResult<bool, errors::StorageError> { + async fn delete_config_by_key( + &self, + key: &str, + ) -> CustomResult<storage::Config, errors::StorageError> { let conn = connection::pg_connection_write(self).await?; let deleted = storage::Config::delete_by_key(&conn, key) .await @@ -226,15 +232,15 @@ impl ConfigInterface for MockDb { result } - async fn delete_config_by_key(&self, key: &str) -> CustomResult<bool, errors::StorageError> { + async fn delete_config_by_key( + &self, + key: &str, + ) -> CustomResult<storage::Config, errors::StorageError> { let mut configs = self.configs.lock().await; let result = configs .iter() .position(|c| c.key == key) - .map(|index| { - configs.remove(index); - true - }) + .map(|index| configs.remove(index)) .ok_or_else(|| { errors::StorageError::ValueNotFound("cannot find config to delete".to_string()) .into() diff --git a/crates/router/src/db/kafka_store.rs b/crates/router/src/db/kafka_store.rs index 0897deb87e5..3b88868001a 100644 --- a/crates/router/src/db/kafka_store.rs +++ b/crates/router/src/db/kafka_store.rs @@ -284,7 +284,10 @@ impl ConfigInterface for KafkaStore { .await } - async fn delete_config_by_key(&self, key: &str) -> CustomResult<bool, errors::StorageError> { + async fn delete_config_by_key( + &self, + key: &str, + ) -> CustomResult<storage::Config, errors::StorageError> { self.diesel_store.delete_config_by_key(key).await } diff --git a/crates/router/src/routes/app.rs b/crates/router/src/routes/app.rs index 41881c60ff7..3a94aef623b 100644 --- a/crates/router/src/routes/app.rs +++ b/crates/router/src/routes/app.rs @@ -813,7 +813,8 @@ impl Configs { .service( web::resource("/{key}") .route(web::get().to(config_key_retrieve)) - .route(web::post().to(config_key_update)), + .route(web::post().to(config_key_update)) + .route(web::delete().to(config_key_delete)), ) } } diff --git a/crates/router/src/routes/configs.rs b/crates/router/src/routes/configs.rs index 45eb45a83b5..d7e96f40235 100644 --- a/crates/router/src/routes/configs.rs +++ b/crates/router/src/routes/configs.rs @@ -71,3 +71,24 @@ pub async fn config_key_update( ) .await } + +#[instrument(skip_all, fields(flow = ?Flow::ConfigKeyDelete))] +pub async fn config_key_delete( + state: web::Data<AppState>, + req: HttpRequest, + path: web::Path<String>, +) -> impl Responder { + let flow = Flow::ConfigKeyDelete; + let key = path.into_inner(); + + api::server_wrap( + flow, + state, + &req, + key, + |state, _, key| configs::config_delete(state, key), + &auth::AdminApiAuth, + api_locking::LockAction::NotApplicable, + ) + .await +} diff --git a/crates/router/src/routes/lock_utils.rs b/crates/router/src/routes/lock_utils.rs index 9393e8ae212..aa4f3dccb8f 100644 --- a/crates/router/src/routes/lock_utils.rs +++ b/crates/router/src/routes/lock_utils.rs @@ -74,6 +74,7 @@ impl From<Flow> for ApiIdentifier { Flow::ConfigKeyCreate | Flow::ConfigKeyFetch | Flow::ConfigKeyUpdate + | Flow::ConfigKeyDelete | Flow::CreateConfigKey => Self::Configs, Flow::CustomersCreate diff --git a/crates/router_env/src/logger/types.rs b/crates/router_env/src/logger/types.rs index 6649b89911a..b99b81f8d6b 100644 --- a/crates/router_env/src/logger/types.rs +++ b/crates/router_env/src/logger/types.rs @@ -82,6 +82,8 @@ pub enum Flow { ConfigKeyFetch, /// ConfigKey Update flow. ConfigKeyUpdate, + /// ConfigKey Delete flow. + ConfigKeyDelete, /// Customers create flow. CustomersCreate, /// Customers retrieve flow.
2024-02-05T14:59:01Z
## 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 --> Added the api to delete config key Fixes #3488 <!-- 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? <!-- 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 config. ```bash curl --location 'http://localhost:8080/configs/' \ --header 'Content-Type: application/json' \ --header 'api-key: test_admin' \ --data '{ "key":"keke", "value": "keke" }' ``` - Delete the config ```bash curl --location --request DELETE 'http://localhost:8080/configs/keke' \ --header 'Content-Type: application/json' \ --header 'api-key: test_admin' ``` - Get the config ``` curl --location --request GET 'http://localhost:8080/configs/keke' \ --header 'Content-Type: application/json' \ --header 'api-key: test_admin' ``` It should return 404 ## 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
073310c1f671ccbb71cc5c8725eca9771e511589
- Create a config. ```bash curl --location 'http://localhost:8080/configs/' \ --header 'Content-Type: application/json' \ --header 'api-key: test_admin' \ --data '{ "key":"keke", "value": "keke" }' ``` - Delete the config ```bash curl --location --request DELETE 'http://localhost:8080/configs/keke' \ --header 'Content-Type: application/json' \ --header 'api-key: test_admin' ``` - Get the config ``` curl --location --request GET 'http://localhost:8080/configs/keke' \ --header 'Content-Type: application/json' \ --header 'api-key: test_admin' ``` It should return 404
juspay/hyperswitch
juspay__hyperswitch-3484
Bug: fix: Change permissions for sample data Change permission for Sample data to `PaymentWrite` instead of `MerchantAccountWrite`
diff --git a/crates/router/src/routes/lock_utils.rs b/crates/router/src/routes/lock_utils.rs index 4cd85efe8d5..2837c1defa4 100644 --- a/crates/router/src/routes/lock_utils.rs +++ b/crates/router/src/routes/lock_utils.rs @@ -179,7 +179,6 @@ impl From<Flow> for ApiIdentifier { | Flow::ResetPassword | Flow::InviteUser | Flow::InviteMultipleUser - | Flow::DeleteUser | Flow::UserSignUpWithMerchantId | Flow::VerifyEmailWithoutInviteChecks | Flow::VerifyEmail @@ -191,7 +190,8 @@ impl From<Flow> for ApiIdentifier { | Flow::GetRoleFromToken | Flow::UpdateUserRole | Flow::GetAuthorizationInfo - | Flow::AcceptInvitation => Self::UserRole, + | Flow::AcceptInvitation + | Flow::DeleteUserRole => Self::UserRole, Flow::GetActionUrl | Flow::SyncOnboardingStatus | Flow::ResetTrackingId => { Self::ConnectorOnboarding diff --git a/crates/router/src/routes/user.rs b/crates/router/src/routes/user.rs index 88e19ddf755..d4bdcaae87f 100644 --- a/crates/router/src/routes/user.rs +++ b/crates/router/src/routes/user.rs @@ -257,7 +257,7 @@ pub async fn generate_sample_data( &http_req, payload.into_inner(), sample_data::generate_sample_data_for_user, - &auth::JWTAuth(Permission::MerchantAccountWrite), + &auth::JWTAuth(Permission::PaymentWrite), api_locking::LockAction::NotApplicable, )) .await @@ -277,7 +277,7 @@ pub async fn delete_sample_data( &http_req, payload.into_inner(), sample_data::delete_sample_data_for_user, - &auth::JWTAuth(Permission::MerchantAccountWrite), + &auth::JWTAuth(Permission::PaymentWrite), api_locking::LockAction::NotApplicable, )) .await diff --git a/crates/router/src/routes/user_role.rs b/crates/router/src/routes/user_role.rs index 3f9ccda8651..ec05db1d615 100644 --- a/crates/router/src/routes/user_role.rs +++ b/crates/router/src/routes/user_role.rs @@ -121,7 +121,7 @@ pub async fn delete_user_role( req: HttpRequest, payload: web::Json<user_role_api::DeleteUserRoleRequest>, ) -> HttpResponse { - let flow = Flow::DeleteUser; + let flow = Flow::DeleteUserRole; Box::pin(api::server_wrap( flow, state.clone(), diff --git a/crates/router_env/src/logger/types.rs b/crates/router_env/src/logger/types.rs index ac2dfb47c63..8e32cb63334 100644 --- a/crates/router_env/src/logger/types.rs +++ b/crates/router_env/src/logger/types.rs @@ -327,8 +327,8 @@ pub enum Flow { InviteUser, /// Invite multiple users InviteMultipleUser, - /// Delete user - DeleteUser, + /// Delete user role + DeleteUserRole, /// Incremental Authorization flow PaymentsIncrementalAuthorization, /// Get action URL for connector onboarding
2024-01-25T14:36:39Z
## Type of Change <!-- Put an `x` in the boxes that apply --> - [x] Bugfix - [ ] New feature - [ ] Enhancement - [ ] Refactoring - [ ] Dependency updates - [ ] Documentation - [ ] CI/CD ## Description - Change permission for sample data generate and delete. Currently it is Merchants write but is as per new use case it should be Payment Write only. - Change the flow name for delete user (it is delete user role as per functionality) ### 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 Permission for sample data needs to be changed. ## How did you test it? Tested locally - singup - generate sample data - delete sample data Curl to generate and delete sample data: ``` curl --location 'http://localhost:8080/user/sample_data' \ --header 'Content-Type: application/json' \ --header 'Cookie: token=eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJ1c2VyX2lkIjoiMWZjNzgyOTUtM2JiMy00OGJjLThlZDgtNzFjMzVjMzMxYWU2IiwibWVyY2hhbnRfaWQiOiJtZXJjaGFudF8xNjk3NzE2ODcwIiwicm9sZV9pZCI6Im1lcmNoYW50X2FkbWluIiwiZXhwIjoxNjk3ODg5NjcxLCJvcmdfaWQiOiJvcmdfejQ5ZExMeTdmbllUODN5TDY3clEifQ.CJzEQ2qbhn-qUiiVBSdvCJiLvWp-5wCF9R54gth6QbQ' \ --header 'Authorization: Bearer JWT' \ --data '{ }' ``` ``` curl --location --request DELETE 'http://localhost:8080/user/sample_data' \ --header 'Content-Type: application/json' \ --header 'Cookie: token=eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJ1c2VyX2lkIjoiMWZjNzgyOTUtM2JiMy00OGJjLThlZDgtNzFjMzVjMzMxYWU2IiwibWVyY2hhbnRfaWQiOiJtZXJjaGFudF8xNjk3NzE2ODcwIiwicm9sZV9pZCI6Im1lcmNoYW50X2FkbWluIiwiZXhwIjoxNjk3ODg5NjcxLCJvcmdfaWQiOiJvcmdfejQ5ZExMeTdmbllUODN5TDY3clEifQ.CJzEQ2qbhn-qUiiVBSdvCJiLvWp-5wCF9R54gth6QbQ' \ --header 'Authorization: Bearer JWT' \ --data '{ }' ``` Response should be 200 Ok for both the cases. ## 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 - [ ] I added a [CHANGELOG](/CHANGELOG.md) entry if applicable
d2accdef410319733d6174057bdca468bde1ae83
Tested locally - singup - generate sample data - delete sample data Curl to generate and delete sample data: ``` curl --location 'http://localhost:8080/user/sample_data' \ --header 'Content-Type: application/json' \ --header 'Cookie: token=eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJ1c2VyX2lkIjoiMWZjNzgyOTUtM2JiMy00OGJjLThlZDgtNzFjMzVjMzMxYWU2IiwibWVyY2hhbnRfaWQiOiJtZXJjaGFudF8xNjk3NzE2ODcwIiwicm9sZV9pZCI6Im1lcmNoYW50X2FkbWluIiwiZXhwIjoxNjk3ODg5NjcxLCJvcmdfaWQiOiJvcmdfejQ5ZExMeTdmbllUODN5TDY3clEifQ.CJzEQ2qbhn-qUiiVBSdvCJiLvWp-5wCF9R54gth6QbQ' \ --header 'Authorization: Bearer JWT' \ --data '{ }' ``` ``` curl --location --request DELETE 'http://localhost:8080/user/sample_data' \ --header 'Content-Type: application/json' \ --header 'Cookie: token=eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJ1c2VyX2lkIjoiMWZjNzgyOTUtM2JiMy00OGJjLThlZDgtNzFjMzVjMzMxYWU2IiwibWVyY2hhbnRfaWQiOiJtZXJjaGFudF8xNjk3NzE2ODcwIiwicm9sZV9pZCI6Im1lcmNoYW50X2FkbWluIiwiZXhwIjoxNjk3ODg5NjcxLCJvcmdfaWQiOiJvcmdfejQ5ZExMeTdmbllUODN5TDY3clEifQ.CJzEQ2qbhn-qUiiVBSdvCJiLvWp-5wCF9R54gth6QbQ' \ --header 'Authorization: Bearer JWT' \ --data '{ }' ``` Response should be 200 Ok for both the cases.
juspay/hyperswitch
juspay__hyperswitch-3483
Bug: adding dispute_id to Kafka events
diff --git a/crates/analytics/docs/clickhouse/cluster_setup/scripts/api_event_logs.sql b/crates/analytics/docs/clickhouse/cluster_setup/scripts/api_event_logs.sql index 0fe194a0e67..ad0fe6d778f 100644 --- a/crates/analytics/docs/clickhouse/cluster_setup/scripts/api_event_logs.sql +++ b/crates/analytics/docs/clickhouse/cluster_setup/scripts/api_event_logs.sql @@ -18,7 +18,8 @@ CREATE TABLE hyperswitch.api_events_queue on cluster '{cluster}' ( `created_at` DateTime CODEC(T64, LZ4), `latency` Nullable(UInt128), `user_agent` Nullable(String), - `ip_addr` Nullable(String) + `ip_addr` Nullable(String), + `dispute_id` Nullable(String) ) ENGINE = Kafka SETTINGS kafka_broker_list = 'hyper-c1-kafka-brokers.kafka-cluster.svc.cluster.local:9092', kafka_topic_list = 'hyperswitch-api-log-events', kafka_group_name = 'hyper-c1', @@ -81,7 +82,8 @@ CREATE TABLE hyperswitch.api_events_dist on cluster '{cluster}' ( `created_at` DateTime64(3), `latency` Nullable(UInt128), `user_agent` Nullable(String), - `ip_addr` Nullable(String) + `ip_addr` Nullable(String), + `dispute_id` Nullable(String) ) ENGINE = Distributed('{cluster}', 'hyperswitch', 'api_events_clustered', rand()); CREATE MATERIALIZED VIEW hyperswitch.api_events_mv on cluster '{cluster}' TO hyperswitch.api_events_dist ( @@ -105,7 +107,8 @@ CREATE MATERIALIZED VIEW hyperswitch.api_events_mv on cluster '{cluster}' TO hyp `created_at` DateTime64(3), `latency` Nullable(UInt128), `user_agent` Nullable(String), - `ip_addr` Nullable(String) + `ip_addr` Nullable(String), + `dispute_id` Nullable(String) ) AS SELECT merchant_id, @@ -158,7 +161,7 @@ WHERE length(_error) > 0 ALTER TABLE hyperswitch.api_events_clustered on cluster '{cluster}' ADD COLUMN `url_path` LowCardinality(Nullable(String)); ALTER TABLE hyperswitch.api_events_clustered on cluster '{cluster}' ADD COLUMN `event_type` LowCardinality(Nullable(String)); - +ALTER TABLE hyperswitch.api_events_clustered on cluster '{cluster}' ADD COLUMN `dispute_id` Nullable(String); CREATE TABLE hyperswitch.api_audit_log ON CLUSTER '{cluster}' ( `merchant_id` LowCardinality(String), @@ -209,7 +212,8 @@ CREATE MATERIALIZED VIEW hyperswitch.api_audit_log_mv ON CLUSTER `{cluster}` TO `created_at` DateTime64(3), `latency` Nullable(UInt128), `user_agent` Nullable(String), - `ip_addr` Nullable(String) + `ip_addr` Nullable(String), + `dispute_id` Nullable(String) ) AS SELECT merchant_id, @@ -232,6 +236,7 @@ SELECT created_at, latency, user_agent, - ip_addr + ip_addr, + dispute_id FROM hyperswitch.api_events_queue WHERE length(_error) = 0 \ No newline at end of file diff --git a/crates/analytics/docs/clickhouse/scripts/api_events.sql b/crates/analytics/docs/clickhouse/scripts/api_events.sql index c3fc3d7b06d..49a6472eaa4 100644 --- a/crates/analytics/docs/clickhouse/scripts/api_events.sql +++ b/crates/analytics/docs/clickhouse/scripts/api_events.sql @@ -23,7 +23,8 @@ CREATE TABLE api_events_queue ( `ip_addr` String, `hs_latency` Nullable(UInt128), `http_method` LowCardinality(String), - `url_path` String + `url_path` String, + `dispute_id` Nullable(String) ) ENGINE = Kafka SETTINGS kafka_broker_list = 'kafka0:29092', kafka_topic_list = 'hyperswitch-api-log-events', kafka_group_name = 'hyper-c1', @@ -57,6 +58,7 @@ CREATE TABLE api_events_dist ( `hs_latency` Nullable(UInt128), `http_method` LowCardinality(String), `url_path` String, + `dispute_id` Nullable(String) INDEX flowIndex flow_type TYPE bloom_filter GRANULARITY 1, INDEX apiIndex api_flow TYPE bloom_filter GRANULARITY 1, INDEX statusIndex status_code TYPE bloom_filter GRANULARITY 1 @@ -92,7 +94,8 @@ CREATE MATERIALIZED VIEW api_events_mv TO api_events_dist ( `ip_addr` String, `hs_latency` Nullable(UInt128), `http_method` LowCardinality(String), - `url_path` String + `url_path` String, + `dispute_id` Nullable(String) ) AS SELECT merchant_id, @@ -120,7 +123,8 @@ SELECT ip_addr, hs_latency, http_method, - url_path + url_path, + dispute_id FROM api_events_queue where length(_error) = 0; diff --git a/crates/api_models/src/events.rs b/crates/api_models/src/events.rs index a8185d2d241..ae0525ac609 100644 --- a/crates/api_models/src/events.rs +++ b/crates/api_models/src/events.rs @@ -1,5 +1,6 @@ pub mod connector_onboarding; pub mod customer; +pub mod dispute; pub mod gsm; mod locker_migration; pub mod payment; @@ -44,8 +45,6 @@ impl_misc_api_event_type!( RetrievePaymentLinkResponse, MandateListConstraints, CreateFileResponse, - DisputeResponse, - SubmitEvidenceRequest, MerchantConnectorResponse, MerchantConnectorId, MandateResponse, diff --git a/crates/api_models/src/events/dispute.rs b/crates/api_models/src/events/dispute.rs new file mode 100644 index 00000000000..101dba3ca02 --- /dev/null +++ b/crates/api_models/src/events/dispute.rs @@ -0,0 +1,25 @@ +use common_utils::events::{ApiEventMetric, ApiEventsType}; + +use super::{DisputeResponse, DisputeResponsePaymentsRetrieve, SubmitEvidenceRequest}; + +impl ApiEventMetric for SubmitEvidenceRequest { + fn get_api_event_type(&self) -> Option<ApiEventsType> { + Some(ApiEventsType::Dispute { + dispute_id: self.dispute_id.clone(), + }) + } +} +impl ApiEventMetric for DisputeResponsePaymentsRetrieve { + fn get_api_event_type(&self) -> Option<ApiEventsType> { + Some(ApiEventsType::Dispute { + dispute_id: self.dispute_id.clone(), + }) + } +} +impl ApiEventMetric for DisputeResponse { + fn get_api_event_type(&self) -> Option<ApiEventsType> { + Some(ApiEventsType::Dispute { + dispute_id: self.dispute_id.clone(), + }) + } +} diff --git a/crates/common_utils/src/events.rs b/crates/common_utils/src/events.rs index c2bf50d96c3..e755e0f9c4c 100644 --- a/crates/common_utils/src/events.rs +++ b/crates/common_utils/src/events.rs @@ -50,6 +50,9 @@ pub enum ApiEventsType { RustLocker, FraudCheck, Recon, + Dispute { + dispute_id: String, + }, } impl ApiEventMetric for serde_json::Value {} diff --git a/crates/router/src/events/api_logs.rs b/crates/router/src/events/api_logs.rs index 78a66d2f04e..3d74a028840 100644 --- a/crates/router/src/events/api_logs.rs +++ b/crates/router/src/events/api_logs.rs @@ -114,7 +114,6 @@ impl_misc_api_event_type!( CreateFileRequest, FileId, AttachEvidenceRequest, - DisputeId, PaymentLinkFormData, ConfigUpdate ); @@ -142,3 +141,11 @@ impl ApiEventMetric for PaymentsRedirectResponseData { }) } } + +impl ApiEventMetric for DisputeId { + fn get_api_event_type(&self) -> Option<ApiEventsType> { + Some(ApiEventsType::Dispute { + dispute_id: self.dispute_id.clone(), + }) + } +}
2024-01-24T12:48:32Z
## Type of Change <!-- Put an `x` in the boxes that apply --> - [ ] Bugfix - [ ] New feature - [x] Enhancement - [ ] Refactoring - [ ] Dependency updates - [ ] Documentation - [ ] CI/CD ## Description adding dispute id to hyperswitch-api-log-events ### 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)? --> check for dispute_id in topic = ```hyperswitch-api-log-events``` via loki ## 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 - [ ] I added a [CHANGELOG](/CHANGELOG.md) entry if applicable
c9d41e2169decf3e9a26999c37fe81b6a8c0362f
check for dispute_id in topic = ```hyperswitch-api-log-events``` via loki
juspay/hyperswitch
juspay__hyperswitch-3517
Bug: feat(EVENT_VIEWER): Add masking for connector responses in connector events Currently connector responses are being logged without masking. In order to protect PII data we need to add masking for the connector responses in connector events & logs
diff --git a/.cargo/config.toml b/.cargo/config.toml index 5b27955262a..c372e06f927 100644 --- a/.cargo/config.toml +++ b/.cargo/config.toml @@ -1,6 +1,7 @@ [target.'cfg(all())'] rustflags = [ "-Funsafe_code", + "-Aclippy::option_map_unit_fn", "-Wclippy::as_conversions", "-Wclippy::expect_used", "-Wclippy::index_refutable_slice", diff --git a/add_connector.md b/add_connector.md index 7fc3dcb27d1..93a9c8d7b99 100644 --- a/add_connector.md +++ b/add_connector.md @@ -9,14 +9,13 @@ This is a guide to contributing new connector to Router. This guide includes ins - Understanding of the Connector APIs which you wish to integrate with Router - Setup of Router repository and running it on local - Access to API credentials for testing the Connector API (you can quickly sign up for sandbox/uat credentials by visiting the website of the connector you wish to integrate) -- Ensure that you have the nightly toolchain installed because the connector template script includes code formatting. +- Ensure that you have the nightly toolchain installed because the connector template script includes code formatting. - Install it using `rustup`: - - ```bash - rustup toolchain install nightly - ``` +Install it using `rustup`: +```bash + rustup toolchain install nightly +``` In Router, there are Connectors and Payment Methods, examples of both are shown below from which the difference is apparent. @@ -28,7 +27,7 @@ A connector is an integration to fulfill payments. Related use cases could be an - Fraud and Risk management platform (like Signifyd, Riskified etc.,) - Payment network (Visa, Master) - Payment authentication services (Cardinal etc.,) -Currently, the router is compatible with 'Payment Processors' and 'Fraud and Risk Management' platforms. Support for additional categories will be expanded in the near future. + Currently, the router is compatible with 'Payment Processors' and 'Fraud and Risk Management' platforms. Support for additional categories will be expanded in the near future. ### What is a Payment Method ? @@ -127,11 +126,13 @@ Let's define `PaymentSource` For request types that involve an amount, the implementation of `TryFrom<&ConnectorRouterData<&T>>` is required: ```rust -impl TryFrom<&CheckoutRouterData<&T>> for PaymentsRequest +impl TryFrom<&CheckoutRouterData<&T>> for PaymentsRequest ``` -else + +else + ```rust -impl TryFrom<T> for PaymentsRequest +impl TryFrom<T> for PaymentsRequest ``` where `T` is a generic type which can be `types::PaymentsAuthorizeRouterData`, `types::PaymentsCaptureRouterData`, etc. @@ -214,6 +215,7 @@ impl ForeignFrom<(CheckoutPaymentStatus, Option<Balances>)> for enums::AttemptSt } } ``` + If you're converting ConnectorPaymentStatus to AttemptStatus without any additional conditions, you can employ the `impl From<ConnectorPaymentStatus> for enums::AttemptStatus`. Note: A payment intent can have multiple payment attempts. `enums::AttemptStatus` represents the status of a payment attempt. @@ -334,26 +336,27 @@ Some recommended fields that needs to be set on connector request and response ```rust reference: item.router_data.connector_request_reference_id.clone(), ``` + - **connector_response_reference_id :** Merchants might face ambiguity when deciding which ID to use in the connector dashboard for payment identification. It is essential to populate the connector_response_reference_id with the appropriate reference ID, allowing merchants to recognize the transaction. This field can be linked to either `merchant_reference` or `connector_transaction_id`, depending on the field that the connector dashboard search functionality supports. ```rust connector_response_reference_id: item.response.reference.or(Some(item.response.id)) ``` -- **resource_id :** The connector assigns an identifier to a payment attempt, referred to as `connector_transaction_id`. This identifier is represented as an enum variant for the `resource_id`. If the connector does not provide a `connector_transaction_id`, the resource_id is set to `NoResponseId`. +- **resource_id :** The connector assigns an identifier to a payment attempt, referred to as `connector_transaction_id`. This identifier is represented as an enum variant for the `resource_id`. If the connector does not provide a `connector_transaction_id`, the resource_id is set to `NoResponseId`. ```rust resource_id: types::ResponseId::ConnectorTransactionId(item.response.id.clone()), ``` + - **redirection_data :** For the implementation of a redirection flow (3D Secure, bank redirects, etc.), assign the redirection link to the `redirection_data`. -```rust +```rust let redirection_data = item.response.links.redirect.map(|href| { services::RedirectForm::from((href.redirection_url, services::Method::Get)) }); ``` - And finally the error type implementation ```rust @@ -379,100 +382,110 @@ The following trait implementations are mandatory Within the `ConnectorCommon` trait, you'll find the following methods : - - `id` method corresponds directly to the connector name. - ```rust - fn id(&self) -> &'static str { - "checkout" - } - ``` - - `get_currency_unit` method anticipates you to [specify the accepted currency unit](#set-the-currency-unit) for the connector. - ```rust - fn get_currency_unit(&self) -> api::CurrencyUnit { - api::CurrencyUnit::Minor - } - ``` - - `common_get_content_type` method requires you to provide the accepted content type for the connector API. - ```rust - fn common_get_content_type(&self) -> &'static str { - "application/json" - } - ``` - - `get_auth_header` method accepts common HTTP Authorization headers that are accepted in all `ConnectorIntegration` flows. - ```rust - fn get_auth_header( - &self, - auth_type: &types::ConnectorAuthType, - ) -> CustomResult<Vec<(String, request::Maskable<String>)>, errors::ConnectorError> { - let auth: checkout::CheckoutAuthType = auth_type - .try_into() - .change_context(errors::ConnectorError::FailedToObtainAuthType)?; - Ok(vec![( - headers::AUTHORIZATION.to_string(), - format!("Bearer {}", auth.api_secret.peek()).into_masked(), - )]) - } - ``` +- `id` method corresponds directly to the connector name. - - `base_url` method is for fetching the base URL of connector's API. Base url needs to be consumed from configs. - ```rust - fn base_url<'a>(&self, connectors: &'a settings::Connectors) -> &'a str { - connectors.checkout.base_url.as_ref() - } - ``` - - `build_error_response` method is common error response handling for a connector if it is same in all cases +```rust + fn id(&self) -> &'static str { + "checkout" + } +``` - ```rust - fn build_error_response( - &self, - res: types::Response, - ) -> CustomResult<types::ErrorResponse, errors::ConnectorError> { - let response: checkout::ErrorResponse = if res.response.is_empty() { - let (error_codes, error_type) = if res.status_code == 401 { - ( - Some(vec!["Invalid api key".to_string()]), - Some("invalid_api_key".to_string()), - ) - } else { - (None, None) - }; - checkout::ErrorResponse { - request_id: None, - error_codes, - error_type, - } - } else { - res.response - .parse_struct("ErrorResponse") - .change_context(errors::ConnectorError::ResponseDeserializationFailed)? - }; +- `get_currency_unit` method anticipates you to [specify the accepted currency unit](#set-the-currency-unit) for the connector. - router_env::logger::info!(error_response=?response); - let errors_list = response.error_codes.clone().unwrap_or_default(); - let option_error_code_message = conn_utils::get_error_code_error_message_based_on_priority( - self.clone(), - errors_list - .into_iter() - .map(|errors| errors.into()) - .collect(), - ); - Ok(types::ErrorResponse { - status_code: res.status_code, - code: option_error_code_message - .clone() - .map(|error_code_message| error_code_message.error_code) - .unwrap_or(consts::NO_ERROR_CODE.to_string()), - message: option_error_code_message - .map(|error_code_message| error_code_message.error_message) - .unwrap_or(consts::NO_ERROR_MESSAGE.to_string()), - reason: response - .error_codes - .map(|errors| errors.join(" & ")) - .or(response.error_type), - attempt_status: None, - connector_transaction_id: None, - }) - } - ``` +```rust + fn get_currency_unit(&self) -> api::CurrencyUnit { + api::CurrencyUnit::Minor + } +``` + +- `common_get_content_type` method requires you to provide the accepted content type for the connector API. + +```rust + fn common_get_content_type(&self) -> &'static str { + "application/json" + } +``` + +- `get_auth_header` method accepts common HTTP Authorization headers that are accepted in all `ConnectorIntegration` flows. + +```rust + fn get_auth_header( + &self, + auth_type: &types::ConnectorAuthType, + ) -> CustomResult<Vec<(String, request::Maskable<String>)>, errors::ConnectorError> { + let auth: checkout::CheckoutAuthType = auth_type + .try_into() + .change_context(errors::ConnectorError::FailedToObtainAuthType)?; + Ok(vec![( + headers::AUTHORIZATION.to_string(), + format!("Bearer {}", auth.api_secret.peek()).into_masked(), + )]) + } +``` + +- `base_url` method is for fetching the base URL of connector's API. Base url needs to be consumed from configs. + +```rust + fn base_url<'a>(&self, connectors: &'a settings::Connectors) -> &'a str { + connectors.checkout.base_url.as_ref() + } +``` + +- `build_error_response` method is common error response handling for a connector if it is same in all cases + +```rust + fn build_error_response( + &self, + res: types::Response, + event_builder: Option<&mut ConnectorEvent>, + ) -> CustomResult<types::ErrorResponse, errors::ConnectorError> { + let response: checkout::ErrorResponse = if res.response.is_empty() { + let (error_codes, error_type) = if res.status_code == 401 { + ( + Some(vec!["Invalid api key".to_string()]), + Some("invalid_api_key".to_string()), + ) + } else { + (None, None) + }; + checkout::ErrorResponse { + request_id: None, + error_codes, + error_type, + } + } else { + res.response + .parse_struct("ErrorResponse") + .change_context(errors::ConnectorError::ResponseDeserializationFailed)? + }; + + router_env::logger::info!(error_response=?response); + let errors_list = response.error_codes.clone().unwrap_or_default(); + let option_error_code_message = conn_utils::get_error_code_error_message_based_on_priority( + self.clone(), + errors_list + .into_iter() + .map(|errors| errors.into()) + .collect(), + ); + Ok(types::ErrorResponse { + status_code: res.status_code, + code: option_error_code_message + .clone() + .map(|error_code_message| error_code_message.error_code) + .unwrap_or(consts::NO_ERROR_CODE.to_string()), + message: option_error_code_message + .map(|error_code_message| error_code_message.error_message) + .unwrap_or(consts::NO_ERROR_MESSAGE.to_string()), + reason: response + .error_codes + .map(|errors| errors.join(" & ")) + .or(response.error_type), + attempt_status: None, + connector_transaction_id: None, + }) + } +``` **ConnectorIntegration :** For every api endpoint contains the url, using request transform and response transform and headers. Within the `ConnectorIntegration` trait, you'll find the following methods implemented(below mentioned is example for authorized flow): @@ -488,6 +501,7 @@ Within the `ConnectorIntegration` trait, you'll find the following methods imple Ok(format!("{}{}", self.base_url(connectors), "payments")) } ``` + - `get_headers` method accepts HTTP headers that are accepted for authorize flow. In this context, it is utilized from the `ConnectorCommonExt` trait, as the connector adheres to common headers across various flows. ```rust @@ -525,6 +539,7 @@ Within the `ConnectorIntegration` trait, you'll find the following methods imple ``` - `build_request` method assembles the API request by providing the method, URL, headers, and request body as parameters. + ```rust fn build_request( &self, @@ -552,17 +567,22 @@ Within the `ConnectorIntegration` trait, you'll find the following methods imple )) } ``` + - `handle_response` method calls transformers where connector response data is transformed into hyperswitch response. + ```rust fn handle_response( &self, data: &types::PaymentsAuthorizeRouterData, + event_builder: Option<&mut ConnectorEvent>, res: types::Response, ) -> CustomResult<types::PaymentsAuthorizeRouterData, errors::ConnectorError> { let response: checkout::PaymentsResponse = res .response .parse_struct("PaymentIntentResponse") .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(), @@ -571,18 +591,22 @@ Within the `ConnectorIntegration` trait, you'll find the following methods imple .change_context(errors::ConnectorError::ResponseHandlingFailed) } ``` + - `get_error_response` method to manage error responses. As the handling of checkout errors remains consistent across various flows, we've incorporated it from the `build_error_response` method within the `ConnectorCommon` trait. + ```rust fn get_error_response( &self, res: types::Response, + event_builder: Option<&mut ConnectorEvent>, ) -> CustomResult<types::ErrorResponse, errors::ConnectorError> { - self.build_error_response(res) + self.build_error_response(res, event_builder) } ``` + **ConnectorCommonExt :** An enhanced trait for `ConnectorCommon` that enables functions with a generic type. This trait includes the `build_headers` method, responsible for constructing both the common headers and the Authorization headers (retrieved from the `get_auth_header` method), returning them as a vector. -```rust +```rust where Self: ConnectorIntegration<Flow, Request, Response>, { @@ -604,11 +628,11 @@ Within the `ConnectorIntegration` trait, you'll find the following methods imple **Payment :** This trait includes several other traits and is meant to represent the functionality related to payments. -**PaymentAuthorize :** This trait extends the `api::ConnectorIntegration `trait with specific types related to payment authorization. +**PaymentAuthorize :** This trait extends the `api::ConnectorIntegration `trait with specific types related to payment authorization. -**PaymentCapture :** This trait extends the `api::ConnectorIntegration `trait with specific types related to manual payment capture. +**PaymentCapture :** This trait extends the `api::ConnectorIntegration `trait with specific types related to manual payment capture. -**PaymentSync :** This trait extends the `api::ConnectorIntegration `trait with specific types related to payment retrieve. +**PaymentSync :** This trait extends the `api::ConnectorIntegration `trait with specific types related to payment retrieve. **Refund :** This trait includes several other traits and is meant to represent the functionality related to Refunds. @@ -616,7 +640,6 @@ Within the `ConnectorIntegration` trait, you'll find the following methods imple **RefundSync :** This trait extends the `api::ConnectorIntegration `trait with specific types related to refunds retrieve. - And the below derive traits - **Debug** @@ -629,9 +652,10 @@ Refer to other connector code for trait implementations. Mostly the rust compile Feel free to connect with us in case of any queries and if you want to confirm the status mapping. ### **Set the currency Unit** + The `get_currency_unit` function, part of the ConnectorCommon trait, enables connectors to specify their accepted currency unit as either `Base` or `Minor`. For instance, Paypal designates its currency in the base unit (for example, USD), whereas Hyperswitch processes amounts in the minor unit (for example, cents). If a connector accepts amounts in the base unit, conversion is required, as illustrated. -``` rust +```rust impl<T> TryFrom<( &types::api::CurrencyUnit, @@ -722,8 +746,9 @@ Prior to executing tests in the shell, ensure that the API keys are configured i ```rust export CONNECTOR_AUTH_FILE_PATH="/hyperswitch/crates/router/tests/connectors/sample_auth.toml" - cargo test --package router --test connectors -- checkout --test-threads=1 + cargo test --package router --test connectors -- checkout --test-threads=1 ``` + All tests should pass and add appropriate tests for connector specific payment flows. ### **Build payment request and response from json schema** diff --git a/connector-template/mod.rs b/connector-template/mod.rs index c64ce431968..987f6a8742f 100644 --- a/connector-template/mod.rs +++ b/connector-template/mod.rs @@ -5,6 +5,7 @@ use error_stack::{ResultExt, IntoReport}; use masking::ExposeInterface; use crate::{ + events::connector_api_logs::ConnectorEvent, configs::settings, utils::{self, BytesExt}, core::{ @@ -95,12 +96,16 @@ impl ConnectorCommon for {{project-name | downcase | pascal_case}} { fn build_error_response( &self, res: Response, + event_builder: Option<&mut ConnectorEvent>, ) -> CustomResult<ErrorResponse, errors::ConnectorError> { let response: {{project-name | downcase}}::{{project-name | downcase | pascal_case}}ErrorResponse = res .response .parse_struct("{{project-name | downcase | pascal_case}}ErrorResponse") .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, @@ -194,9 +199,12 @@ impl fn handle_response( &self, data: &types::PaymentsAuthorizeRouterData, + event_builder: Option<&mut ConnectorEvent>, res: Response, ) -> CustomResult<types::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 { response, data: data.clone(), @@ -204,8 +212,8 @@ impl }) } - fn get_error_response(&self, res: Response) -> CustomResult<ErrorResponse,errors::ConnectorError> { - self.build_error_response(res) + fn get_error_response(&self, res: Response, event_builder: Option<&mut ConnectorEvent>) -> CustomResult<ErrorResponse,errors::ConnectorError> { + self.build_error_response(res, event_builder) } } @@ -251,24 +259,28 @@ impl fn handle_response( &self, data: &types::PaymentsSyncRouterData, + event_builder: Option<&mut ConnectorEvent>, res: Response, ) -> CustomResult<types::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 { 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) + self.build_error_response(res, event_builder) } } @@ -328,12 +340,15 @@ impl fn handle_response( &self, data: &types::PaymentsCaptureRouterData, + event_builder: Option<&mut ConnectorEvent>, res: Response, ) -> CustomResult<types::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 { response, data: data.clone(), @@ -344,8 +359,9 @@ impl fn get_error_response( &self, res: Response, + event_builder: Option<&mut ConnectorEvent> ) -> CustomResult<ErrorResponse, errors::ConnectorError> { - self.build_error_response(res) + self.build_error_response(res, event_builder) } } @@ -401,9 +417,12 @@ impl 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: {{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 { response, data: data.clone(), @@ -411,8 +430,8 @@ impl }) } - fn get_error_response(&self, res: Response) -> CustomResult<ErrorResponse,errors::ConnectorError> { - self.build_error_response(res) + fn get_error_response(&self, res: Response, event_builder: Option<&mut ConnectorEvent>) -> CustomResult<ErrorResponse,errors::ConnectorError> { + self.build_error_response(res, event_builder) } } @@ -449,9 +468,12 @@ impl fn handle_response( &self, data: &types::RefundSyncRouterData, + event_builder: Option<&mut ConnectorEvent>, res: Response, ) -> CustomResult<types::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 { response, data: data.clone(), @@ -459,8 +481,8 @@ impl }) } - fn get_error_response(&self, res: Response) -> CustomResult<ErrorResponse,errors::ConnectorError> { - self.build_error_response(res) + fn get_error_response(&self, res: Response, event_builder: Option<&mut ConnectorEvent>) -> CustomResult<ErrorResponse,errors::ConnectorError> { + self.build_error_response(res, event_builder) } } diff --git a/crates/analytics/docs/clickhouse/cluster_setup/README.md b/crates/analytics/docs/clickhouse/cluster_setup/README.md deleted file mode 100644 index cd5f2dfeb02..00000000000 --- a/crates/analytics/docs/clickhouse/cluster_setup/README.md +++ /dev/null @@ -1,347 +0,0 @@ -# Tutorial for set up clickhouse server - - -## Single server with docker - - -- Run server - -``` -docker run -d --name clickhouse-server -p 9000:9000 --ulimit nofile=262144:262144 yandex/clickhouse-server - -``` - -- Run client - -``` -docker run -it --rm --link clickhouse-server:clickhouse-server yandex/clickhouse-client --host clickhouse-server -``` - -Now you can see if it success setup or not. - - -## Setup Cluster - - -This part we will setup - -- 1 cluster, with 3 shards -- Each shard has 2 replica server -- Use ReplicatedMergeTree & Distributed table to setup our table. - - -### Cluster - -Let's see our docker-compose.yml first. - -``` -version: '3' - -services: - clickhouse-zookeeper: - image: zookeeper - ports: - - "2181:2181" - - "2182:2182" - container_name: clickhouse-zookeeper - hostname: clickhouse-zookeeper - - clickhouse-01: - image: yandex/clickhouse-server - hostname: clickhouse-01 - container_name: clickhouse-01 - ports: - - 9001:9000 - volumes: - - ./config/clickhouse_config.xml:/etc/clickhouse-server/config.xml - - ./config/clickhouse_metrika.xml:/etc/clickhouse-server/metrika.xml - - ./config/macros/macros-01.xml:/etc/clickhouse-server/config.d/macros.xml - # - ./data/server-01:/var/lib/clickhouse - ulimits: - nofile: - soft: 262144 - hard: 262144 - depends_on: - - "clickhouse-zookeeper" - - clickhouse-02: - image: yandex/clickhouse-server - hostname: clickhouse-02 - container_name: clickhouse-02 - ports: - - 9002:9000 - volumes: - - ./config/clickhouse_config.xml:/etc/clickhouse-server/config.xml - - ./config/clickhouse_metrika.xml:/etc/clickhouse-server/metrika.xml - - ./config/macros/macros-02.xml:/etc/clickhouse-server/config.d/macros.xml - # - ./data/server-02:/var/lib/clickhouse - ulimits: - nofile: - soft: 262144 - hard: 262144 - depends_on: - - "clickhouse-zookeeper" - - clickhouse-03: - image: yandex/clickhouse-server - hostname: clickhouse-03 - container_name: clickhouse-03 - ports: - - 9003:9000 - volumes: - - ./config/clickhouse_config.xml:/etc/clickhouse-server/config.xml - - ./config/clickhouse_metrika.xml:/etc/clickhouse-server/metrika.xml - - ./config/macros/macros-03.xml:/etc/clickhouse-server/config.d/macros.xml - # - ./data/server-03:/var/lib/clickhouse - ulimits: - nofile: - soft: 262144 - hard: 262144 - depends_on: - - "clickhouse-zookeeper" - - clickhouse-04: - image: yandex/clickhouse-server - hostname: clickhouse-04 - container_name: clickhouse-04 - ports: - - 9004:9000 - volumes: - - ./config/clickhouse_config.xml:/etc/clickhouse-server/config.xml - - ./config/clickhouse_metrika.xml:/etc/clickhouse-server/metrika.xml - - ./config/macros/macros-04.xml:/etc/clickhouse-server/config.d/macros.xml - # - ./data/server-04:/var/lib/clickhouse - ulimits: - nofile: - soft: 262144 - hard: 262144 - depends_on: - - "clickhouse-zookeeper" - - clickhouse-05: - image: yandex/clickhouse-server - hostname: clickhouse-05 - container_name: clickhouse-05 - ports: - - 9005:9000 - volumes: - - ./config/clickhouse_config.xml:/etc/clickhouse-server/config.xml - - ./config/clickhouse_metrika.xml:/etc/clickhouse-server/metrika.xml - - ./config/macros/macros-05.xml:/etc/clickhouse-server/config.d/macros.xml - # - ./data/server-05:/var/lib/clickhouse - ulimits: - nofile: - soft: 262144 - hard: 262144 - depends_on: - - "clickhouse-zookeeper" - - clickhouse-06: - image: yandex/clickhouse-server - hostname: clickhouse-06 - container_name: clickhouse-06 - ports: - - 9006:9000 - volumes: - - ./config/clickhouse_config.xml:/etc/clickhouse-server/config.xml - - ./config/clickhouse_metrika.xml:/etc/clickhouse-server/metrika.xml - - ./config/macros/macros-06.xml:/etc/clickhouse-server/config.d/macros.xml - # - ./data/server-06:/var/lib/clickhouse - ulimits: - nofile: - soft: 262144 - hard: 262144 - depends_on: - - "clickhouse-zookeeper" -networks: - default: - external: - name: clickhouse-net -``` - - -We have 6 clickhouse server container and one zookeeper container. - - -**To enable replication ZooKeeper is required. ClickHouse will take care of data consistency on all replicas and run restore procedure after failure automatically. It's recommended to deploy ZooKeeper cluster to separate servers.** - -**ZooKeeper is not a requirement — in some simple cases you can duplicate the data by writing it into all the replicas from your application code. This approach is not recommended — in this case ClickHouse is not able to guarantee data consistency on all replicas. This remains the responsibility of your application.** - - -Let's see config file. - -`./config/clickhouse_config.xml` is the default config file in docker, we copy it out and add this line - -``` - <!-- If element has 'incl' attribute, then for it's value will be used corresponding substitution from another file. - By default, path to file with substitutions is /etc/metrika.xml. It could be changed in config in 'include_from' element. - Values for substitutions are specified in /yandex/name_of_substitution elements in that file. - --> - <include_from>/etc/clickhouse-server/metrika.xml</include_from> -``` - - -So lets see `clickhouse_metrika.xml` - -``` -<yandex> - <clickhouse_remote_servers> - <cluster_1> - <shard> - <weight>1</weight> - <internal_replication>true</internal_replication> - <replica> - <host>clickhouse-01</host> - <port>9000</port> - </replica> - <replica> - <host>clickhouse-06</host> - <port>9000</port> - </replica> - </shard> - <shard> - <weight>1</weight> - <internal_replication>true</internal_replication> - <replica> - <host>clickhouse-02</host> - <port>9000</port> - </replica> - <replica> - <host>clickhouse-03</host> - <port>9000</port> - </replica> - </shard> - <shard> - <weight>1</weight> - <internal_replication>true</internal_replication> - - <replica> - <host>clickhouse-04</host> - <port>9000</port> - </replica> - <replica> - <host>clickhouse-05</host> - <port>9000</port> - </replica> - </shard> - </cluster_1> - </clickhouse_remote_servers> - <zookeeper-servers> - <node index="1"> - <host>clickhouse-zookeeper</host> - <port>2181</port> - </node> - </zookeeper-servers> - <networks> - <ip>::/0</ip> - </networks> - <clickhouse_compression> - <case> - <min_part_size>10000000000</min_part_size> - <min_part_size_ratio>0.01</min_part_size_ratio> - <method>lz4</method> - </case> - </clickhouse_compression> -</yandex> -``` - -and macros.xml, each instances has there own macros settings, like server 1: - -``` -<yandex> - <macros> - <replica>clickhouse-01</replica> - <shard>01</shard> - <layer>01</layer> - </macros> -</yandex> -``` - - -**Make sure your macros settings is equal to remote server settings in metrika.xml** - -So now you can start the server. - -``` -docker network create clickhouse-net -docker-compose up -d -``` - -Conn to server and see if the cluster settings fine; - -``` -docker run -it --rm --network="clickhouse-net" --link clickhouse-01:clickhouse-server yandex/clickhouse-client --host clickhouse-server -``` - -```sql -clickhouse-01 :) select * from system.clusters; - -SELECT * -FROM system.clusters - -┌─cluster─────────────────────┬─shard_num─┬─shard_weight─┬─replica_num─┬─host_name─────┬─host_address─┬─port─┬─is_local─┬─user────┬─default_database─┐ -│ cluster_1 │ 1 │ 1 │ 1 │ clickhouse-01 │ 172.21.0.4 │ 9000 │ 1 │ default │ │ -│ cluster_1 │ 1 │ 1 │ 2 │ clickhouse-06 │ 172.21.0.5 │ 9000 │ 1 │ default │ │ -│ cluster_1 │ 2 │ 1 │ 1 │ clickhouse-02 │ 172.21.0.8 │ 9000 │ 0 │ default │ │ -│ cluster_1 │ 2 │ 1 │ 2 │ clickhouse-03 │ 172.21.0.6 │ 9000 │ 0 │ default │ │ -│ cluster_1 │ 3 │ 1 │ 1 │ clickhouse-04 │ 172.21.0.7 │ 9000 │ 0 │ default │ │ -│ cluster_1 │ 3 │ 1 │ 2 │ clickhouse-05 │ 172.21.0.3 │ 9000 │ 0 │ default │ │ -│ test_shard_localhost │ 1 │ 1 │ 1 │ localhost │ 127.0.0.1 │ 9000 │ 1 │ default │ │ -│ test_shard_localhost_secure │ 1 │ 1 │ 1 │ localhost │ 127.0.0.1 │ 9440 │ 0 │ default │ │ -└─────────────────────────────┴───────────┴──────────────┴─────────────┴───────────────┴──────────────┴──────┴──────────┴─────────┴──────────────────┘ -``` - -If you see this, it means cluster's settings work well(but not conn fine). - - -### Replica Table - -So now we have a cluster and replica settings. For clickhouse, we need to create ReplicatedMergeTree Table as a local table in every server. - -```sql -CREATE TABLE ttt (id Int32) ENGINE = ReplicatedMergeTree('/clickhouse/tables/{layer}-{shard}/ttt', '{replica}') PARTITION BY id ORDER BY id -``` - -and Create Distributed Table conn to local table - -```sql -CREATE TABLE ttt_all as ttt ENGINE = Distributed(cluster_1, default, ttt, rand()); -``` - - -### Insert and test - -gen some data and test. - - -``` -# docker exec into client server 1 and -for ((idx=1;idx<=100;++idx)); do clickhouse-client --host clickhouse-server --query "Insert into default.ttt_all values ($idx)"; done; -``` - -For Distributed table. - -``` -select count(*) from ttt_all; -``` - -For loacl table. - -``` -select count(*) from ttt; -``` - - -## Authentication - -Please see config/users.xml - - -- Conn -```bash -docker run -it --rm --network="clickhouse-net" --link clickhouse-01:clickhouse-server yandex/clickhouse-client --host clickhouse-server -u user1 --password 123456 -``` - -## Source - -- https://clickhouse.yandex/docs/en/operations/table_engines/replication/#creating-replicated-tables diff --git a/crates/analytics/docs/clickhouse/cluster_setup/config/clickhouse_config.xml b/crates/analytics/docs/clickhouse/cluster_setup/config/clickhouse_config.xml deleted file mode 100644 index 94c854dc273..00000000000 --- a/crates/analytics/docs/clickhouse/cluster_setup/config/clickhouse_config.xml +++ /dev/null @@ -1,370 +0,0 @@ -<?xml version="1.0"?> -<yandex> - <logger> - <!-- Possible levels: https://github.com/pocoproject/poco/blob/develop/Foundation/include/Poco/Logger.h#L105 --> - <level>error</level> - <size>1000M</size> - <console>1</console> - <count>10</count> - <!-- <console>1</console> --> <!-- Default behavior is autodetection (log to console if not daemon mode and is tty) --> - </logger> - <!--display_name>production</display_name--> <!-- It is the name that will be shown in the client --> - <http_port>8123</http_port> - <tcp_port>9000</tcp_port> - - <!-- For HTTPS and SSL over native protocol. --> - <!-- - <https_port>8443</https_port> - <tcp_port_secure>9440</tcp_port_secure> - --> - - <!-- Used with https_port and tcp_port_secure. Full ssl options list: https://github.com/ClickHouse-Extras/poco/blob/master/NetSSL_OpenSSL/include/Poco/Net/SSLManager.h#L71 --> - <openSSL> - <server> <!-- Used for https server AND secure tcp port --> - <!-- openssl req -subj "/CN=localhost" -new -newkey rsa:2048 -days 365 -nodes -x509 -keyout /etc/clickhouse-server/server.key -out /etc/clickhouse-server/server.crt --> - <certificateFile>/etc/clickhouse-server/server.crt</certificateFile> - <privateKeyFile>/etc/clickhouse-server/server.key</privateKeyFile> - <!-- openssl dhparam -out /etc/clickhouse-server/dhparam.pem 4096 --> - <dhParamsFile>/etc/clickhouse-server/dhparam.pem</dhParamsFile> - <verificationMode>none</verificationMode> - <loadDefaultCAFile>true</loadDefaultCAFile> - <cacheSessions>true</cacheSessions> - <disableProtocols>sslv2,sslv3</disableProtocols> - <preferServerCiphers>true</preferServerCiphers> - </server> - - <client> <!-- Used for connecting to https dictionary source --> - <loadDefaultCAFile>true</loadDefaultCAFile> - <cacheSessions>true</cacheSessions> - <disableProtocols>sslv2,sslv3</disableProtocols> - <preferServerCiphers>true</preferServerCiphers> - <!-- Use for self-signed: <verificationMode>none</verificationMode> --> - <invalidCertificateHandler> - <!-- Use for self-signed: <name>AcceptCertificateHandler</name> --> - <name>RejectCertificateHandler</name> - </invalidCertificateHandler> - </client> - </openSSL> - - <!-- Default root page on http[s] server. For example load UI from https://tabix.io/ when opening http://localhost:8123 --> - <!-- - <http_server_default_response><![CDATA[<html ng-app="SMI2"><head><base href="http://ui.tabix.io/"></head><body><div ui-view="" class="content-ui"></div><script src="http://loader.tabix.io/master.js"></script></body></html>]]></http_server_default_response> - --> - - <!-- Port for communication between replicas. Used for data exchange. --> - <interserver_http_port>9009</interserver_http_port> - - <!-- Hostname that is used by other replicas to request this server. - If not specified, than it is determined analogous to 'hostname -f' command. - This setting could be used to switch replication to another network interface. - --> - <!-- - <interserver_http_host>example.yandex.ru</interserver_http_host> - --> - - <!-- Listen specified host. use :: (wildcard IPv6 address), if you want to accept connections both with IPv4 and IPv6 from everywhere. --> - <!-- <listen_host>::</listen_host> --> - <!-- Same for hosts with disabled ipv6: --> - <!-- <listen_host>0.0.0.0</listen_host> --> - - <!-- Default values - try listen localhost on ipv4 and ipv6: --> - <!-- - <listen_host>::1</listen_host> - <listen_host>127.0.0.1</listen_host> - --> - <!-- Don't exit if ipv6 or ipv4 unavailable, but listen_host with this protocol specified --> - <!-- <listen_try>0</listen_try> --> - - <!-- Allow listen on same address:port --> - <!-- <listen_reuse_port>0</listen_reuse_port> --> - - <!-- <listen_backlog>64</listen_backlog> --> - - <max_connections>4096</max_connections> - <keep_alive_timeout>3</keep_alive_timeout> - - <!-- Maximum number of concurrent queries. --> - <max_concurrent_queries>100</max_concurrent_queries> - - <!-- Set limit on number of open files (default: maximum). This setting makes sense on Mac OS X because getrlimit() fails to retrieve - correct maximum value. --> - <!-- <max_open_files>262144</max_open_files> --> - - <!-- Size of cache of uncompressed blocks of data, used in tables of MergeTree family. - In bytes. Cache is single for server. Memory is allocated only on demand. - Cache is used when 'use_uncompressed_cache' user setting turned on (off by default). - Uncompressed cache is advantageous only for very short queries and in rare cases. - --> - <uncompressed_cache_size>8589934592</uncompressed_cache_size> - - <!-- Approximate size of mark cache, used in tables of MergeTree family. - In bytes. Cache is single for server. Memory is allocated only on demand. - You should not lower this value. - --> - <mark_cache_size>5368709120</mark_cache_size> - - - <!-- Path to data directory, with trailing slash. --> - <path>/var/lib/clickhouse/</path> - - <!-- Path to temporary data for processing hard queries. --> - <tmp_path>/var/lib/clickhouse/tmp/</tmp_path> - - <!-- Directory with user provided files that are accessible by 'file' table function. --> - <user_files_path>/var/lib/clickhouse/user_files/</user_files_path> - - <!-- Path to configuration file with users, access rights, profiles of settings, quotas. --> - <users_config>users.xml</users_config> - - <!-- Default profile of settings. --> - <default_profile>default</default_profile> - - <!-- System profile of settings. This settings are used by internal processes (Buffer storage, Distributed DDL worker and so on). --> - <!-- <system_profile>default</system_profile> --> - - <!-- Default database. --> - <default_database>default</default_database> - - <!-- Server time zone could be set here. - - Time zone is used when converting between String and DateTime types, - when printing DateTime in text formats and parsing DateTime from text, - it is used in date and time related functions, if specific time zone was not passed as an argument. - - Time zone is specified as identifier from IANA time zone database, like UTC or Africa/Abidjan. - If not specified, system time zone at server startup is used. - - Please note, that server could display time zone alias instead of specified name. - Example: W-SU is an alias for Europe/Moscow and Zulu is an alias for UTC. - --> - <!-- <timezone>Europe/Moscow</timezone> --> - - <!-- You can specify umask here (see "man umask"). Server will apply it on startup. - Number is always parsed as octal. Default umask is 027 (other users cannot read logs, data files, etc; group can only read). - --> - <!-- <umask>022</umask> --> - - <!-- Configuration of clusters that could be used in Distributed tables. - https://clickhouse.yandex/docs/en/table_engines/distributed/ - --> - <remote_servers incl="clickhouse_remote_servers" > - <!-- Test only shard config for testing distributed storage --> - <test_shard_localhost> - <shard> - <replica> - <host>localhost</host> - <port>9000</port> - </replica> - </shard> - </test_shard_localhost> - <test_shard_localhost_secure> - <shard> - <replica> - <host>localhost</host> - <port>9440</port> - <secure>1</secure> - </replica> - </shard> - </test_shard_localhost_secure> - </remote_servers> - - - <!-- If element has 'incl' attribute, then for it's value will be used corresponding substitution from another file. - By default, path to file with substitutions is /etc/metrika.xml. It could be changed in config in 'include_from' element. - Values for substitutions are specified in /yandex/name_of_substitution elements in that file. - --> - <include_from>/etc/clickhouse-server/metrika.xml</include_from> - <!-- ZooKeeper is used to store metadata about replicas, when using Replicated tables. - Optional. If you don't use replicated tables, you could omit that. - - See https://clickhouse.yandex/docs/en/table_engines/replication/ - --> - <zookeeper incl="zookeeper-servers" optional="true" /> - - <!-- Substitutions for parameters of replicated tables. - Optional. If you don't use replicated tables, you could omit that. - - See https://clickhouse.yandex/docs/en/table_engines/replication/#creating-replicated-tables - --> - <macros incl="macros" optional="true" /> - - - <!-- Reloading interval for embedded dictionaries, in seconds. Default: 3600. --> - <builtin_dictionaries_reload_interval>3600</builtin_dictionaries_reload_interval> - - - <!-- Maximum session timeout, in seconds. Default: 3600. --> - <max_session_timeout>3600</max_session_timeout> - - <!-- Default session timeout, in seconds. Default: 60. --> - <default_session_timeout>60</default_session_timeout> - - <!-- Sending data to Graphite for monitoring. Several sections can be defined. --> - <!-- - interval - send every X second - root_path - prefix for keys - hostname_in_path - append hostname to root_path (default = true) - metrics - send data from table system.metrics - events - send data from table system.events - asynchronous_metrics - send data from table system.asynchronous_metrics - --> - <!-- - <graphite> - <host>localhost</host> - <port>42000</port> - <timeout>0.1</timeout> - <interval>60</interval> - <root_path>one_min</root_path> - <hostname_in_path>true</hostname_in_path> - - <metrics>true</metrics> - <events>true</events> - <asynchronous_metrics>true</asynchronous_metrics> - </graphite> - <graphite> - <host>localhost</host> - <port>42000</port> - <timeout>0.1</timeout> - <interval>1</interval> - <root_path>one_sec</root_path> - - <metrics>true</metrics> - <events>true</events> - <asynchronous_metrics>false</asynchronous_metrics> - </graphite> - --> - - - <!-- Query log. Used only for queries with setting log_queries = 1. --> - <query_log> - <!-- What table to insert data. If table is not exist, it will be created. - When query log structure is changed after system update, - then old table will be renamed and new table will be created automatically. - --> - <database>system</database> - <table>query_log</table> - <!-- - PARTITION BY expr https://clickhouse.yandex/docs/en/table_engines/custom_partitioning_key/ - Example: - event_date - toMonday(event_date) - toYYYYMM(event_date) - toStartOfHour(event_time) - --> - <partition_by>toYYYYMM(event_date)</partition_by> - <!-- Interval of flushing data. --> - <flush_interval_milliseconds>7500</flush_interval_milliseconds> - </query_log> - - - <!-- Uncomment if use part_log - <part_log> - <database>system</database> - <table>part_log</table> - - <flush_interval_milliseconds>7500</flush_interval_milliseconds> - </part_log> - --> - - - <!-- Parameters for embedded dictionaries, used in Yandex.Metrica. - See https://clickhouse.yandex/docs/en/dicts/internal_dicts/ - --> - - <!-- Path to file with region hierarchy. --> - <!-- <path_to_regions_hierarchy_file>/opt/geo/regions_hierarchy.txt</path_to_regions_hierarchy_file> --> - - <!-- Path to directory with files containing names of regions --> - <!-- <path_to_regions_names_files>/opt/geo/</path_to_regions_names_files> --> - - - <!-- Configuration of external dictionaries. See: - https://clickhouse.yandex/docs/en/dicts/external_dicts/ - --> - <dictionaries_config>*_dictionary.xml</dictionaries_config> - - <!-- Uncomment if you want data to be compressed 30-100% better. - Don't do that if you just started using ClickHouse. - --> - <compression incl="clickhouse_compression"> - <!-- - <!- - Set of variants. Checked in order. Last matching case wins. If nothing matches, lz4 will be used. - -> - <case> - - <!- - Conditions. All must be satisfied. Some conditions may be omitted. - -> - <min_part_size>10000000000</min_part_size> <!- - Min part size in bytes. - -> - <min_part_size_ratio>0.01</min_part_size_ratio> <!- - Min size of part relative to whole table size. - -> - - <!- - What compression method to use. - -> - <method>zstd</method> - </case> - --> - </compression> - - <!-- Allow to execute distributed DDL queries (CREATE, DROP, ALTER, RENAME) on cluster. - Works only if ZooKeeper is enabled. Comment it if such functionality isn't required. --> - <distributed_ddl> - <!-- Path in ZooKeeper to queue with DDL queries --> - <path>/clickhouse/task_queue/ddl</path> - - <!-- Settings from this profile will be used to execute DDL queries --> - <!-- <profile>default</profile> --> - </distributed_ddl> - - <!-- Settings to fine tune MergeTree tables. See documentation in source code, in MergeTreeSettings.h --> - <!-- - <merge_tree> - <max_suspicious_broken_parts>5</max_suspicious_broken_parts> - </merge_tree> - --> - - <!-- Protection from accidental DROP. - If size of a MergeTree table is greater than max_table_size_to_drop (in bytes) than table could not be dropped with any DROP query. - If you want do delete one table and don't want to restart clickhouse-server, you could create special file <clickhouse-path>/flags/force_drop_table and make DROP once. - By default max_table_size_to_drop is 50GB; max_table_size_to_drop=0 allows to DROP any tables. - The same for max_partition_size_to_drop. - Uncomment to disable protection. - --> - <!-- <max_table_size_to_drop>0</max_table_size_to_drop> --> - <!-- <max_partition_size_to_drop>0</max_partition_size_to_drop> --> - - <!-- Example of parameters for GraphiteMergeTree table engine --> - <graphite_rollup_example> - <pattern> - <regexp>click_cost</regexp> - <function>any</function> - <retention> - <age>0</age> - <precision>3600</precision> - </retention> - <retention> - <age>86400</age> - <precision>60</precision> - </retention> - </pattern> - <default> - <function>max</function> - <retention> - <age>0</age> - <precision>60</precision> - </retention> - <retention> - <age>3600</age> - <precision>300</precision> - </retention> - <retention> - <age>86400</age> - <precision>3600</precision> - </retention> - </default> - </graphite_rollup_example> - - <!-- Directory in <clickhouse-path> containing schema files for various input formats. - The directory will be created if it doesn't exist. - --> - <format_schema_path>/var/lib/clickhouse/format_schemas/</format_schema_path> - - <!-- Uncomment to disable ClickHouse internal DNS caching. --> - <!-- <disable_internal_dns_cache>1</disable_internal_dns_cache> --> -</yandex> - diff --git a/crates/analytics/docs/clickhouse/cluster_setup/config/clickhouse_metrika.xml b/crates/analytics/docs/clickhouse/cluster_setup/config/clickhouse_metrika.xml deleted file mode 100644 index b58ffc34bc2..00000000000 --- a/crates/analytics/docs/clickhouse/cluster_setup/config/clickhouse_metrika.xml +++ /dev/null @@ -1,60 +0,0 @@ -<yandex> - <clickhouse_remote_servers> - <cluster_1> - <shard> - <weight>1</weight> - <internal_replication>true</internal_replication> - <replica> - <host>clickhouse-01</host> - <port>9000</port> - </replica> - <replica> - <host>clickhouse-06</host> - <port>9000</port> - </replica> - </shard> - <shard> - <weight>1</weight> - <internal_replication>true</internal_replication> - <replica> - <host>clickhouse-02</host> - <port>9000</port> - </replica> - <replica> - <host>clickhouse-03</host> - <port>9000</port> - </replica> - </shard> - <shard> - <weight>1</weight> - <internal_replication>true</internal_replication> - - <replica> - <host>clickhouse-04</host> - <port>9000</port> - </replica> - <replica> - <host>clickhouse-05</host> - <port>9000</port> - </replica> - </shard> - </cluster_1> - </clickhouse_remote_servers> - <zookeeper-servers> - <node index="1"> - <host>clickhouse-zookeeper</host> - <port>2181</port> - </node> - </zookeeper-servers> - <networks> - <ip>::/0</ip> - </networks> - <clickhouse_compression> - <case> - <min_part_size>10000000000</min_part_size> - <min_part_size_ratio>0.01</min_part_size_ratio> - <method>lz4</method> - </case> - </clickhouse_compression> -</yandex> - diff --git a/crates/analytics/docs/clickhouse/cluster_setup/config/macros/macros-01.xml b/crates/analytics/docs/clickhouse/cluster_setup/config/macros/macros-01.xml deleted file mode 100644 index 75df1c5916e..00000000000 --- a/crates/analytics/docs/clickhouse/cluster_setup/config/macros/macros-01.xml +++ /dev/null @@ -1,9 +0,0 @@ -<yandex> - <macros> - <replica>clickhouse-01</replica> - <shard>01</shard> - <layer>01</layer> - <installation>data</installation> - <cluster>cluster_1</cluster> - </macros> -</yandex> diff --git a/crates/analytics/docs/clickhouse/cluster_setup/config/macros/macros-02.xml b/crates/analytics/docs/clickhouse/cluster_setup/config/macros/macros-02.xml deleted file mode 100644 index 67e4a545b30..00000000000 --- a/crates/analytics/docs/clickhouse/cluster_setup/config/macros/macros-02.xml +++ /dev/null @@ -1,9 +0,0 @@ -<yandex> - <macros> - <replica>clickhouse-02</replica> - <shard>02</shard> - <layer>01</layer> - <installation>data</installation> - <cluster>cluster_1</cluster> - </macros> -</yandex> diff --git a/crates/analytics/docs/clickhouse/cluster_setup/config/macros/macros-03.xml b/crates/analytics/docs/clickhouse/cluster_setup/config/macros/macros-03.xml deleted file mode 100644 index e9278191b80..00000000000 --- a/crates/analytics/docs/clickhouse/cluster_setup/config/macros/macros-03.xml +++ /dev/null @@ -1,9 +0,0 @@ -<yandex> - <macros> - <replica>clickhouse-03</replica> - <shard>02</shard> - <layer>01</layer> - <installation>data</installation> - <cluster>cluster_1</cluster> - </macros> -</yandex> diff --git a/crates/analytics/docs/clickhouse/cluster_setup/config/macros/macros-04.xml b/crates/analytics/docs/clickhouse/cluster_setup/config/macros/macros-04.xml deleted file mode 100644 index 033c0ad1152..00000000000 --- a/crates/analytics/docs/clickhouse/cluster_setup/config/macros/macros-04.xml +++ /dev/null @@ -1,9 +0,0 @@ -<yandex> - <macros> - <replica>clickhouse-04</replica> - <shard>03</shard> - <layer>01</layer> - <installation>data</installation> - <cluster>cluster_1</cluster> - </macros> -</yandex> diff --git a/crates/analytics/docs/clickhouse/cluster_setup/config/macros/macros-05.xml b/crates/analytics/docs/clickhouse/cluster_setup/config/macros/macros-05.xml deleted file mode 100644 index c63314c5ace..00000000000 --- a/crates/analytics/docs/clickhouse/cluster_setup/config/macros/macros-05.xml +++ /dev/null @@ -1,9 +0,0 @@ -<yandex> - <macros> - <replica>clickhouse-05</replica> - <shard>03</shard> - <layer>01</layer> - <installation>data</installation> - <cluster>cluster_1</cluster> - </macros> -</yandex> diff --git a/crates/analytics/docs/clickhouse/cluster_setup/config/macros/macros-06.xml b/crates/analytics/docs/clickhouse/cluster_setup/config/macros/macros-06.xml deleted file mode 100644 index 4b01bda9948..00000000000 --- a/crates/analytics/docs/clickhouse/cluster_setup/config/macros/macros-06.xml +++ /dev/null @@ -1,9 +0,0 @@ -<yandex> - <macros> - <replica>clickhouse-06</replica> - <shard>01</shard> - <layer>01</layer> - <installation>data</installation> - <cluster>cluster_1</cluster> - </macros> -</yandex> diff --git a/crates/analytics/docs/clickhouse/cluster_setup/config/users.xml b/crates/analytics/docs/clickhouse/cluster_setup/config/users.xml deleted file mode 100644 index e1b8de78e37..00000000000 --- a/crates/analytics/docs/clickhouse/cluster_setup/config/users.xml +++ /dev/null @@ -1,117 +0,0 @@ -<?xml version="1.0"?> -<yandex> - <!-- Profiles of settings. --> - <profiles> - <!-- Default settings. --> - <default> - <!-- Maximum memory usage for processing single query, in bytes. --> - <max_memory_usage>10000000000</max_memory_usage> - - <!-- Use cache of uncompressed blocks of data. Meaningful only for processing many of very short queries. --> - <use_uncompressed_cache>0</use_uncompressed_cache> - - <!-- How to choose between replicas during distributed query processing. - random - choose random replica from set of replicas with minimum number of errors - nearest_hostname - from set of replicas with minimum number of errors, choose replica - with minimum number of different symbols between replica's hostname and local hostname - (Hamming distance). - in_order - first live replica is chosen in specified order. - --> - <load_balancing>random</load_balancing> - </default> - - <!-- Profile that allows only read queries. --> - <readonly> - <readonly>1</readonly> - </readonly> - </profiles> - - <!-- Users and ACL. --> - <users> - <user1> - <password>123456</password> - <networks incl="networks" replace="replace"> - <ip>::/0</ip> - </networks> - <profile>default</profile> - <quota>default</quota> - </user1> - <!-- If user name was not specified, 'default' user is used. --> - <default> - <!-- Password could be specified in plaintext or in SHA256 (in hex format). - - If you want to specify password in plaintext (not recommended), place it in 'password' element. - Example: <password>qwerty</password>. - Password could be empty. - - If you want to specify SHA256, place it in 'password_sha256_hex' element. - Example: <password_sha256_hex>65e84be33532fb784c48129675f9eff3a682b27168c0ea744b2cf58ee02337c5</password_sha256_hex> - - How to generate decent password: - Execute: PASSWORD=$(base64 < /dev/urandom | head -c8); echo "$PASSWORD"; echo -n "$PASSWORD" | sha256sum | tr -d '-' - In first line will be password and in second - corresponding SHA256. - --> - <password></password> - - <!-- List of networks with open access. - - To open access from everywhere, specify: - <ip>::/0</ip> - - To open access only from localhost, specify: - <ip>::1</ip> - <ip>127.0.0.1</ip> - - Each element of list has one of the following forms: - <ip> IP-address or network mask. Examples: 213.180.204.3 or 10.0.0.1/8 or 10.0.0.1/255.255.255.0 - 2a02:6b8::3 or 2a02:6b8::3/64 or 2a02:6b8::3/ffff:ffff:ffff:ffff::. - <host> Hostname. Example: server01.yandex.ru. - To check access, DNS query is performed, and all received addresses compared to peer address. - <host_regexp> Regular expression for host names. Example, ^server\d\d-\d\d-\d\.yandex\.ru$ - To check access, DNS PTR query is performed for peer address and then regexp is applied. - Then, for result of PTR query, another DNS query is performed and all received addresses compared to peer address. - Strongly recommended that regexp is ends with $ - All results of DNS requests are cached till server restart. - --> - <networks incl="networks" replace="replace"> - <ip>::/0</ip> - </networks> - - <!-- Settings profile for user. --> - <profile>default</profile> - - <!-- Quota for user. --> - <quota>default</quota> - </default> - - <!-- Example of user with readonly access. --> - <readonly> - <password></password> - <networks incl="networks" replace="replace"> - <ip>::1</ip> - <ip>127.0.0.1</ip> - </networks> - <profile>readonly</profile> - <quota>default</quota> - </readonly> - </users> - - <!-- Quotas. --> - <quotas> - <!-- Name of quota. --> - <default> - <!-- Limits for time interval. You could specify many intervals with different limits. --> - <interval> - <!-- Length of interval. --> - <duration>3600</duration> - - <!-- No limits. Just calculate resource usage for time interval. --> - <queries>0</queries> - <errors>0</errors> - <result_rows>0</result_rows> - <read_rows>0</read_rows> - <execution_time>0</execution_time> - </interval> - </default> - </quotas> -</yandex> diff --git a/crates/analytics/docs/clickhouse/cluster_setup/docker-compose.yml b/crates/analytics/docs/clickhouse/cluster_setup/docker-compose.yml deleted file mode 100644 index 96d7618b47e..00000000000 --- a/crates/analytics/docs/clickhouse/cluster_setup/docker-compose.yml +++ /dev/null @@ -1,198 +0,0 @@ -version: '3' - -networks: - ckh_net: - -services: - clickhouse-zookeeper: - image: zookeeper - ports: - - "2181:2181" - - "2182:2182" - container_name: clickhouse-zookeeper - hostname: clickhouse-zookeeper - networks: - - ckh_net - - clickhouse-01: - image: clickhouse/clickhouse-server - hostname: clickhouse-01 - container_name: clickhouse-01 - networks: - - ckh_net - ports: - - 9001:9000 - - 8124:8123 - volumes: - - ./config/clickhouse_config.xml:/etc/clickhouse-server/config.xml - - ./config/clickhouse_metrika.xml:/etc/clickhouse-server/metrika.xml - - ./config/macros/macros-01.xml:/etc/clickhouse-server/config.d/macros.xml - - ./config/users.xml:/etc/clickhouse-server/users.xml - # - ./data/server-01:/var/lib/clickhouse - ulimits: - nofile: - soft: 262144 - hard: 262144 - depends_on: - - "clickhouse-zookeeper" - - clickhouse-02: - image: clickhouse/clickhouse-server - hostname: clickhouse-02 - container_name: clickhouse-02 - networks: - - ckh_net - ports: - - 9002:9000 - - 8125:8123 - volumes: - - ./config/clickhouse_config.xml:/etc/clickhouse-server/config.xml - - ./config/clickhouse_metrika.xml:/etc/clickhouse-server/metrika.xml - - ./config/macros/macros-02.xml:/etc/clickhouse-server/config.d/macros.xml - - ./config/users.xml:/etc/clickhouse-server/users.xml - # - ./data/server-02:/var/lib/clickhouse - ulimits: - nofile: - soft: 262144 - hard: 262144 - depends_on: - - "clickhouse-zookeeper" - - clickhouse-03: - image: clickhouse/clickhouse-server - hostname: clickhouse-03 - container_name: clickhouse-03 - networks: - - ckh_net - ports: - - 9003:9000 - - 8126:8123 - volumes: - - ./config/clickhouse_config.xml:/etc/clickhouse-server/config.xml - - ./config/clickhouse_metrika.xml:/etc/clickhouse-server/metrika.xml - - ./config/macros/macros-03.xml:/etc/clickhouse-server/config.d/macros.xml - - ./config/users.xml:/etc/clickhouse-server/users.xml - # - ./data/server-03:/var/lib/clickhouse - ulimits: - nofile: - soft: 262144 - hard: 262144 - depends_on: - - "clickhouse-zookeeper" - - clickhouse-04: - image: clickhouse/clickhouse-server - hostname: clickhouse-04 - container_name: clickhouse-04 - networks: - - ckh_net - ports: - - 9004:9000 - - 8127:8123 - volumes: - - ./config/clickhouse_config.xml:/etc/clickhouse-server/config.xml - - ./config/clickhouse_metrika.xml:/etc/clickhouse-server/metrika.xml - - ./config/macros/macros-04.xml:/etc/clickhouse-server/config.d/macros.xml - - ./config/users.xml:/etc/clickhouse-server/users.xml - # - ./data/server-04:/var/lib/clickhouse - ulimits: - nofile: - soft: 262144 - hard: 262144 - depends_on: - - "clickhouse-zookeeper" - - clickhouse-05: - image: clickhouse/clickhouse-server - hostname: clickhouse-05 - container_name: clickhouse-05 - networks: - - ckh_net - ports: - - 9005:9000 - - 8128:8123 - volumes: - - ./config/clickhouse_config.xml:/etc/clickhouse-server/config.xml - - ./config/clickhouse_metrika.xml:/etc/clickhouse-server/metrika.xml - - ./config/macros/macros-05.xml:/etc/clickhouse-server/config.d/macros.xml - - ./config/users.xml:/etc/clickhouse-server/users.xml - # - ./data/server-05:/var/lib/clickhouse - ulimits: - nofile: - soft: 262144 - hard: 262144 - depends_on: - - "clickhouse-zookeeper" - - clickhouse-06: - image: clickhouse/clickhouse-server - hostname: clickhouse-06 - container_name: clickhouse-06 - networks: - - ckh_net - ports: - - 9006:9000 - - 8129:8123 - volumes: - - ./config/clickhouse_config.xml:/etc/clickhouse-server/config.xml - - ./config/clickhouse_metrika.xml:/etc/clickhouse-server/metrika.xml - - ./config/macros/macros-06.xml:/etc/clickhouse-server/config.d/macros.xml - - ./config/users.xml:/etc/clickhouse-server/users.xml - # - ./data/server-06:/var/lib/clickhouse - ulimits: - nofile: - soft: 262144 - hard: 262144 - depends_on: - - "clickhouse-zookeeper" - - kafka0: - image: confluentinc/cp-kafka:7.0.5 - hostname: kafka0 - container_name: kafka0 - ports: - - 9092:9092 - - 9093 - - 9997 - - 29092 - environment: - KAFKA_BROKER_ID: 1 - KAFKA_LISTENER_SECURITY_PROTOCOL_MAP: PLAINTEXT:PLAINTEXT,CONTROLLER:PLAINTEXT,PLAINTEXT_HOST:PLAINTEXT - KAFKA_ADVERTISED_LISTENERS: PLAINTEXT://kafka0:29092,PLAINTEXT_HOST://localhost:9092 - KAFKA_INTER_BROKER_LISTENER_NAME: PLAINTEXT - KAFKA_OFFSETS_TOPIC_REPLICATION_FACTOR: 1 - KAFKA_GROUP_INITIAL_REBALANCE_DELAY_MS: 0 - KAFKA_TRANSACTION_STATE_LOG_MIN_ISR: 1 - KAFKA_TRANSACTION_STATE_LOG_REPLICATION_FACTOR: 1 - KAFKA_PROCESS_ROLES: 'broker,controller' - KAFKA_NODE_ID: 1 - KAFKA_CONTROLLER_QUORUM_VOTERS: '1@kafka0:29093' - KAFKA_LISTENERS: 'PLAINTEXT://kafka0:29092,CONTROLLER://kafka0:29093,PLAINTEXT_HOST://0.0.0.0:9092' - KAFKA_CONTROLLER_LISTENER_NAMES: 'CONTROLLER' - KAFKA_LOG_DIRS: '/tmp/kraft-combined-logs' - JMX_PORT: 9997 - KAFKA_JMX_OPTS: -Dcom.sun.management.jmxremote -Dcom.sun.management.jmxremote.authenticate=false -Dcom.sun.management.jmxremote.ssl=false -Djava.rmi.server.hostname=kafka0 -Dcom.sun.management.jmxremote.rmi.port=9997 - volumes: - - ./kafka-script.sh:/tmp/update_run.sh - command: "bash -c 'if [ ! -f /tmp/update_run.sh ]; then echo \"ERROR: Did you forget the update_run.sh file that came with this docker-compose.yml file?\" && exit 1 ; else /tmp/update_run.sh && /etc/confluent/docker/run ; fi'" - networks: - ckh_net: - aliases: - - hyper-c1-kafka-brokers.kafka-cluster.svc.cluster.local - - - # Kafka UI for debugging kafka queues - kafka-ui: - container_name: kafka-ui - image: provectuslabs/kafka-ui:latest - ports: - - 8090:8080 - depends_on: - - kafka0 - networks: - - ckh_net - environment: - KAFKA_CLUSTERS_0_NAME: local - KAFKA_CLUSTERS_0_BOOTSTRAPSERVERS: kafka0:29092 - KAFKA_CLUSTERS_0_JMXPORT: 9997 - diff --git a/crates/analytics/docs/clickhouse/cluster_setup/kafka-script.sh b/crates/analytics/docs/clickhouse/cluster_setup/kafka-script.sh deleted file mode 100755 index 023c832b4e1..00000000000 --- a/crates/analytics/docs/clickhouse/cluster_setup/kafka-script.sh +++ /dev/null @@ -1,11 +0,0 @@ -# This script is required to run kafka cluster (without zookeeper) -#!/bin/sh - -# Docker workaround: Remove check for KAFKA_ZOOKEEPER_CONNECT parameter -sed -i '/KAFKA_ZOOKEEPER_CONNECT/d' /etc/confluent/docker/configure - -# Docker workaround: Ignore cub zk-ready -sed -i 's/cub zk-ready/echo ignore zk-ready/' /etc/confluent/docker/ensure - -# KRaft required step: Format the storage directory with a new cluster ID -echo "kafka-storage format --ignore-formatted -t $(kafka-storage random-uuid) -c /etc/kafka/kafka.properties" >> /etc/confluent/docker/ensure \ No newline at end of file diff --git a/crates/analytics/docs/clickhouse/cluster_setup/scripts/api_event_logs.sql b/crates/analytics/docs/clickhouse/cluster_setup/scripts/api_event_logs.sql deleted file mode 100644 index ad0fe6d778f..00000000000 --- a/crates/analytics/docs/clickhouse/cluster_setup/scripts/api_event_logs.sql +++ /dev/null @@ -1,242 +0,0 @@ -CREATE TABLE hyperswitch.api_events_queue on cluster '{cluster}' ( - `merchant_id` String, - `payment_id` Nullable(String), - `refund_id` Nullable(String), - `payment_method_id` Nullable(String), - `payment_method` Nullable(String), - `payment_method_type` Nullable(String), - `customer_id` Nullable(String), - `user_id` Nullable(String), - `request_id` String, - `flow_type` LowCardinality(String), - `api_name` LowCardinality(String), - `request` String, - `response` String, - `status_code` UInt32, - `url_path` LowCardinality(Nullable(String)), - `event_type` LowCardinality(Nullable(String)), - `created_at` DateTime CODEC(T64, LZ4), - `latency` Nullable(UInt128), - `user_agent` Nullable(String), - `ip_addr` Nullable(String), - `dispute_id` Nullable(String) -) ENGINE = Kafka SETTINGS kafka_broker_list = 'hyper-c1-kafka-brokers.kafka-cluster.svc.cluster.local:9092', -kafka_topic_list = 'hyperswitch-api-log-events', -kafka_group_name = 'hyper-c1', -kafka_format = 'JSONEachRow', -kafka_handle_error_mode = 'stream'; - - -CREATE TABLE hyperswitch.api_events_clustered on cluster '{cluster}' ( - `merchant_id` String, - `payment_id` Nullable(String), - `refund_id` Nullable(String), - `payment_method_id` Nullable(String), - `payment_method` Nullable(String), - `payment_method_type` Nullable(String), - `customer_id` Nullable(String), - `user_id` Nullable(String), - `request_id` Nullable(String), - `flow_type` LowCardinality(String), - `api_name` LowCardinality(String), - `request` String, - `response` String, - `status_code` UInt32, - `inserted_at` DateTime DEFAULT now() CODEC(T64, LZ4), - `created_at` DateTime DEFAULT now() CODEC(T64, LZ4), - `latency` Nullable(UInt128), - `user_agent` Nullable(String), - `ip_addr` Nullable(String), - INDEX flowIndex flow_type TYPE bloom_filter GRANULARITY 1, - INDEX apiIndex api_name TYPE bloom_filter GRANULARITY 1, - INDEX statusIndex status_code TYPE bloom_filter GRANULARITY 1 -) ENGINE = ReplicatedMergeTree( - '/clickhouse/{installation}/{cluster}/tables/{shard}/hyperswitch/api_events_clustered', - '{replica}' -) -PARTITION BY toStartOfDay(created_at) -ORDER BY - (created_at, merchant_id, flow_type, status_code, api_name) -TTL created_at + toIntervalMonth(6) -; - - -CREATE TABLE hyperswitch.api_events_dist on cluster '{cluster}' ( - `merchant_id` String, - `payment_id` Nullable(String), - `refund_id` Nullable(String), - `payment_method_id` Nullable(String), - `payment_method` Nullable(String), - `payment_method_type` Nullable(String), - `customer_id` Nullable(String), - `user_id` Nullable(String), - `request_id` Nullable(String), - `flow_type` LowCardinality(String), - `api_name` LowCardinality(String), - `request` String, - `response` String, - `status_code` UInt32, - `url_path` LowCardinality(Nullable(String)), - `event_type` LowCardinality(Nullable(String)), - `inserted_at` DateTime64(3), - `created_at` DateTime64(3), - `latency` Nullable(UInt128), - `user_agent` Nullable(String), - `ip_addr` Nullable(String), - `dispute_id` Nullable(String) -) ENGINE = Distributed('{cluster}', 'hyperswitch', 'api_events_clustered', rand()); - -CREATE MATERIALIZED VIEW hyperswitch.api_events_mv on cluster '{cluster}' TO hyperswitch.api_events_dist ( - `merchant_id` String, - `payment_id` Nullable(String), - `refund_id` Nullable(String), - `payment_method_id` Nullable(String), - `payment_method` Nullable(String), - `payment_method_type` Nullable(String), - `customer_id` Nullable(String), - `user_id` Nullable(String), - `request_id` Nullable(String), - `flow_type` LowCardinality(String), - `api_name` LowCardinality(String), - `request` String, - `response` String, - `status_code` UInt32, - `url_path` LowCardinality(Nullable(String)), - `event_type` LowCardinality(Nullable(String)), - `inserted_at` DateTime64(3), - `created_at` DateTime64(3), - `latency` Nullable(UInt128), - `user_agent` Nullable(String), - `ip_addr` Nullable(String), - `dispute_id` Nullable(String) -) AS -SELECT - merchant_id, - payment_id, - refund_id, - payment_method_id, - payment_method, - payment_method_type, - customer_id, - user_id, - request_id, - flow_type, - api_name, - request, - response, - status_code, - url_path, - event_type, - now() as inserted_at, - created_at, - latency, - user_agent, - ip_addr -FROM - hyperswitch.api_events_queue -WHERE length(_error) = 0; - - -CREATE MATERIALIZED VIEW hyperswitch.api_events_parse_errors on cluster '{cluster}' -( - `topic` String, - `partition` Int64, - `offset` Int64, - `raw` String, - `error` String -) -ENGINE = MergeTree -ORDER BY (topic, partition, offset) -SETTINGS index_granularity = 8192 AS -SELECT - _topic AS topic, - _partition AS partition, - _offset AS offset, - _raw_message AS raw, - _error AS error -FROM hyperswitch.api_events_queue -WHERE length(_error) > 0 -; - - -ALTER TABLE hyperswitch.api_events_clustered on cluster '{cluster}' ADD COLUMN `url_path` LowCardinality(Nullable(String)); -ALTER TABLE hyperswitch.api_events_clustered on cluster '{cluster}' ADD COLUMN `event_type` LowCardinality(Nullable(String)); -ALTER TABLE hyperswitch.api_events_clustered on cluster '{cluster}' ADD COLUMN `dispute_id` Nullable(String); - -CREATE TABLE hyperswitch.api_audit_log ON CLUSTER '{cluster}' ( - `merchant_id` LowCardinality(String), - `payment_id` String, - `refund_id` Nullable(String), - `payment_method_id` Nullable(String), - `payment_method` Nullable(String), - `payment_method_type` Nullable(String), - `user_id` Nullable(String), - `request_id` Nullable(String), - `flow_type` LowCardinality(String), - `api_name` LowCardinality(String), - `request` String, - `response` String, - `status_code` UInt32, - `inserted_at` DateTime DEFAULT now() CODEC(T64, LZ4), - `created_at` DateTime DEFAULT now() CODEC(T64, LZ4), - `latency` Nullable(UInt128), - `user_agent` Nullable(String), - `ip_addr` Nullable(String), - `url_path` LowCardinality(Nullable(String)), - `event_type` LowCardinality(Nullable(String)), - `customer_id` LowCardinality(Nullable(String)) -) ENGINE = ReplicatedMergeTree( '/clickhouse/{installation}/{cluster}/tables/{shard}/hyperswitch/api_audit_log', '{replica}' ) PARTITION BY merchant_id -ORDER BY (merchant_id, payment_id) -TTL created_at + toIntervalMonth(18) -SETTINGS index_granularity = 8192 - - -CREATE MATERIALIZED VIEW hyperswitch.api_audit_log_mv ON CLUSTER `{cluster}` TO hyperswitch.api_audit_log( - `merchant_id` LowCardinality(String), - `payment_id` String, - `refund_id` Nullable(String), - `payment_method_id` Nullable(String), - `payment_method` Nullable(String), - `payment_method_type` Nullable(String), - `customer_id` Nullable(String), - `user_id` Nullable(String), - `request_id` Nullable(String), - `flow_type` LowCardinality(String), - `api_name` LowCardinality(String), - `request` String, - `response` String, - `status_code` UInt32, - `url_path` LowCardinality(Nullable(String)), - `event_type` LowCardinality(Nullable(String)), - `inserted_at` DateTime64(3), - `created_at` DateTime64(3), - `latency` Nullable(UInt128), - `user_agent` Nullable(String), - `ip_addr` Nullable(String), - `dispute_id` Nullable(String) -) AS -SELECT - merchant_id, - multiIf(payment_id IS NULL, '', payment_id) AS payment_id, - refund_id, - payment_method_id, - payment_method, - payment_method_type, - customer_id, - user_id, - request_id, - flow_type, - api_name, - request, - response, - status_code, - url_path, - api_event_type AS event_type, - now() AS inserted_at, - created_at, - latency, - user_agent, - ip_addr, - dispute_id -FROM hyperswitch.api_events_queue -WHERE length(_error) = 0 \ No newline at end of file diff --git a/crates/analytics/docs/clickhouse/cluster_setup/scripts/payment_attempts.sql b/crates/analytics/docs/clickhouse/cluster_setup/scripts/payment_attempts.sql deleted file mode 100644 index 3a6281ae905..00000000000 --- a/crates/analytics/docs/clickhouse/cluster_setup/scripts/payment_attempts.sql +++ /dev/null @@ -1,217 +0,0 @@ -CREATE TABLE hyperswitch.payment_attempt_queue on cluster '{cluster}' ( - `payment_id` String, - `merchant_id` String, - `attempt_id` String, - `status` LowCardinality(String), - `amount` Nullable(UInt32), - `currency` LowCardinality(Nullable(String)), - `connector` LowCardinality(Nullable(String)), - `save_to_locker` Nullable(Bool), - `error_message` Nullable(String), - `offer_amount` Nullable(UInt32), - `surcharge_amount` Nullable(UInt32), - `tax_amount` Nullable(UInt32), - `payment_method_id` Nullable(String), - `payment_method` LowCardinality(Nullable(String)), - `payment_method_type` LowCardinality(Nullable(String)), - `connector_transaction_id` Nullable(String), - `capture_method` LowCardinality(Nullable(String)), - `capture_on` Nullable(DateTime) CODEC(T64, LZ4), - `confirm` Bool, - `authentication_type` LowCardinality(Nullable(String)), - `cancellation_reason` Nullable(String), - `amount_to_capture` Nullable(UInt32), - `mandate_id` Nullable(String), - `browser_info` Nullable(String), - `error_code` Nullable(String), - `connector_metadata` Nullable(String), - `payment_experience` Nullable(String), - `created_at` DateTime CODEC(T64, LZ4), - `last_synced` Nullable(DateTime) CODEC(T64, LZ4), - `modified_at` DateTime CODEC(T64, LZ4), - `sign_flag` Int8 -) ENGINE = Kafka SETTINGS kafka_broker_list = 'kafka0:29092', -kafka_topic_list = 'hyperswitch-payment-attempt-events', -kafka_group_name = 'hyper-c1', -kafka_format = 'JSONEachRow', -kafka_handle_error_mode = 'stream'; - - -CREATE TABLE hyperswitch.payment_attempt_dist on cluster '{cluster}' ( - `payment_id` String, - `merchant_id` String, - `attempt_id` String, - `status` LowCardinality(String), - `amount` Nullable(UInt32), - `currency` LowCardinality(Nullable(String)), - `connector` LowCardinality(Nullable(String)), - `save_to_locker` Nullable(Bool), - `error_message` Nullable(String), - `offer_amount` Nullable(UInt32), - `surcharge_amount` Nullable(UInt32), - `tax_amount` Nullable(UInt32), - `payment_method_id` Nullable(String), - `payment_method` LowCardinality(Nullable(String)), - `payment_method_type` LowCardinality(Nullable(String)), - `connector_transaction_id` Nullable(String), - `capture_method` Nullable(String), - `capture_on` Nullable(DateTime) CODEC(T64, LZ4), - `confirm` Bool, - `authentication_type` LowCardinality(Nullable(String)), - `cancellation_reason` Nullable(String), - `amount_to_capture` Nullable(UInt32), - `mandate_id` Nullable(String), - `browser_info` Nullable(String), - `error_code` Nullable(String), - `connector_metadata` Nullable(String), - `payment_experience` Nullable(String), - `created_at` DateTime DEFAULT now() CODEC(T64, LZ4), - `last_synced` Nullable(DateTime) CODEC(T64, LZ4), - `modified_at` DateTime DEFAULT now() CODEC(T64, LZ4), - `inserted_at` DateTime DEFAULT now() CODEC(T64, LZ4), - `sign_flag` Int8 -) ENGINE = Distributed('{cluster}', 'hyperswitch', 'payment_attempt_clustered', cityHash64(attempt_id)); - - - -CREATE MATERIALIZED VIEW hyperswitch.payment_attempt_mv on cluster '{cluster}' TO hyperswitch.payment_attempt_dist ( - `payment_id` String, - `merchant_id` String, - `attempt_id` String, - `status` LowCardinality(String), - `amount` Nullable(UInt32), - `currency` LowCardinality(Nullable(String)), - `connector` LowCardinality(Nullable(String)), - `save_to_locker` Nullable(Bool), - `error_message` Nullable(String), - `offer_amount` Nullable(UInt32), - `surcharge_amount` Nullable(UInt32), - `tax_amount` Nullable(UInt32), - `payment_method_id` Nullable(String), - `payment_method` LowCardinality(Nullable(String)), - `payment_method_type` LowCardinality(Nullable(String)), - `connector_transaction_id` Nullable(String), - `capture_method` Nullable(String), - `confirm` Bool, - `authentication_type` LowCardinality(Nullable(String)), - `cancellation_reason` Nullable(String), - `amount_to_capture` Nullable(UInt32), - `mandate_id` Nullable(String), - `browser_info` Nullable(String), - `error_code` Nullable(String), - `connector_metadata` Nullable(String), - `payment_experience` Nullable(String), - `created_at` DateTime64(3), - `capture_on` Nullable(DateTime64(3)), - `last_synced` Nullable(DateTime64(3)), - `modified_at` DateTime64(3), - `inserted_at` DateTime64(3), - `sign_flag` Int8 -) AS -SELECT - payment_id, - merchant_id, - attempt_id, - status, - amount, - currency, - connector, - save_to_locker, - error_message, - offer_amount, - surcharge_amount, - tax_amount, - payment_method_id, - payment_method, - payment_method_type, - connector_transaction_id, - capture_method, - confirm, - authentication_type, - cancellation_reason, - amount_to_capture, - mandate_id, - browser_info, - error_code, - connector_metadata, - payment_experience, - created_at, - capture_on, - last_synced, - modified_at, - now() as inserted_at, - sign_flag -FROM - hyperswitch.payment_attempt_queue -WHERE length(_error) = 0; - - -CREATE TABLE hyperswitch.payment_attempt_clustered on cluster '{cluster}' ( - `payment_id` String, - `merchant_id` String, - `attempt_id` String, - `status` LowCardinality(String), - `amount` Nullable(UInt32), - `currency` LowCardinality(Nullable(String)), - `connector` LowCardinality(Nullable(String)), - `save_to_locker` Nullable(Bool), - `error_message` Nullable(String), - `offer_amount` Nullable(UInt32), - `surcharge_amount` Nullable(UInt32), - `tax_amount` Nullable(UInt32), - `payment_method_id` Nullable(String), - `payment_method` LowCardinality(Nullable(String)), - `payment_method_type` LowCardinality(Nullable(String)), - `connector_transaction_id` Nullable(String), - `capture_method` Nullable(String), - `capture_on` Nullable(DateTime) CODEC(T64, LZ4), - `confirm` Bool, - `authentication_type` LowCardinality(Nullable(String)), - `cancellation_reason` Nullable(String), - `amount_to_capture` Nullable(UInt32), - `mandate_id` Nullable(String), - `browser_info` Nullable(String), - `error_code` Nullable(String), - `connector_metadata` Nullable(String), - `payment_experience` Nullable(String), - `created_at` DateTime DEFAULT now() CODEC(T64, LZ4), - `last_synced` Nullable(DateTime) CODEC(T64, LZ4), - `modified_at` DateTime DEFAULT now() CODEC(T64, LZ4), - `inserted_at` DateTime DEFAULT now() CODEC(T64, LZ4), - `sign_flag` Int8, - INDEX connectorIndex connector TYPE bloom_filter GRANULARITY 1, - INDEX paymentMethodIndex payment_method TYPE bloom_filter GRANULARITY 1, - INDEX authenticationTypeIndex authentication_type TYPE bloom_filter GRANULARITY 1, - INDEX currencyIndex currency TYPE bloom_filter GRANULARITY 1, - INDEX statusIndex status TYPE bloom_filter GRANULARITY 1 -) ENGINE = ReplicatedCollapsingMergeTree( - '/clickhouse/{installation}/{cluster}/tables/{shard}/hyperswitch/payment_attempt_clustered', - '{replica}', - sign_flag -) -PARTITION BY toStartOfDay(created_at) -ORDER BY - (created_at, merchant_id, attempt_id) -TTL created_at + toIntervalMonth(6) -; - -CREATE MATERIALIZED VIEW hyperswitch.payment_attempt_parse_errors on cluster '{cluster}' -( - `topic` String, - `partition` Int64, - `offset` Int64, - `raw` String, - `error` String -) -ENGINE = MergeTree -ORDER BY (topic, partition, offset) -SETTINGS index_granularity = 8192 AS -SELECT - _topic AS topic, - _partition AS partition, - _offset AS offset, - _raw_message AS raw, - _error AS error -FROM hyperswitch.payment_attempt_queue -WHERE length(_error) > 0 -; \ No newline at end of file diff --git a/crates/analytics/docs/clickhouse/cluster_setup/scripts/payment_intents.sql b/crates/analytics/docs/clickhouse/cluster_setup/scripts/payment_intents.sql deleted file mode 100644 index eb2d83140e9..00000000000 --- a/crates/analytics/docs/clickhouse/cluster_setup/scripts/payment_intents.sql +++ /dev/null @@ -1,165 +0,0 @@ -CREATE TABLE hyperswitch.payment_intents_queue on cluster '{cluster}' ( - `payment_id` String, - `merchant_id` String, - `status` LowCardinality(String), - `amount` UInt32, - `currency` LowCardinality(Nullable(String)), - `amount_captured` Nullable(UInt32), - `customer_id` Nullable(String), - `description` Nullable(String), - `return_url` Nullable(String), - `connector_id` LowCardinality(Nullable(String)), - `statement_descriptor_name` Nullable(String), - `statement_descriptor_suffix` Nullable(String), - `setup_future_usage` LowCardinality(Nullable(String)), - `off_session` Nullable(Bool), - `client_secret` Nullable(String), - `active_attempt_id` String, - `business_country` String, - `business_label` String, - `modified_at` DateTime, - `created_at` DateTime, - `last_synced` Nullable(DateTime) CODEC(T64, LZ4), - `sign_flag` Int8 -) ENGINE = Kafka SETTINGS kafka_broker_list = 'kafka0:29092', -kafka_topic_list = 'hyperswitch-payment-intent-events', -kafka_group_name = 'hyper-c1', -kafka_format = 'JSONEachRow', -kafka_handle_error_mode = 'stream'; - -CREATE TABLE hyperswitch.payment_intents_dist on cluster '{cluster}' ( - `payment_id` String, - `merchant_id` String, - `status` LowCardinality(String), - `amount` UInt32, - `currency` LowCardinality(Nullable(String)), - `amount_captured` Nullable(UInt32), - `customer_id` Nullable(String), - `description` Nullable(String), - `return_url` Nullable(String), - `connector_id` LowCardinality(Nullable(String)), - `statement_descriptor_name` Nullable(String), - `statement_descriptor_suffix` Nullable(String), - `setup_future_usage` LowCardinality(Nullable(String)), - `off_session` Nullable(Bool), - `client_secret` Nullable(String), - `active_attempt_id` String, - `business_country` LowCardinality(String), - `business_label` String, - `modified_at` DateTime DEFAULT now() CODEC(T64, LZ4), - `created_at` DateTime DEFAULT now() CODEC(T64, LZ4), - `last_synced` Nullable(DateTime) CODEC(T64, LZ4), - `inserted_at` DateTime DEFAULT now() CODEC(T64, LZ4), - `sign_flag` Int8 -) ENGINE = Distributed('{cluster}', 'hyperswitch', 'payment_intents_clustered', cityHash64(payment_id)); - -CREATE TABLE hyperswitch.payment_intents_clustered on cluster '{cluster}' ( - `payment_id` String, - `merchant_id` String, - `status` LowCardinality(String), - `amount` UInt32, - `currency` LowCardinality(Nullable(String)), - `amount_captured` Nullable(UInt32), - `customer_id` Nullable(String), - `description` Nullable(String), - `return_url` Nullable(String), - `connector_id` LowCardinality(Nullable(String)), - `statement_descriptor_name` Nullable(String), - `statement_descriptor_suffix` Nullable(String), - `setup_future_usage` LowCardinality(Nullable(String)), - `off_session` Nullable(Bool), - `client_secret` Nullable(String), - `active_attempt_id` String, - `business_country` LowCardinality(String), - `business_label` String, - `modified_at` DateTime DEFAULT now() CODEC(T64, LZ4), - `created_at` DateTime DEFAULT now() CODEC(T64, LZ4), - `last_synced` Nullable(DateTime) CODEC(T64, LZ4), - `inserted_at` DateTime DEFAULT now() CODEC(T64, LZ4), - `sign_flag` Int8, - INDEX connectorIndex connector_id TYPE bloom_filter GRANULARITY 1, - INDEX currencyIndex currency TYPE bloom_filter GRANULARITY 1, - INDEX statusIndex status TYPE bloom_filter GRANULARITY 1 -) ENGINE = ReplicatedCollapsingMergeTree( - '/clickhouse/{installation}/{cluster}/tables/{shard}/hyperswitch/payment_intents_clustered', - '{replica}', - sign_flag -) -PARTITION BY toStartOfDay(created_at) -ORDER BY - (created_at, merchant_id, payment_id) -TTL created_at + toIntervalMonth(6) -; - -CREATE MATERIALIZED VIEW hyperswitch.payment_intent_mv on cluster '{cluster}' TO hyperswitch.payment_intents_dist ( - `payment_id` String, - `merchant_id` String, - `status` LowCardinality(String), - `amount` UInt32, - `currency` LowCardinality(Nullable(String)), - `amount_captured` Nullable(UInt32), - `customer_id` Nullable(String), - `description` Nullable(String), - `return_url` Nullable(String), - `connector_id` LowCardinality(Nullable(String)), - `statement_descriptor_name` Nullable(String), - `statement_descriptor_suffix` Nullable(String), - `setup_future_usage` LowCardinality(Nullable(String)), - `off_session` Nullable(Bool), - `client_secret` Nullable(String), - `active_attempt_id` String, - `business_country` LowCardinality(String), - `business_label` String, - `modified_at` DateTime64(3), - `created_at` DateTime64(3), - `last_synced` Nullable(DateTime64(3)), - `inserted_at` DateTime64(3), - `sign_flag` Int8 -) AS -SELECT - payment_id, - merchant_id, - status, - amount, - currency, - amount_captured, - customer_id, - description, - return_url, - connector_id, - statement_descriptor_name, - statement_descriptor_suffix, - setup_future_usage, - off_session, - client_secret, - active_attempt_id, - business_country, - business_label, - modified_at, - created_at, - last_synced, - now() as inserted_at, - sign_flag -FROM hyperswitch.payment_intents_queue -WHERE length(_error) = 0; - -CREATE MATERIALIZED VIEW hyperswitch.payment_intent_parse_errors on cluster '{cluster}' -( - `topic` String, - `partition` Int64, - `offset` Int64, - `raw` String, - `error` String -) -ENGINE = MergeTree -ORDER BY (topic, partition, offset) -SETTINGS index_granularity = 8192 AS -SELECT - _topic AS topic, - _partition AS partition, - _offset AS offset, - _raw_message AS raw, - _error AS error -FROM hyperswitch.payment_intents_queue -WHERE length(_error) > 0 -; diff --git a/crates/analytics/docs/clickhouse/cluster_setup/scripts/refund_analytics.sql b/crates/analytics/docs/clickhouse/cluster_setup/scripts/refund_analytics.sql deleted file mode 100644 index bf5f6e0e240..00000000000 --- a/crates/analytics/docs/clickhouse/cluster_setup/scripts/refund_analytics.sql +++ /dev/null @@ -1,173 +0,0 @@ -CREATE TABLE hyperswitch.refund_queue on cluster '{cluster}' ( - `internal_reference_id` String, - `refund_id` String, - `payment_id` String, - `merchant_id` String, - `connector_transaction_id` String, - `connector` LowCardinality(Nullable(String)), - `connector_refund_id` Nullable(String), - `external_reference_id` Nullable(String), - `refund_type` LowCardinality(String), - `total_amount` Nullable(UInt32), - `currency` LowCardinality(String), - `refund_amount` Nullable(UInt32), - `refund_status` LowCardinality(String), - `sent_to_gateway` Bool, - `refund_error_message` Nullable(String), - `refund_arn` Nullable(String), - `attempt_id` String, - `description` Nullable(String), - `refund_reason` Nullable(String), - `refund_error_code` Nullable(String), - `created_at` DateTime, - `modified_at` DateTime, - `sign_flag` Int8 -) ENGINE = Kafka SETTINGS kafka_broker_list = 'kafka0:29092', -kafka_topic_list = 'hyperswitch-refund-events', -kafka_group_name = 'hyper-c1', -kafka_format = 'JSONEachRow', -kafka_handle_error_mode = 'stream'; - -CREATE TABLE hyperswitch.refund_dist on cluster '{cluster}' ( - `internal_reference_id` String, - `refund_id` String, - `payment_id` String, - `merchant_id` String, - `connector_transaction_id` String, - `connector` LowCardinality(Nullable(String)), - `connector_refund_id` Nullable(String), - `external_reference_id` Nullable(String), - `refund_type` LowCardinality(String), - `total_amount` Nullable(UInt32), - `currency` LowCardinality(String), - `refund_amount` Nullable(UInt32), - `refund_status` LowCardinality(String), - `sent_to_gateway` Bool, - `refund_error_message` Nullable(String), - `refund_arn` Nullable(String), - `attempt_id` String, - `description` Nullable(String), - `refund_reason` Nullable(String), - `refund_error_code` Nullable(String), - `created_at` DateTime DEFAULT now() CODEC(T64, LZ4), - `modified_at` DateTime DEFAULT now() CODEC(T64, LZ4), - `inserted_at` DateTime DEFAULT now() CODEC(T64, LZ4), - `sign_flag` Int8 -) ENGINE = Distributed('{cluster}', 'hyperswitch', 'refund_clustered', cityHash64(refund_id)); - - - -CREATE TABLE hyperswitch.refund_clustered on cluster '{cluster}' ( - `internal_reference_id` String, - `refund_id` String, - `payment_id` String, - `merchant_id` String, - `connector_transaction_id` String, - `connector` LowCardinality(Nullable(String)), - `connector_refund_id` Nullable(String), - `external_reference_id` Nullable(String), - `refund_type` LowCardinality(String), - `total_amount` Nullable(UInt32), - `currency` LowCardinality(String), - `refund_amount` Nullable(UInt32), - `refund_status` LowCardinality(String), - `sent_to_gateway` Bool, - `refund_error_message` Nullable(String), - `refund_arn` Nullable(String), - `attempt_id` String, - `description` Nullable(String), - `refund_reason` Nullable(String), - `refund_error_code` Nullable(String), - `created_at` DateTime DEFAULT now() CODEC(T64, LZ4), - `modified_at` DateTime DEFAULT now() CODEC(T64, LZ4), - `inserted_at` DateTime DEFAULT now() CODEC(T64, LZ4), - `sign_flag` Int8, - INDEX connectorIndex connector TYPE bloom_filter GRANULARITY 1, - INDEX refundTypeIndex refund_type TYPE bloom_filter GRANULARITY 1, - INDEX currencyIndex currency TYPE bloom_filter GRANULARITY 1, - INDEX statusIndex refund_status TYPE bloom_filter GRANULARITY 1 -) ENGINE = ReplicatedCollapsingMergeTree( - '/clickhouse/{installation}/{cluster}/tables/{shard}/hyperswitch/refund_clustered', - '{replica}', - sign_flag -) -PARTITION BY toStartOfDay(created_at) -ORDER BY - (created_at, merchant_id, refund_id) -TTL created_at + toIntervalMonth(6) -; - -CREATE MATERIALIZED VIEW hyperswitch.kafka_parse_refund on cluster '{cluster}' TO hyperswitch.refund_dist ( - `internal_reference_id` String, - `refund_id` String, - `payment_id` String, - `merchant_id` String, - `connector_transaction_id` String, - `connector` LowCardinality(Nullable(String)), - `connector_refund_id` Nullable(String), - `external_reference_id` Nullable(String), - `refund_type` LowCardinality(String), - `total_amount` Nullable(UInt32), - `currency` LowCardinality(String), - `refund_amount` Nullable(UInt32), - `refund_status` LowCardinality(String), - `sent_to_gateway` Bool, - `refund_error_message` Nullable(String), - `refund_arn` Nullable(String), - `attempt_id` String, - `description` Nullable(String), - `refund_reason` Nullable(String), - `refund_error_code` Nullable(String), - `created_at` DateTime64(3), - `modified_at` DateTime64(3), - `inserted_at` DateTime64(3), - `sign_flag` Int8 -) AS -SELECT - internal_reference_id, - refund_id, - payment_id, - merchant_id, - connector_transaction_id, - connector, - connector_refund_id, - external_reference_id, - refund_type, - total_amount, - currency, - refund_amount, - refund_status, - sent_to_gateway, - refund_error_message, - refund_arn, - attempt_id, - description, - refund_reason, - refund_error_code, - created_at, - modified_at, - now() as inserted_at, - sign_flag -FROM hyperswitch.refund_queue -WHERE length(_error) = 0; - -CREATE MATERIALIZED VIEW hyperswitch.refund_parse_errors on cluster '{cluster}' -( - `topic` String, - `partition` Int64, - `offset` Int64, - `raw` String, - `error` String -) -ENGINE = MergeTree -ORDER BY (topic, partition, offset) -SETTINGS index_granularity = 8192 AS -SELECT - _topic AS topic, - _partition AS partition, - _offset AS offset, - _raw_message AS raw, - _error AS error -FROM hyperswitch.refund_queue -WHERE length(_error) > 0 -; \ No newline at end of file diff --git a/crates/analytics/docs/clickhouse/cluster_setup/scripts/sdk_events.sql b/crates/analytics/docs/clickhouse/cluster_setup/scripts/sdk_events.sql deleted file mode 100644 index 37766392bc7..00000000000 --- a/crates/analytics/docs/clickhouse/cluster_setup/scripts/sdk_events.sql +++ /dev/null @@ -1,156 +0,0 @@ -CREATE TABLE hyperswitch.sdk_events_queue on cluster '{cluster}' ( - `payment_id` Nullable(String), - `merchant_id` String, - `remote_ip` Nullable(String), - `log_type` LowCardinality(Nullable(String)), - `event_name` LowCardinality(Nullable(String)), - `first_event` LowCardinality(Nullable(String)), - `latency` Nullable(UInt32), - `timestamp` String, - `browser_name` LowCardinality(Nullable(String)), - `browser_version` Nullable(String), - `platform` LowCardinality(Nullable(String)), - `source` LowCardinality(Nullable(String)), - `category` LowCardinality(Nullable(String)), - `version` LowCardinality(Nullable(String)), - `value` Nullable(String), - `component` LowCardinality(Nullable(String)), - `payment_method` LowCardinality(Nullable(String)), - `payment_experience` LowCardinality(Nullable(String)) -) ENGINE = Kafka SETTINGS - kafka_broker_list = 'hyper-c1-kafka-brokers.kafka-cluster.svc.cluster.local:9092', - kafka_topic_list = 'hyper-sdk-logs', - kafka_group_name = 'hyper-c1', - kafka_format = 'JSONEachRow', - kafka_handle_error_mode = 'stream'; - -CREATE TABLE hyperswitch.sdk_events_clustered on cluster '{cluster}' ( - `payment_id` Nullable(String), - `merchant_id` String, - `remote_ip` Nullable(String), - `log_type` LowCardinality(Nullable(String)), - `event_name` LowCardinality(Nullable(String)), - `first_event` Bool DEFAULT 1, - `browser_name` LowCardinality(Nullable(String)), - `browser_version` Nullable(String), - `platform` LowCardinality(Nullable(String)), - `source` LowCardinality(Nullable(String)), - `category` LowCardinality(Nullable(String)), - `version` LowCardinality(Nullable(String)), - `value` Nullable(String), - `component` LowCardinality(Nullable(String)), - `payment_method` LowCardinality(Nullable(String)), - `payment_experience` LowCardinality(Nullable(String)) DEFAULT '', - `created_at` DateTime64(3) DEFAULT now64() CODEC(T64, LZ4), - `inserted_at` DateTime64(3) DEFAULT now64() CODEC(T64, LZ4), - `latency` Nullable(UInt32) DEFAULT 0, - INDEX paymentMethodIndex payment_method TYPE bloom_filter GRANULARITY 1, - INDEX eventIndex event_name TYPE bloom_filter GRANULARITY 1, - INDEX platformIndex platform TYPE bloom_filter GRANULARITY 1, - INDEX logTypeIndex log_type TYPE bloom_filter GRANULARITY 1, - INDEX categoryIndex category TYPE bloom_filter GRANULARITY 1, - INDEX sourceIndex source TYPE bloom_filter GRANULARITY 1, - INDEX componentIndex component TYPE bloom_filter GRANULARITY 1, - INDEX firstEventIndex first_event TYPE bloom_filter GRANULARITY 1 -) ENGINE = ReplicatedMergeTree( - '/clickhouse/{installation}/{cluster}/tables/{shard}/hyperswitch/sdk_events_clustered', '{replica}' -) -PARTITION BY - toStartOfDay(created_at) -ORDER BY - (created_at, merchant_id) -TTL - toDateTime(created_at) + toIntervalMonth(6) -SETTINGS - index_granularity = 8192 -; - -CREATE TABLE hyperswitch.sdk_events_dist on cluster '{cluster}' ( - `payment_id` Nullable(String), - `merchant_id` String, - `remote_ip` Nullable(String), - `log_type` LowCardinality(Nullable(String)), - `event_name` LowCardinality(Nullable(String)), - `first_event` Bool DEFAULT 1, - `browser_name` LowCardinality(Nullable(String)), - `browser_version` Nullable(String), - `platform` LowCardinality(Nullable(String)), - `source` LowCardinality(Nullable(String)), - `category` LowCardinality(Nullable(String)), - `version` LowCardinality(Nullable(String)), - `value` Nullable(String), - `component` LowCardinality(Nullable(String)), - `payment_method` LowCardinality(Nullable(String)), - `payment_experience` LowCardinality(Nullable(String)) DEFAULT '', - `created_at` DateTime64(3) DEFAULT now64() CODEC(T64, LZ4), - `inserted_at` DateTime64(3) DEFAULT now64() CODEC(T64, LZ4), - `latency` Nullable(UInt32) DEFAULT 0 -) ENGINE = Distributed( - '{cluster}', 'hyperswitch', 'sdk_events_clustered', rand() -); - -CREATE MATERIALIZED VIEW hyperswitch.sdk_events_mv on cluster '{cluster}' TO hyperswitch.sdk_events_dist ( - `payment_id` Nullable(String), - `merchant_id` String, - `remote_ip` Nullable(String), - `log_type` LowCardinality(Nullable(String)), - `event_name` LowCardinality(Nullable(String)), - `first_event` Bool, - `latency` Nullable(UInt32), - `browser_name` LowCardinality(Nullable(String)), - `browser_version` Nullable(String), - `platform` LowCardinality(Nullable(String)), - `source` LowCardinality(Nullable(String)), - `category` LowCardinality(Nullable(String)), - `version` LowCardinality(Nullable(String)), - `value` Nullable(String), - `component` LowCardinality(Nullable(String)), - `payment_method` LowCardinality(Nullable(String)), - `payment_experience` LowCardinality(Nullable(String)), - `created_at` DateTime64(3) -) AS -SELECT - payment_id, - merchant_id, - remote_ip, - log_type, - event_name, - multiIf(first_event = 'true', 1, 0) AS first_event, - latency, - browser_name, - browser_version, - platform, - source, - category, - version, - value, - component, - payment_method, - payment_experience, - toDateTime64(timestamp, 3) AS created_at -FROM - hyperswitch.sdk_events_queue -WHERE length(_error) = 0 -; - -CREATE MATERIALIZED VIEW hyperswitch.sdk_parse_errors on cluster '{cluster}' ( - `topic` String, - `partition` Int64, - `offset` Int64, - `raw` String, - `error` String -) ENGINE = MergeTree - ORDER BY (topic, partition, offset) -SETTINGS - index_granularity = 8192 AS -SELECT - _topic AS topic, - _partition AS partition, - _offset AS offset, - _raw_message AS raw, - _error AS error -FROM - hyperswitch.sdk_events_queue -WHERE - length(_error) > 0 -; diff --git a/crates/analytics/docs/clickhouse/cluster_setup/scripts/seed_scripts.sql b/crates/analytics/docs/clickhouse/cluster_setup/scripts/seed_scripts.sql deleted file mode 100644 index 202b94ac604..00000000000 --- a/crates/analytics/docs/clickhouse/cluster_setup/scripts/seed_scripts.sql +++ /dev/null @@ -1 +0,0 @@ -create database hyperswitch on cluster '{cluster}'; \ No newline at end of file diff --git a/crates/analytics/docs/clickhouse/scripts/connector_events.sql b/crates/analytics/docs/clickhouse/scripts/connector_events.sql index 4a53f9edb0b..47bbd7aec00 100644 --- a/crates/analytics/docs/clickhouse/scripts/connector_events.sql +++ b/crates/analytics/docs/clickhouse/scripts/connector_events.sql @@ -6,6 +6,7 @@ CREATE TABLE connector_events_queue ( `flow` LowCardinality(String), `request` String, `response` Nullable(String), + `masked_response` Nullable(String), `error` Nullable(String), `status_code` UInt32, `created_at` DateTime64(3), @@ -28,22 +29,23 @@ CREATE TABLE connector_events_dist ( `flow` LowCardinality(String), `request` String, `response` Nullable(String), + `masked_response` Nullable(String), `error` Nullable(String), `status_code` UInt32, `created_at` DateTime64(3), - `inserted_at` DateTime64(3), + `inserted_at` DateTime DEFAULT now() CODEC(T64, LZ4), `latency` UInt128, `method` LowCardinality(String), `refund_id` Nullable(String), `dispute_id` Nullable(String), - INDEX flowIndex flowTYPE bloom_filter GRANULARITY 1, + INDEX flowIndex flow TYPE bloom_filter GRANULARITY 1, INDEX connectorIndex connector_name TYPE bloom_filter GRANULARITY 1, INDEX statusIndex status_code TYPE bloom_filter GRANULARITY 1 ) ENGINE = MergeTree PARTITION BY toStartOfDay(created_at) ORDER BY - (created_at, merchant_id, flow_type, status_code, api_flow) -TTL created_at + toIntervalMonth(6) + (created_at, merchant_id, connector_name, flow) +TTL inserted_at + toIntervalMonth(6) ; CREATE MATERIALIZED VIEW connector_events_mv TO connector_events_dist ( @@ -54,6 +56,7 @@ CREATE MATERIALIZED VIEW connector_events_mv TO connector_events_dist ( `flow` LowCardinality(String), `request` String, `response` Nullable(String), + `masked_response` Nullable(String), `error` Nullable(String), `status_code` UInt32, `created_at` DateTime64(3), @@ -70,6 +73,7 @@ SELECT flow, request, response, + masked_response, error, status_code, created_at, diff --git a/crates/analytics/src/connector_events/events.rs b/crates/analytics/src/connector_events/events.rs index 47044811a8b..0a13074d729 100644 --- a/crates/analytics/src/connector_events/events.rs +++ b/crates/analytics/src/connector_events/events.rs @@ -62,6 +62,7 @@ pub struct ConnectorEventsResult { pub request_id: Option<String>, pub flow: String, pub request: String, + #[serde(rename = "masked_response")] pub response: Option<String>, pub error: Option<String>, pub status_code: u16, diff --git a/crates/router/src/connector/aci.rs b/crates/router/src/connector/aci.rs index bbb88209b27..b20b27f0228 100644 --- a/crates/router/src/connector/aci.rs +++ b/crates/router/src/connector/aci.rs @@ -11,6 +11,7 @@ use super::utils::PaymentsAuthorizeRequestData; use crate::{ configs::settings, core::errors::{self, CustomResult}, + events::connector_api_logs::ConnectorEvent, headers, services::{ self, @@ -58,11 +59,14 @@ impl ConnectorCommon for Aci { fn build_error_response( &self, res: types::Response, + event_builder: Option<&mut ConnectorEvent>, ) -> CustomResult<types::ErrorResponse, errors::ConnectorError> { let response: aci::AciErrorResponse = res .response .parse_struct("AciErrorResponse") .change_context(errors::ConnectorError::ResponseDeserializationFailed)?; + event_builder.map(|i| i.set_error_response_body(&response)); + router_env::logger::info!(connector_response=?response); Ok(types::ErrorResponse { status_code: res.status_code, code: response.result.code, @@ -221,6 +225,7 @@ impl fn handle_response( &self, data: &types::PaymentsSyncRouterData, + event_builder: Option<&mut ConnectorEvent>, res: types::Response, ) -> CustomResult<types::PaymentsSyncRouterData, errors::ConnectorError> where @@ -231,6 +236,8 @@ impl res.response .parse_struct("AciPaymentsResponse") .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(), @@ -242,8 +249,9 @@ impl fn get_error_response( &self, res: types::Response, + event_builder: Option<&mut ConnectorEvent>, ) -> CustomResult<types::ErrorResponse, errors::ConnectorError> { - self.build_error_response(res) + self.build_error_response(res, event_builder) } } @@ -335,12 +343,15 @@ impl fn handle_response( &self, data: &types::PaymentsAuthorizeRouterData, + event_builder: Option<&mut ConnectorEvent>, res: types::Response, ) -> CustomResult<types::PaymentsAuthorizeRouterData, errors::ConnectorError> { let response: aci::AciPaymentsResponse = res.response .parse_struct("AciPaymentsResponse") .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(), @@ -352,8 +363,9 @@ impl fn get_error_response( &self, res: types::Response, + event_builder: Option<&mut ConnectorEvent>, ) -> CustomResult<types::ErrorResponse, errors::ConnectorError> { - self.build_error_response(res) + self.build_error_response(res, event_builder) } } @@ -422,12 +434,15 @@ impl fn handle_response( &self, data: &types::PaymentsCancelRouterData, + event_builder: Option<&mut ConnectorEvent>, res: types::Response, ) -> CustomResult<types::PaymentsCancelRouterData, errors::ConnectorError> { let response: aci::AciPaymentsResponse = res.response .parse_struct("AciPaymentsResponse") .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(), @@ -439,8 +454,9 @@ impl fn get_error_response( &self, res: types::Response, + event_builder: Option<&mut ConnectorEvent>, ) -> CustomResult<types::ErrorResponse, errors::ConnectorError> { - self.build_error_response(res) + self.build_error_response(res, event_builder) } } @@ -522,12 +538,16 @@ impl services::ConnectorIntegration<api::Execute, types::RefundsData, types::Ref fn handle_response( &self, data: &types::RefundsRouterData<api::Execute>, + event_builder: Option<&mut ConnectorEvent>, res: types::Response, ) -> CustomResult<types::RefundsRouterData<api::Execute>, errors::ConnectorError> { let response: aci::AciRefundResponse = res .response .parse_struct("AciRefundResponse") .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(), @@ -538,8 +558,9 @@ impl services::ConnectorIntegration<api::Execute, types::RefundsData, types::Ref fn get_error_response( &self, res: types::Response, + event_builder: Option<&mut ConnectorEvent>, ) -> CustomResult<types::ErrorResponse, errors::ConnectorError> { - self.build_error_response(res) + self.build_error_response(res, event_builder) } } diff --git a/crates/router/src/connector/aci/transformers.rs b/crates/router/src/connector/aci/transformers.rs index 92c7e164c4c..ed56fc5f524 100644 --- a/crates/router/src/connector/aci/transformers.rs +++ b/crates/router/src/connector/aci/transformers.rs @@ -653,7 +653,7 @@ impl FromStr for AciPaymentStatus { } } -#[derive(Debug, Default, Clone, Deserialize, PartialEq, Eq)] +#[derive(Debug, Default, Clone, Deserialize, PartialEq, Eq, Serialize)] #[serde(rename_all = "camelCase")] pub struct AciPaymentsResponse { id: String, @@ -666,7 +666,7 @@ pub struct AciPaymentsResponse { pub(super) redirect: Option<AciRedirectionData>, } -#[derive(Debug, Default, Clone, Deserialize, PartialEq, Eq)] +#[derive(Debug, Default, Clone, Deserialize, PartialEq, Eq, Serialize)] #[serde(rename_all = "camelCase")] pub struct AciErrorResponse { ndc: String, @@ -675,7 +675,7 @@ pub struct AciErrorResponse { pub(super) result: ResultCode, } -#[derive(Clone, Debug, Deserialize, PartialEq, Eq)] +#[derive(Clone, Debug, Deserialize, PartialEq, Eq, Serialize)] #[serde(rename_all = "camelCase")] pub struct AciRedirectionData { method: Option<services::Method>, @@ -683,13 +683,13 @@ pub struct AciRedirectionData { url: Url, } -#[derive(Clone, Debug, Deserialize, PartialEq, Eq)] +#[derive(Clone, Debug, Deserialize, PartialEq, Eq, Serialize)] pub struct Parameters { name: String, value: String, } -#[derive(Default, Debug, Clone, Deserialize, PartialEq, Eq)] +#[derive(Default, Debug, Clone, Deserialize, PartialEq, Eq, Serialize)] #[serde(rename_all = "camelCase")] pub struct ResultCode { pub(super) code: String, @@ -697,7 +697,7 @@ pub struct ResultCode { pub(super) parameter_errors: Option<Vec<ErrorParameters>>, } -#[derive(Default, Debug, Clone, Deserialize, PartialEq, Eq)] +#[derive(Default, Debug, Clone, Deserialize, PartialEq, Eq, Serialize)] pub struct ErrorParameters { pub(super) name: String, pub(super) value: Option<String>, @@ -824,7 +824,7 @@ impl From<AciRefundStatus> for enums::RefundStatus { } #[allow(dead_code)] -#[derive(Debug, Clone, Deserialize)] +#[derive(Debug, Clone, Deserialize, Serialize)] #[serde(rename_all = "camelCase")] pub struct AciRefundResponse { id: String, diff --git a/crates/router/src/connector/adyen.rs b/crates/router/src/connector/adyen.rs index fa9a5617ffb..554de564b68 100644 --- a/crates/router/src/connector/adyen.rs +++ b/crates/router/src/connector/adyen.rs @@ -16,6 +16,7 @@ use crate::{ configs::settings, consts, core::errors::{self, CustomResult}, + events::connector_api_logs::ConnectorEvent, headers, logger, services::{ self, @@ -61,11 +62,16 @@ impl ConnectorCommon for Adyen { fn build_error_response( &self, res: types::Response, + event_builder: Option<&mut ConnectorEvent>, ) -> CustomResult<types::ErrorResponse, errors::ConnectorError> { let response: adyen::ErrorResponse = res .response .parse_struct("ErrorResponse") .change_context(errors::ConnectorError::ResponseDeserializationFailed)?; + + event_builder.map(|i| i.set_error_response_body(&response)); + router_env::logger::info!(connector_response=?response); + Ok(types::ErrorResponse { status_code: res.status_code, code: response.error_code, @@ -207,6 +213,7 @@ impl fn handle_response( &self, data: &types::SetupMandateRouterData, + event_builder: Option<&mut ConnectorEvent>, res: types::Response, ) -> CustomResult< types::RouterData< @@ -225,6 +232,8 @@ impl .response .parse_struct("AdyenPaymentResponse") .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, @@ -240,19 +249,9 @@ impl fn get_error_response( &self, res: types::Response, + event_builder: Option<&mut ConnectorEvent>, ) -> CustomResult<types::ErrorResponse, errors::ConnectorError> { - let response: adyen::ErrorResponse = res - .response - .parse_struct("ErrorResponse") - .change_context(errors::ConnectorError::ResponseDeserializationFailed)?; - Ok(types::ErrorResponse { - status_code: res.status_code, - code: response.error_code, - message: response.message, - reason: None, - attempt_status: None, - connector_transaction_id: None, - }) + self.build_error_response(res, event_builder) } } @@ -338,13 +337,15 @@ impl fn handle_response( &self, data: &types::PaymentsCaptureRouterData, + event_builder: Option<&mut ConnectorEvent>, res: types::Response, ) -> CustomResult<types::PaymentsCaptureRouterData, errors::ConnectorError> { let response: adyen::AdyenCaptureResponse = res .response .parse_struct("AdyenCaptureResponse") .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(), @@ -355,19 +356,9 @@ impl fn get_error_response( &self, res: types::Response, + event_builder: Option<&mut ConnectorEvent>, ) -> CustomResult<types::ErrorResponse, errors::ConnectorError> { - let response: adyen::ErrorResponse = res - .response - .parse_struct("adyen::ErrorResponse") - .change_context(errors::ConnectorError::ResponseDeserializationFailed)?; - Ok(types::ErrorResponse { - status_code: res.status_code, - code: response.error_code, - message: response.message, - reason: None, - attempt_status: None, - connector_transaction_id: None, - }) + self.build_error_response(res, event_builder) } } @@ -488,6 +479,7 @@ impl fn handle_response( &self, data: &types::RouterData<api::PSync, types::PaymentsSyncData, types::PaymentsResponseData>, + event_builder: Option<&mut ConnectorEvent>, res: types::Response, ) -> CustomResult<types::PaymentsSyncRouterData, errors::ConnectorError> { logger::debug!(payment_sync_response=?res); @@ -495,6 +487,8 @@ impl .response .parse_struct("AdyenPaymentResponse") .change_context(errors::ConnectorError::ResponseDeserializationFailed)?; + event_builder.map(|i| i.set_response_body(&response)); + router_env::logger::info!(connector_response=?response); let is_multiple_capture_sync = match data.request.sync_type { types::SyncRequestType::MultipleCaptureSync(_) => true, types::SyncRequestType::SinglePaymentSync => false, @@ -515,19 +509,9 @@ impl fn get_error_response( &self, res: types::Response, + event_builder: Option<&mut ConnectorEvent>, ) -> CustomResult<types::ErrorResponse, errors::ConnectorError> { - let response: adyen::ErrorResponse = res - .response - .parse_struct("ErrorResponse") - .change_context(errors::ConnectorError::ResponseDeserializationFailed)?; - Ok(types::ErrorResponse { - status_code: res.status_code, - code: response.error_code, - message: response.message, - reason: None, - attempt_status: None, - connector_transaction_id: None, - }) + self.build_error_response(res, event_builder) } fn get_multiple_capture_sync_method( @@ -615,12 +599,15 @@ impl fn handle_response( &self, data: &types::PaymentsAuthorizeRouterData, + event_builder: Option<&mut ConnectorEvent>, res: types::Response, ) -> CustomResult<types::PaymentsAuthorizeRouterData, errors::ConnectorError> { let response: adyen::AdyenPaymentResponse = res .response .parse_struct("AdyenPaymentResponse") .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, @@ -637,19 +624,9 @@ impl fn get_error_response( &self, res: types::Response, + event_builder: Option<&mut ConnectorEvent>, ) -> CustomResult<types::ErrorResponse, errors::ConnectorError> { - let response: adyen::ErrorResponse = res - .response - .parse_struct("ErrorResponse") - .change_context(errors::ConnectorError::ResponseDeserializationFailed)?; - Ok(types::ErrorResponse { - status_code: res.status_code, - code: response.error_code, - message: response.message, - reason: None, - attempt_status: None, - connector_transaction_id: None, - }) + self.build_error_response(res, event_builder) } } @@ -724,12 +701,15 @@ impl fn handle_response( &self, data: &types::PaymentsPreProcessingRouterData, + event_builder: Option<&mut ConnectorEvent>, res: types::Response, ) -> CustomResult<types::PaymentsPreProcessingRouterData, errors::ConnectorError> { let response: adyen::AdyenBalanceResponse = res .response .parse_struct("AdyenBalanceResponse") .change_context(errors::ConnectorError::ResponseDeserializationFailed)?; + event_builder.map(|i| i.set_response_body(&response)); + router_env::logger::info!(connector_response=?response); let currency = match data.request.currency { Some(currency) => currency, @@ -769,8 +749,9 @@ impl fn get_error_response( &self, res: types::Response, + event_builder: Option<&mut ConnectorEvent>, ) -> CustomResult<types::ErrorResponse, errors::ConnectorError> { - self.build_error_response(res) + self.build_error_response(res, event_builder) } } @@ -840,12 +821,15 @@ impl fn handle_response( &self, data: &types::PaymentsCancelRouterData, + event_builder: Option<&mut ConnectorEvent>, res: types::Response, ) -> CustomResult<types::PaymentsCancelRouterData, errors::ConnectorError> { let response: adyen::AdyenCancelResponse = res .response .parse_struct("AdyenCancelResponse") .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(), @@ -857,19 +841,9 @@ impl fn get_error_response( &self, res: types::Response, + event_builder: Option<&mut ConnectorEvent>, ) -> CustomResult<types::ErrorResponse, errors::ConnectorError> { - let response: adyen::ErrorResponse = res - .response - .parse_struct("ErrorResponse") - .change_context(errors::ConnectorError::ResponseDeserializationFailed)?; - Ok(types::ErrorResponse { - status_code: res.status_code, - code: response.error_code, - message: response.message, - reason: None, - attempt_status: None, - connector_transaction_id: None, - }) + self.build_error_response(res, event_builder) } } @@ -950,12 +924,15 @@ impl services::ConnectorIntegration<api::PoCancel, types::PayoutsData, types::Pa fn handle_response( &self, data: &types::PayoutsRouterData<api::PoCancel>, + event_builder: Option<&mut ConnectorEvent>, res: types::Response, ) -> CustomResult<types::PayoutsRouterData<api::PoCancel>, errors::ConnectorError> { let response: adyen::AdyenPayoutResponse = res .response .parse_struct("AdyenPayoutResponse") .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(), @@ -966,8 +943,9 @@ impl services::ConnectorIntegration<api::PoCancel, types::PayoutsData, types::Pa fn get_error_response( &self, res: types::Response, + event_builder: Option<&mut ConnectorEvent>, ) -> CustomResult<types::ErrorResponse, errors::ConnectorError> { - self.build_error_response(res) + self.build_error_response(res, event_builder) } } @@ -1039,12 +1017,15 @@ impl services::ConnectorIntegration<api::PoCreate, types::PayoutsData, types::Pa fn handle_response( &self, data: &types::PayoutsRouterData<api::PoCreate>, + event_builder: Option<&mut ConnectorEvent>, res: types::Response, ) -> CustomResult<types::PayoutsRouterData<api::PoCreate>, errors::ConnectorError> { let response: adyen::AdyenPayoutResponse = res .response .parse_struct("AdyenPayoutResponse") .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(), @@ -1055,8 +1036,9 @@ impl services::ConnectorIntegration<api::PoCreate, types::PayoutsData, types::Pa fn get_error_response( &self, res: types::Response, + event_builder: Option<&mut ConnectorEvent>, ) -> CustomResult<types::ErrorResponse, errors::ConnectorError> { - self.build_error_response(res) + self.build_error_response(res, event_builder) } } @@ -1133,12 +1115,15 @@ impl fn handle_response( &self, data: &types::PayoutsRouterData<api::PoEligibility>, + event_builder: Option<&mut ConnectorEvent>, res: types::Response, ) -> CustomResult<types::PayoutsRouterData<api::PoEligibility>, errors::ConnectorError> { let response: adyen::AdyenPayoutResponse = res .response .parse_struct("AdyenPayoutResponse") .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(), @@ -1149,8 +1134,9 @@ impl fn get_error_response( &self, res: types::Response, + event_builder: Option<&mut ConnectorEvent>, ) -> CustomResult<types::ErrorResponse, errors::ConnectorError> { - self.build_error_response(res) + self.build_error_response(res, event_builder) } } @@ -1239,12 +1225,15 @@ impl services::ConnectorIntegration<api::PoFulfill, types::PayoutsData, types::P fn handle_response( &self, data: &types::PayoutsRouterData<api::PoFulfill>, + event_builder: Option<&mut ConnectorEvent>, res: types::Response, ) -> CustomResult<types::PayoutsRouterData<api::PoFulfill>, errors::ConnectorError> { let response: adyen::AdyenPayoutResponse = res .response .parse_struct("AdyenPayoutResponse") .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(), @@ -1255,8 +1244,9 @@ impl services::ConnectorIntegration<api::PoFulfill, types::PayoutsData, types::P fn get_error_response( &self, res: types::Response, + event_builder: Option<&mut ConnectorEvent>, ) -> CustomResult<types::ErrorResponse, errors::ConnectorError> { - self.build_error_response(res) + self.build_error_response(res, event_builder) } } @@ -1336,12 +1326,15 @@ impl services::ConnectorIntegration<api::Execute, types::RefundsData, types::Ref fn handle_response( &self, data: &types::RefundsRouterData<api::Execute>, + event_builder: Option<&mut ConnectorEvent>, res: types::Response, ) -> CustomResult<types::RefundsRouterData<api::Execute>, errors::ConnectorError> { let response: adyen::AdyenRefundResponse = res .response .parse_struct("AdyenRefundResponse") .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(), @@ -1353,19 +1346,9 @@ impl services::ConnectorIntegration<api::Execute, types::RefundsData, types::Ref fn get_error_response( &self, res: types::Response, + event_builder: Option<&mut ConnectorEvent>, ) -> CustomResult<types::ErrorResponse, errors::ConnectorError> { - let response: adyen::ErrorResponse = res - .response - .parse_struct("ErrorResponse") - .change_context(errors::ConnectorError::ResponseDeserializationFailed)?; - Ok(types::ErrorResponse { - status_code: res.status_code, - code: response.error_code, - message: response.message, - reason: None, - attempt_status: None, - connector_transaction_id: None, - }) + self.build_error_response(res, event_builder) } } diff --git a/crates/router/src/connector/adyen/transformers.rs b/crates/router/src/connector/adyen/transformers.rs index 0d8343b0c86..a79826e2f19 100644 --- a/crates/router/src/connector/adyen/transformers.rs +++ b/crates/router/src/connector/adyen/transformers.rs @@ -208,7 +208,7 @@ pub struct AdyenBalanceRequest<'a> { pub merchant_account: Secret<String>, } -#[derive(Debug, Deserialize)] +#[derive(Debug, Deserialize, Serialize)] #[serde(rename_all = "camelCase")] pub struct AdyenBalanceResponse { pub psp_reference: String, @@ -297,7 +297,7 @@ pub struct AdyenThreeDS { pub result_code: Option<String>, } -#[derive(Debug, Clone, Deserialize)] +#[derive(Debug, Clone, Deserialize, Serialize)] #[serde(untagged)] pub enum AdyenPaymentResponse { Response(Box<Response>), @@ -328,7 +328,7 @@ pub struct RedirectionErrorResponse { refusal_reason: String, } -#[derive(Debug, Clone, Deserialize)] +#[derive(Debug, Clone, Deserialize, Serialize)] #[serde(rename_all = "camelCase")] pub struct RedirectionResponse { result_code: AdyenStatus, @@ -337,7 +337,7 @@ pub struct RedirectionResponse { refusal_reason_code: Option<String>, } -#[derive(Debug, Clone, Deserialize)] +#[derive(Debug, Clone, Deserialize, Serialize)] #[serde(rename_all = "camelCase")] pub struct PresentToShopperResponse { psp_reference: Option<String>, @@ -347,7 +347,7 @@ pub struct PresentToShopperResponse { refusal_reason_code: Option<String>, } -#[derive(Debug, Clone, Deserialize)] +#[derive(Debug, Clone, Deserialize, Serialize)] #[serde(rename_all = "camelCase")] pub struct QrCodeResponseResponse { result_code: AdyenStatus, @@ -1077,14 +1077,14 @@ pub struct AdyenCancelRequest { reference: String, } -#[derive(Default, Debug, Deserialize)] +#[derive(Default, Debug, Deserialize, Serialize)] #[serde(rename_all = "camelCase")] pub struct AdyenCancelResponse { psp_reference: String, status: CancelStatus, } -#[derive(Default, Debug, Deserialize)] +#[derive(Default, Debug, Deserialize, Serialize)] #[serde(rename_all = "lowercase")] pub enum CancelStatus { Received, diff --git a/crates/router/src/connector/airwallex.rs b/crates/router/src/connector/airwallex.rs index 19d69b688c9..103c5852ac4 100644 --- a/crates/router/src/connector/airwallex.rs +++ b/crates/router/src/connector/airwallex.rs @@ -18,6 +18,7 @@ use crate::{ errors::{self, CustomResult}, payments, }, + events::connector_api_logs::ConnectorEvent, headers, logger, routes, services::{ self, @@ -83,6 +84,7 @@ impl ConnectorCommon for Airwallex { fn build_error_response( &self, res: Response, + event_builder: Option<&mut ConnectorEvent>, ) -> CustomResult<ErrorResponse, errors::ConnectorError> { logger::debug!(payu_error_response=?res); let response: airwallex::AirwallexErrorResponse = res @@ -90,6 +92,9 @@ impl ConnectorCommon for Airwallex { .parse_struct("Airwallex ErrorResponse") .change_context(errors::ConnectorError::ResponseDeserializationFailed)?; + event_builder.map(|i| i.set_error_response_body(&response)); + router_env::logger::info!(connector_response=?response); + Ok(ErrorResponse { status_code: res.status_code, code: response.code, @@ -205,6 +210,7 @@ impl ConnectorIntegration<api::AccessTokenAuth, types::AccessTokenRequestData, t fn handle_response( &self, data: &types::RefreshTokenRouterData, + event_builder: Option<&mut ConnectorEvent>, res: Response, ) -> CustomResult<types::RefreshTokenRouterData, errors::ConnectorError> { logger::debug!(access_token_response=?res); @@ -213,6 +219,9 @@ impl ConnectorIntegration<api::AccessTokenAuth, types::AccessTokenRequestData, t .parse_struct("airwallex AirwallexAuthUpdateResponse") .change_context(errors::ConnectorError::ResponseDeserializationFailed)?; + event_builder.map(|i| i.set_response_body(&response)); + router_env::logger::info!(connector_response=?response); + types::ResponseRouterData { response, data: data.clone(), @@ -225,9 +234,9 @@ impl ConnectorIntegration<api::AccessTokenAuth, types::AccessTokenRequestData, t fn get_error_response( &self, res: Response, + event_builder: Option<&mut ConnectorEvent>, ) -> CustomResult<ErrorResponse, errors::ConnectorError> { - logger::debug!(access_token_error_response=?res); - self.build_error_response(res) + self.build_error_response(res, event_builder) } } @@ -292,13 +301,17 @@ impl fn handle_response( &self, data: &types::PaymentsInitRouterData, + event_builder: Option<&mut ConnectorEvent>, res: Response, ) -> CustomResult<types::PaymentsInitRouterData, errors::ConnectorError> { let response: airwallex::AirwallexPaymentsResponse = res .response .parse_struct("airwallex AirwallexPaymentsResponse") .change_context(errors::ConnectorError::ResponseDeserializationFailed)?; - logger::debug!(nuvei_session_response=?response); + + event_builder.map(|i| i.set_response_body(&response)); + router_env::logger::info!(connector_response=?response); + types::ResponseRouterData { response, data: data.clone(), @@ -311,8 +324,9 @@ impl fn get_error_response( &self, res: Response, + event_builder: Option<&mut ConnectorEvent>, ) -> CustomResult<ErrorResponse, errors::ConnectorError> { - self.build_error_response(res) + self.build_error_response(res, event_builder) } } @@ -420,13 +434,15 @@ impl ConnectorIntegration<api::Authorize, types::PaymentsAuthorizeData, types::P fn handle_response( &self, data: &types::PaymentsAuthorizeRouterData, + event_builder: Option<&mut ConnectorEvent>, res: Response, ) -> CustomResult<types::PaymentsAuthorizeRouterData, errors::ConnectorError> { let response: airwallex::AirwallexPaymentsResponse = res .response .parse_struct("AirwallexPaymentsResponse") .change_context(errors::ConnectorError::ResponseDeserializationFailed)?; - logger::debug!(airwallexpayments_create_response=?response); + event_builder.map(|i| i.set_response_body(&response)); + router_env::logger::info!(connector_response=?response); types::ResponseRouterData { response, data: data.clone(), @@ -439,8 +455,9 @@ impl ConnectorIntegration<api::Authorize, types::PaymentsAuthorizeData, types::P fn get_error_response( &self, res: Response, + event_builder: Option<&mut ConnectorEvent>, ) -> CustomResult<ErrorResponse, errors::ConnectorError> { - self.build_error_response(res) + self.build_error_response(res, event_builder) } } @@ -496,6 +513,7 @@ impl ConnectorIntegration<api::PSync, types::PaymentsSyncData, types::PaymentsRe fn handle_response( &self, data: &types::PaymentsSyncRouterData, + event_builder: Option<&mut ConnectorEvent>, res: Response, ) -> CustomResult<types::PaymentsSyncRouterData, errors::ConnectorError> { logger::debug!(payment_sync_response=?res); @@ -503,6 +521,8 @@ impl ConnectorIntegration<api::PSync, types::PaymentsSyncData, types::PaymentsRe .response .parse_struct("airwallex AirwallexPaymentsSyncResponse") .change_context(errors::ConnectorError::ResponseDeserializationFailed)?; + event_builder.map(|i| i.set_response_body(&response)); + router_env::logger::info!(connector_response=?response); types::PaymentsSyncRouterData::try_from(types::ResponseRouterData { response, data: data.clone(), @@ -514,8 +534,9 @@ impl ConnectorIntegration<api::PSync, types::PaymentsSyncData, types::PaymentsRe fn get_error_response( &self, res: Response, + event_builder: Option<&mut ConnectorEvent>, ) -> CustomResult<ErrorResponse, errors::ConnectorError> { - self.build_error_response(res) + self.build_error_response(res, event_builder) } } @@ -584,12 +605,15 @@ impl fn handle_response( &self, data: &types::PaymentsCompleteAuthorizeRouterData, + event_builder: Option<&mut ConnectorEvent>, res: Response, ) -> CustomResult<types::PaymentsCompleteAuthorizeRouterData, errors::ConnectorError> { let response: airwallex::AirwallexPaymentsResponse = res .response .parse_struct("AirwallexPaymentsResponse") .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(), @@ -601,8 +625,9 @@ impl fn get_error_response( &self, res: Response, + event_builder: Option<&mut ConnectorEvent>, ) -> CustomResult<ErrorResponse, errors::ConnectorError> { - self.build_error_response(res) + self.build_error_response(res, event_builder) } } @@ -669,13 +694,15 @@ impl ConnectorIntegration<api::Capture, types::PaymentsCaptureData, types::Payme fn handle_response( &self, data: &types::PaymentsCaptureRouterData, + event_builder: Option<&mut ConnectorEvent>, res: Response, ) -> CustomResult<types::PaymentsCaptureRouterData, errors::ConnectorError> { let response: airwallex::AirwallexPaymentsResponse = res .response .parse_struct("Airwallex PaymentsResponse") .change_context(errors::ConnectorError::ResponseDeserializationFailed)?; - logger::debug!(airwallexpayments_create_response=?response); + event_builder.map(|i| i.set_response_body(&response)); + router_env::logger::info!(connector_response=?response); types::ResponseRouterData { response, data: data.clone(), @@ -688,8 +715,9 @@ impl ConnectorIntegration<api::Capture, types::PaymentsCaptureData, types::Payme fn get_error_response( &self, res: Response, + event_builder: Option<&mut ConnectorEvent>, ) -> CustomResult<ErrorResponse, errors::ConnectorError> { - self.build_error_response(res) + self.build_error_response(res, event_builder) } } @@ -743,13 +771,15 @@ impl ConnectorIntegration<api::Void, types::PaymentsCancelData, types::PaymentsR fn handle_response( &self, data: &types::PaymentsCancelRouterData, + event_builder: Option<&mut ConnectorEvent>, res: Response, ) -> CustomResult<types::PaymentsCancelRouterData, errors::ConnectorError> { let response: airwallex::AirwallexPaymentsResponse = res .response .parse_struct("Airwallex PaymentsResponse") .change_context(errors::ConnectorError::ResponseDeserializationFailed)?; - logger::debug!(airwallexpayments_create_response=?response); + event_builder.map(|i| i.set_response_body(&response)); + router_env::logger::info!(connector_response=?response); types::ResponseRouterData { response, data: data.clone(), @@ -780,8 +810,9 @@ impl ConnectorIntegration<api::Void, types::PaymentsCancelData, types::PaymentsR fn get_error_response( &self, res: Response, + event_builder: Option<&mut ConnectorEvent>, ) -> CustomResult<ErrorResponse, errors::ConnectorError> { - self.build_error_response(res) + self.build_error_response(res, event_builder) } } @@ -853,6 +884,7 @@ impl ConnectorIntegration<api::Execute, types::RefundsData, types::RefundsRespon fn handle_response( &self, data: &types::RefundsRouterData<api::Execute>, + event_builder: Option<&mut ConnectorEvent>, res: Response, ) -> CustomResult<types::RefundsRouterData<api::Execute>, errors::ConnectorError> { logger::debug!(target: "router::connector::airwallex", response=?res); @@ -860,6 +892,8 @@ impl ConnectorIntegration<api::Execute, types::RefundsData, types::RefundsRespon .response .parse_struct("airwallex RefundResponse") .change_context(errors::ConnectorError::RequestEncodingFailed)?; + event_builder.map(|i| i.set_response_body(&response)); + router_env::logger::info!(connector_response=?response); types::ResponseRouterData { response, data: data.clone(), @@ -872,8 +906,9 @@ impl ConnectorIntegration<api::Execute, types::RefundsData, types::RefundsRespon fn get_error_response( &self, res: Response, + event_builder: Option<&mut ConnectorEvent>, ) -> CustomResult<ErrorResponse, errors::ConnectorError> { - self.build_error_response(res) + self.build_error_response(res, event_builder) } } @@ -923,6 +958,7 @@ impl ConnectorIntegration<api::RSync, types::RefundsData, types::RefundsResponse fn handle_response( &self, data: &types::RefundSyncRouterData, + event_builder: Option<&mut ConnectorEvent>, res: Response, ) -> CustomResult<types::RefundSyncRouterData, errors::ConnectorError> { logger::debug!(target: "router::connector::airwallex", response=?res); @@ -930,6 +966,8 @@ impl ConnectorIntegration<api::RSync, types::RefundsData, types::RefundsResponse .response .parse_struct("airwallex RefundResponse") .change_context(errors::ConnectorError::ResponseDeserializationFailed)?; + event_builder.map(|i| i.set_response_body(&response)); + router_env::logger::info!(connector_response=?response); types::ResponseRouterData { response, data: data.clone(), @@ -942,8 +980,9 @@ impl ConnectorIntegration<api::RSync, types::RefundsData, types::RefundsResponse fn get_error_response( &self, res: Response, + event_builder: Option<&mut ConnectorEvent>, ) -> CustomResult<ErrorResponse, errors::ConnectorError> { - self.build_error_response(res) + self.build_error_response(res, event_builder) } } diff --git a/crates/router/src/connector/airwallex/transformers.rs b/crates/router/src/connector/airwallex/transformers.rs index 2de7f6fe00f..692458715f7 100644 --- a/crates/router/src/connector/airwallex/transformers.rs +++ b/crates/router/src/connector/airwallex/transformers.rs @@ -259,7 +259,7 @@ fn get_wallet_details( Ok(wallet_details) } -#[derive(Deserialize)] +#[derive(Deserialize, Debug, Serialize)] pub struct AirwallexAuthUpdateResponse { #[serde(with = "common_utils::custom_serde::iso8601")] expires_at: PrimitiveDateTime, @@ -368,7 +368,7 @@ impl TryFrom<&types::PaymentsCancelRouterData> for AirwallexPaymentsCancelReques } // PaymentsResponse -#[derive(Debug, Clone, Default, Deserialize, PartialEq)] +#[derive(Debug, Clone, Default, Deserialize, PartialEq, Serialize)] #[serde(rename_all = "SCREAMING_SNAKE_CASE")] pub enum AirwallexPaymentStatus { Succeeded, @@ -413,7 +413,7 @@ pub enum AirwallexNextActionStage { WaitingUserInfoInput, } -#[derive(Debug, Clone, Deserialize, PartialEq)] +#[derive(Debug, Clone, Deserialize, PartialEq, Serialize)] pub struct AirwallexRedirectFormData { #[serde(rename = "JWT")] jwt: Option<String>, @@ -424,7 +424,7 @@ pub struct AirwallexRedirectFormData { version: Option<String>, } -#[derive(Debug, Clone, Deserialize, PartialEq)] +#[derive(Debug, Clone, Deserialize, PartialEq, Serialize)] pub struct AirwallexPaymentsNextAction { url: Url, method: services::Method, @@ -432,7 +432,7 @@ pub struct AirwallexPaymentsNextAction { stage: AirwallexNextActionStage, } -#[derive(Default, Debug, Clone, Deserialize, PartialEq)] +#[derive(Default, Debug, Clone, Deserialize, PartialEq, Serialize)] pub struct AirwallexPaymentsResponse { status: AirwallexPaymentStatus, //Unique identifier for the PaymentIntent @@ -443,7 +443,7 @@ pub struct AirwallexPaymentsResponse { next_action: Option<AirwallexPaymentsNextAction>, } -#[derive(Default, Debug, Clone, Deserialize, PartialEq)] +#[derive(Default, Debug, Clone, Deserialize, PartialEq, Serialize)] pub struct AirwallexPaymentsSyncResponse { status: AirwallexPaymentStatus, //Unique identifier for the PaymentIntent diff --git a/crates/router/src/connector/authorizedotnet.rs b/crates/router/src/connector/authorizedotnet.rs index 0686ee6a3b8..e8ef9195d02 100644 --- a/crates/router/src/connector/authorizedotnet.rs +++ b/crates/router/src/connector/authorizedotnet.rs @@ -15,6 +15,7 @@ use crate::{ errors::{self, CustomResult}, payments, }, + events::connector_api_logs::ConnectorEvent, headers, services::{self, request, ConnectorIntegration, ConnectorValidation}, types::{ @@ -196,6 +197,7 @@ impl ConnectorIntegration<api::Capture, types::PaymentsCaptureData, types::Payme fn handle_response( &self, data: &types::PaymentsCaptureRouterData, + event_builder: Option<&mut ConnectorEvent>, res: types::Response, ) -> CustomResult<types::PaymentsCaptureRouterData, errors::ConnectorError> { use bytes::Buf; @@ -209,7 +211,8 @@ impl ConnectorIntegration<api::Capture, types::PaymentsCaptureData, types::Payme let response: authorizedotnet::AuthorizedotnetPaymentsResponse = intermediate_response .parse_struct("AuthorizedotnetPaymentsResponse") .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(), @@ -220,8 +223,9 @@ impl ConnectorIntegration<api::Capture, types::PaymentsCaptureData, types::Payme fn get_error_response( &self, res: types::Response, + event_builder: Option<&mut ConnectorEvent>, ) -> CustomResult<types::ErrorResponse, errors::ConnectorError> { - get_error_response(res) + get_error_response(res, event_builder) } } @@ -279,6 +283,7 @@ impl ConnectorIntegration<api::PSync, types::PaymentsSyncData, types::PaymentsRe fn handle_response( &self, data: &types::PaymentsSyncRouterData, + event_builder: Option<&mut ConnectorEvent>, res: types::Response, ) -> CustomResult<types::PaymentsSyncRouterData, errors::ConnectorError> { use bytes::Buf; @@ -292,7 +297,8 @@ impl ConnectorIntegration<api::PSync, types::PaymentsSyncData, types::PaymentsRe let response: authorizedotnet::AuthorizedotnetSyncResponse = intermediate_response .parse_struct("AuthorizedotnetSyncResponse") .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(), @@ -303,8 +309,9 @@ impl ConnectorIntegration<api::PSync, types::PaymentsSyncData, types::PaymentsRe fn get_error_response( &self, res: types::Response, + event_builder: Option<&mut ConnectorEvent>, ) -> CustomResult<types::ErrorResponse, errors::ConnectorError> { - get_error_response(res) + get_error_response(res, event_builder) } } @@ -378,6 +385,7 @@ impl ConnectorIntegration<api::Authorize, types::PaymentsAuthorizeData, types::P fn handle_response( &self, data: &types::PaymentsAuthorizeRouterData, + event_builder: Option<&mut ConnectorEvent>, res: types::Response, ) -> CustomResult<types::PaymentsAuthorizeRouterData, errors::ConnectorError> { use bytes::Buf; @@ -391,6 +399,8 @@ impl ConnectorIntegration<api::Authorize, types::PaymentsAuthorizeData, types::P let response: authorizedotnet::AuthorizedotnetPaymentsResponse = intermediate_response .parse_struct("AuthorizedotnetPaymentsResponse") .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(), @@ -401,8 +411,9 @@ impl ConnectorIntegration<api::Authorize, types::PaymentsAuthorizeData, types::P fn get_error_response( &self, res: types::Response, + event_builder: Option<&mut ConnectorEvent>, ) -> CustomResult<types::ErrorResponse, errors::ConnectorError> { - get_error_response(res) + get_error_response(res, event_builder) } } @@ -459,6 +470,7 @@ impl ConnectorIntegration<api::Void, types::PaymentsCancelData, types::PaymentsR fn handle_response( &self, data: &types::PaymentsCancelRouterData, + event_builder: Option<&mut ConnectorEvent>, res: types::Response, ) -> CustomResult<types::PaymentsCancelRouterData, errors::ConnectorError> { use bytes::Buf; @@ -472,7 +484,8 @@ impl ConnectorIntegration<api::Void, types::PaymentsCancelData, types::PaymentsR let response: authorizedotnet::AuthorizedotnetVoidResponse = intermediate_response .parse_struct("AuthorizedotnetPaymentsResponse") .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(), @@ -483,8 +496,9 @@ impl ConnectorIntegration<api::Void, types::PaymentsCancelData, types::PaymentsR fn get_error_response( &self, res: types::Response, + event_builder: Option<&mut ConnectorEvent>, ) -> CustomResult<types::ErrorResponse, errors::ConnectorError> { - get_error_response(res) + get_error_response(res, event_builder) } } @@ -554,6 +568,7 @@ impl ConnectorIntegration<api::Execute, types::RefundsData, types::RefundsRespon fn handle_response( &self, data: &types::RefundsRouterData<api::Execute>, + event_builder: Option<&mut ConnectorEvent>, res: types::Response, ) -> CustomResult<types::RefundsRouterData<api::Execute>, errors::ConnectorError> { use bytes::Buf; @@ -567,7 +582,8 @@ impl ConnectorIntegration<api::Execute, types::RefundsData, types::RefundsRespon let response: authorizedotnet::AuthorizedotnetRefundResponse = intermediate_response .parse_struct("AuthorizedotnetRefundResponse") .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(), @@ -578,8 +594,9 @@ impl ConnectorIntegration<api::Execute, types::RefundsData, types::RefundsRespon fn get_error_response( &self, res: types::Response, + event_builder: Option<&mut ConnectorEvent>, ) -> CustomResult<types::ErrorResponse, errors::ConnectorError> { - get_error_response(res) + get_error_response(res, event_builder) } } @@ -644,6 +661,7 @@ impl ConnectorIntegration<api::RSync, types::RefundsData, types::RefundsResponse fn handle_response( &self, data: &types::RefundsRouterData<api::RSync>, + event_builder: Option<&mut ConnectorEvent>, res: types::Response, ) -> CustomResult<types::RefundsRouterData<api::RSync>, errors::ConnectorError> { use bytes::Buf; @@ -657,6 +675,8 @@ impl ConnectorIntegration<api::RSync, types::RefundsData, types::RefundsResponse let response: authorizedotnet::AuthorizedotnetSyncResponse = intermediate_response .parse_struct("AuthorizedotnetSyncResponse") .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(), @@ -667,8 +687,9 @@ impl ConnectorIntegration<api::RSync, types::RefundsData, types::RefundsResponse fn get_error_response( &self, res: types::Response, + event_builder: Option<&mut ConnectorEvent>, ) -> CustomResult<types::ErrorResponse, errors::ConnectorError> { - get_error_response(res) + get_error_response(res, event_builder) } } @@ -742,6 +763,7 @@ impl fn handle_response( &self, data: &types::PaymentsCompleteAuthorizeRouterData, + event_builder: Option<&mut ConnectorEvent>, res: types::Response, ) -> CustomResult<types::PaymentsCompleteAuthorizeRouterData, errors::ConnectorError> { use bytes::Buf; @@ -755,7 +777,8 @@ impl let response: authorizedotnet::AuthorizedotnetPaymentsResponse = intermediate_response .parse_struct("AuthorizedotnetPaymentsResponse") .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(), @@ -766,8 +789,9 @@ impl fn get_error_response( &self, res: types::Response, + event_builder: Option<&mut ConnectorEvent>, ) -> CustomResult<types::ErrorResponse, errors::ConnectorError> { - get_error_response(res) + get_error_response(res, event_builder) } } @@ -873,11 +897,15 @@ fn get_error_response( status_code, .. }: types::Response, + event_builder: Option<&mut ConnectorEvent>, ) -> CustomResult<types::ErrorResponse, errors::ConnectorError> { let response: authorizedotnet::AuthorizedotnetPaymentsResponse = response .parse_struct("AuthorizedotnetPaymentsResponse") .change_context(errors::ConnectorError::ResponseDeserializationFailed)?; + event_builder.map(|i| i.set_error_response_body(&response)); + router_env::logger::info!(connector_response=?response); + match response.transaction_response { Some(authorizedotnet::TransactionResponse::AuthorizedotnetTransactionResponse( payment_response, diff --git a/crates/router/src/connector/authorizedotnet/transformers.rs b/crates/router/src/connector/authorizedotnet/transformers.rs index 96cf3b6ffc5..3377457f38a 100644 --- a/crates/router/src/connector/authorizedotnet/transformers.rs +++ b/crates/router/src/connector/authorizedotnet/transformers.rs @@ -388,7 +388,7 @@ impl TryFrom<&AuthorizedotnetRouterData<&types::PaymentsCaptureRouterData>> } } -#[derive(Debug, Clone, Default, serde::Deserialize)] +#[derive(Debug, Clone, Default, serde::Deserialize, serde::Serialize)] pub enum AuthorizedotnetPaymentStatus { #[serde(rename = "1")] Approved, @@ -403,7 +403,7 @@ pub enum AuthorizedotnetPaymentStatus { RequiresAction, } -#[derive(Debug, Clone, serde::Deserialize)] +#[derive(Debug, Clone, serde::Deserialize, Serialize)] pub enum AuthorizedotnetRefundStatus { #[serde(rename = "1")] Approved, @@ -448,27 +448,27 @@ pub struct ResponseMessages { pub message: Vec<ResponseMessage>, } -#[derive(Debug, Clone, Deserialize)] +#[derive(Debug, Clone, Deserialize, Serialize)] #[serde(rename_all = "camelCase")] pub struct ErrorMessage { pub error_code: String, pub error_text: String, } -#[derive(Debug, Clone, Deserialize)] +#[derive(Debug, Clone, Deserialize, Serialize)] #[serde(untagged)] pub enum TransactionResponse { AuthorizedotnetTransactionResponse(Box<AuthorizedotnetTransactionResponse>), AuthorizedotnetTransactionResponseError(Box<AuthorizedotnetTransactionResponseError>), } -#[derive(Debug, Clone, Deserialize)] +#[derive(Debug, Clone, Deserialize, Serialize)] #[serde(rename_all = "PascalCase")] pub struct AuthorizedotnetTransactionResponseError { _supplemental_data_qualification_indicator: i64, } -#[derive(Debug, Clone, Deserialize)] +#[derive(Debug, Clone, Deserialize, Serialize)] #[serde(rename_all = "camelCase")] pub struct AuthorizedotnetTransactionResponse { response_code: AuthorizedotnetPaymentStatus, @@ -480,7 +480,7 @@ pub struct AuthorizedotnetTransactionResponse { secure_acceptance: Option<SecureAcceptance>, } -#[derive(Debug, Clone, Deserialize)] +#[derive(Debug, Clone, Deserialize, Serialize)] #[serde(rename_all = "camelCase")] pub struct RefundResponse { response_code: AuthorizedotnetRefundStatus, @@ -492,27 +492,27 @@ pub struct RefundResponse { pub errors: Option<Vec<ErrorMessage>>, } -#[derive(Debug, Clone, Deserialize)] +#[derive(Debug, Clone, Deserialize, Serialize)] #[serde(rename_all = "PascalCase")] pub struct SecureAcceptance { secure_acceptance_url: Option<url::Url>, } -#[derive(Debug, Clone, Deserialize)] +#[derive(Debug, Clone, Deserialize, Serialize)] #[serde(rename_all = "camelCase")] pub struct AuthorizedotnetPaymentsResponse { pub transaction_response: Option<TransactionResponse>, pub messages: ResponseMessages, } -#[derive(Debug, Clone, Deserialize)] +#[derive(Debug, Clone, Deserialize, Serialize)] #[serde(rename_all = "camelCase")] pub struct AuthorizedotnetVoidResponse { pub transaction_response: Option<VoidResponse>, pub messages: ResponseMessages, } -#[derive(Debug, Clone, Deserialize)] +#[derive(Debug, Clone, Deserialize, Serialize)] #[serde(rename_all = "camelCase")] pub struct VoidResponse { response_code: AuthorizedotnetVoidStatus, @@ -523,7 +523,7 @@ pub struct VoidResponse { pub errors: Option<Vec<ErrorMessage>>, } -#[derive(Debug, Clone, Deserialize)] +#[derive(Debug, Clone, Deserialize, Serialize)] pub enum AuthorizedotnetVoidStatus { #[serde(rename = "1")] Approved, @@ -773,7 +773,7 @@ impl From<AuthorizedotnetRefundStatus> for enums::RefundStatus { } } -#[derive(Debug, Deserialize)] +#[derive(Debug, Deserialize, Serialize)] #[serde(rename_all = "camelCase")] pub struct AuthorizedotnetRefundResponse { pub transaction_response: RefundResponse, diff --git a/crates/router/src/connector/bambora.rs b/crates/router/src/connector/bambora.rs index 37c6ae6cd6b..df078e895d0 100644 --- a/crates/router/src/connector/bambora.rs +++ b/crates/router/src/connector/bambora.rs @@ -18,7 +18,8 @@ use crate::{ errors::{self, CustomResult}, payments, }, - headers, logger, + events::connector_api_logs::ConnectorEvent, + headers, services::{ self, request::{self, Mask}, @@ -85,12 +86,16 @@ impl ConnectorCommon for Bambora { fn build_error_response( &self, res: Response, + event_builder: Option<&mut ConnectorEvent>, ) -> CustomResult<ErrorResponse, errors::ConnectorError> { let response: bambora::BamboraErrorResponse = res .response .parse_struct("BamboraErrorResponse") .change_context(errors::ConnectorError::ResponseDeserializationFailed)?; + event_builder.map(|i| i.set_error_response_body(&response)); + router_env::logger::info!(connector_response=?response); + Ok(ErrorResponse { status_code: res.status_code, code: response.code.to_string(), @@ -215,12 +220,15 @@ impl ConnectorIntegration<api::Void, types::PaymentsCancelData, types::PaymentsR fn handle_response( &self, data: &types::PaymentsCancelRouterData, + event_builder: Option<&mut ConnectorEvent>, res: Response, ) -> CustomResult<types::PaymentsCancelRouterData, errors::ConnectorError> { let response: bambora::BamboraResponse = res .response .parse_struct("bambora PaymentsResponse") .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, @@ -235,8 +243,9 @@ impl ConnectorIntegration<api::Void, types::PaymentsCancelData, types::PaymentsR fn get_error_response( &self, res: Response, + event_builder: Option<&mut ConnectorEvent>, ) -> CustomResult<ErrorResponse, errors::ConnectorError> { - self.build_error_response(res) + self.build_error_response(res, event_builder) } } @@ -299,19 +308,23 @@ impl ConnectorIntegration<api::PSync, types::PaymentsSyncData, types::PaymentsRe fn get_error_response( &self, res: Response, + event_builder: Option<&mut ConnectorEvent>, ) -> CustomResult<ErrorResponse, errors::ConnectorError> { - self.build_error_response(res) + self.build_error_response(res, event_builder) } fn handle_response( &self, data: &types::PaymentsSyncRouterData, + event_builder: Option<&mut ConnectorEvent>, res: Response, ) -> CustomResult<types::PaymentsSyncRouterData, errors::ConnectorError> { let response: bambora::BamboraResponse = res .response .parse_struct("bambora PaymentsResponse") .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, @@ -384,13 +397,15 @@ impl ConnectorIntegration<api::Capture, types::PaymentsCaptureData, types::Payme fn handle_response( &self, data: &types::PaymentsCaptureRouterData, + event_builder: Option<&mut ConnectorEvent>, res: Response, ) -> CustomResult<types::PaymentsCaptureRouterData, errors::ConnectorError> { let response: bambora::BamboraResponse = res .response .parse_struct("Bambora PaymentsResponse") .change_context(errors::ConnectorError::ResponseDeserializationFailed)?; - logger::debug!(bamborapayments_create_response=?response); + event_builder.map(|i| i.set_response_body(&response)); + router_env::logger::info!(connector_response=?response); types::RouterData::try_from(( types::ResponseRouterData { response, @@ -405,8 +420,9 @@ impl ConnectorIntegration<api::Capture, types::PaymentsCaptureData, types::Payme fn get_error_response( &self, res: Response, + event_builder: Option<&mut ConnectorEvent>, ) -> CustomResult<ErrorResponse, errors::ConnectorError> { - self.build_error_response(res) + self.build_error_response(res, event_builder) } } @@ -478,13 +494,16 @@ impl ConnectorIntegration<api::Authorize, types::PaymentsAuthorizeData, types::P fn handle_response( &self, data: &types::PaymentsAuthorizeRouterData, + event_builder: Option<&mut ConnectorEvent>, res: Response, ) -> CustomResult<types::PaymentsAuthorizeRouterData, errors::ConnectorError> { let response: bambora::BamboraResponse = res .response .parse_struct("PaymentIntentResponse") .change_context(errors::ConnectorError::ResponseDeserializationFailed)?; - logger::debug!(bamborapayments_create_response=?response); + event_builder.map(|i| i.set_response_body(&response)); + router_env::logger::info!(connector_response=?response); + types::RouterData::try_from(( types::ResponseRouterData { response, @@ -499,8 +518,9 @@ impl ConnectorIntegration<api::Authorize, types::PaymentsAuthorizeData, types::P fn get_error_response( &self, res: Response, + event_builder: Option<&mut ConnectorEvent>, ) -> CustomResult<ErrorResponse, errors::ConnectorError> { - self.build_error_response(res) + self.build_error_response(res, event_builder) } } @@ -569,12 +589,15 @@ impl ConnectorIntegration<api::Execute, types::RefundsData, types::RefundsRespon 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: bambora::RefundResponse = res .response .parse_struct("bambora RefundResponse") .change_context(errors::ConnectorError::RequestEncodingFailed)?; + event_builder.map(|i| i.set_response_body(&response)); + router_env::logger::info!(connector_response=?response); types::RefundsRouterData::try_from(types::ResponseRouterData { response, data: data.clone(), @@ -586,8 +609,9 @@ impl ConnectorIntegration<api::Execute, types::RefundsData, types::RefundsRespon fn get_error_response( &self, res: Response, + event_builder: Option<&mut ConnectorEvent>, ) -> CustomResult<ErrorResponse, errors::ConnectorError> { - self.build_error_response(res) + self.build_error_response(res, event_builder) } } @@ -637,12 +661,15 @@ impl ConnectorIntegration<api::RSync, types::RefundsData, types::RefundsResponse fn handle_response( &self, data: &types::RefundSyncRouterData, + event_builder: Option<&mut ConnectorEvent>, res: Response, ) -> CustomResult<types::RefundSyncRouterData, errors::ConnectorError> { let response: bambora::RefundResponse = res .response .parse_struct("bambora 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(), @@ -654,8 +681,9 @@ impl ConnectorIntegration<api::RSync, types::RefundsData, types::RefundsResponse fn get_error_response( &self, res: Response, + event_builder: Option<&mut ConnectorEvent>, ) -> CustomResult<ErrorResponse, errors::ConnectorError> { - self.build_error_response(res) + self.build_error_response(res, event_builder) } } @@ -774,13 +802,16 @@ impl fn handle_response( &self, data: &types::PaymentsCompleteAuthorizeRouterData, + event_builder: Option<&mut ConnectorEvent>, res: Response, ) -> CustomResult<types::PaymentsCompleteAuthorizeRouterData, errors::ConnectorError> { let response: bambora::BamboraResponse = res .response .parse_struct("Bambora PaymentsResponse") .change_context(errors::ConnectorError::ResponseDeserializationFailed)?; - logger::debug!(bamborapayments_create_response=?response); + event_builder.map(|i| i.set_response_body(&response)); + router_env::logger::info!(connector_response=?response); + types::RouterData::try_from(( types::ResponseRouterData { response, @@ -795,7 +826,8 @@ impl fn get_error_response( &self, res: Response, + event_builder: Option<&mut ConnectorEvent>, ) -> CustomResult<ErrorResponse, errors::ConnectorError> { - self.build_error_response(res) + self.build_error_response(res, event_builder) } } diff --git a/crates/router/src/connector/bambora/transformers.rs b/crates/router/src/connector/bambora/transformers.rs index 8f18ca272dd..d2c99bbaca0 100644 --- a/crates/router/src/connector/bambora/transformers.rs +++ b/crates/router/src/connector/bambora/transformers.rs @@ -272,14 +272,14 @@ where Ok(res) } -#[derive(Debug, Clone, Deserialize)] +#[derive(Debug, Clone, Deserialize, Serialize)] #[serde(untagged)] pub enum BamboraResponse { NormalTransaction(Box<BamboraPaymentsResponse>), ThreeDsResponse(Box<Bambora3DsResponse>), } -#[derive(Default, Debug, Clone, Deserialize, PartialEq)] +#[derive(Default, Debug, Clone, Deserialize, PartialEq, Serialize)] pub struct BamboraPaymentsResponse { #[serde(deserialize_with = "str_or_i32")] id: String, @@ -309,7 +309,7 @@ pub struct BamboraPaymentsResponse { risk_score: Option<f32>, } -#[derive(Debug, Clone, Deserialize)] +#[derive(Debug, Clone, Deserialize, Serialize)] pub struct Bambora3DsResponse { #[serde(rename = "3d_session_data")] three_d_session_data: String, @@ -332,7 +332,7 @@ pub struct CardResponse { pub(crate) cres: Option<common_utils::pii::SecretSerdeValue>, } -#[derive(Default, Debug, Clone, Deserialize, PartialEq)] +#[derive(Default, Debug, Clone, Deserialize, PartialEq, Serialize)] pub struct CardData { name: Option<String>, expiry_month: Option<String>, @@ -466,7 +466,7 @@ impl From<RefundStatus> for enums::RefundStatus { } } -#[derive(Default, Debug, Clone, Deserialize)] +#[derive(Default, Debug, Clone, Deserialize, Serialize)] pub struct RefundResponse { #[serde(deserialize_with = "str_or_i32")] pub id: String, diff --git a/crates/router/src/connector/bankofamerica.rs b/crates/router/src/connector/bankofamerica.rs index 589852c6b56..8a72e65f976 100644 --- a/crates/router/src/connector/bankofamerica.rs +++ b/crates/router/src/connector/bankofamerica.rs @@ -18,6 +18,7 @@ use crate::{ connector::{utils as connector_utils, utils::RefundsRequestData}, consts, core::errors::{self, CustomResult}, + events::connector_api_logs::ConnectorEvent, headers, services::{ self, @@ -197,12 +198,16 @@ impl ConnectorCommon for Bankofamerica { fn build_error_response( &self, res: Response, + event_builder: Option<&mut ConnectorEvent>, ) -> CustomResult<ErrorResponse, errors::ConnectorError> { let response: bankofamerica::BankOfAmericaErrorResponse = res .response .parse_struct("BankOfAmerica ErrorResponse") .change_context(errors::ConnectorError::ResponseDeserializationFailed)?; + event_builder.map(|i| i.set_error_response_body(&response)); + router_env::logger::info!(connector_response=?response); + let error_message = if res.status_code == 401 { consts::CONNECTOR_UNAUTHORIZED_ERROR } else { @@ -390,12 +395,15 @@ impl fn handle_response( &self, data: &types::PaymentsPreProcessingRouterData, + event_builder: Option<&mut ConnectorEvent>, res: Response, ) -> CustomResult<types::PaymentsPreProcessingRouterData, errors::ConnectorError> { let response: bankofamerica::BankOfAmericaPreProcessingResponse = res .response .parse_struct("BankOfAmerica AuthEnrollmentResponse") .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(), @@ -406,8 +414,9 @@ impl fn get_error_response( &self, res: Response, + event_builder: Option<&mut ConnectorEvent>, ) -> CustomResult<ErrorResponse, errors::ConnectorError> { - self.build_error_response(res) + self.build_error_response(res, event_builder) } } @@ -488,6 +497,7 @@ impl ConnectorIntegration<api::Authorize, types::PaymentsAuthorizeData, types::P fn handle_response( &self, data: &types::PaymentsAuthorizeRouterData, + event_builder: Option<&mut ConnectorEvent>, res: Response, ) -> CustomResult<types::PaymentsAuthorizeRouterData, errors::ConnectorError> { if data.is_three_ds() && data.request.is_card() { @@ -495,6 +505,8 @@ impl ConnectorIntegration<api::Authorize, types::PaymentsAuthorizeData, types::P .response .parse_struct("Bankofamerica AuthSetupResponse") .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(), @@ -505,6 +517,8 @@ impl ConnectorIntegration<api::Authorize, types::PaymentsAuthorizeData, types::P .response .parse_struct("Bankofamerica 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 { response, data: data.clone(), @@ -516,18 +530,24 @@ impl ConnectorIntegration<api::Authorize, types::PaymentsAuthorizeData, types::P fn get_error_response( &self, res: Response, + event_builder: Option<&mut ConnectorEvent>, ) -> CustomResult<ErrorResponse, errors::ConnectorError> { - self.build_error_response(res) + self.build_error_response(res, event_builder) } fn get_5xx_error_response( &self, res: Response, + event_builder: Option<&mut ConnectorEvent>, ) -> CustomResult<ErrorResponse, errors::ConnectorError> { let response: bankofamerica::BankOfAmericaServerErrorResponse = res .response .parse_struct("BankOfAmericaServerErrorResponse") .change_context(errors::ConnectorError::ResponseDeserializationFailed)?; + + event_builder.map(|event| event.set_response_body(&response)); + router_env::logger::info!(error_response=?response); + let attempt_status = match response.reason { Some(reason) => match reason { transformers::Reason::SystemError => Some(enums::AttemptStatus::Failure), @@ -612,12 +632,15 @@ impl fn handle_response( &self, data: &types::PaymentsCompleteAuthorizeRouterData, + event_builder: Option<&mut ConnectorEvent>, res: Response, ) -> CustomResult<types::PaymentsCompleteAuthorizeRouterData, errors::ConnectorError> { let response: bankofamerica::BankOfAmericaPaymentsResponse = res .response .parse_struct("BankOfAmerica 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 { response, data: data.clone(), @@ -628,18 +651,24 @@ impl fn get_error_response( &self, res: Response, + event_builder: Option<&mut ConnectorEvent>, ) -> CustomResult<ErrorResponse, errors::ConnectorError> { - self.build_error_response(res) + self.build_error_response(res, event_builder) } fn get_5xx_error_response( &self, res: Response, + event_builder: Option<&mut ConnectorEvent>, ) -> CustomResult<ErrorResponse, errors::ConnectorError> { let response: bankofamerica::BankOfAmericaServerErrorResponse = res .response .parse_struct("BankOfAmericaServerErrorResponse") .change_context(errors::ConnectorError::ResponseDeserializationFailed)?; + + event_builder.map(|event| event.set_response_body(&response)); + router_env::logger::info!(error_response=?response); + let attempt_status = match response.reason { Some(reason) => match reason { transformers::Reason::SystemError => Some(enums::AttemptStatus::Failure), @@ -713,12 +742,15 @@ impl ConnectorIntegration<api::PSync, types::PaymentsSyncData, types::PaymentsRe fn handle_response( &self, data: &types::PaymentsSyncRouterData, + event_builder: Option<&mut ConnectorEvent>, res: Response, ) -> CustomResult<types::PaymentsSyncRouterData, errors::ConnectorError> { let response: bankofamerica::BankOfAmericaTransactionResponse = res .response .parse_struct("BankOfAmerica 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 { response, data: data.clone(), @@ -729,8 +761,9 @@ impl ConnectorIntegration<api::PSync, types::PaymentsSyncData, types::PaymentsRe fn get_error_response( &self, res: Response, + event_builder: Option<&mut ConnectorEvent>, ) -> CustomResult<ErrorResponse, errors::ConnectorError> { - self.build_error_response(res) + self.build_error_response(res, event_builder) } } @@ -800,12 +833,15 @@ impl ConnectorIntegration<api::Capture, types::PaymentsCaptureData, types::Payme fn handle_response( &self, data: &types::PaymentsCaptureRouterData, + event_builder: Option<&mut ConnectorEvent>, res: Response, ) -> CustomResult<types::PaymentsCaptureRouterData, errors::ConnectorError> { let response: bankofamerica::BankOfAmericaPaymentsResponse = res .response .parse_struct("BankOfAmerica 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 { response, data: data.clone(), @@ -816,19 +852,24 @@ impl ConnectorIntegration<api::Capture, types::PaymentsCaptureData, types::Payme fn get_error_response( &self, res: Response, + event_builder: Option<&mut ConnectorEvent>, ) -> CustomResult<ErrorResponse, errors::ConnectorError> { - self.build_error_response(res) + self.build_error_response(res, event_builder) } fn get_5xx_error_response( &self, res: Response, + event_builder: Option<&mut ConnectorEvent>, ) -> CustomResult<ErrorResponse, errors::ConnectorError> { let response: bankofamerica::BankOfAmericaServerErrorResponse = res .response .parse_struct("BankOfAmericaServerErrorResponse") .change_context(errors::ConnectorError::ResponseDeserializationFailed)?; + event_builder.map(|event| event.set_response_body(&response)); + router_env::logger::info!(error_response=?response); + Ok(ErrorResponse { status_code: res.status_code, reason: response.status.clone(), @@ -915,12 +956,15 @@ impl ConnectorIntegration<api::Void, types::PaymentsCancelData, types::PaymentsR fn handle_response( &self, data: &types::PaymentsCancelRouterData, + event_builder: Option<&mut ConnectorEvent>, res: Response, ) -> CustomResult<types::PaymentsCancelRouterData, errors::ConnectorError> { let response: bankofamerica::BankOfAmericaPaymentsResponse = res .response .parse_struct("BankOfAmerica 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 { response, data: data.clone(), @@ -931,19 +975,24 @@ impl ConnectorIntegration<api::Void, types::PaymentsCancelData, types::PaymentsR fn get_error_response( &self, res: Response, + event_builder: Option<&mut ConnectorEvent>, ) -> CustomResult<ErrorResponse, errors::ConnectorError> { - self.build_error_response(res) + self.build_error_response(res, event_builder) } fn get_5xx_error_response( &self, res: Response, + event_builder: Option<&mut ConnectorEvent>, ) -> CustomResult<ErrorResponse, errors::ConnectorError> { let response: bankofamerica::BankOfAmericaServerErrorResponse = res .response .parse_struct("BankOfAmericaServerErrorResponse") .change_context(errors::ConnectorError::ResponseDeserializationFailed)?; + event_builder.map(|event| event.set_response_body(&response)); + router_env::logger::info!(error_response=?response); + Ok(ErrorResponse { status_code: res.status_code, reason: response.status.clone(), @@ -1022,12 +1071,15 @@ impl ConnectorIntegration<api::Execute, types::RefundsData, types::RefundsRespon 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: bankofamerica::BankOfAmericaRefundResponse = res .response .parse_struct("bankofamerica 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(), @@ -1038,8 +1090,9 @@ impl ConnectorIntegration<api::Execute, types::RefundsData, types::RefundsRespon fn get_error_response( &self, res: Response, + event_builder: Option<&mut ConnectorEvent>, ) -> CustomResult<ErrorResponse, errors::ConnectorError> { - self.build_error_response(res) + self.build_error_response(res, event_builder) } } @@ -1092,12 +1145,15 @@ impl ConnectorIntegration<api::RSync, types::RefundsData, types::RefundsResponse fn handle_response( &self, data: &types::RefundSyncRouterData, + event_builder: Option<&mut ConnectorEvent>, res: Response, ) -> CustomResult<types::RefundSyncRouterData, errors::ConnectorError> { let response: bankofamerica::BankOfAmericaRsyncResponse = res .response .parse_struct("bankofamerica 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(), @@ -1108,8 +1164,9 @@ impl ConnectorIntegration<api::RSync, types::RefundsData, types::RefundsResponse fn get_error_response( &self, res: Response, + event_builder: Option<&mut ConnectorEvent>, ) -> CustomResult<ErrorResponse, errors::ConnectorError> { - self.build_error_response(res) + self.build_error_response(res, event_builder) } } diff --git a/crates/router/src/connector/bankofamerica/transformers.rs b/crates/router/src/connector/bankofamerica/transformers.rs index 0b8158c10af..de53b991d89 100644 --- a/crates/router/src/connector/bankofamerica/transformers.rs +++ b/crates/router/src/connector/bankofamerica/transformers.rs @@ -427,13 +427,13 @@ pub struct ClientProcessorInformation { avs: Option<Avs>, } -#[derive(Debug, Clone, Deserialize)] +#[derive(Debug, Clone, Deserialize, Serialize)] #[serde(rename_all = "camelCase")] pub struct ClientRiskInformation { rules: Option<Vec<ClientRiskInformationRules>>, } -#[derive(Debug, Clone, Deserialize)] +#[derive(Debug, Clone, Deserialize, Serialize)] pub struct ClientRiskInformationRules { name: String, } @@ -825,7 +825,7 @@ impl TryFrom<&BankOfAmericaRouterData<&types::PaymentsAuthorizeRouterData>> } } -#[derive(Clone, Debug, Deserialize)] +#[derive(Clone, Debug, Deserialize, Serialize)] #[serde(rename_all = "SCREAMING_SNAKE_CASE")] pub enum BankofamericaPaymentStatus { Authorized, @@ -886,7 +886,7 @@ impl ForeignFrom<(BankofamericaPaymentStatus, bool)> for enums::AttemptStatus { } } -#[derive(Debug, Deserialize)] +#[derive(Debug, Deserialize, Serialize)] #[serde(rename_all = "camelCase")] pub struct BankOfAmericaConsumerAuthInformationResponse { access_token: String, @@ -894,7 +894,7 @@ pub struct BankOfAmericaConsumerAuthInformationResponse { reference_id: String, } -#[derive(Debug, Deserialize)] +#[derive(Debug, Deserialize, Serialize)] #[serde(rename_all = "camelCase")] pub struct ClientAuthSetupInfoResponse { id: String, @@ -902,21 +902,21 @@ pub struct ClientAuthSetupInfoResponse { consumer_authentication_information: BankOfAmericaConsumerAuthInformationResponse, } -#[derive(Debug, Deserialize)] +#[derive(Debug, Deserialize, Serialize)] #[serde(untagged)] pub enum BankOfAmericaAuthSetupResponse { ClientAuthSetupInfo(ClientAuthSetupInfoResponse), ErrorInformation(BankOfAmericaErrorInformationResponse), } -#[derive(Debug, Deserialize)] +#[derive(Debug, Deserialize, Serialize)] #[serde(untagged)] pub enum BankOfAmericaPaymentsResponse { ClientReferenceInformation(BankOfAmericaClientReferenceResponse), ErrorInformation(BankOfAmericaErrorInformationResponse), } -#[derive(Clone, Debug, Deserialize)] +#[derive(Clone, Debug, Deserialize, Serialize)] #[serde(rename_all = "camelCase")] pub struct BankOfAmericaClientReferenceResponse { id: String, @@ -927,14 +927,14 @@ pub struct BankOfAmericaClientReferenceResponse { error_information: Option<BankOfAmericaErrorInformation>, } -#[derive(Clone, Debug, Deserialize)] +#[derive(Clone, Debug, Deserialize, Serialize)] #[serde(rename_all = "camelCase")] pub struct BankOfAmericaErrorInformationResponse { id: String, error_information: BankOfAmericaErrorInformation, } -#[derive(Clone, Debug, Deserialize)] +#[derive(Clone, Debug, Deserialize, Serialize)] pub struct BankOfAmericaErrorInformation { reason: Option<String>, message: Option<String>, @@ -1310,7 +1310,7 @@ impl TryFrom<&BankOfAmericaRouterData<&types::PaymentsCompleteAuthorizeRouterDat } } -#[derive(Debug, Deserialize)] +#[derive(Debug, Deserialize, Serialize)] #[serde(rename_all = "SCREAMING_SNAKE_CASE")] pub enum BankOfAmericaAuthEnrollmentStatus { PendingAuthentication, @@ -1334,7 +1334,7 @@ pub struct BankOfAmericaThreeDSMetadata { three_ds_data: BankOfAmericaConsumerAuthValidateResponse, } -#[derive(Debug, Deserialize)] +#[derive(Debug, Deserialize, Serialize)] #[serde(rename_all = "camelCase")] pub struct BankOfAmericaConsumerAuthInformationEnrollmentResponse { access_token: Option<String>, @@ -1344,7 +1344,7 @@ pub struct BankOfAmericaConsumerAuthInformationEnrollmentResponse { validate_response: BankOfAmericaConsumerAuthValidateResponse, } -#[derive(Debug, Deserialize)] +#[derive(Debug, Deserialize, Serialize)] #[serde(rename_all = "camelCase")] pub struct ClientAuthCheckInfoResponse { id: String, @@ -1354,7 +1354,7 @@ pub struct ClientAuthCheckInfoResponse { error_information: Option<BankOfAmericaErrorInformation>, } -#[derive(Debug, Deserialize)] +#[derive(Debug, Deserialize, Serialize)] #[serde(untagged)] pub enum BankOfAmericaPreProcessingResponse { ClientAuthCheckInfo(Box<ClientAuthCheckInfoResponse>), @@ -1644,14 +1644,14 @@ impl<F> } } -#[derive(Debug, Deserialize)] +#[derive(Debug, Deserialize, Serialize)] #[serde(untagged)] pub enum BankOfAmericaTransactionResponse { ApplicationInformation(BankOfAmericaApplicationInfoResponse), ErrorInformation(BankOfAmericaErrorInformationResponse), } -#[derive(Debug, Deserialize)] +#[derive(Debug, Deserialize, Serialize)] #[serde(rename_all = "camelCase")] pub struct BankOfAmericaApplicationInfoResponse { id: String, @@ -1660,7 +1660,7 @@ pub struct BankOfAmericaApplicationInfoResponse { error_information: Option<BankOfAmericaErrorInformation>, } -#[derive(Debug, Deserialize)] +#[derive(Debug, Deserialize, Serialize)] #[serde(rename_all = "camelCase")] pub struct ApplicationInformation { status: BankofamericaPaymentStatus, @@ -1879,7 +1879,7 @@ impl From<BankofamericaRefundStatus> for enums::RefundStatus { } } -#[derive(Debug, Deserialize)] +#[derive(Debug, Deserialize, Serialize)] #[serde(rename_all = "camelCase")] pub struct BankOfAmericaRefundResponse { id: String, @@ -1903,7 +1903,7 @@ impl TryFrom<types::RefundsResponseRouterData<api::Execute, BankOfAmericaRefundR } } -#[derive(Debug, Deserialize)] +#[derive(Debug, Deserialize, Serialize)] #[serde(rename_all = "SCREAMING_SNAKE_CASE")] pub enum BankofamericaRefundStatus { Succeeded, @@ -1913,13 +1913,13 @@ pub enum BankofamericaRefundStatus { Voided, } -#[derive(Debug, Deserialize)] +#[derive(Debug, Deserialize, Serialize)] #[serde(rename_all = "camelCase")] pub struct RsyncApplicationInformation { status: BankofamericaRefundStatus, } -#[derive(Debug, Deserialize)] +#[derive(Debug, Deserialize, Serialize)] #[serde(rename_all = "camelCase")] pub struct BankOfAmericaRsyncResponse { id: String, @@ -1945,7 +1945,7 @@ impl TryFrom<types::RefundsResponseRouterData<api::RSync, BankOfAmericaRsyncResp } } -#[derive(Debug, Deserialize)] +#[derive(Debug, Deserialize, Serialize)] #[serde(rename_all = "camelCase")] pub struct BankOfAmericaStandardErrorResponse { pub error_information: Option<ErrorInformation>, @@ -1955,7 +1955,7 @@ pub struct BankOfAmericaStandardErrorResponse { pub details: Option<Vec<Details>>, } -#[derive(Debug, Deserialize)] +#[derive(Debug, Deserialize, Serialize)] #[serde(rename_all = "camelCase")] pub struct BankOfAmericaServerErrorResponse { pub status: Option<String>, @@ -1963,7 +1963,7 @@ pub struct BankOfAmericaServerErrorResponse { pub reason: Option<Reason>, } -#[derive(Debug, Deserialize)] +#[derive(Debug, Deserialize, Serialize)] #[serde(rename_all = "SCREAMING_SNAKE_CASE")] pub enum Reason { SystemError, @@ -1971,32 +1971,32 @@ pub enum Reason { ServiceTimeout, } -#[derive(Debug, Deserialize)] +#[derive(Debug, Deserialize, Serialize)] pub struct BankOfAmericaAuthenticationErrorResponse { pub response: AuthenticationErrorInformation, } -#[derive(Debug, Deserialize)] +#[derive(Debug, Deserialize, Serialize)] #[serde(untagged)] pub enum BankOfAmericaErrorResponse { AuthenticationError(BankOfAmericaAuthenticationErrorResponse), StandardError(BankOfAmericaStandardErrorResponse), } -#[derive(Debug, Deserialize, Clone)] +#[derive(Debug, Deserialize, Clone, Serialize)] #[serde(rename_all = "camelCase")] pub struct Details { pub field: String, pub reason: String, } -#[derive(Debug, Default, Deserialize)] +#[derive(Debug, Default, Deserialize, Serialize)] pub struct ErrorInformation { pub message: String, pub reason: String, } -#[derive(Debug, Default, Deserialize)] +#[derive(Debug, Default, Deserialize, Serialize)] pub struct AuthenticationErrorInformation { pub rmsg: String, } diff --git a/crates/router/src/connector/bitpay.rs b/crates/router/src/connector/bitpay.rs index 4a8108d04b8..61e8cb03a27 100644 --- a/crates/router/src/connector/bitpay.rs +++ b/crates/router/src/connector/bitpay.rs @@ -12,6 +12,7 @@ use crate::{ configs::settings, consts, core::errors::{self, CustomResult}, + events::connector_api_logs::ConnectorEvent, headers, services::{ self, @@ -109,10 +110,14 @@ impl ConnectorCommon for Bitpay { fn build_error_response( &self, res: Response, + event_builder: Option<&mut ConnectorEvent>, ) -> CustomResult<ErrorResponse, errors::ConnectorError> { let response: bitpay::BitpayErrorResponse = res.response.parse_struct("BitpayErrorResponse").switch()?; + event_builder.map(|i| i.set_error_response_body(&response)); + router_env::logger::info!(connector_response=?response); + Ok(ErrorResponse { status_code: res.status_code, code: response @@ -226,12 +231,15 @@ impl ConnectorIntegration<api::Authorize, types::PaymentsAuthorizeData, types::P fn handle_response( &self, data: &types::PaymentsAuthorizeRouterData, + event_builder: Option<&mut ConnectorEvent>, res: Response, ) -> CustomResult<types::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 { response, data: data.clone(), @@ -242,8 +250,9 @@ impl ConnectorIntegration<api::Authorize, types::PaymentsAuthorizeData, types::P fn get_error_response( &self, res: Response, + event_builder: Option<&mut ConnectorEvent>, ) -> CustomResult<ErrorResponse, errors::ConnectorError> { - self.build_error_response(res) + self.build_error_response(res, event_builder) } } @@ -300,12 +309,15 @@ impl ConnectorIntegration<api::PSync, types::PaymentsSyncData, types::PaymentsRe fn handle_response( &self, data: &types::PaymentsSyncRouterData, + event_builder: Option<&mut ConnectorEvent>, res: Response, ) -> CustomResult<types::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 { response, data: data.clone(), @@ -316,8 +328,9 @@ impl ConnectorIntegration<api::PSync, types::PaymentsSyncData, types::PaymentsRe fn get_error_response( &self, res: Response, + event_builder: Option<&mut ConnectorEvent>, ) -> CustomResult<ErrorResponse, errors::ConnectorError> { - self.build_error_response(res) + self.build_error_response(res, event_builder) } } diff --git a/crates/router/src/connector/bitpay/transformers.rs b/crates/router/src/connector/bitpay/transformers.rs index 0ddf2dbf913..148a5a45636 100644 --- a/crates/router/src/connector/bitpay/transformers.rs +++ b/crates/router/src/connector/bitpay/transformers.rs @@ -266,7 +266,7 @@ impl TryFrom<types::RefundsResponseRouterData<api::RSync, RefundResponse>> } } -#[derive(Debug, Deserialize)] +#[derive(Debug, Deserialize, Serialize)] pub struct BitpayErrorResponse { pub error: String, pub code: Option<String>, diff --git a/crates/router/src/connector/bluesnap.rs b/crates/router/src/connector/bluesnap.rs index e54d8320d0f..824a073136f 100644 --- a/crates/router/src/connector/bluesnap.rs +++ b/crates/router/src/connector/bluesnap.rs @@ -24,6 +24,7 @@ use crate::{ errors::{self, CustomResult}, payments, }, + events::connector_api_logs::ConnectorEvent, headers, logger, services::{ self, @@ -96,13 +97,16 @@ impl ConnectorCommon for Bluesnap { fn build_error_response( &self, res: Response, + event_builder: Option<&mut ConnectorEvent>, ) -> CustomResult<ErrorResponse, errors::ConnectorError> { logger::debug!(bluesnap_error_response=?res); let response: bluesnap::BluesnapErrors = res .response .parse_struct("BluesnapErrorResponse") .change_context(errors::ConnectorError::ResponseDeserializationFailed)?; - router_env::logger::info!(error_response=?response); + + event_builder.map(|i| i.set_error_response_body(&response)); + router_env::logger::info!(connector_response=?response); let response_error_message = match response { bluesnap::BluesnapErrors::Payment(error_response) => { @@ -307,12 +311,14 @@ impl ConnectorIntegration<api::Void, types::PaymentsCancelData, types::PaymentsR fn handle_response( &self, data: &types::PaymentsCancelRouterData, + event_builder: Option<&mut ConnectorEvent>, res: Response, ) -> CustomResult<types::PaymentsCancelRouterData, errors::ConnectorError> { let response: bluesnap::BluesnapPaymentsResponse = res .response .parse_struct("BluesnapPaymentsResponse") .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, @@ -325,8 +331,9 @@ impl ConnectorIntegration<api::Void, types::PaymentsCancelData, types::PaymentsR fn get_error_response( &self, res: Response, + event_builder: Option<&mut ConnectorEvent>, ) -> CustomResult<ErrorResponse, errors::ConnectorError> { - self.build_error_response(res) + self.build_error_response(res, event_builder) } } @@ -399,19 +406,22 @@ impl ConnectorIntegration<api::PSync, types::PaymentsSyncData, types::PaymentsRe fn get_error_response( &self, res: Response, + event_builder: Option<&mut ConnectorEvent>, ) -> CustomResult<ErrorResponse, errors::ConnectorError> { - self.build_error_response(res) + self.build_error_response(res, event_builder) } fn handle_response( &self, data: &types::PaymentsSyncRouterData, + event_builder: Option<&mut ConnectorEvent>, res: Response, ) -> CustomResult<types::PaymentsSyncRouterData, errors::ConnectorError> { let response: bluesnap::BluesnapPaymentsResponse = res .response .parse_struct("BluesnapPaymentsResponse") .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, @@ -487,12 +497,14 @@ impl ConnectorIntegration<api::Capture, types::PaymentsCaptureData, types::Payme fn handle_response( &self, data: &types::PaymentsCaptureRouterData, + event_builder: Option<&mut ConnectorEvent>, res: Response, ) -> CustomResult<types::PaymentsCaptureRouterData, errors::ConnectorError> { let response: bluesnap::BluesnapPaymentsResponse = res .response .parse_struct("Bluesnap BluesnapPaymentsResponse") .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, @@ -505,8 +517,9 @@ impl ConnectorIntegration<api::Capture, types::PaymentsCaptureData, types::Payme fn get_error_response( &self, res: Response, + event_builder: Option<&mut ConnectorEvent>, ) -> CustomResult<ErrorResponse, errors::ConnectorError> { - self.build_error_response(res) + self.build_error_response(res, event_builder) } } @@ -572,13 +585,15 @@ impl ConnectorIntegration<api::Session, types::PaymentsSessionData, types::Payme fn handle_response( &self, data: &types::PaymentsSessionRouterData, + event_builder: Option<&mut ConnectorEvent>, res: Response, ) -> CustomResult<types::PaymentsSessionRouterData, errors::ConnectorError> { let response: bluesnap::BluesnapWalletTokenResponse = res .response .parse_struct("BluesnapWalletTokenResponse") .change_context(errors::ConnectorError::ResponseDeserializationFailed)?; - router_env::logger::info!(connector_response=?response); + event_builder.map(|i| i.set_response_body(&response)); + types::RouterData::try_from(types::ResponseRouterData { response, data: data.clone(), @@ -589,8 +604,9 @@ impl ConnectorIntegration<api::Session, types::PaymentsSessionData, types::Payme fn get_error_response( &self, res: Response, + event_builder: Option<&mut ConnectorEvent>, ) -> CustomResult<ErrorResponse, errors::ConnectorError> { - self.build_error_response(res) + self.build_error_response(res, event_builder) } } @@ -681,6 +697,7 @@ impl ConnectorIntegration<api::Authorize, types::PaymentsAuthorizeData, types::P fn handle_response( &self, data: &types::PaymentsAuthorizeRouterData, + event_builder: Option<&mut ConnectorEvent>, res: Response, ) -> CustomResult<types::PaymentsAuthorizeRouterData, errors::ConnectorError> { match (data.is_three_ds() && data.request.is_card(), res.headers) { @@ -692,6 +709,13 @@ impl ConnectorIntegration<api::Authorize, types::PaymentsAuthorizeData, types::P .last() .ok_or(errors::ConnectorError::ResponseHandlingFailed)? .to_string(); + + let response = + serde_json::json!({"payment_fields_token": payment_fields_token.clone()}); + + event_builder.map(|i| i.set_response_body(&response)); + router_env::logger::info!(connector_response=?response); + Ok(types::RouterData { status: enums::AttemptStatus::AuthenticationPending, response: Ok(types::PaymentsResponseData::TransactionResponse { @@ -713,6 +737,7 @@ impl ConnectorIntegration<api::Authorize, types::PaymentsAuthorizeData, types::P .response .parse_struct("BluesnapPaymentsResponse") .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, @@ -726,8 +751,9 @@ impl ConnectorIntegration<api::Authorize, types::PaymentsAuthorizeData, types::P fn get_error_response( &self, res: Response, + event_builder: Option<&mut ConnectorEvent>, ) -> CustomResult<ErrorResponse, errors::ConnectorError> { - self.build_error_response(res) + self.build_error_response(res, event_builder) } } @@ -799,12 +825,14 @@ impl fn handle_response( &self, data: &types::PaymentsCompleteAuthorizeRouterData, + event_builder: Option<&mut ConnectorEvent>, res: Response, ) -> CustomResult<types::PaymentsCompleteAuthorizeRouterData, errors::ConnectorError> { let response: bluesnap::BluesnapPaymentsResponse = res .response .parse_struct("BluesnapPaymentsResponse") .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, @@ -817,8 +845,9 @@ impl fn get_error_response( &self, res: Response, + event_builder: Option<&mut ConnectorEvent>, ) -> CustomResult<ErrorResponse, errors::ConnectorError> { - self.build_error_response(res) + self.build_error_response(res, event_builder) } } @@ -891,12 +920,14 @@ impl ConnectorIntegration<api::Execute, types::RefundsData, types::RefundsRespon 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: bluesnap::RefundResponse = res .response .parse_struct("bluesnap 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 { response, @@ -909,8 +940,9 @@ impl ConnectorIntegration<api::Execute, types::RefundsData, types::RefundsRespon fn get_error_response( &self, res: Response, + event_builder: Option<&mut ConnectorEvent>, ) -> CustomResult<ErrorResponse, errors::ConnectorError> { - self.build_error_response(res) + self.build_error_response(res, event_builder) } } @@ -974,12 +1006,14 @@ impl ConnectorIntegration<api::RSync, types::RefundsData, types::RefundsResponse fn handle_response( &self, data: &types::RefundSyncRouterData, + event_builder: Option<&mut ConnectorEvent>, res: Response, ) -> CustomResult<types::RefundSyncRouterData, errors::ConnectorError> { let response: bluesnap::BluesnapPaymentsResponse = res .response .parse_struct("bluesnap BluesnapPaymentsResponse") .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, @@ -992,8 +1026,9 @@ impl ConnectorIntegration<api::RSync, types::RefundsData, types::RefundsResponse fn get_error_response( &self, res: Response, + event_builder: Option<&mut ConnectorEvent>, ) -> CustomResult<ErrorResponse, errors::ConnectorError> { - self.build_error_response(res) + self.build_error_response(res, event_builder) } } diff --git a/crates/router/src/connector/bluesnap/transformers.rs b/crates/router/src/connector/bluesnap/transformers.rs index e98b98e874a..f1c27d72749 100644 --- a/crates/router/src/connector/bluesnap/transformers.rs +++ b/crates/router/src/connector/bluesnap/transformers.rs @@ -926,14 +926,14 @@ impl<F> TryFrom<&BluesnapRouterData<&types::RefundsRouterData<F>>> for BluesnapR } } -#[derive(Debug, Clone, Default, Deserialize)] +#[derive(Debug, Clone, Default, Deserialize, Serialize)] #[serde(rename_all = "UPPERCASE")] pub enum BluesnapRefundStatus { Success, #[default] Pending, } -#[derive(Default, Debug, Clone, Deserialize)] +#[derive(Default, Debug, Clone, Deserialize, Serialize)] #[serde(rename_all = "camelCase")] pub struct RefundResponse { refund_transaction_id: i32, @@ -1122,13 +1122,13 @@ pub struct ErrorDetails { pub error_name: Option<String>, } -#[derive(Default, Debug, Clone, Deserialize)] +#[derive(Default, Debug, Clone, Deserialize, Serialize)] #[serde(rename_all = "camelCase")] pub struct BluesnapErrorResponse { pub message: Vec<ErrorDetails>, } -#[derive(Default, Debug, Clone, Deserialize)] +#[derive(Default, Debug, Clone, Deserialize, Serialize)] #[serde(rename_all = "camelCase")] pub struct BluesnapAuthErrorResponse { pub error_code: String, @@ -1136,7 +1136,7 @@ pub struct BluesnapAuthErrorResponse { pub error_name: Option<String>, } -#[derive(Debug, Clone, Deserialize)] +#[derive(Debug, Clone, Deserialize, Serialize)] #[serde(untagged)] pub enum BluesnapErrors { Payment(BluesnapErrorResponse), diff --git a/crates/router/src/connector/boku.rs b/crates/router/src/connector/boku.rs index 39566e08d47..7b470593e7f 100644 --- a/crates/router/src/connector/boku.rs +++ b/crates/router/src/connector/boku.rs @@ -15,6 +15,7 @@ use crate::{ configs::settings, consts, core::errors::{self, CustomResult}, + events::connector_api_logs::ConnectorEvent, headers, logger, routes::metrics, services::{ @@ -117,6 +118,7 @@ impl ConnectorCommon for Boku { fn build_error_response( &self, res: Response, + event_builder: Option<&mut ConnectorEvent>, ) -> CustomResult<ErrorResponse, errors::ConnectorError> { let response_data: Result<boku::BokuErrorResponse, Report<errors::ConnectorError>> = res .response @@ -124,15 +126,19 @@ impl ConnectorCommon for Boku { .change_context(errors::ConnectorError::ResponseDeserializationFailed); match response_data { - Ok(response) => Ok(ErrorResponse { - status_code: res.status_code, - code: response.code, - message: response.message, - reason: response.reason, - attempt_status: None, - connector_transaction_id: None, - }), - Err(_) => get_xml_deserialized(res), + Ok(response) => { + 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, + }) + } + Err(_) => get_xml_deserialized(res, event_builder), } } } @@ -252,6 +258,7 @@ impl ConnectorIntegration<api::Authorize, types::PaymentsAuthorizeData, types::P fn handle_response( &self, data: &types::PaymentsAuthorizeRouterData, + event_builder: Option<&mut ConnectorEvent>, res: Response, ) -> CustomResult<types::PaymentsAuthorizeRouterData, errors::ConnectorError> { let response_data = String::from_utf8(res.response.to_vec()) @@ -262,7 +269,8 @@ impl ConnectorIntegration<api::Authorize, types::PaymentsAuthorizeData, types::P .parse_xml::<boku::BokuResponse>() .into_report() .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(), @@ -273,8 +281,9 @@ impl ConnectorIntegration<api::Authorize, types::PaymentsAuthorizeData, types::P fn get_error_response( &self, res: Response, + event_builder: Option<&mut ConnectorEvent>, ) -> CustomResult<ErrorResponse, errors::ConnectorError> { - self.build_error_response(res) + self.build_error_response(res, event_builder) } } @@ -336,6 +345,7 @@ impl ConnectorIntegration<api::PSync, types::PaymentsSyncData, types::PaymentsRe fn handle_response( &self, data: &types::PaymentsSyncRouterData, + event_builder: Option<&mut ConnectorEvent>, res: Response, ) -> CustomResult<types::PaymentsSyncRouterData, errors::ConnectorError> { let response_data = String::from_utf8(res.response.to_vec()) @@ -346,7 +356,8 @@ impl ConnectorIntegration<api::PSync, types::PaymentsSyncData, types::PaymentsRe .parse_xml::<boku::BokuResponse>() .into_report() .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(), @@ -357,8 +368,9 @@ impl ConnectorIntegration<api::PSync, types::PaymentsSyncData, types::PaymentsRe fn get_error_response( &self, res: Response, + event_builder: Option<&mut ConnectorEvent>, ) -> CustomResult<ErrorResponse, errors::ConnectorError> { - self.build_error_response(res) + self.build_error_response(res, event_builder) } } @@ -416,6 +428,7 @@ impl ConnectorIntegration<api::Capture, types::PaymentsCaptureData, types::Payme fn handle_response( &self, data: &types::PaymentsCaptureRouterData, + event_builder: Option<&mut ConnectorEvent>, res: Response, ) -> CustomResult<types::PaymentsCaptureRouterData, errors::ConnectorError> { let response_data = String::from_utf8(res.response.to_vec()) @@ -426,7 +439,8 @@ impl ConnectorIntegration<api::Capture, types::PaymentsCaptureData, types::Payme .parse_xml::<boku::BokuResponse>() .into_report() .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(), @@ -437,8 +451,9 @@ impl ConnectorIntegration<api::Capture, types::PaymentsCaptureData, types::Payme fn get_error_response( &self, res: Response, + event_builder: Option<&mut ConnectorEvent>, ) -> CustomResult<ErrorResponse, errors::ConnectorError> { - self.build_error_response(res) + self.build_error_response(res, event_builder) } } @@ -504,12 +519,17 @@ impl ConnectorIntegration<api::Execute, types::RefundsData, types::RefundsRespon 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: boku::RefundResponse = res .response .parse_struct("boku RefundResponse") .change_context(errors::ConnectorError::ResponseDeserializationFailed)?; + + event_builder.map(|i| i.set_error_response_body(&response)); + router_env::logger::info!(connector_response=?response); + types::RouterData::try_from(types::ResponseRouterData { response, data: data.clone(), @@ -520,8 +540,9 @@ impl ConnectorIntegration<api::Execute, types::RefundsData, types::RefundsRespon fn get_error_response( &self, res: Response, + event_builder: Option<&mut ConnectorEvent>, ) -> CustomResult<ErrorResponse, errors::ConnectorError> { - self.build_error_response(res) + self.build_error_response(res, event_builder) } } @@ -581,12 +602,15 @@ impl ConnectorIntegration<api::RSync, types::RefundsData, types::RefundsResponse fn handle_response( &self, data: &types::RefundSyncRouterData, + event_builder: Option<&mut ConnectorEvent>, res: Response, ) -> CustomResult<types::RefundSyncRouterData, errors::ConnectorError> { let response: boku::BokuRsyncResponse = res .response .parse_struct("boku BokuRsyncResponse") .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(), @@ -597,8 +621,9 @@ impl ConnectorIntegration<api::RSync, types::RefundsData, types::RefundsResponse fn get_error_response( &self, res: Response, + event_builder: Option<&mut ConnectorEvent>, ) -> CustomResult<ErrorResponse, errors::ConnectorError> { - self.build_error_response(res) + self.build_error_response(res, event_builder) } } @@ -638,7 +663,10 @@ fn get_country_url( } // validate xml format for the error -fn get_xml_deserialized(res: Response) -> CustomResult<ErrorResponse, errors::ConnectorError> { +fn get_xml_deserialized( + res: Response, + event_builder: Option<&mut ConnectorEvent>, +) -> CustomResult<ErrorResponse, errors::ConnectorError> { metrics::RESPONSE_DESERIALIZATION_FAILURE.add( &metrics::CONTEXT, 1, @@ -649,6 +677,9 @@ fn get_xml_deserialized(res: Response) -> CustomResult<ErrorResponse, errors::Co .into_report() .change_context(errors::ConnectorError::ResponseDeserializationFailed)?; + event_builder.map(|i| i.set_error_response_body(&response_data)); + router_env::logger::info!(connector_response=?response_data); + // check for whether the response is in xml format match roxmltree::Document::parse(&response_data) { // in case of unexpected response but in xml format diff --git a/crates/router/src/connector/boku/transformers.rs b/crates/router/src/connector/boku/transformers.rs index 6d830f85110..5f36225fd40 100644 --- a/crates/router/src/connector/boku/transformers.rs +++ b/crates/router/src/connector/boku/transformers.rs @@ -225,14 +225,14 @@ pub struct BokuMetaData { pub(super) country: String, } -#[derive(Debug, Clone, Deserialize)] +#[derive(Debug, Clone, Deserialize, Serialize)] #[serde(rename_all = "kebab-case")] pub enum BokuResponse { BeginSingleChargeResponse(BokuPaymentsResponse), QueryChargeResponse(BokuPsyncResponse), } -#[derive(Debug, Clone, Deserialize)] +#[derive(Debug, Clone, Deserialize, Serialize)] #[serde(rename_all = "kebab-case")] pub struct BokuPaymentsResponse { charge_status: String, // xml parse only string to fields @@ -240,26 +240,26 @@ pub struct BokuPaymentsResponse { hosted: Option<HostedUrlResponse>, } -#[derive(Debug, Clone, Deserialize)] +#[derive(Debug, Clone, Deserialize, Serialize)] #[serde(rename_all = "kebab-case")] pub struct HostedUrlResponse { redirect_url: Option<Url>, } -#[derive(Debug, Clone, Deserialize)] +#[derive(Debug, Clone, Deserialize, Serialize)] #[serde(rename = "query-charge-response")] #[serde(rename_all = "kebab-case")] pub struct BokuPsyncResponse { charges: ChargeResponseData, } -#[derive(Debug, Clone, Deserialize)] +#[derive(Debug, Clone, Deserialize, Serialize)] #[serde(rename_all = "kebab-case")] pub struct ChargeResponseData { charge: SingleChargeResponseData, } -#[derive(Debug, Clone, Deserialize)] +#[derive(Debug, Clone, Deserialize, Serialize)] #[serde(rename_all = "kebab-case")] pub struct SingleChargeResponseData { charge_status: String, @@ -368,7 +368,7 @@ impl<F> TryFrom<&types::RefundsRouterData<F>> for BokuRefundRequest { } } -#[derive(Debug, Clone, Deserialize)] +#[derive(Debug, Clone, Deserialize, Serialize)] #[serde(rename = "refund-charge-response")] pub struct RefundResponse { charge_id: String, @@ -424,20 +424,20 @@ impl TryFrom<&types::RefundSyncRouterData> for BokuRsyncRequest { } } -#[derive(Debug, Clone, Deserialize)] +#[derive(Debug, Clone, Deserialize, Serialize)] #[serde(rename = "query-refund-response")] #[serde(rename_all = "kebab-case")] pub struct BokuRsyncResponse { refunds: RefundResponseData, } -#[derive(Debug, Clone, Deserialize)] +#[derive(Debug, Clone, Deserialize, Serialize)] #[serde(rename_all = "kebab-case")] pub struct RefundResponseData { refund: SingleRefundResponseData, } -#[derive(Debug, Clone, Deserialize)] +#[derive(Debug, Clone, Deserialize, Serialize)] #[serde(rename_all = "kebab-case")] pub struct SingleRefundResponseData { refund_status: String, // quick-xml only parse string as a field diff --git a/crates/router/src/connector/braintree.rs b/crates/router/src/connector/braintree.rs index 4f2686abb13..629a9661033 100644 --- a/crates/router/src/connector/braintree.rs +++ b/crates/router/src/connector/braintree.rs @@ -20,6 +20,7 @@ use crate::{ errors::{self, CustomResult}, payments, }, + events::connector_api_logs::ConnectorEvent, headers, logger, services::{ self, @@ -103,12 +104,16 @@ impl ConnectorCommon for Braintree { fn build_error_response( &self, res: types::Response, + event_builder: Option<&mut ConnectorEvent>, ) -> CustomResult<ErrorResponse, errors::ConnectorError> { let response: Result<braintree::ErrorResponse, Report<common_utils::errors::ParsingError>> = res.response.parse_struct("Braintree Error Response"); match response { Ok(braintree::ErrorResponse::BraintreeApiErrorResponse(response)) => { + event_builder.map(|i| i.set_error_response_body(&response)); + router_env::logger::info!(connector_response=?response); + let error_object = response.api_error_response.errors; let error = error_object.errors.first().or(error_object .transaction @@ -135,15 +140,21 @@ impl ConnectorCommon for Braintree { connector_transaction_id: None, }) } - Ok(braintree::ErrorResponse::BraintreeErrorResponse(response)) => Ok(ErrorResponse { - status_code: res.status_code, - code: consts::NO_ERROR_CODE.to_string(), - message: consts::NO_ERROR_MESSAGE.to_string(), - reason: Some(response.errors), - attempt_status: None, - connector_transaction_id: None, - }), + Ok(braintree::ErrorResponse::BraintreeErrorResponse(response)) => { + event_builder.map(|i| i.set_error_response_body(&response)); + router_env::logger::info!(connector_response=?response); + + Ok(ErrorResponse { + status_code: res.status_code, + code: consts::NO_ERROR_CODE.to_string(), + message: consts::NO_ERROR_MESSAGE.to_string(), + reason: Some(response.errors), + attempt_status: None, + connector_transaction_id: None, + }) + } Err(error_msg) => { + event_builder.map(|event| event.set_error(serde_json::json!({"error": res.response.escape_ascii().to_string(), "status_code": res.status_code}))); logger::error!(deserialization_error =? error_msg); utils::handle_json_response_deserialization_failure(res, "braintree".to_owned()) } @@ -256,8 +267,9 @@ impl ConnectorIntegration<api::Session, types::PaymentsSessionData, types::Payme fn get_error_response( &self, res: types::Response, + event_builder: Option<&mut ConnectorEvent>, ) -> CustomResult<ErrorResponse, errors::ConnectorError> { - self.build_error_response(res) + self.build_error_response(res, event_builder) } fn get_request_body( @@ -272,12 +284,15 @@ impl ConnectorIntegration<api::Session, types::PaymentsSessionData, types::Payme fn handle_response( &self, data: &types::PaymentsSessionRouterData, + event_builder: Option<&mut ConnectorEvent>, res: types::Response, ) -> CustomResult<types::PaymentsSessionRouterData, errors::ConnectorError> { let response: braintree::BraintreeSessionTokenResponse = res .response .parse_struct("braintree SessionTokenResponse") .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(), @@ -355,6 +370,7 @@ impl fn handle_response( &self, data: &types::TokenizationRouterData, + event_builder: Option<&mut ConnectorEvent>, res: types::Response, ) -> CustomResult<types::TokenizationRouterData, errors::ConnectorError> where @@ -364,6 +380,8 @@ impl .response .parse_struct("BraintreeTokenResponse") .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, @@ -374,8 +392,9 @@ impl fn get_error_response( &self, res: types::Response, + event_builder: Option<&mut ConnectorEvent>, ) -> CustomResult<ErrorResponse, errors::ConnectorError> { - self.build_error_response(res) + self.build_error_response(res, event_builder) } } @@ -505,12 +524,15 @@ impl ConnectorIntegration<api::Capture, types::PaymentsCaptureData, types::Payme fn handle_response( &self, data: &types::PaymentsCaptureRouterData, + event_builder: Option<&mut ConnectorEvent>, res: types::Response, ) -> CustomResult<types::PaymentsCaptureRouterData, errors::ConnectorError> { let response: braintree_graphql_transformers::BraintreeCaptureResponse = res .response .parse_struct("Braintree 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(), @@ -521,8 +543,9 @@ impl ConnectorIntegration<api::Capture, types::PaymentsCaptureData, types::Payme fn get_error_response( &self, res: types::Response, + event_builder: Option<&mut ConnectorEvent>, ) -> CustomResult<ErrorResponse, errors::ConnectorError> { - self.build_error_response(res) + self.build_error_response(res, event_builder) } } @@ -646,6 +669,7 @@ impl ConnectorIntegration<api::PSync, types::PaymentsSyncData, types::PaymentsRe fn handle_response( &self, data: &types::PaymentsSyncRouterData, + event_builder: Option<&mut ConnectorEvent>, res: types::Response, ) -> CustomResult<types::PaymentsSyncRouterData, errors::ConnectorError> { let connector_api_version = &data.connector_api_version; @@ -655,6 +679,8 @@ impl ConnectorIntegration<api::PSync, types::PaymentsSyncData, types::PaymentsRe .response .parse_struct("Braintree 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 { response, data: data.clone(), @@ -666,6 +692,8 @@ impl ConnectorIntegration<api::PSync, types::PaymentsSyncData, types::PaymentsRe .response .parse_struct("Braintree PaymentsResponse") .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(), @@ -678,8 +706,9 @@ impl ConnectorIntegration<api::PSync, types::PaymentsSyncData, types::PaymentsRe fn get_error_response( &self, res: types::Response, + event_builder: Option<&mut ConnectorEvent>, ) -> CustomResult<ErrorResponse, errors::ConnectorError> { - self.build_error_response(res) + self.build_error_response(res, event_builder) } } @@ -796,6 +825,7 @@ impl ConnectorIntegration<api::Authorize, types::PaymentsAuthorizeData, types::P fn handle_response( &self, data: &types::PaymentsAuthorizeRouterData, + event_builder: Option<&mut ConnectorEvent>, res: types::Response, ) -> CustomResult<types::PaymentsAuthorizeRouterData, errors::ConnectorError> { let connector_api_version = &data.connector_api_version; @@ -806,6 +836,8 @@ impl ConnectorIntegration<api::Authorize, types::PaymentsAuthorizeData, types::P .response .parse_struct("Braintree PaymentsResponse") .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(), @@ -817,6 +849,8 @@ impl ConnectorIntegration<api::Authorize, types::PaymentsAuthorizeData, types::P .response .parse_struct("Braintree AuthResponse") .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(), @@ -829,6 +863,8 @@ impl ConnectorIntegration<api::Authorize, types::PaymentsAuthorizeData, types::P .response .parse_struct("Braintree PaymentsResponse") .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(), @@ -841,8 +877,9 @@ impl ConnectorIntegration<api::Authorize, types::PaymentsAuthorizeData, types::P fn get_error_response( &self, res: types::Response, + event_builder: Option<&mut ConnectorEvent>, ) -> CustomResult<ErrorResponse, errors::ConnectorError> { - self.build_error_response(res) + self.build_error_response(res, event_builder) } } @@ -947,6 +984,7 @@ impl ConnectorIntegration<api::Void, types::PaymentsCancelData, types::PaymentsR fn handle_response( &self, data: &types::PaymentsCancelRouterData, + event_builder: Option<&mut ConnectorEvent>, res: types::Response, ) -> CustomResult<types::PaymentsCancelRouterData, errors::ConnectorError> { let connector_api_version = &data.connector_api_version; @@ -956,6 +994,8 @@ impl ConnectorIntegration<api::Void, types::PaymentsCancelData, types::PaymentsR .response .parse_struct("Braintree VoidResponse") .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(), @@ -967,6 +1007,8 @@ impl ConnectorIntegration<api::Void, types::PaymentsCancelData, types::PaymentsR .response .parse_struct("Braintree PaymentsVoidResponse") .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(), @@ -979,8 +1021,9 @@ impl ConnectorIntegration<api::Void, types::PaymentsCancelData, types::PaymentsR fn get_error_response( &self, res: types::Response, + event_builder: Option<&mut ConnectorEvent>, ) -> CustomResult<ErrorResponse, errors::ConnectorError> { - self.build_error_response(res) + self.build_error_response(res, event_builder) } } @@ -1103,6 +1146,7 @@ impl ConnectorIntegration<api::Execute, types::RefundsData, types::RefundsRespon fn handle_response( &self, data: &types::RefundsRouterData<api::Execute>, + event_builder: Option<&mut ConnectorEvent>, res: types::Response, ) -> CustomResult<types::RefundsRouterData<api::Execute>, errors::ConnectorError> { let connector_api_version = &data.connector_api_version; @@ -1112,6 +1156,8 @@ impl ConnectorIntegration<api::Execute, types::RefundsData, types::RefundsRespon .response .parse_struct("Braintree 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 { response, data: data.clone(), @@ -1123,6 +1169,8 @@ impl ConnectorIntegration<api::Execute, types::RefundsData, types::RefundsRespon .response .parse_struct("Braintree 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 { response, data: data.clone(), @@ -1135,8 +1183,9 @@ impl ConnectorIntegration<api::Execute, types::RefundsData, types::RefundsRespon fn get_error_response( &self, res: types::Response, + event_builder: Option<&mut ConnectorEvent>, ) -> CustomResult<ErrorResponse, errors::ConnectorError> { - self.build_error_response(res) + self.build_error_response(res, event_builder) } } @@ -1221,6 +1270,7 @@ impl ConnectorIntegration<api::RSync, types::RefundsData, types::RefundsResponse fn handle_response( &self, data: &types::RefundSyncRouterData, + event_builder: Option<&mut ConnectorEvent>, res: types::Response, ) -> CustomResult< types::RouterData<api::RSync, types::RefundsData, types::RefundsResponseData>, @@ -1233,6 +1283,8 @@ impl ConnectorIntegration<api::RSync, types::RefundsData, types::RefundsResponse .response .parse_struct("Braintree 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(), @@ -1244,6 +1296,8 @@ impl ConnectorIntegration<api::RSync, types::RefundsData, types::RefundsResponse .response .parse_struct("Braintree 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(), @@ -1255,8 +1309,9 @@ impl ConnectorIntegration<api::RSync, types::RefundsData, types::RefundsResponse fn get_error_response( &self, res: types::Response, + event_builder: Option<&mut ConnectorEvent>, ) -> CustomResult<ErrorResponse, errors::ConnectorError> { - self.build_error_response(res) + self.build_error_response(res, event_builder) } } @@ -1626,6 +1681,7 @@ impl fn handle_response( &self, data: &types::PaymentsCompleteAuthorizeRouterData, + event_builder: Option<&mut ConnectorEvent>, res: types::Response, ) -> CustomResult<types::PaymentsCompleteAuthorizeRouterData, errors::ConnectorError> { match connector_utils::PaymentsCompleteAuthorizeRequestData::is_auto_capture(&data.request)? @@ -1635,6 +1691,7 @@ impl .response .parse_struct("Braintree PaymentsResponse") .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, @@ -1647,6 +1704,8 @@ impl .response .parse_struct("Braintree AuthResponse") .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(), @@ -1659,7 +1718,8 @@ impl fn get_error_response( &self, res: types::Response, + event_builder: Option<&mut ConnectorEvent>, ) -> CustomResult<ErrorResponse, errors::ConnectorError> { - self.build_error_response(res) + self.build_error_response(res, event_builder) } } diff --git a/crates/router/src/connector/braintree/braintree_graphql_transformers.rs b/crates/router/src/connector/braintree/braintree_graphql_transformers.rs index e0baf034f72..436cd8dfa36 100644 --- a/crates/router/src/connector/braintree/braintree_graphql_transformers.rs +++ b/crates/router/src/connector/braintree/braintree_graphql_transformers.rs @@ -182,12 +182,12 @@ impl TryFrom<&BraintreeRouterData<&types::PaymentsCompleteAuthorizeRouterData>> } } -#[derive(Debug, Clone, Deserialize)] +#[derive(Debug, Clone, Deserialize, Serialize)] pub struct AuthResponse { data: DataAuthResponse, } -#[derive(Debug, Clone, Deserialize)] +#[derive(Debug, Clone, Deserialize, Serialize)] #[serde(untagged)] pub enum BraintreeAuthResponse { AuthResponse(Box<AuthResponse>), @@ -195,26 +195,26 @@ pub enum BraintreeAuthResponse { ErrorResponse(Box<ErrorResponse>), } -#[derive(Debug, Clone, Deserialize)] +#[derive(Debug, Clone, Deserialize, Serialize)] #[serde(untagged)] pub enum BraintreeCompleteAuthResponse { AuthResponse(Box<AuthResponse>), ErrorResponse(Box<ErrorResponse>), } -#[derive(Debug, Clone, Deserialize)] +#[derive(Debug, Clone, Deserialize, Serialize)] pub struct TransactionAuthChargeResponseBody { id: String, status: BraintreePaymentStatus, } -#[derive(Debug, Clone, Deserialize)] +#[derive(Debug, Clone, Deserialize, Serialize)] #[serde(rename_all = "camelCase")] pub struct DataAuthResponse { authorize_credit_card: AuthChargeCreditCard, } -#[derive(Debug, Clone, Deserialize)] +#[derive(Debug, Clone, Deserialize, Serialize)] pub struct AuthChargeCreditCard { transaction: TransactionAuthChargeResponseBody, } @@ -351,7 +351,7 @@ fn get_error_response<T>( // } // } -#[derive(Debug, Clone, Deserialize)] +#[derive(Debug, Clone, Deserialize, Serialize)] #[serde(rename_all = "SCREAMING_SNAKE_CASE")] pub enum BraintreePaymentStatus { Authorized, @@ -369,13 +369,13 @@ pub enum BraintreePaymentStatus { SubmittedForSettlement, } -#[derive(Debug, Clone, Deserialize)] +#[derive(Debug, Clone, Deserialize, Serialize)] pub struct ErrorDetails { pub message: String, pub extensions: Option<AdditionalErrorDetails>, } -#[derive(Debug, Clone, Deserialize)] +#[derive(Debug, Clone, Deserialize, Serialize)] #[serde(rename_all = "camelCase")] pub struct AdditionalErrorDetails { pub legacy_code: Option<String>, @@ -553,12 +553,12 @@ impl<F> } } -#[derive(Debug, Clone, Deserialize)] +#[derive(Debug, Clone, Deserialize, Serialize)] pub struct PaymentsResponse { data: DataResponse, } -#[derive(Debug, Clone, Deserialize)] +#[derive(Debug, Clone, Deserialize, Serialize)] #[serde(untagged)] pub enum BraintreePaymentsResponse { PaymentsResponse(Box<PaymentsResponse>), @@ -566,14 +566,14 @@ pub enum BraintreePaymentsResponse { ErrorResponse(Box<ErrorResponse>), } -#[derive(Debug, Clone, Deserialize)] +#[derive(Debug, Clone, Deserialize, Serialize)] #[serde(untagged)] pub enum BraintreeCompleteChargeResponse { PaymentsResponse(Box<PaymentsResponse>), ErrorResponse(Box<ErrorResponse>), } -#[derive(Debug, Clone, Deserialize)] +#[derive(Debug, Clone, Deserialize, Serialize)] #[serde(rename_all = "camelCase")] pub struct DataResponse { charge_credit_card: AuthChargeCreditCard, @@ -633,7 +633,7 @@ impl<F> TryFrom<BraintreeRouterData<&types::RefundsRouterData<F>>> for Braintree } } -#[derive(Debug, Clone, Deserialize)] +#[derive(Debug, Clone, Deserialize, Serialize)] #[serde(rename_all = "SCREAMING_SNAKE_CASE")] pub enum BraintreeRefundStatus { SettlementPending, @@ -654,30 +654,30 @@ impl From<BraintreeRefundStatus> for enums::RefundStatus { } } -#[derive(Debug, Clone, Deserialize)] +#[derive(Debug, Clone, Deserialize, Serialize)] pub struct BraintreeRefundTransactionBody { pub id: String, pub status: BraintreeRefundStatus, } -#[derive(Debug, Clone, Deserialize)] +#[derive(Debug, Clone, Deserialize, Serialize)] pub struct BraintreeRefundTransaction { pub refund: BraintreeRefundTransactionBody, } -#[derive(Debug, Clone, Deserialize)] +#[derive(Debug, Clone, Deserialize, Serialize)] #[serde(rename_all = "camelCase")] pub struct BraintreeRefundResponseData { pub refund_transaction: BraintreeRefundTransaction, } -#[derive(Debug, Clone, Deserialize)] +#[derive(Debug, Clone, Deserialize, Serialize)] pub struct RefundResponse { pub data: BraintreeRefundResponseData, } -#[derive(Debug, Clone, Deserialize)] +#[derive(Debug, Clone, Deserialize, Serialize)] #[serde(untagged)] pub enum BraintreeRefundResponse { RefundResponse(Box<RefundResponse>), @@ -733,38 +733,38 @@ impl TryFrom<&types::RefundSyncRouterData> for BraintreeRSyncRequest { } } -#[derive(Debug, Clone, Deserialize)] +#[derive(Debug, Clone, Deserialize, Serialize)] pub struct RSyncNodeData { id: String, status: BraintreeRefundStatus, } -#[derive(Debug, Clone, Deserialize)] +#[derive(Debug, Clone, Deserialize, Serialize)] pub struct RSyncEdgeData { node: RSyncNodeData, } -#[derive(Debug, Clone, Deserialize)] +#[derive(Debug, Clone, Deserialize, Serialize)] pub struct RefundData { edges: Vec<RSyncEdgeData>, } -#[derive(Debug, Clone, Deserialize)] +#[derive(Debug, Clone, Deserialize, Serialize)] pub struct RSyncSearchData { refunds: RefundData, } -#[derive(Debug, Clone, Deserialize)] +#[derive(Debug, Clone, Deserialize, Serialize)] pub struct RSyncResponseData { search: RSyncSearchData, } -#[derive(Debug, Clone, Deserialize)] +#[derive(Debug, Clone, Deserialize, Serialize)] pub struct RSyncResponse { data: RSyncResponseData, } -#[derive(Debug, Clone, Deserialize)] +#[derive(Debug, Clone, Deserialize, Serialize)] #[serde(untagged)] pub enum BraintreeRSyncResponse { RSyncResponse(Box<RSyncResponse>), @@ -897,51 +897,51 @@ impl TryFrom<&types::TokenizationRouterData> for BraintreeTokenRequest { } } -#[derive(Default, Debug, Clone, Deserialize)] +#[derive(Default, Debug, Clone, Deserialize, Serialize)] pub struct TokenizePaymentMethodData { id: String, } -#[derive(Default, Debug, Clone, Deserialize)] +#[derive(Default, Debug, Clone, Deserialize, Serialize)] #[serde(rename_all = "camelCase")] pub struct TokenizeCreditCardData { payment_method: TokenizePaymentMethodData, } -#[derive(Default, Debug, Clone, Deserialize)] +#[derive(Default, Debug, Clone, Deserialize, Serialize)] #[serde(rename_all = "camelCase")] pub struct ClientToken { client_token: Secret<String>, } -#[derive(Default, Debug, Clone, Deserialize)] +#[derive(Default, Debug, Clone, Deserialize, Serialize)] #[serde(rename_all = "camelCase")] pub struct TokenizeCreditCard { tokenize_credit_card: TokenizeCreditCardData, } -#[derive(Default, Debug, Clone, Deserialize)] +#[derive(Default, Debug, Clone, Deserialize, Serialize)] #[serde(rename_all = "camelCase")] pub struct ClientTokenData { create_client_token: ClientToken, } -#[derive(Default, Debug, Clone, Deserialize)] +#[derive(Default, Debug, Clone, Deserialize, Serialize)] pub struct ClientTokenResponse { data: ClientTokenData, } -#[derive(Default, Debug, Clone, Deserialize)] +#[derive(Default, Debug, Clone, Deserialize, Serialize)] pub struct TokenResponse { data: TokenizeCreditCard, } -#[derive(Default, Debug, Clone, Deserialize)] +#[derive(Default, Debug, Clone, Deserialize, Serialize)] pub struct ErrorResponse { errors: Vec<ErrorDetails>, } -#[derive(Debug, Clone, Deserialize)] +#[derive(Debug, Clone, Deserialize, Serialize)] #[serde(untagged)] pub enum BraintreeTokenResponse { TokenResponse(Box<TokenResponse>), @@ -1020,29 +1020,29 @@ impl TryFrom<&BraintreeRouterData<&types::PaymentsCaptureRouterData>> for Braint } } -#[derive(Debug, Clone, Deserialize)] +#[derive(Debug, Clone, Deserialize, Serialize)] pub struct CaptureResponseTransactionBody { id: String, status: BraintreePaymentStatus, } -#[derive(Debug, Clone, Deserialize)] +#[derive(Debug, Clone, Deserialize, Serialize)] pub struct CaptureTransactionData { transaction: CaptureResponseTransactionBody, } -#[derive(Debug, Clone, Deserialize)] +#[derive(Debug, Clone, Deserialize, Serialize)] #[serde(rename_all = "camelCase")] pub struct CaptureResponseData { capture_transaction: CaptureTransactionData, } -#[derive(Debug, Clone, Deserialize)] +#[derive(Debug, Clone, Deserialize, Serialize)] pub struct CaptureResponse { data: CaptureResponseData, } -#[derive(Debug, Clone, Deserialize)] +#[derive(Debug, Clone, Deserialize, Serialize)] #[serde(untagged)] pub enum BraintreeCaptureResponse { CaptureResponse(Box<CaptureResponse>), @@ -1112,29 +1112,29 @@ impl TryFrom<&types::PaymentsCancelRouterData> for BraintreeCancelRequest { } } -#[derive(Debug, Clone, Deserialize)] +#[derive(Debug, Clone, Deserialize, Serialize)] pub struct CancelResponseTransactionBody { id: String, status: BraintreePaymentStatus, } -#[derive(Debug, Clone, Deserialize)] +#[derive(Debug, Clone, Deserialize, Serialize)] pub struct CancelTransactionData { reversal: CancelResponseTransactionBody, } -#[derive(Debug, Clone, Deserialize)] +#[derive(Debug, Clone, Deserialize, Serialize)] #[serde(rename_all = "camelCase")] pub struct CancelResponseData { reverse_transaction: CancelTransactionData, } -#[derive(Debug, Clone, Deserialize)] +#[derive(Debug, Clone, Deserialize, Serialize)] pub struct CancelResponse { data: CancelResponseData, } -#[derive(Debug, Clone, Deserialize)] +#[derive(Debug, Clone, Deserialize, Serialize)] #[serde(untagged)] pub enum BraintreeCancelResponse { CancelResponse(Box<CancelResponse>), @@ -1194,40 +1194,40 @@ impl TryFrom<&types::PaymentsSyncRouterData> for BraintreePSyncRequest { } } -#[derive(Debug, Clone, Deserialize)] +#[derive(Debug, Clone, Deserialize, Serialize)] pub struct NodeData { id: String, status: BraintreePaymentStatus, } -#[derive(Debug, Clone, Deserialize)] +#[derive(Debug, Clone, Deserialize, Serialize)] pub struct EdgeData { node: NodeData, } -#[derive(Debug, Clone, Deserialize)] +#[derive(Debug, Clone, Deserialize, Serialize)] pub struct TransactionData { edges: Vec<EdgeData>, } -#[derive(Debug, Clone, Deserialize)] +#[derive(Debug, Clone, Deserialize, Serialize)] pub struct SearchData { transactions: TransactionData, } -#[derive(Debug, Clone, Deserialize)] +#[derive(Debug, Clone, Deserialize, Serialize)] pub struct PSyncResponseData { search: SearchData, } -#[derive(Debug, Clone, Deserialize)] +#[derive(Debug, Clone, Deserialize, Serialize)] #[serde(untagged)] pub enum BraintreePSyncResponse { PSyncResponse(Box<PSyncResponse>), ErrorResponse(Box<ErrorResponse>), } -#[derive(Debug, Clone, Deserialize)] +#[derive(Debug, Clone, Deserialize, Serialize)] pub struct PSyncResponse { data: PSyncResponseData, } diff --git a/crates/router/src/connector/braintree/transformers.rs b/crates/router/src/connector/braintree/transformers.rs index f4bd62add3b..8846753117c 100644 --- a/crates/router/src/connector/braintree/transformers.rs +++ b/crates/router/src/connector/braintree/transformers.rs @@ -178,7 +178,7 @@ impl TryFrom<&types::ConnectorAuthType> for BraintreeAuthType { } } -#[derive(Debug, Default, Clone, Deserialize, Eq, PartialEq)] +#[derive(Debug, Default, Clone, Deserialize, Eq, PartialEq, Serialize)] #[serde(rename_all = "snake_case")] pub enum BraintreePaymentStatus { Succeeded, @@ -272,25 +272,25 @@ impl<F, T> } } -#[derive(Default, Debug, Clone, Deserialize)] +#[derive(Default, Debug, Clone, Deserialize, Serialize)] #[serde(rename_all = "camelCase")] pub struct BraintreePaymentsResponse { transaction: TransactionResponse, } -#[derive(Default, Debug, Clone, Deserialize)] +#[derive(Default, Debug, Clone, Deserialize, Serialize)] #[serde(rename_all = "camelCase")] pub struct ClientToken { pub value: String, } -#[derive(Default, Debug, Clone, Deserialize)] +#[derive(Default, Debug, Clone, Deserialize, Serialize)] #[serde(rename_all = "camelCase")] pub struct BraintreeSessionTokenResponse { pub client_token: ClientToken, } -#[derive(Default, Debug, Clone, Deserialize, Eq, PartialEq)] +#[derive(Default, Debug, Clone, Deserialize, Eq, PartialEq, Serialize)] #[serde(rename_all = "camelCase")] pub struct TransactionResponse { id: String, @@ -299,42 +299,42 @@ pub struct TransactionResponse { status: BraintreePaymentStatus, } -#[derive(Debug, Deserialize)] +#[derive(Debug, Deserialize, Serialize)] #[serde(rename_all = "camelCase")] pub struct BraintreeApiErrorResponse { pub api_error_response: ApiErrorResponse, } -#[derive(Debug, Deserialize)] +#[derive(Debug, Deserialize, Serialize)] pub struct ErrorsObject { pub errors: Vec<ErrorObject>, pub transaction: Option<TransactionError>, } -#[derive(Debug, Deserialize)] +#[derive(Debug, Deserialize, Serialize)] #[serde(rename_all = "camelCase")] pub struct TransactionError { pub errors: Vec<ErrorObject>, pub credit_card: Option<CreditCardError>, } -#[derive(Debug, Deserialize)] +#[derive(Debug, Deserialize, Serialize)] pub struct CreditCardError { pub errors: Vec<ErrorObject>, } -#[derive(Debug, Deserialize)] +#[derive(Debug, Deserialize, Serialize)] pub struct ErrorObject { pub code: String, pub message: String, } -#[derive(Debug, Default, Deserialize)] +#[derive(Debug, Default, Deserialize, Serialize)] #[serde(rename_all = "camelCase")] pub struct BraintreeErrorResponse { pub errors: String, } -#[derive(Debug, Deserialize)] +#[derive(Debug, Deserialize, Serialize)] #[serde(rename_all = "camelCase")] #[serde(untagged)] @@ -343,7 +343,7 @@ pub enum ErrorResponse { BraintreeErrorResponse(Box<BraintreeErrorResponse>), } -#[derive(Debug, Deserialize)] +#[derive(Debug, Deserialize, Serialize)] pub struct ApiErrorResponse { pub message: String, pub errors: ErrorsObject, @@ -378,7 +378,7 @@ impl<F> TryFrom<&types::RefundsRouterData<F>> for BraintreeRefundRequest { } #[allow(dead_code)] -#[derive(Debug, Default, Deserialize, Clone)] +#[derive(Debug, Default, Deserialize, Clone, Serialize)] pub enum RefundStatus { Succeeded, Failed, @@ -396,7 +396,7 @@ impl From<RefundStatus> for enums::RefundStatus { } } -#[derive(Default, Debug, Clone, Deserialize)] +#[derive(Default, Debug, Clone, Deserialize, Serialize)] pub struct RefundResponse { pub id: String, pub status: RefundStatus, diff --git a/crates/router/src/connector/cashtocode.rs b/crates/router/src/connector/cashtocode.rs index 5a628f775b6..127451f3836 100644 --- a/crates/router/src/connector/cashtocode.rs +++ b/crates/router/src/connector/cashtocode.rs @@ -12,6 +12,7 @@ use super::utils as connector_utils; use crate::{ configs::settings::{self}, core::errors::{self, CustomResult}, + events::connector_api_logs::ConnectorEvent, headers, services::{ self, @@ -109,11 +110,16 @@ impl ConnectorCommon for Cashtocode { fn build_error_response( &self, res: Response, + event_builder: Option<&mut ConnectorEvent>, ) -> CustomResult<ErrorResponse, errors::ConnectorError> { let response: cashtocode::CashtocodeErrorResponse = res .response .parse_struct("CashtocodeErrorResponse") .change_context(errors::ConnectorError::ResponseDeserializationFailed)?; + + event_builder.map(|i| i.set_error_response_body(&response)); + router_env::logger::info!(connector_response=?response); + Ok(ErrorResponse { status_code: res.status_code, code: response.error.to_string(), @@ -249,12 +255,16 @@ impl ConnectorIntegration<api::Authorize, types::PaymentsAuthorizeData, types::P fn handle_response( &self, data: &types::PaymentsAuthorizeRouterData, + event_builder: Option<&mut ConnectorEvent>, res: Response, ) -> CustomResult<types::PaymentsAuthorizeRouterData, errors::ConnectorError> { let response: cashtocode::CashtocodePaymentsResponse = res .response .parse_struct("Cashtocode 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(), @@ -265,8 +275,9 @@ impl ConnectorIntegration<api::Authorize, types::PaymentsAuthorizeData, types::P fn get_error_response( &self, res: Response, + event_builder: Option<&mut ConnectorEvent>, ) -> CustomResult<ErrorResponse, errors::ConnectorError> { - self.build_error_response(res) + self.build_error_response(res, event_builder) } } @@ -277,12 +288,15 @@ impl ConnectorIntegration<api::PSync, types::PaymentsSyncData, types::PaymentsRe fn handle_response( &self, data: &types::PaymentsSyncRouterData, + event_builder: Option<&mut ConnectorEvent>, res: Response, ) -> CustomResult<types::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 { response, data: data.clone(), @@ -293,8 +307,9 @@ impl ConnectorIntegration<api::PSync, types::PaymentsSyncData, types::PaymentsRe fn get_error_response( &self, res: Response, + event_builder: Option<&mut ConnectorEvent>, ) -> CustomResult<ErrorResponse, errors::ConnectorError> { - self.build_error_response(res) + self.build_error_response(res, event_builder) } } diff --git a/crates/router/src/connector/cashtocode/transformers.rs b/crates/router/src/connector/cashtocode/transformers.rs index 8a92956756a..6e930d5cb4b 100644 --- a/crates/router/src/connector/cashtocode/transformers.rs +++ b/crates/router/src/connector/cashtocode/transformers.rs @@ -168,7 +168,7 @@ impl From<CashtocodePaymentStatus> for enums::AttemptStatus { } } -#[derive(Debug, Deserialize, Clone)] +#[derive(Debug, Deserialize, Clone, Serialize)] pub struct CashtocodeErrors { pub message: String, pub path: String, @@ -176,20 +176,20 @@ pub struct CashtocodeErrors { pub event_type: String, } -#[derive(Debug, Deserialize)] +#[derive(Debug, Deserialize, Serialize)] #[serde(untagged)] pub enum CashtocodePaymentsResponse { CashtoCodeError(CashtocodeErrorResponse), CashtoCodeData(CashtocodePaymentsResponseData), } -#[derive(Debug, Deserialize)] +#[derive(Debug, Deserialize, Serialize)] #[serde(rename_all = "camelCase")] pub struct CashtocodePaymentsResponseData { pub pay_url: url::Url, } -#[derive(Debug, Clone, Deserialize)] +#[derive(Debug, Clone, Deserialize, Serialize)] #[serde(rename_all = "camelCase")] pub struct CashtocodePaymentsSyncResponse { pub transaction_id: String, @@ -319,7 +319,7 @@ impl<F, T> } } -#[derive(Debug, Deserialize)] +#[derive(Debug, Deserialize, Serialize)] pub struct CashtocodeErrorResponse { pub error: serde_json::Value, pub error_description: String, diff --git a/crates/router/src/connector/checkout.rs b/crates/router/src/connector/checkout.rs index 382737a28f6..ea2c4fefd30 100644 --- a/crates/router/src/connector/checkout.rs +++ b/crates/router/src/connector/checkout.rs @@ -19,6 +19,7 @@ use crate::{ errors::{self, CustomResult}, payments, }, + events::connector_api_logs::ConnectorEvent, headers, services::{ self, @@ -89,6 +90,7 @@ impl ConnectorCommon for Checkout { fn build_error_response( &self, res: types::Response, + event_builder: Option<&mut ConnectorEvent>, ) -> CustomResult<types::ErrorResponse, errors::ConnectorError> { let response: checkout::ErrorResponse = if res.response.is_empty() { let (error_codes, error_type) = if res.status_code == 401 { @@ -110,7 +112,9 @@ impl ConnectorCommon for Checkout { .change_context(errors::ConnectorError::ResponseDeserializationFailed)? }; - router_env::logger::info!(error_response=?response); + event_builder.map(|i| i.set_error_response_body(&response)); + router_env::logger::info!(connector_response=?response); + let errors_list = response.error_codes.clone().unwrap_or_default(); let option_error_code_message = conn_utils::get_error_code_error_message_based_on_priority( self.clone(), @@ -237,6 +241,7 @@ impl fn handle_response( &self, data: &types::TokenizationRouterData, + event_builder: Option<&mut ConnectorEvent>, res: types::Response, ) -> CustomResult<types::TokenizationRouterData, errors::ConnectorError> where @@ -246,8 +251,8 @@ impl .response .parse_struct("CheckoutTokenResponse") .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(), @@ -259,8 +264,9 @@ impl fn get_error_response( &self, res: types::Response, + event_builder: Option<&mut ConnectorEvent>, ) -> CustomResult<types::ErrorResponse, errors::ConnectorError> { - self.build_error_response(res) + self.build_error_response(res, event_builder) } } @@ -362,14 +368,15 @@ impl ConnectorIntegration<api::Capture, types::PaymentsCaptureData, types::Payme fn handle_response( &self, data: &types::PaymentsCaptureRouterData, + event_builder: Option<&mut ConnectorEvent>, res: types::Response, ) -> CustomResult<types::PaymentsCaptureRouterData, errors::ConnectorError> { let response: checkout::PaymentCaptureResponse = res .response .parse_struct("CaptureResponse") .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(), @@ -381,8 +388,9 @@ impl ConnectorIntegration<api::Capture, types::PaymentsCaptureData, types::Payme fn get_error_response( &self, res: types::Response, + event_builder: Option<&mut ConnectorEvent>, ) -> CustomResult<types::ErrorResponse, errors::ConnectorError> { - self.build_error_response(res) + self.build_error_response(res, event_builder) } } @@ -436,6 +444,7 @@ impl ConnectorIntegration<api::PSync, types::PaymentsSyncData, types::PaymentsRe fn handle_response( &self, data: &types::PaymentsSyncRouterData, + event_builder: Option<&mut ConnectorEvent>, res: types::Response, ) -> CustomResult<types::PaymentsSyncRouterData, errors::ConnectorError> where @@ -449,6 +458,7 @@ impl ConnectorIntegration<api::PSync, types::PaymentsSyncData, types::PaymentsRe .response .parse_struct("checkout::PaymentsResponseEnum") .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, @@ -462,6 +472,7 @@ impl ConnectorIntegration<api::PSync, types::PaymentsSyncData, types::PaymentsRe .response .parse_struct("PaymentsResponse") .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, @@ -482,8 +493,9 @@ impl ConnectorIntegration<api::PSync, types::PaymentsSyncData, types::PaymentsRe fn get_error_response( &self, res: types::Response, + event_builder: Option<&mut ConnectorEvent>, ) -> CustomResult<types::ErrorResponse, errors::ConnectorError> { - self.build_error_response(res) + self.build_error_response(res, event_builder) } } @@ -549,12 +561,14 @@ impl ConnectorIntegration<api::Authorize, types::PaymentsAuthorizeData, types::P fn handle_response( &self, data: &types::PaymentsAuthorizeRouterData, + event_builder: Option<&mut ConnectorEvent>, res: types::Response, ) -> CustomResult<types::PaymentsAuthorizeRouterData, errors::ConnectorError> { let response: checkout::PaymentsResponse = res .response .parse_struct("PaymentIntentResponse") .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, @@ -567,8 +581,9 @@ impl ConnectorIntegration<api::Authorize, types::PaymentsAuthorizeData, types::P fn get_error_response( &self, res: types::Response, + event_builder: Option<&mut ConnectorEvent>, ) -> CustomResult<types::ErrorResponse, errors::ConnectorError> { - self.build_error_response(res) + self.build_error_response(res, event_builder) } } @@ -624,14 +639,18 @@ impl ConnectorIntegration<api::Void, types::PaymentsCancelData, types::PaymentsR fn handle_response( &self, data: &types::PaymentsCancelRouterData, + event_builder: Option<&mut ConnectorEvent>, res: types::Response, ) -> CustomResult<types::PaymentsCancelRouterData, errors::ConnectorError> { let mut response: checkout::PaymentVoidResponse = res .response .parse_struct("PaymentVoidResponse") .change_context(errors::ConnectorError::ResponseDeserializationFailed)?; + event_builder.map(|i| i.set_response_body(&response)); router_env::logger::info!(connector_response=?response); + response.status = res.status_code; + types::RouterData::try_from(types::ResponseRouterData { response, data: data.clone(), @@ -643,8 +662,9 @@ impl ConnectorIntegration<api::Void, types::PaymentsCancelData, types::PaymentsR fn get_error_response( &self, res: types::Response, + event_builder: Option<&mut ConnectorEvent>, ) -> CustomResult<types::ErrorResponse, errors::ConnectorError> { - self.build_error_response(res) + self.build_error_response(res, event_builder) } } @@ -717,12 +737,14 @@ impl ConnectorIntegration<api::Execute, types::RefundsData, types::RefundsRespon fn handle_response( &self, data: &types::RefundsRouterData<api::Execute>, + event_builder: Option<&mut ConnectorEvent>, res: types::Response, ) -> CustomResult<types::RefundsRouterData<api::Execute>, errors::ConnectorError> { let response: checkout::RefundResponse = res .response .parse_struct("checkout::RefundResponse") .change_context(errors::ConnectorError::ResponseDeserializationFailed)?; + event_builder.map(|i| i.set_response_body(&response)); router_env::logger::info!(connector_response=?response); let response = checkout::CheckoutRefundResponse { response, @@ -740,8 +762,9 @@ impl ConnectorIntegration<api::Execute, types::RefundsData, types::RefundsRespon fn get_error_response( &self, res: types::Response, + event_builder: Option<&mut ConnectorEvent>, ) -> CustomResult<types::ErrorResponse, errors::ConnectorError> { - self.build_error_response(res) + self.build_error_response(res, event_builder) } } @@ -785,6 +808,7 @@ impl ConnectorIntegration<api::RSync, types::RefundsData, types::RefundsResponse fn handle_response( &self, data: &types::RefundsRouterData<api::RSync>, + event_builder: Option<&mut ConnectorEvent>, res: types::Response, ) -> CustomResult<types::RefundsRouterData<api::RSync>, errors::ConnectorError> { let refund_action_id = data.request.get_connector_refund_id()?; @@ -793,6 +817,8 @@ impl ConnectorIntegration<api::RSync, types::RefundsData, types::RefundsResponse .response .parse_struct("checkout::CheckoutRefundResponse") .change_context(errors::ConnectorError::ResponseDeserializationFailed)?; + + event_builder.map(|i| i.set_response_body(&response)); router_env::logger::info!(connector_response=?response); let response = response @@ -811,8 +837,9 @@ impl ConnectorIntegration<api::RSync, types::RefundsData, types::RefundsResponse fn get_error_response( &self, res: types::Response, + event_builder: Option<&mut ConnectorEvent>, ) -> CustomResult<types::ErrorResponse, errors::ConnectorError> { - self.build_error_response(res) + self.build_error_response(res, event_builder) } } @@ -870,6 +897,7 @@ impl fn handle_response( &self, data: &types::AcceptDisputeRouterData, + _event_builder: Option<&mut ConnectorEvent>, _res: types::Response, ) -> CustomResult<types::AcceptDisputeRouterData, errors::ConnectorError> { Ok(types::AcceptDisputeRouterData { @@ -884,8 +912,9 @@ impl fn get_error_response( &self, res: types::Response, + event_builder: Option<&mut ConnectorEvent>, ) -> CustomResult<types::ErrorResponse, errors::ConnectorError> { - self.build_error_response(res) + self.build_error_response(res, event_builder) } } @@ -983,6 +1012,7 @@ impl ConnectorIntegration<api::Upload, types::UploadFileRequestData, types::Uplo fn handle_response( &self, data: &types::UploadFileRouterData, + event_builder: Option<&mut ConnectorEvent>, res: types::Response, ) -> CustomResult< types::RouterData<api::Upload, types::UploadFileRequestData, types::UploadFileResponse>, @@ -992,6 +1022,7 @@ impl ConnectorIntegration<api::Upload, types::UploadFileRequestData, types::Uplo .response .parse_struct("Checkout FileUploadResponse") .change_context(errors::ConnectorError::ResponseDeserializationFailed)?; + event_builder.map(|i| i.set_response_body(&response)); router_env::logger::info!(connector_response=?response); Ok(types::UploadFileRouterData { response: Ok(types::UploadFileResponse { @@ -1004,8 +1035,9 @@ impl ConnectorIntegration<api::Upload, types::UploadFileRequestData, types::Uplo fn get_error_response( &self, res: types::Response, + event_builder: Option<&mut ConnectorEvent>, ) -> CustomResult<types::ErrorResponse, errors::ConnectorError> { - self.build_error_response(res) + self.build_error_response(res, event_builder) } } @@ -1077,6 +1109,7 @@ impl fn handle_response( &self, data: &types::SubmitEvidenceRouterData, + _event_builder: Option<&mut ConnectorEvent>, _res: types::Response, ) -> CustomResult<types::SubmitEvidenceRouterData, errors::ConnectorError> { Ok(types::SubmitEvidenceRouterData { @@ -1091,8 +1124,9 @@ impl fn get_error_response( &self, res: types::Response, + event_builder: Option<&mut ConnectorEvent>, ) -> CustomResult<types::ErrorResponse, errors::ConnectorError> { - self.build_error_response(res) + self.build_error_response(res, event_builder) } } @@ -1148,6 +1182,7 @@ impl fn handle_response( &self, data: &types::DefendDisputeRouterData, + _event_builder: Option<&mut ConnectorEvent>, _res: types::Response, ) -> CustomResult<types::DefendDisputeRouterData, errors::ConnectorError> { Ok(types::DefendDisputeRouterData { @@ -1162,8 +1197,9 @@ impl fn get_error_response( &self, res: types::Response, + event_builder: Option<&mut ConnectorEvent>, ) -> CustomResult<types::ErrorResponse, errors::ConnectorError> { - self.build_error_response(res) + self.build_error_response(res, event_builder) } } diff --git a/crates/router/src/connector/checkout/transformers.rs b/crates/router/src/connector/checkout/transformers.rs index 6e7656c38a6..f96bd50ffc8 100644 --- a/crates/router/src/connector/checkout/transformers.rs +++ b/crates/router/src/connector/checkout/transformers.rs @@ -152,7 +152,7 @@ impl TryFrom<&types::TokenizationRouterData> for TokenRequest { } } -#[derive(Debug, Eq, PartialEq, Deserialize)] +#[derive(Debug, Eq, PartialEq, Deserialize, Serialize)] pub struct CheckoutTokenResponse { token: Secret<String>, } @@ -555,7 +555,7 @@ pub struct PaymentsResponse { response_summary: Option<String>, } -#[derive(Debug, Deserialize)] +#[derive(Debug, Deserialize, Serialize)] #[serde(untagged)] pub enum PaymentsResponseEnum { ActionResponse(Vec<ActionResponse>), @@ -723,7 +723,7 @@ impl TryFrom<types::PaymentsSyncResponseRouterData<PaymentsResponseEnum>> pub struct PaymentVoidRequest { reference: String, } -#[derive(Clone, Default, Debug, Eq, PartialEq, Deserialize)] +#[derive(Clone, Default, Debug, Eq, PartialEq, Deserialize, Serialize)] pub struct PaymentVoidResponse { #[serde(skip)] pub(super) status: u16, @@ -816,7 +816,7 @@ impl TryFrom<&CheckoutRouterData<&types::PaymentsCaptureRouterData>> for Payment } } -#[derive(Debug, Deserialize)] +#[derive(Debug, Deserialize, Serialize)] pub struct PaymentCaptureResponse { pub action_id: String, pub reference: Option<String>, @@ -885,7 +885,7 @@ impl<F> TryFrom<&CheckoutRouterData<&types::RefundsRouterData<F>>> for RefundReq } } #[allow(dead_code)] -#[derive(Deserialize, Debug)] +#[derive(Deserialize, Debug, Serialize)] pub struct RefundResponse { action_id: String, reference: String, @@ -943,14 +943,14 @@ impl TryFrom<types::RefundsResponseRouterData<api::RSync, CheckoutRefundResponse } } -#[derive(Debug, Default, Eq, PartialEq, Deserialize)] +#[derive(Debug, Default, Eq, PartialEq, Deserialize, Serialize)] pub struct ErrorResponse { pub request_id: Option<String>, pub error_type: Option<String>, pub error_codes: Option<Vec<String>>, } -#[derive(Deserialize, Debug, PartialEq)] +#[derive(Deserialize, Debug, PartialEq, Serialize)] pub enum ActionType { Authorization, Void, @@ -962,7 +962,7 @@ pub enum ActionType { CardVerification, } -#[derive(Deserialize, Debug)] +#[derive(Deserialize, Debug, Serialize)] pub struct ActionResponse { #[serde(rename = "id")] pub action_id: String, @@ -1278,7 +1278,7 @@ pub fn construct_file_upload_request( Ok(multipart) } -#[derive(Debug, Deserialize)] +#[derive(Debug, Deserialize, Serialize)] pub struct FileUploadResponse { #[serde(rename = "id")] pub file_id: String, diff --git a/crates/router/src/connector/coinbase.rs b/crates/router/src/connector/coinbase.rs index 76f88b66326..1886b651172 100644 --- a/crates/router/src/connector/coinbase.rs +++ b/crates/router/src/connector/coinbase.rs @@ -13,6 +13,7 @@ use crate::{ configs::settings, connector::utils as connector_utils, core::errors::{self, CustomResult}, + events::connector_api_logs::ConnectorEvent, headers, services::{ self, @@ -97,12 +98,16 @@ impl ConnectorCommon for Coinbase { fn build_error_response( &self, res: Response, + event_builder: Option<&mut ConnectorEvent>, ) -> CustomResult<ErrorResponse, errors::ConnectorError> { let response: coinbase::CoinbaseErrorResponse = res .response .parse_struct("CoinbaseErrorResponse") .change_context(errors::ConnectorError::ResponseDeserializationFailed)?; + event_builder.map(|i| i.set_error_response_body(&response)); + router_env::logger::info!(connector_response=?response); + Ok(ErrorResponse { status_code: res.status_code, code: response.error.error_type, @@ -229,12 +234,15 @@ impl ConnectorIntegration<api::Authorize, types::PaymentsAuthorizeData, types::P fn handle_response( &self, data: &types::PaymentsAuthorizeRouterData, + event_builder: Option<&mut ConnectorEvent>, res: Response, ) -> CustomResult<types::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 { response, data: data.clone(), @@ -246,8 +254,9 @@ impl ConnectorIntegration<api::Authorize, types::PaymentsAuthorizeData, types::P fn get_error_response( &self, res: Response, + event_builder: Option<&mut ConnectorEvent>, ) -> CustomResult<ErrorResponse, errors::ConnectorError> { - self.build_error_response(res) + self.build_error_response(res, event_builder) } } @@ -300,12 +309,15 @@ impl ConnectorIntegration<api::PSync, types::PaymentsSyncData, types::PaymentsRe fn handle_response( &self, data: &types::PaymentsSyncRouterData, + event_builder: Option<&mut ConnectorEvent>, res: Response, ) -> CustomResult<types::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 { response, data: data.clone(), @@ -317,8 +329,9 @@ impl ConnectorIntegration<api::PSync, types::PaymentsSyncData, types::PaymentsRe fn get_error_response( &self, res: Response, + event_builder: Option<&mut ConnectorEvent>, ) -> CustomResult<ErrorResponse, errors::ConnectorError> { - self.build_error_response(res) + self.build_error_response(res, event_builder) } } diff --git a/crates/router/src/connector/coinbase/transformers.rs b/crates/router/src/connector/coinbase/transformers.rs index b1435e50df9..5b3b6f63278 100644 --- a/crates/router/src/connector/coinbase/transformers.rs +++ b/crates/router/src/connector/coinbase/transformers.rs @@ -234,7 +234,7 @@ impl TryFrom<types::RefundsResponseRouterData<api::RSync, RefundResponse>> } } -#[derive(Debug, Deserialize)] +#[derive(Debug, Deserialize, Serialize)] pub struct CoinbaseErrorData { #[serde(rename = "type")] pub error_type: String, @@ -242,7 +242,7 @@ pub struct CoinbaseErrorData { pub code: Option<String>, } -#[derive(Debug, Deserialize)] +#[derive(Debug, Deserialize, Serialize)] pub struct CoinbaseErrorResponse { pub error: CoinbaseErrorData, } diff --git a/crates/router/src/connector/cryptopay.rs b/crates/router/src/connector/cryptopay.rs index 8727461ba34..af33ae21d76 100644 --- a/crates/router/src/connector/cryptopay.rs +++ b/crates/router/src/connector/cryptopay.rs @@ -20,6 +20,7 @@ use crate::{ configs::settings, consts, core::errors::{self, CustomResult}, + events::connector_api_logs::ConnectorEvent, headers, services::{ self, @@ -160,12 +161,16 @@ impl ConnectorCommon for Cryptopay { fn build_error_response( &self, res: Response, + event_builder: Option<&mut ConnectorEvent>, ) -> CustomResult<ErrorResponse, errors::ConnectorError> { let response: cryptopay::CryptopayErrorResponse = res .response .parse_struct("CryptopayErrorResponse") .change_context(errors::ConnectorError::ResponseDeserializationFailed)?; + event_builder.map(|i| i.set_error_response_body(&response)); + router_env::logger::info!(connector_response=?response); + Ok(ErrorResponse { status_code: res.status_code, code: response.error.code, @@ -273,12 +278,15 @@ impl ConnectorIntegration<api::Authorize, types::PaymentsAuthorizeData, types::P fn handle_response( &self, data: &types::PaymentsAuthorizeRouterData, + event_builder: Option<&mut ConnectorEvent>, res: Response, ) -> CustomResult<types::PaymentsAuthorizeRouterData, errors::ConnectorError> { let response: cryptopay::CryptopayPaymentsResponse = res .response .parse_struct("Cryptopay 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(), @@ -289,8 +297,9 @@ impl ConnectorIntegration<api::Authorize, types::PaymentsAuthorizeData, types::P fn get_error_response( &self, res: Response, + event_builder: Option<&mut ConnectorEvent>, ) -> CustomResult<ErrorResponse, errors::ConnectorError> { - self.build_error_response(res) + self.build_error_response(res, event_builder) } } @@ -353,12 +362,15 @@ impl ConnectorIntegration<api::PSync, types::PaymentsSyncData, types::PaymentsRe fn handle_response( &self, data: &types::PaymentsSyncRouterData, + event_builder: Option<&mut ConnectorEvent>, res: Response, ) -> CustomResult<types::PaymentsSyncRouterData, errors::ConnectorError> { let response: cryptopay::CryptopayPaymentsResponse = res .response .parse_struct("cryptopay 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(), @@ -369,8 +381,9 @@ impl ConnectorIntegration<api::PSync, types::PaymentsSyncData, types::PaymentsRe fn get_error_response( &self, res: Response, + event_builder: Option<&mut ConnectorEvent>, ) -> CustomResult<ErrorResponse, errors::ConnectorError> { - self.build_error_response(res) + self.build_error_response(res, event_builder) } } diff --git a/crates/router/src/connector/cybersource.rs b/crates/router/src/connector/cybersource.rs index 7970656d6e3..5597af94e3f 100644 --- a/crates/router/src/connector/cybersource.rs +++ b/crates/router/src/connector/cybersource.rs @@ -18,6 +18,7 @@ use crate::{ connector::{utils as connector_utils, utils::RefundsRequestData}, consts, core::errors::{self, CustomResult}, + events::connector_api_logs::ConnectorEvent, headers, services::{ self, @@ -114,12 +115,16 @@ impl ConnectorCommon for Cybersource { fn build_error_response( &self, res: types::Response, + event_builder: Option<&mut ConnectorEvent>, ) -> CustomResult<types::ErrorResponse, errors::ConnectorError> { let response: cybersource::CybersourceErrorResponse = res .response .parse_struct("Cybersource ErrorResponse") .change_context(errors::ConnectorError::ResponseDeserializationFailed)?; + event_builder.map(|i| i.set_error_response_body(&response)); + router_env::logger::info!(connector_response=?response); + let error_message = if res.status_code == 401 { consts::CONNECTOR_UNAUTHORIZED_ERROR } else { @@ -357,12 +362,15 @@ impl fn handle_response( &self, data: &types::SetupMandateRouterData, + event_builder: Option<&mut ConnectorEvent>, res: types::Response, ) -> CustomResult<types::SetupMandateRouterData, errors::ConnectorError> { let response: cybersource::CybersourceSetupMandatesResponse = res .response .parse_struct("CybersourceSetupMandatesResponse") .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(), @@ -373,8 +381,9 @@ impl fn get_error_response( &self, res: types::Response, + event_builder: Option<&mut ConnectorEvent>, ) -> CustomResult<types::ErrorResponse, errors::ConnectorError> { - self.build_error_response(res) + self.build_error_response(res, event_builder) } } @@ -428,9 +437,11 @@ impl fn handle_response( &self, data: &types::MandateRevokeRouterData, + event_builder: Option<&mut ConnectorEvent>, res: types::Response, ) -> CustomResult<types::MandateRevokeRouterData, errors::ConnectorError> { if matches!(res.status_code, 204) { + event_builder.map(|i| i.set_response_body(&serde_json::json!({"mandate_status": common_enums::MandateStatus::Revoked.to_string()}))); Ok(types::MandateRevokeRouterData { response: Ok(types::MandateRevokeResponseData { mandate_status: common_enums::MandateStatus::Revoked, @@ -444,6 +455,13 @@ impl .change_context(errors::ConnectorError::ResponseHandlingFailed)?; let response_string = response_value.to_string(); + event_builder.map(|i| { + i.set_response_body( + &serde_json::json!({"response_string": response_string.clone()}), + ) + }); + router_env::logger::info!(connector_response=?response_string); + Ok(types::MandateRevokeRouterData { response: Err(types::ErrorResponse { code: consts::NO_ERROR_CODE.to_string(), @@ -460,8 +478,9 @@ impl fn get_error_response( &self, res: types::Response, + event_builder: Option<&mut ConnectorEvent>, ) -> CustomResult<types::ErrorResponse, errors::ConnectorError> { - self.build_error_response(res) + self.build_error_response(res, event_builder) } } impl ConnectorIntegration<api::AccessTokenAuth, types::AccessTokenRequestData, types::AccessToken> @@ -563,12 +582,15 @@ impl fn handle_response( &self, data: &types::PaymentsPreProcessingRouterData, + event_builder: Option<&mut ConnectorEvent>, res: types::Response, ) -> CustomResult<types::PaymentsPreProcessingRouterData, errors::ConnectorError> { let response: cybersource::CybersourcePreProcessingResponse = res .response .parse_struct("Cybersource AuthEnrollmentResponse") .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(), @@ -579,8 +601,9 @@ impl fn get_error_response( &self, res: types::Response, + event_builder: Option<&mut ConnectorEvent>, ) -> CustomResult<types::ErrorResponse, errors::ConnectorError> { - self.build_error_response(res) + self.build_error_response(res, event_builder) } } @@ -649,6 +672,7 @@ impl ConnectorIntegration<api::Capture, types::PaymentsCaptureData, types::Payme fn handle_response( &self, data: &types::PaymentsCaptureRouterData, + event_builder: Option<&mut ConnectorEvent>, res: types::Response, ) -> CustomResult< types::RouterData<api::Capture, types::PaymentsCaptureData, types::PaymentsResponseData>, @@ -658,6 +682,8 @@ impl ConnectorIntegration<api::Capture, types::PaymentsCaptureData, types::Payme .response .parse_struct("Cybersource 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 { response, data: data.clone(), @@ -667,19 +693,24 @@ impl ConnectorIntegration<api::Capture, types::PaymentsCaptureData, types::Payme fn get_error_response( &self, res: types::Response, + event_builder: Option<&mut ConnectorEvent>, ) -> CustomResult<types::ErrorResponse, errors::ConnectorError> { - self.build_error_response(res) + self.build_error_response(res, event_builder) } fn get_5xx_error_response( &self, res: types::Response, + event_builder: Option<&mut ConnectorEvent>, ) -> CustomResult<types::ErrorResponse, errors::ConnectorError> { let response: cybersource::CybersourceServerErrorResponse = res .response .parse_struct("CybersourceServerErrorResponse") .change_context(errors::ConnectorError::ResponseDeserializationFailed)?; + event_builder.map(|event| event.set_response_body(&response)); + router_env::logger::info!(error_response=?response); + Ok(types::ErrorResponse { status_code: res.status_code, reason: response.status.clone(), @@ -747,12 +778,15 @@ impl ConnectorIntegration<api::PSync, types::PaymentsSyncData, types::PaymentsRe fn handle_response( &self, data: &types::PaymentsSyncRouterData, + event_builder: Option<&mut ConnectorEvent>, res: types::Response, ) -> CustomResult<types::PaymentsSyncRouterData, errors::ConnectorError> { let response: cybersource::CybersourceTransactionResponse = res .response .parse_struct("Cybersource 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 { response, data: data.clone(), @@ -762,8 +796,9 @@ impl ConnectorIntegration<api::PSync, types::PaymentsSyncData, types::PaymentsRe fn get_error_response( &self, res: types::Response, + event_builder: Option<&mut ConnectorEvent>, ) -> CustomResult<types::ErrorResponse, errors::ConnectorError> { - self.build_error_response(res) + self.build_error_response(res, event_builder) } } @@ -851,6 +886,7 @@ impl ConnectorIntegration<api::Authorize, types::PaymentsAuthorizeData, types::P fn handle_response( &self, data: &types::PaymentsAuthorizeRouterData, + event_builder: Option<&mut ConnectorEvent>, res: types::Response, ) -> CustomResult<types::PaymentsAuthorizeRouterData, errors::ConnectorError> { if data.is_three_ds() @@ -861,6 +897,8 @@ impl ConnectorIntegration<api::Authorize, types::PaymentsAuthorizeData, types::P .response .parse_struct("Cybersource AuthSetupResponse") .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(), @@ -871,6 +909,8 @@ impl ConnectorIntegration<api::Authorize, types::PaymentsAuthorizeData, types::P .response .parse_struct("Cybersource 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 { response, data: data.clone(), @@ -882,18 +922,24 @@ impl ConnectorIntegration<api::Authorize, types::PaymentsAuthorizeData, types::P fn get_error_response( &self, res: types::Response, + event_builder: Option<&mut ConnectorEvent>, ) -> CustomResult<types::ErrorResponse, errors::ConnectorError> { - self.build_error_response(res) + self.build_error_response(res, event_builder) } fn get_5xx_error_response( &self, res: types::Response, + event_builder: Option<&mut ConnectorEvent>, ) -> CustomResult<types::ErrorResponse, errors::ConnectorError> { let response: cybersource::CybersourceServerErrorResponse = res .response .parse_struct("CybersourceServerErrorResponse") .change_context(errors::ConnectorError::ResponseDeserializationFailed)?; + + event_builder.map(|event| event.set_response_body(&response)); + router_env::logger::info!(error_response=?response); + let attempt_status = match response.reason { Some(reason) => match reason { transformers::Reason::SystemError => Some(enums::AttemptStatus::Failure), @@ -981,12 +1027,15 @@ impl fn handle_response( &self, data: &types::PaymentsCompleteAuthorizeRouterData, + event_builder: Option<&mut ConnectorEvent>, res: types::Response, ) -> CustomResult<types::PaymentsCompleteAuthorizeRouterData, errors::ConnectorError> { let response: cybersource::CybersourcePaymentsResponse = res .response .parse_struct("Cybersource 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 { response, data: data.clone(), @@ -997,18 +1046,24 @@ impl fn get_error_response( &self, res: types::Response, + event_builder: Option<&mut ConnectorEvent>, ) -> CustomResult<types::ErrorResponse, errors::ConnectorError> { - self.build_error_response(res) + self.build_error_response(res, event_builder) } fn get_5xx_error_response( &self, res: types::Response, + event_builder: Option<&mut ConnectorEvent>, ) -> CustomResult<types::ErrorResponse, errors::ConnectorError> { let response: cybersource::CybersourceServerErrorResponse = res .response .parse_struct("CybersourceServerErrorResponse") .change_context(errors::ConnectorError::ResponseDeserializationFailed)?; + + event_builder.map(|event| event.set_response_body(&response)); + router_env::logger::info!(error_response=?response); + let attempt_status = match response.reason { Some(reason) => match reason { transformers::Reason::SystemError => Some(enums::AttemptStatus::Failure), @@ -1099,12 +1154,15 @@ impl ConnectorIntegration<api::Void, types::PaymentsCancelData, types::PaymentsR fn handle_response( &self, data: &types::PaymentsCancelRouterData, + event_builder: Option<&mut ConnectorEvent>, res: types::Response, ) -> CustomResult<types::PaymentsCancelRouterData, errors::ConnectorError> { let response: cybersource::CybersourcePaymentsResponse = res .response .parse_struct("Cybersource 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 { response, data: data.clone(), @@ -1115,19 +1173,24 @@ impl ConnectorIntegration<api::Void, types::PaymentsCancelData, types::PaymentsR fn get_error_response( &self, res: types::Response, + event_builder: Option<&mut ConnectorEvent>, ) -> CustomResult<types::ErrorResponse, errors::ConnectorError> { - self.build_error_response(res) + self.build_error_response(res, event_builder) } fn get_5xx_error_response( &self, res: types::Response, + event_builder: Option<&mut ConnectorEvent>, ) -> CustomResult<types::ErrorResponse, errors::ConnectorError> { let response: cybersource::CybersourceServerErrorResponse = res .response .parse_struct("CybersourceServerErrorResponse") .change_context(errors::ConnectorError::ResponseDeserializationFailed)?; + event_builder.map(|event| event.set_response_body(&response)); + router_env::logger::info!(error_response=?response); + Ok(types::ErrorResponse { status_code: res.status_code, reason: response.status.clone(), @@ -1210,12 +1273,15 @@ impl ConnectorIntegration<api::Execute, types::RefundsData, types::RefundsRespon fn handle_response( &self, data: &types::RefundExecuteRouterData, + event_builder: Option<&mut ConnectorEvent>, res: types::Response, ) -> CustomResult<types::RefundExecuteRouterData, errors::ConnectorError> { let response: cybersource::CybersourceRefundResponse = res .response .parse_struct("Cybersource 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(), @@ -1225,8 +1291,9 @@ impl ConnectorIntegration<api::Execute, types::RefundsData, types::RefundsRespon fn get_error_response( &self, res: types::Response, + event_builder: Option<&mut ConnectorEvent>, ) -> CustomResult<types::ErrorResponse, errors::ConnectorError> { - self.build_error_response(res) + self.build_error_response(res, event_builder) } } @@ -1276,12 +1343,15 @@ impl ConnectorIntegration<api::RSync, types::RefundsData, types::RefundsResponse fn handle_response( &self, data: &types::RefundSyncRouterData, + event_builder: Option<&mut ConnectorEvent>, res: types::Response, ) -> CustomResult<types::RefundSyncRouterData, errors::ConnectorError> { let response: cybersource::CybersourceRsyncResponse = res .response .parse_struct("Cybersource 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(), @@ -1291,8 +1361,9 @@ impl ConnectorIntegration<api::RSync, types::RefundsData, types::RefundsResponse fn get_error_response( &self, res: types::Response, + event_builder: Option<&mut ConnectorEvent>, ) -> CustomResult<types::ErrorResponse, errors::ConnectorError> { - self.build_error_response(res) + self.build_error_response(res, event_builder) } } @@ -1373,6 +1444,7 @@ impl fn handle_response( &self, data: &types::PaymentsIncrementalAuthorizationRouterData, + event_builder: Option<&mut ConnectorEvent>, res: types::Response, ) -> CustomResult< types::RouterData< @@ -1386,6 +1458,8 @@ impl .response .parse_struct("Cybersource 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 { response, @@ -1399,8 +1473,9 @@ impl fn get_error_response( &self, res: types::Response, + event_builder: Option<&mut ConnectorEvent>, ) -> CustomResult<types::ErrorResponse, errors::ConnectorError> { - self.build_error_response(res) + self.build_error_response(res, event_builder) } } diff --git a/crates/router/src/connector/cybersource/transformers.rs b/crates/router/src/connector/cybersource/transformers.rs index 324fe77d0bc..646fe179da6 100644 --- a/crates/router/src/connector/cybersource/transformers.rs +++ b/crates/router/src/connector/cybersource/transformers.rs @@ -1303,7 +1303,7 @@ impl TryFrom<&types::ConnectorAuthType> for CybersourceAuthType { } } -#[derive(Debug, Clone, Deserialize)] +#[derive(Debug, Clone, Deserialize, Serialize)] #[serde(rename_all = "SCREAMING_SNAKE_CASE")] pub enum CybersourcePaymentStatus { Authorized, @@ -1325,7 +1325,7 @@ pub enum CybersourcePaymentStatus { //PartialAuthorized, not being consumed yet. } -#[derive(Debug, Clone, Deserialize)] +#[derive(Debug, Clone, Deserialize, Serialize)] #[serde(rename_all = "SCREAMING_SNAKE_CASE")] pub enum CybersourceIncrementalAuthorizationStatus { Authorized, @@ -1380,14 +1380,14 @@ impl From<CybersourceIncrementalAuthorizationStatus> for common_enums::Authoriza } } -#[derive(Debug, Deserialize)] +#[derive(Debug, Deserialize, Serialize)] #[serde(untagged)] pub enum CybersourcePaymentsResponse { ClientReferenceInformation(CybersourceClientReferenceResponse), ErrorInformation(CybersourceErrorInformationResponse), } -#[derive(Clone, Debug, Deserialize)] +#[derive(Clone, Debug, Deserialize, Serialize)] #[serde(rename_all = "camelCase")] pub struct CybersourceClientReferenceResponse { id: String, @@ -1399,14 +1399,14 @@ pub struct CybersourceClientReferenceResponse { error_information: Option<CybersourceErrorInformation>, } -#[derive(Debug, Clone, Deserialize)] +#[derive(Debug, Clone, Deserialize, Serialize)] #[serde(rename_all = "camelCase")] pub struct CybersourceErrorInformationResponse { id: String, error_information: CybersourceErrorInformation, } -#[derive(Debug, Deserialize)] +#[derive(Debug, Deserialize, Serialize)] #[serde(rename_all = "camelCase")] pub struct CybersourceConsumerAuthInformationResponse { access_token: String, @@ -1414,7 +1414,7 @@ pub struct CybersourceConsumerAuthInformationResponse { reference_id: String, } -#[derive(Debug, Deserialize)] +#[derive(Debug, Deserialize, Serialize)] #[serde(rename_all = "camelCase")] pub struct ClientAuthSetupInfoResponse { id: String, @@ -1422,21 +1422,21 @@ pub struct ClientAuthSetupInfoResponse { consumer_authentication_information: CybersourceConsumerAuthInformationResponse, } -#[derive(Debug, Deserialize)] +#[derive(Debug, Deserialize, Serialize)] #[serde(untagged)] pub enum CybersourceAuthSetupResponse { ClientAuthSetupInfo(ClientAuthSetupInfoResponse), ErrorInformation(CybersourceErrorInformationResponse), } -#[derive(Debug, Clone, Deserialize)] +#[derive(Debug, Clone, Deserialize, Serialize)] #[serde(rename_all = "camelCase")] pub struct CybersourcePaymentsIncrementalAuthorizationResponse { status: CybersourceIncrementalAuthorizationStatus, error_information: Option<CybersourceErrorInformation>, } -#[derive(Debug, Deserialize)] +#[derive(Debug, Deserialize, Serialize)] #[serde(untagged)] pub enum CybersourceSetupMandatesResponse { ClientReferenceInformation(CybersourceClientReferenceResponse), @@ -1462,24 +1462,24 @@ pub struct Avs { code_raw: Option<String>, } -#[derive(Debug, Clone, Deserialize)] +#[derive(Debug, Clone, Deserialize, Serialize)] #[serde(rename_all = "camelCase")] pub struct ClientRiskInformation { rules: Option<Vec<ClientRiskInformationRules>>, } -#[derive(Debug, Clone, Deserialize)] +#[derive(Debug, Clone, Deserialize, Serialize)] pub struct ClientRiskInformationRules { name: String, } -#[derive(Debug, Clone, Deserialize)] +#[derive(Debug, Clone, Deserialize, Serialize)] #[serde(rename_all = "camelCase")] pub struct CybersourceTokenInformation { payment_instrument: CybersoucrePaymentInstrument, } -#[derive(Debug, Clone, Deserialize)] +#[derive(Debug, Clone, Deserialize, Serialize)] pub struct CybersourceErrorInformation { reason: Option<String>, message: Option<String>, @@ -1908,7 +1908,7 @@ impl TryFrom<&CybersourceRouterData<&types::PaymentsCompleteAuthorizeRouterData> } } -#[derive(Debug, Deserialize)] +#[derive(Debug, Deserialize, Serialize)] #[serde(rename_all = "SCREAMING_SNAKE_CASE")] pub enum CybersourceAuthEnrollmentStatus { PendingAuthentication, @@ -1932,7 +1932,7 @@ pub struct CybersourceThreeDSMetadata { three_ds_data: CybersourceConsumerAuthValidateResponse, } -#[derive(Debug, Deserialize)] +#[derive(Debug, Deserialize, Serialize)] #[serde(rename_all = "camelCase")] pub struct CybersourceConsumerAuthInformationEnrollmentResponse { access_token: Option<String>, @@ -1942,7 +1942,7 @@ pub struct CybersourceConsumerAuthInformationEnrollmentResponse { validate_response: CybersourceConsumerAuthValidateResponse, } -#[derive(Debug, Deserialize)] +#[derive(Debug, Deserialize, Serialize)] #[serde(rename_all = "camelCase")] pub struct ClientAuthCheckInfoResponse { id: String, @@ -1952,7 +1952,7 @@ pub struct ClientAuthCheckInfoResponse { error_information: Option<CybersourceErrorInformation>, } -#[derive(Debug, Deserialize)] +#[derive(Debug, Deserialize, Serialize)] #[serde(untagged)] pub enum CybersourcePreProcessingResponse { ClientAuthCheckInfo(Box<ClientAuthCheckInfoResponse>), @@ -2335,14 +2335,14 @@ impl<F, T> } } -#[derive(Debug, Deserialize)] +#[derive(Debug, Deserialize, Serialize)] #[serde(untagged)] pub enum CybersourceTransactionResponse { ApplicationInformation(CybersourceApplicationInfoResponse), ErrorInformation(CybersourceErrorInformationResponse), } -#[derive(Debug, Deserialize)] +#[derive(Debug, Deserialize, Serialize)] #[serde(rename_all = "camelCase")] pub struct CybersourceApplicationInfoResponse { id: String, @@ -2351,7 +2351,7 @@ pub struct CybersourceApplicationInfoResponse { error_information: Option<CybersourceErrorInformation>, } -#[derive(Clone, Debug, Deserialize)] +#[derive(Clone, Debug, Deserialize, Serialize)] #[serde(rename_all = "camelCase")] pub struct ApplicationInformation { status: CybersourcePaymentStatus, @@ -2474,7 +2474,7 @@ impl From<CybersourceRefundStatus> for enums::RefundStatus { } } -#[derive(Debug, Deserialize)] +#[derive(Debug, Deserialize, Serialize)] #[serde(rename_all = "SCREAMING_SNAKE_CASE")] pub enum CybersourceRefundStatus { Succeeded, @@ -2484,7 +2484,7 @@ pub enum CybersourceRefundStatus { Voided, } -#[derive(Debug, Deserialize)] +#[derive(Debug, Deserialize, Serialize)] #[serde(rename_all = "camelCase")] pub struct CybersourceRefundResponse { id: String, @@ -2508,13 +2508,13 @@ impl TryFrom<types::RefundsResponseRouterData<api::Execute, CybersourceRefundRes } } -#[derive(Debug, Deserialize)] +#[derive(Debug, Deserialize, Serialize)] #[serde(rename_all = "camelCase")] pub struct RsyncApplicationInformation { status: CybersourceRefundStatus, } -#[derive(Debug, Deserialize)] +#[derive(Debug, Deserialize, Serialize)] #[serde(rename_all = "camelCase")] pub struct CybersourceRsyncResponse { id: String, @@ -2540,7 +2540,7 @@ impl TryFrom<types::RefundsResponseRouterData<api::RSync, CybersourceRsyncRespon } } -#[derive(Debug, Deserialize)] +#[derive(Debug, Deserialize, Serialize)] #[serde(rename_all = "camelCase")] pub struct CybersourceStandardErrorResponse { pub error_information: Option<ErrorInformation>, @@ -2550,13 +2550,13 @@ pub struct CybersourceStandardErrorResponse { pub details: Option<Vec<Details>>, } -#[derive(Debug, Deserialize)] +#[derive(Debug, Deserialize, Serialize)] #[serde(rename_all = "camelCase")] pub struct CybersourceNotAvailableErrorResponse { pub errors: Vec<CybersourceNotAvailableErrorObject>, } -#[derive(Debug, Deserialize)] +#[derive(Debug, Deserialize, Serialize)] #[serde(rename_all = "camelCase")] pub struct CybersourceNotAvailableErrorObject { #[serde(rename = "type")] @@ -2564,7 +2564,7 @@ pub struct CybersourceNotAvailableErrorObject { pub message: Option<String>, } -#[derive(Debug, Deserialize)] +#[derive(Debug, Deserialize, Serialize)] #[serde(rename_all = "camelCase")] pub struct CybersourceServerErrorResponse { pub status: Option<String>, @@ -2572,7 +2572,7 @@ pub struct CybersourceServerErrorResponse { pub reason: Option<Reason>, } -#[derive(Debug, Deserialize)] +#[derive(Debug, Deserialize, Serialize)] #[serde(rename_all = "SCREAMING_SNAKE_CASE")] pub enum Reason { SystemError, @@ -2580,12 +2580,12 @@ pub enum Reason { ServiceTimeout, } -#[derive(Debug, Deserialize)] +#[derive(Debug, Deserialize, Serialize)] pub struct CybersourceAuthenticationErrorResponse { pub response: AuthenticationErrorInformation, } -#[derive(Debug, Deserialize)] +#[derive(Debug, Deserialize, Serialize)] #[serde(untagged)] pub enum CybersourceErrorResponse { AuthenticationError(CybersourceAuthenticationErrorResponse), @@ -2594,20 +2594,20 @@ pub enum CybersourceErrorResponse { StandardError(CybersourceStandardErrorResponse), } -#[derive(Debug, Deserialize, Clone)] +#[derive(Debug, Deserialize, Clone, Serialize)] #[serde(rename_all = "camelCase")] pub struct Details { pub field: String, pub reason: String, } -#[derive(Debug, Default, Deserialize)] +#[derive(Debug, Default, Deserialize, Serialize)] pub struct ErrorInformation { pub message: String, pub reason: String, } -#[derive(Debug, Default, Deserialize)] +#[derive(Debug, Default, Deserialize, Serialize)] pub struct AuthenticationErrorInformation { pub rmsg: String, } diff --git a/crates/router/src/connector/dlocal.rs b/crates/router/src/connector/dlocal.rs index 1e6fc7561ed..5487fd68a51 100644 --- a/crates/router/src/connector/dlocal.rs +++ b/crates/router/src/connector/dlocal.rs @@ -17,6 +17,7 @@ use crate::{ configs::settings, connector::utils as connector_utils, core::errors::{self, CustomResult}, + events::connector_api_logs::ConnectorEvent, headers, logger, services::{ self, @@ -120,12 +121,16 @@ impl ConnectorCommon for Dlocal { fn build_error_response( &self, res: Response, + event_builder: Option<&mut ConnectorEvent>, ) -> CustomResult<ErrorResponse, errors::ConnectorError> { let response: dlocal::DlocalErrorResponse = res .response .parse_struct("Dlocal ErrorResponse") .change_context(errors::ConnectorError::ResponseDeserializationFailed)?; + event_builder.map(|i: &mut ConnectorEvent| i.set_error_response_body(&response)); + router_env::logger::info!(connector_response=?response); + Ok(ErrorResponse { status_code: res.status_code, code: response.code.to_string(), @@ -259,6 +264,7 @@ impl ConnectorIntegration<api::Authorize, types::PaymentsAuthorizeData, types::P fn handle_response( &self, data: &types::PaymentsAuthorizeRouterData, + event_builder: Option<&mut ConnectorEvent>, res: Response, ) -> CustomResult<types::PaymentsAuthorizeRouterData, errors::ConnectorError> { logger::debug!(dlocal_payments_authorize_response=?res); @@ -266,6 +272,10 @@ impl ConnectorIntegration<api::Authorize, types::PaymentsAuthorizeData, types::P .response .parse_struct("Dlocal PaymentsAuthorizeResponse") .change_context(errors::ConnectorError::ResponseDeserializationFailed)?; + + event_builder.map(|i| i.set_response_body(&response)); + router_env::logger::info!(connector_response=?response); + types::ResponseRouterData { response, data: data.clone(), @@ -278,8 +288,9 @@ impl ConnectorIntegration<api::Authorize, types::PaymentsAuthorizeData, types::P fn get_error_response( &self, res: Response, + event_builder: Option<&mut ConnectorEvent>, ) -> CustomResult<ErrorResponse, errors::ConnectorError> { - self.build_error_response(res) + self.build_error_response(res, event_builder) } } @@ -329,13 +340,15 @@ impl ConnectorIntegration<api::PSync, types::PaymentsSyncData, types::PaymentsRe fn get_error_response( &self, res: Response, + event_builder: Option<&mut ConnectorEvent>, ) -> CustomResult<ErrorResponse, errors::ConnectorError> { - self.build_error_response(res) + self.build_error_response(res, event_builder) } fn handle_response( &self, data: &types::PaymentsSyncRouterData, + event_builder: Option<&mut ConnectorEvent>, res: Response, ) -> CustomResult<types::PaymentsSyncRouterData, errors::ConnectorError> { logger::debug!(dlocal_payment_sync_response=?res); @@ -343,6 +356,8 @@ impl ConnectorIntegration<api::PSync, types::PaymentsSyncData, types::PaymentsRe .response .parse_struct("Dlocal 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(), @@ -407,6 +422,7 @@ impl ConnectorIntegration<api::Capture, types::PaymentsCaptureData, types::Payme fn handle_response( &self, data: &types::PaymentsCaptureRouterData, + event_builder: Option<&mut ConnectorEvent>, res: Response, ) -> CustomResult<types::PaymentsCaptureRouterData, errors::ConnectorError> { logger::debug!(dlocal_payments_capture_response=?res); @@ -414,6 +430,8 @@ impl ConnectorIntegration<api::Capture, types::PaymentsCaptureData, types::Payme .response .parse_struct("Dlocal PaymentsCaptureResponse") .change_context(errors::ConnectorError::ResponseDeserializationFailed)?; + event_builder.map(|i| i.set_response_body(&response)); + router_env::logger::info!(connector_response=?response); types::ResponseRouterData { response, data: data.clone(), @@ -426,8 +444,9 @@ impl ConnectorIntegration<api::Capture, types::PaymentsCaptureData, types::Payme fn get_error_response( &self, res: Response, + event_builder: Option<&mut ConnectorEvent>, ) -> CustomResult<ErrorResponse, errors::ConnectorError> { - self.build_error_response(res) + self.build_error_response(res, event_builder) } } @@ -477,6 +496,7 @@ impl ConnectorIntegration<api::Void, types::PaymentsCancelData, types::PaymentsR fn handle_response( &self, data: &types::PaymentsCancelRouterData, + event_builder: Option<&mut ConnectorEvent>, res: Response, ) -> CustomResult<types::PaymentsCancelRouterData, errors::ConnectorError> { logger::debug!(dlocal_payments_cancel_response=?res); @@ -484,6 +504,9 @@ impl ConnectorIntegration<api::Void, types::PaymentsCancelData, types::PaymentsR .response .parse_struct("Dlocal PaymentsCancelResponse") .change_context(errors::ConnectorError::ResponseDeserializationFailed)?; + event_builder.map(|i| i.set_response_body(&response)); + router_env::logger::info!(connector_response=?response); + types::ResponseRouterData { response, data: data.clone(), @@ -496,8 +519,9 @@ impl ConnectorIntegration<api::Void, types::PaymentsCancelData, types::PaymentsR fn get_error_response( &self, res: Response, + event_builder: Option<&mut ConnectorEvent>, ) -> CustomResult<ErrorResponse, errors::ConnectorError> { - self.build_error_response(res) + self.build_error_response(res, event_builder) } } @@ -559,6 +583,7 @@ impl ConnectorIntegration<api::Execute, types::RefundsData, types::RefundsRespon fn handle_response( &self, data: &types::RefundsRouterData<api::Execute>, + event_builder: Option<&mut ConnectorEvent>, res: Response, ) -> CustomResult<types::RefundsRouterData<api::Execute>, errors::ConnectorError> { logger::debug!(dlocal_refund_response=?res); @@ -566,6 +591,8 @@ impl ConnectorIntegration<api::Execute, types::RefundsData, types::RefundsRespon res.response .parse_struct("Dlocal RefundResponse") .change_context(errors::ConnectorError::RequestEncodingFailed)?; + event_builder.map(|i| i.set_response_body(&response)); + router_env::logger::info!(connector_response=?response); types::ResponseRouterData { response, data: data.clone(), @@ -578,8 +605,9 @@ impl ConnectorIntegration<api::Execute, types::RefundsData, types::RefundsRespon fn get_error_response( &self, res: Response, + event_builder: Option<&mut ConnectorEvent>, ) -> CustomResult<ErrorResponse, errors::ConnectorError> { - self.build_error_response(res) + self.build_error_response(res, event_builder) } } @@ -627,6 +655,7 @@ impl ConnectorIntegration<api::RSync, types::RefundsData, types::RefundsResponse fn handle_response( &self, data: &types::RefundSyncRouterData, + event_builder: Option<&mut ConnectorEvent>, res: Response, ) -> CustomResult<types::RefundSyncRouterData, errors::ConnectorError> { logger::debug!(dlocal_refund_sync_response=?res); @@ -634,6 +663,8 @@ impl ConnectorIntegration<api::RSync, types::RefundsData, types::RefundsResponse .response .parse_struct("Dlocal RefundSyncResponse") .change_context(errors::ConnectorError::ResponseDeserializationFailed)?; + event_builder.map(|i| i.set_response_body(&response)); + router_env::logger::info!(connector_response=?response); types::ResponseRouterData { response, data: data.clone(), @@ -646,8 +677,9 @@ impl ConnectorIntegration<api::RSync, types::RefundsData, types::RefundsResponse fn get_error_response( &self, res: Response, + event_builder: Option<&mut ConnectorEvent>, ) -> CustomResult<ErrorResponse, errors::ConnectorError> { - self.build_error_response(res) + self.build_error_response(res, event_builder) } } diff --git a/crates/router/src/connector/dummyconnector.rs b/crates/router/src/connector/dummyconnector.rs index 28d9eaedf07..85b87f26c5e 100644 --- a/crates/router/src/connector/dummyconnector.rs +++ b/crates/router/src/connector/dummyconnector.rs @@ -11,6 +11,7 @@ use crate::{ configs::settings, connector::utils as connector_utils, core::errors::{self, CustomResult}, + events::connector_api_logs::ConnectorEvent, headers, services::{ self, @@ -101,12 +102,16 @@ impl<const T: u8> ConnectorCommon for DummyConnector<T> { fn build_error_response( &self, res: Response, + event_builder: Option<&mut ConnectorEvent>, ) -> CustomResult<ErrorResponse, errors::ConnectorError> { let response: transformers::DummyConnectorErrorResponse = res .response .parse_struct("DummyConnectorErrorResponse") .change_context(errors::ConnectorError::ResponseDeserializationFailed)?; + event_builder.map(|i| i.set_error_response_body(&response)); + router_env::logger::info!(connector_response=?response); + Ok(ErrorResponse { status_code: res.status_code, code: response.error.code, @@ -235,13 +240,15 @@ impl<const T: u8> fn handle_response( &self, data: &types::PaymentsAuthorizeRouterData, + event_builder: Option<&mut ConnectorEvent>, res: Response, ) -> CustomResult<types::PaymentsAuthorizeRouterData, errors::ConnectorError> { let response: transformers::PaymentsResponse = res .response .parse_struct("DummyConnector PaymentsResponse") .change_context(errors::ConnectorError::ResponseDeserializationFailed)?; - println!("handle_response: {:#?}", response); + 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(), @@ -253,8 +260,9 @@ impl<const T: u8> fn get_error_response( &self, res: Response, + event_builder: Option<&mut ConnectorEvent>, ) -> CustomResult<ErrorResponse, errors::ConnectorError> { - self.build_error_response(res) + self.build_error_response(res, event_builder) } } @@ -313,12 +321,15 @@ impl<const T: u8> fn handle_response( &self, data: &types::PaymentsSyncRouterData, + event_builder: Option<&mut ConnectorEvent>, res: Response, ) -> CustomResult<types::PaymentsSyncRouterData, errors::ConnectorError> { let response: transformers::PaymentsResponse = res .response .parse_struct("dummyconnector 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(), @@ -330,8 +341,9 @@ impl<const T: u8> fn get_error_response( &self, res: Response, + event_builder: Option<&mut ConnectorEvent>, ) -> CustomResult<ErrorResponse, errors::ConnectorError> { - self.build_error_response(res) + self.build_error_response(res, event_builder) } } @@ -387,12 +399,15 @@ impl<const T: u8> fn handle_response( &self, data: &types::PaymentsCaptureRouterData, + event_builder: Option<&mut ConnectorEvent>, res: Response, ) -> CustomResult<types::PaymentsCaptureRouterData, errors::ConnectorError> { let response: transformers::PaymentsResponse = res .response .parse_struct("transformers 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(), @@ -404,8 +419,9 @@ impl<const T: u8> fn get_error_response( &self, res: Response, + event_builder: Option<&mut ConnectorEvent>, ) -> CustomResult<ErrorResponse, errors::ConnectorError> { - self.build_error_response(res) + self.build_error_response(res, event_builder) } } @@ -473,12 +489,15 @@ impl<const T: u8> ConnectorIntegration<api::Execute, types::RefundsData, types:: 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: transformers::RefundResponse = res .response .parse_struct("transformers 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(), @@ -490,8 +509,9 @@ impl<const T: u8> ConnectorIntegration<api::Execute, types::RefundsData, types:: fn get_error_response( &self, res: Response, + event_builder: Option<&mut ConnectorEvent>, ) -> CustomResult<ErrorResponse, errors::ConnectorError> { - self.build_error_response(res) + self.build_error_response(res, event_builder) } } @@ -541,12 +561,15 @@ impl<const T: u8> ConnectorIntegration<api::RSync, types::RefundsData, types::Re fn handle_response( &self, data: &types::RefundSyncRouterData, + event_builder: Option<&mut ConnectorEvent>, res: Response, ) -> CustomResult<types::RefundSyncRouterData, errors::ConnectorError> { let response: transformers::RefundResponse = res .response .parse_struct("transformers 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(), @@ -558,8 +581,9 @@ impl<const T: u8> ConnectorIntegration<api::RSync, types::RefundsData, types::Re fn get_error_response( &self, res: Response, + event_builder: Option<&mut ConnectorEvent>, ) -> CustomResult<ErrorResponse, errors::ConnectorError> { - self.build_error_response(res) + self.build_error_response(res, event_builder) } } diff --git a/crates/router/src/connector/fiserv.rs b/crates/router/src/connector/fiserv.rs index 0bd82115627..5cbfee51947 100644 --- a/crates/router/src/connector/fiserv.rs +++ b/crates/router/src/connector/fiserv.rs @@ -17,6 +17,7 @@ use crate::{ connector::utils as connector_utils, consts, core::errors::{self, CustomResult}, + events::connector_api_logs::ConnectorEvent, headers, logger, services::{ self, @@ -129,12 +130,16 @@ impl ConnectorCommon for Fiserv { fn build_error_response( &self, res: types::Response, + event_builder: Option<&mut ConnectorEvent>, ) -> CustomResult<types::ErrorResponse, errors::ConnectorError> { let response: fiserv::ErrorResponse = res .response .parse_struct("Fiserv ErrorResponse") .change_context(errors::ConnectorError::ResponseDeserializationFailed)?; + event_builder.map(|i| i.set_error_response_body(&response)); + router_env::logger::info!(connector_response=?response); + let fiserv::ErrorResponse { error, details } = response; Ok(error @@ -290,12 +295,15 @@ impl ConnectorIntegration<api::Void, types::PaymentsCancelData, types::PaymentsR fn handle_response( &self, data: &types::PaymentsCancelRouterData, + event_builder: Option<&mut ConnectorEvent>, res: types::Response, ) -> CustomResult<types::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::ResponseRouterData { response, data: data.clone(), @@ -308,8 +316,9 @@ impl ConnectorIntegration<api::Void, types::PaymentsCancelData, types::PaymentsR fn get_error_response( &self, res: types::Response, + event_builder: Option<&mut ConnectorEvent>, ) -> CustomResult<types::ErrorResponse, errors::ConnectorError> { - self.build_error_response(res) + self.build_error_response(res, event_builder) } } @@ -373,13 +382,15 @@ impl ConnectorIntegration<api::PSync, types::PaymentsSyncData, types::PaymentsRe fn handle_response( &self, data: &types::PaymentsSyncRouterData, + event_builder: Option<&mut ConnectorEvent>, res: types::Response, ) -> CustomResult<types::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::ResponseRouterData { response, data: data.clone(), @@ -392,8 +403,9 @@ impl ConnectorIntegration<api::PSync, types::PaymentsSyncData, types::PaymentsRe fn get_error_response( &self, res: types::Response, + event_builder: Option<&mut ConnectorEvent>, ) -> CustomResult<types::ErrorResponse, errors::ConnectorError> { - self.build_error_response(res) + self.build_error_response(res, event_builder) } } @@ -452,12 +464,17 @@ impl ConnectorIntegration<api::Capture, types::PaymentsCaptureData, types::Payme fn handle_response( &self, data: &types::PaymentsCaptureRouterData, + event_builder: Option<&mut ConnectorEvent>, res: types::Response, ) -> CustomResult<types::PaymentsCaptureRouterData, errors::ConnectorError> { let response: fiserv::FiservPaymentsResponse = res .response .parse_struct("Fiserv Payment Response") .change_context(errors::ConnectorError::ResponseDeserializationFailed)?; + + event_builder.map(|i| i.set_response_body(&response)); + router_env::logger::info!(connector_response=?response); + types::ResponseRouterData { response, data: data.clone(), @@ -481,8 +498,9 @@ impl ConnectorIntegration<api::Capture, types::PaymentsCaptureData, types::Payme fn get_error_response( &self, res: types::Response, + event_builder: Option<&mut ConnectorEvent>, ) -> CustomResult<types::ErrorResponse, errors::ConnectorError> { - self.build_error_response(res) + self.build_error_response(res, event_builder) } } @@ -564,12 +582,15 @@ impl ConnectorIntegration<api::Authorize, types::PaymentsAuthorizeData, types::P fn handle_response( &self, data: &types::PaymentsAuthorizeRouterData, + event_builder: Option<&mut ConnectorEvent>, res: types::Response, ) -> CustomResult<types::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::ResponseRouterData { response, data: data.clone(), @@ -582,8 +603,9 @@ impl ConnectorIntegration<api::Authorize, types::PaymentsAuthorizeData, types::P fn get_error_response( &self, res: types::Response, + event_builder: Option<&mut ConnectorEvent>, ) -> CustomResult<types::ErrorResponse, errors::ConnectorError> { - self.build_error_response(res) + self.build_error_response(res, event_builder) } } @@ -649,6 +671,7 @@ impl ConnectorIntegration<api::Execute, types::RefundsData, types::RefundsRespon fn handle_response( &self, data: &types::RefundsRouterData<api::Execute>, + event_builder: Option<&mut ConnectorEvent>, res: types::Response, ) -> CustomResult<types::RefundsRouterData<api::Execute>, errors::ConnectorError> { logger::debug!(target: "router::connector::fiserv", response=?res); @@ -656,6 +679,8 @@ impl ConnectorIntegration<api::Execute, types::RefundsData, types::RefundsRespon 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::ResponseRouterData { response, data: data.clone(), @@ -667,8 +692,9 @@ impl ConnectorIntegration<api::Execute, types::RefundsData, types::RefundsRespon fn get_error_response( &self, res: types::Response, + event_builder: Option<&mut ConnectorEvent>, ) -> CustomResult<types::ErrorResponse, errors::ConnectorError> { - self.build_error_response(res) + self.build_error_response(res, event_builder) } } @@ -728,6 +754,7 @@ impl ConnectorIntegration<api::RSync, types::RefundsData, types::RefundsResponse fn handle_response( &self, data: &types::RefundSyncRouterData, + event_builder: Option<&mut ConnectorEvent>, res: types::Response, ) -> CustomResult<types::RefundSyncRouterData, errors::ConnectorError> { logger::debug!(target: "router::connector::fiserv", response=?res); @@ -736,6 +763,8 @@ impl ConnectorIntegration<api::RSync, types::RefundsData, types::RefundsResponse .response .parse_struct("Fiserv Refund Response") .change_context(errors::ConnectorError::ResponseDeserializationFailed)?; + event_builder.map(|i| i.set_response_body(&response)); + router_env::logger::info!(connector_response=?response); types::ResponseRouterData { response, data: data.clone(), @@ -748,8 +777,9 @@ impl ConnectorIntegration<api::RSync, types::RefundsData, types::RefundsResponse fn get_error_response( &self, res: types::Response, + event_builder: Option<&mut ConnectorEvent>, ) -> CustomResult<types::ErrorResponse, errors::ConnectorError> { - self.build_error_response(res) + self.build_error_response(res, event_builder) } } diff --git a/crates/router/src/connector/fiserv/transformers.rs b/crates/router/src/connector/fiserv/transformers.rs index 00109f89207..e2511dc8d56 100644 --- a/crates/router/src/connector/fiserv/transformers.rs +++ b/crates/router/src/connector/fiserv/transformers.rs @@ -257,14 +257,14 @@ impl TryFrom<&types::PaymentsCancelRouterData> for FiservCancelRequest { } } -#[derive(Debug, Default, Deserialize)] +#[derive(Debug, Default, Deserialize, Serialize)] #[serde(rename_all = "camelCase")] pub struct ErrorResponse { pub details: Option<Vec<ErrorDetails>>, pub error: Option<Vec<ErrorDetails>>, } -#[derive(Debug, Default, Deserialize)] +#[derive(Debug, Default, Deserialize, Serialize)] #[serde(rename_all = "camelCase")] pub struct ErrorDetails { #[serde(rename = "type")] diff --git a/crates/router/src/connector/forte.rs b/crates/router/src/connector/forte.rs index f23907232c4..f179e8a8cce 100644 --- a/crates/router/src/connector/forte.rs +++ b/crates/router/src/connector/forte.rs @@ -17,6 +17,7 @@ use crate::{ }, consts, core::errors::{self, CustomResult}, + events::connector_api_logs::ConnectorEvent, headers, services::{ self, @@ -116,11 +117,16 @@ impl ConnectorCommon for Forte { fn build_error_response( &self, res: Response, + event_builder: Option<&mut ConnectorEvent>, ) -> CustomResult<ErrorResponse, errors::ConnectorError> { let response: forte::ForteErrorResponse = res .response .parse_struct("Forte ErrorResponse") .change_context(errors::ConnectorError::ResponseDeserializationFailed)?; + + event_builder.map(|i| i.set_error_response_body(&response)); + router_env::logger::info!(connector_response=?response); + let message = response.response.response_desc; let code = response .response @@ -248,12 +254,17 @@ impl ConnectorIntegration<api::Authorize, types::PaymentsAuthorizeData, types::P fn handle_response( &self, data: &types::PaymentsAuthorizeRouterData, + event_builder: Option<&mut ConnectorEvent>, res: Response, ) -> CustomResult<types::PaymentsAuthorizeRouterData, errors::ConnectorError> { let response: forte::FortePaymentsResponse = res .response .parse_struct("Forte AuthorizeResponse") .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(), @@ -264,8 +275,9 @@ impl ConnectorIntegration<api::Authorize, types::PaymentsAuthorizeData, types::P fn get_error_response( &self, res: Response, + event_builder: Option<&mut ConnectorEvent>, ) -> CustomResult<ErrorResponse, errors::ConnectorError> { - self.build_error_response(res) + self.build_error_response(res, event_builder) } } @@ -318,12 +330,17 @@ impl ConnectorIntegration<api::PSync, types::PaymentsSyncData, types::PaymentsRe fn handle_response( &self, data: &types::PaymentsSyncRouterData, + event_builder: Option<&mut ConnectorEvent>, res: Response, ) -> CustomResult<types::PaymentsSyncRouterData, errors::ConnectorError> { let response: forte::FortePaymentsSyncResponse = res .response .parse_struct("forte 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(), @@ -334,8 +351,9 @@ impl ConnectorIntegration<api::PSync, types::PaymentsSyncData, types::PaymentsRe fn get_error_response( &self, res: Response, + event_builder: Option<&mut ConnectorEvent>, ) -> CustomResult<ErrorResponse, errors::ConnectorError> { - self.build_error_response(res) + self.build_error_response(res, event_builder) } } @@ -400,12 +418,17 @@ impl ConnectorIntegration<api::Capture, types::PaymentsCaptureData, types::Payme fn handle_response( &self, data: &types::PaymentsCaptureRouterData, + event_builder: Option<&mut ConnectorEvent>, res: Response, ) -> CustomResult<types::PaymentsCaptureRouterData, errors::ConnectorError> { let response: forte::ForteCaptureResponse = res .response .parse_struct("Forte 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(), @@ -416,8 +439,9 @@ impl ConnectorIntegration<api::Capture, types::PaymentsCaptureData, types::Payme fn get_error_response( &self, res: Response, + event_builder: Option<&mut ConnectorEvent>, ) -> CustomResult<ErrorResponse, errors::ConnectorError> { - self.build_error_response(res) + self.build_error_response(res, event_builder) } } impl ConnectorIntegration<api::Void, types::PaymentsCancelData, types::PaymentsResponseData> @@ -479,12 +503,17 @@ impl ConnectorIntegration<api::Void, types::PaymentsCancelData, types::PaymentsR fn handle_response( &self, data: &types::PaymentsCancelRouterData, + event_builder: Option<&mut ConnectorEvent>, res: Response, ) -> CustomResult<types::PaymentsCancelRouterData, errors::ConnectorError> { let response: forte::ForteCancelResponse = res .response .parse_struct("forte CancelResponse") .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(), @@ -495,8 +524,9 @@ impl ConnectorIntegration<api::Void, types::PaymentsCancelData, types::PaymentsR fn get_error_response( &self, res: Response, + event_builder: Option<&mut ConnectorEvent>, ) -> CustomResult<ErrorResponse, errors::ConnectorError> { - self.build_error_response(res) + self.build_error_response(res, event_builder) } } @@ -558,12 +588,17 @@ impl ConnectorIntegration<api::Execute, types::RefundsData, types::RefundsRespon 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: forte::RefundResponse = res .response .parse_struct("forte 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(), @@ -574,8 +609,9 @@ impl ConnectorIntegration<api::Execute, types::RefundsData, types::RefundsRespon fn get_error_response( &self, res: Response, + event_builder: Option<&mut ConnectorEvent>, ) -> CustomResult<ErrorResponse, errors::ConnectorError> { - self.build_error_response(res) + self.build_error_response(res, event_builder) } } @@ -625,12 +661,17 @@ impl ConnectorIntegration<api::RSync, types::RefundsData, types::RefundsResponse fn handle_response( &self, data: &types::RefundSyncRouterData, + event_builder: Option<&mut ConnectorEvent>, res: Response, ) -> CustomResult<types::RefundSyncRouterData, errors::ConnectorError> { let response: forte::RefundSyncResponse = res .response .parse_struct("forte 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(), @@ -641,8 +682,9 @@ impl ConnectorIntegration<api::RSync, types::RefundsData, types::RefundsResponse fn get_error_response( &self, res: Response, + event_builder: Option<&mut ConnectorEvent>, ) -> CustomResult<ErrorResponse, errors::ConnectorError> { - self.build_error_response(res) + self.build_error_response(res, event_builder) } } diff --git a/crates/router/src/connector/forte/transformers.rs b/crates/router/src/connector/forte/transformers.rs index 4c770eb788d..83bcb2c551b 100644 --- a/crates/router/src/connector/forte/transformers.rs +++ b/crates/router/src/connector/forte/transformers.rs @@ -151,7 +151,7 @@ impl TryFrom<&types::ConnectorAuthType> for ForteAuthType { } } // PaymentsResponse -#[derive(Debug, Deserialize)] +#[derive(Debug, Deserialize, Serialize)] #[serde(rename_all = "lowercase")] pub enum FortePaymentStatus { Complete, @@ -188,7 +188,7 @@ impl ForeignFrom<(ForteResponseCode, ForteAction)> for enums::AttemptStatus { } } -#[derive(Debug, Deserialize)] +#[derive(Debug, Deserialize, Serialize)] pub struct CardResponse { pub name_on_card: Secret<String>, pub last_4_account_number: String, @@ -196,7 +196,7 @@ pub struct CardResponse { pub card_type: String, } -#[derive(Debug, Deserialize)] +#[derive(Debug, Deserialize, Serialize)] pub enum ForteResponseCode { A01, A05, @@ -218,7 +218,7 @@ impl From<ForteResponseCode> for enums::AttemptStatus { } } -#[derive(Debug, Deserialize)] +#[derive(Debug, Deserialize, Serialize)] pub struct ResponseStatus { pub environment: String, pub response_type: String, @@ -237,7 +237,7 @@ pub enum ForteAction { Verify, } -#[derive(Debug, Deserialize)] +#[derive(Debug, Deserialize, Serialize)] pub struct FortePaymentsResponse { pub transaction_id: String, pub location_id: String, @@ -286,7 +286,7 @@ impl<F, T> //PsyncResponse -#[derive(Debug, Deserialize)] +#[derive(Debug, Deserialize, Serialize)] pub struct FortePaymentsSyncResponse { pub transaction_id: String, pub location_id: String, @@ -356,7 +356,7 @@ impl TryFrom<&types::PaymentsCaptureRouterData> for ForteCaptureRequest { } } -#[derive(Debug, Deserialize)] +#[derive(Debug, Deserialize, Serialize)] pub struct CaptureResponseStatus { pub environment: String, pub response_type: String, @@ -365,7 +365,7 @@ pub struct CaptureResponseStatus { pub authorization_code: String, } // Capture Response -#[derive(Debug, Deserialize)] +#[derive(Debug, Deserialize, Serialize)] pub struct ForteCaptureResponse { pub transaction_id: String, pub original_transaction_id: String, @@ -423,7 +423,7 @@ impl TryFrom<&types::PaymentsCancelRouterData> for ForteCancelRequest { } } -#[derive(Debug, Deserialize)] +#[derive(Debug, Deserialize, Serialize)] pub struct CancelResponseStatus { pub response_type: String, pub response_code: ForteResponseCode, @@ -431,7 +431,7 @@ pub struct CancelResponseStatus { pub authorization_code: String, } -#[derive(Debug, Deserialize)] +#[derive(Debug, Deserialize, Serialize)] pub struct ForteCancelResponse { pub transaction_id: String, pub location_id: String, @@ -495,7 +495,7 @@ impl<F> TryFrom<&types::RefundsRouterData<F>> for ForteRefundRequest { } } -#[derive(Debug, Deserialize)] +#[derive(Debug, Deserialize, Serialize)] #[serde(rename_all = "lowercase")] pub enum RefundStatus { Complete, @@ -523,7 +523,7 @@ impl From<ForteResponseCode> for enums::RefundStatus { } } -#[derive(Debug, Deserialize)] +#[derive(Debug, Deserialize, Serialize)] pub struct RefundResponse { pub transaction_id: String, pub original_transaction_id: String, @@ -550,7 +550,7 @@ impl TryFrom<types::RefundsResponseRouterData<api::Execute, RefundResponse>> } } -#[derive(Debug, Deserialize)] +#[derive(Debug, Deserialize, Serialize)] pub struct RefundSyncResponse { status: RefundStatus, transaction_id: String, @@ -573,7 +573,7 @@ impl TryFrom<types::RefundsResponseRouterData<api::RSync, RefundSyncResponse>> } } -#[derive(Debug, Deserialize)] +#[derive(Debug, Deserialize, Serialize)] pub struct ErrorResponseStatus { pub environment: String, pub response_type: Option<String>, @@ -581,7 +581,7 @@ pub struct ErrorResponseStatus { pub response_desc: String, } -#[derive(Debug, Deserialize)] +#[derive(Debug, Deserialize, Serialize)] pub struct ForteErrorResponse { pub response: ErrorResponseStatus, } diff --git a/crates/router/src/connector/globalpay.rs b/crates/router/src/connector/globalpay.rs index 76954217eef..620805eb3e5 100644 --- a/crates/router/src/connector/globalpay.rs +++ b/crates/router/src/connector/globalpay.rs @@ -25,6 +25,7 @@ use crate::{ errors::{self, CustomResult}, payments, }, + events::connector_api_logs::ConnectorEvent, headers, services::{ self, @@ -93,12 +94,16 @@ impl ConnectorCommon for Globalpay { fn build_error_response( &self, res: types::Response, + event_builder: Option<&mut ConnectorEvent>, ) -> CustomResult<ErrorResponse, errors::ConnectorError> { let response: transformers::GlobalpayErrorResponse = res .response .parse_struct("Globalpay ErrorResponse") .change_context(errors::ConnectorError::ResponseDeserializationFailed)?; + event_builder.map(|i| i.set_error_response_body(&response)); + router_env::logger::info!(connector_response=?response); + Ok(ErrorResponse { status_code: res.status_code, code: response.error_code, @@ -196,6 +201,7 @@ impl fn handle_response( &self, data: &types::PaymentsCompleteAuthorizeRouterData, + event_builder: Option<&mut ConnectorEvent>, res: types::Response, ) -> CustomResult<types::PaymentsCompleteAuthorizeRouterData, errors::ConnectorError> { let response: GlobalpayPaymentsResponse = res @@ -203,6 +209,9 @@ impl .parse_struct("Globalpay PaymentsResponse") .switch()?; + 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(), @@ -214,8 +223,9 @@ impl fn get_error_response( &self, res: types::Response, + event_builder: Option<&mut ConnectorEvent>, ) -> CustomResult<ErrorResponse, errors::ConnectorError> { - self.build_error_response(res) + self.build_error_response(res, event_builder) } } @@ -282,6 +292,7 @@ impl ConnectorIntegration<api::AccessTokenAuth, types::AccessTokenRequestData, t fn handle_response( &self, data: &types::RefreshTokenRouterData, + event_builder: Option<&mut ConnectorEvent>, res: types::Response, ) -> CustomResult<types::RefreshTokenRouterData, errors::ConnectorError> { let response: GlobalpayRefreshTokenResponse = res @@ -289,6 +300,9 @@ impl ConnectorIntegration<api::AccessTokenAuth, types::AccessTokenRequestData, t .parse_struct("Globalpay PaymentsResponse") .change_context(errors::ConnectorError::ResponseDeserializationFailed)?; + event_builder.map(|i| i.set_response_body(&response)); + router_env::logger::info!(connector_response=?response); + types::ResponseRouterData { response, data: data.clone(), @@ -301,12 +315,16 @@ impl ConnectorIntegration<api::AccessTokenAuth, types::AccessTokenRequestData, t fn get_error_response( &self, res: types::Response, + event_builder: Option<&mut ConnectorEvent>, ) -> CustomResult<ErrorResponse, errors::ConnectorError> { let response: GlobalpayRefreshTokenErrorResponse = res .response .parse_struct("Globalpay ErrorResponse") .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.error_code, @@ -415,12 +433,15 @@ impl ConnectorIntegration<api::Void, types::PaymentsCancelData, types::PaymentsR fn handle_response( &self, data: &types::PaymentsCancelRouterData, + event_builder: Option<&mut ConnectorEvent>, res: types::Response, ) -> CustomResult<types::PaymentsCancelRouterData, errors::ConnectorError> { let response: GlobalpayPaymentsResponse = res .response .parse_struct("Globalpay PaymentsResponse") .change_context(errors::ConnectorError::ResponseDeserializationFailed)?; + event_builder.map(|i| i.set_response_body(&response)); + router_env::logger::info!(connector_response=?response); types::ResponseRouterData { response, data: data.clone(), @@ -433,8 +454,9 @@ impl ConnectorIntegration<api::Void, types::PaymentsCancelData, types::PaymentsR fn get_error_response( &self, res: types::Response, + event_builder: Option<&mut ConnectorEvent>, ) -> CustomResult<ErrorResponse, errors::ConnectorError> { - self.build_error_response(res) + self.build_error_response(res, event_builder) } } @@ -487,19 +509,25 @@ impl ConnectorIntegration<api::PSync, types::PaymentsSyncData, types::PaymentsRe fn get_error_response( &self, res: types::Response, + event_builder: Option<&mut ConnectorEvent>, ) -> CustomResult<ErrorResponse, errors::ConnectorError> { - self.build_error_response(res) + self.build_error_response(res, event_builder) } fn handle_response( &self, data: &types::PaymentsSyncRouterData, + event_builder: Option<&mut ConnectorEvent>, res: types::Response, ) -> CustomResult<types::PaymentsSyncRouterData, errors::ConnectorError> { let response: GlobalpayPaymentsResponse = res .response .parse_struct("globalpay PaymentsResponse") .change_context(errors::ConnectorError::ResponseDeserializationFailed)?; + + event_builder.map(|i| i.set_response_body(&response)); + router_env::logger::info!(connector_response=?response); + let is_multiple_capture_sync = match data.request.sync_type { types::SyncRequestType::MultipleCaptureSync(_) => true, types::SyncRequestType::SinglePaymentSync => false, @@ -581,12 +609,15 @@ impl ConnectorIntegration<api::Capture, types::PaymentsCaptureData, types::Payme fn handle_response( &self, data: &types::PaymentsCaptureRouterData, + event_builder: Option<&mut ConnectorEvent>, res: types::Response, ) -> CustomResult<types::PaymentsCaptureRouterData, errors::ConnectorError> { let response: GlobalpayPaymentsResponse = res .response .parse_struct("Globalpay PaymentsResponse") .change_context(errors::ConnectorError::ResponseDeserializationFailed)?; + event_builder.map(|i| i.set_response_body(&response)); + router_env::logger::info!(connector_response=?response); types::ResponseRouterData { response, data: data.clone(), @@ -599,8 +630,9 @@ impl ConnectorIntegration<api::Capture, types::PaymentsCaptureData, types::Payme fn get_error_response( &self, res: types::Response, + event_builder: Option<&mut ConnectorEvent>, ) -> CustomResult<ErrorResponse, errors::ConnectorError> { - self.build_error_response(res) + self.build_error_response(res, event_builder) } } @@ -670,12 +702,15 @@ impl ConnectorIntegration<api::Authorize, types::PaymentsAuthorizeData, types::P fn handle_response( &self, data: &types::PaymentsAuthorizeRouterData, + event_builder: Option<&mut ConnectorEvent>, res: types::Response, ) -> CustomResult<types::PaymentsAuthorizeRouterData, errors::ConnectorError> { let response: GlobalpayPaymentsResponse = res .response .parse_struct("Globalpay PaymentsResponse") .change_context(errors::ConnectorError::ResponseDeserializationFailed)?; + event_builder.map(|i| i.set_response_body(&response)); + router_env::logger::info!(connector_response=?response); types::ResponseRouterData { response, data: data.clone(), @@ -688,8 +723,9 @@ impl ConnectorIntegration<api::Authorize, types::PaymentsAuthorizeData, types::P fn get_error_response( &self, res: types::Response, + event_builder: Option<&mut ConnectorEvent>, ) -> CustomResult<ErrorResponse, errors::ConnectorError> { - self.build_error_response(res) + self.build_error_response(res, event_builder) } } @@ -755,12 +791,17 @@ impl ConnectorIntegration<api::Execute, types::RefundsData, types::RefundsRespon fn handle_response( &self, data: &types::RefundsRouterData<api::Execute>, + event_builder: Option<&mut ConnectorEvent>, res: types::Response, ) -> CustomResult<types::RefundsRouterData<api::Execute>, errors::ConnectorError> { let response: GlobalpayPaymentsResponse = res .response .parse_struct("globalpay 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 { response, data: data.clone(), @@ -772,8 +813,9 @@ impl ConnectorIntegration<api::Execute, types::RefundsData, types::RefundsRespon fn get_error_response( &self, res: types::Response, + event_builder: Option<&mut ConnectorEvent>, ) -> CustomResult<ErrorResponse, errors::ConnectorError> { - self.build_error_response(res) + self.build_error_response(res, event_builder) } } @@ -823,12 +865,15 @@ impl ConnectorIntegration<api::RSync, types::RefundsData, types::RefundsResponse fn handle_response( &self, data: &types::RefundSyncRouterData, + event_builder: Option<&mut ConnectorEvent>, res: types::Response, ) -> CustomResult<types::RefundSyncRouterData, errors::ConnectorError> { let response: GlobalpayPaymentsResponse = res .response .parse_struct("globalpay RefundResponse") .change_context(errors::ConnectorError::ResponseDeserializationFailed)?; + event_builder.map(|i| i.set_response_body(&response)); + router_env::logger::info!(connector_response=?response); types::ResponseRouterData { response, data: data.clone(), @@ -841,8 +886,9 @@ impl ConnectorIntegration<api::RSync, types::RefundsData, types::RefundsResponse fn get_error_response( &self, res: types::Response, + event_builder: Option<&mut ConnectorEvent>, ) -> CustomResult<ErrorResponse, errors::ConnectorError> { - self.build_error_response(res) + self.build_error_response(res, event_builder) } } diff --git a/crates/router/src/connector/globalpay/response.rs b/crates/router/src/connector/globalpay/response.rs index 7416d6f716a..201297c399e 100644 --- a/crates/router/src/connector/globalpay/response.rs +++ b/crates/router/src/connector/globalpay/response.rs @@ -70,13 +70,13 @@ pub struct Action { pub action_type: Option<String>, } -#[derive(Debug, Deserialize)] +#[derive(Debug, Deserialize, Serialize)] pub struct GlobalpayRefreshTokenResponse { pub token: Secret<String>, pub seconds_to_expire: i64, } -#[derive(Debug, Deserialize)] +#[derive(Debug, Deserialize, Serialize)] pub struct GlobalpayRefreshTokenErrorResponse { pub error_code: String, pub detailed_error_description: String, diff --git a/crates/router/src/connector/globepay.rs b/crates/router/src/connector/globepay.rs index 8f8b01de8ef..d480e35cfc0 100644 --- a/crates/router/src/connector/globepay.rs +++ b/crates/router/src/connector/globepay.rs @@ -18,6 +18,7 @@ use crate::{ configs::settings, consts, core::errors::{self, CustomResult}, + events::connector_api_logs::ConnectorEvent, headers, services::{self, request, ConnectorIntegration, ConnectorValidation}, types::{ @@ -114,12 +115,16 @@ impl ConnectorCommon for Globepay { fn build_error_response( &self, res: Response, + event_builder: Option<&mut ConnectorEvent>, ) -> CustomResult<ErrorResponse, errors::ConnectorError> { let response: globepay::GlobepayErrorResponse = res .response .parse_struct("GlobepayErrorResponse") .change_context(errors::ConnectorError::ResponseDeserializationFailed)?; + event_builder.map(|i| i.set_error_response_body(&response)); + router_env::logger::info!(connector_response=?response); + Ok(ErrorResponse { status_code: res.status_code, code: response.return_code.to_string(), @@ -237,12 +242,17 @@ impl ConnectorIntegration<api::Authorize, types::PaymentsAuthorizeData, types::P fn handle_response( &self, data: &types::PaymentsAuthorizeRouterData, + event_builder: Option<&mut ConnectorEvent>, res: Response, ) -> CustomResult<types::PaymentsAuthorizeRouterData, errors::ConnectorError> { let response: globepay::GlobepayPaymentsResponse = res .response .parse_struct("Globepay 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(), @@ -253,8 +263,9 @@ impl ConnectorIntegration<api::Authorize, types::PaymentsAuthorizeData, types::P fn get_error_response( &self, res: Response, + event_builder: Option<&mut ConnectorEvent>, ) -> CustomResult<ErrorResponse, errors::ConnectorError> { - self.build_error_response(res) + self.build_error_response(res, event_builder) } } @@ -305,12 +316,17 @@ impl ConnectorIntegration<api::PSync, types::PaymentsSyncData, types::PaymentsRe fn handle_response( &self, data: &types::PaymentsSyncRouterData, + event_builder: Option<&mut ConnectorEvent>, res: Response, ) -> CustomResult<types::PaymentsSyncRouterData, errors::ConnectorError> { let response: globepay::GlobepaySyncResponse = res .response .parse_struct("globepay 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(), @@ -321,8 +337,9 @@ impl ConnectorIntegration<api::PSync, types::PaymentsSyncData, types::PaymentsRe fn get_error_response( &self, res: Response, + event_builder: Option<&mut ConnectorEvent>, ) -> CustomResult<ErrorResponse, errors::ConnectorError> { - self.build_error_response(res) + self.build_error_response(res, event_builder) } } @@ -409,12 +426,17 @@ impl ConnectorIntegration<api::Execute, types::RefundsData, types::RefundsRespon 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: globepay::GlobepayRefundResponse = res .response .parse_struct("Globalpay 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(), @@ -425,8 +447,9 @@ impl ConnectorIntegration<api::Execute, types::RefundsData, types::RefundsRespon fn get_error_response( &self, res: Response, + event_builder: Option<&mut ConnectorEvent>, ) -> CustomResult<ErrorResponse, errors::ConnectorError> { - self.build_error_response(res) + self.build_error_response(res, event_builder) } } @@ -476,12 +499,17 @@ impl ConnectorIntegration<api::RSync, types::RefundsData, types::RefundsResponse fn handle_response( &self, data: &types::RefundSyncRouterData, + event_builder: Option<&mut ConnectorEvent>, res: Response, ) -> CustomResult<types::RefundSyncRouterData, errors::ConnectorError> { let response: globepay::GlobepayRefundResponse = res .response .parse_struct("Globalpay 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(), @@ -492,8 +520,9 @@ impl ConnectorIntegration<api::RSync, types::RefundsData, types::RefundsResponse fn get_error_response( &self, res: Response, + event_builder: Option<&mut ConnectorEvent>, ) -> CustomResult<ErrorResponse, errors::ConnectorError> { - self.build_error_response(res) + self.build_error_response(res, event_builder) } } diff --git a/crates/router/src/connector/globepay/transformers.rs b/crates/router/src/connector/globepay/transformers.rs index a874fc21d29..5cb22890b7c 100644 --- a/crates/router/src/connector/globepay/transformers.rs +++ b/crates/router/src/connector/globepay/transformers.rs @@ -102,7 +102,7 @@ impl TryFrom<&types::ConnectorAuthType> for GlobepayAuthType { } } -#[derive(Debug, Deserialize)] +#[derive(Debug, Deserialize, Serialize)] #[serde(rename_all = "SCREAMING_SNAKE_CASE")] pub enum GlobepayPaymentStatus { Success, @@ -123,7 +123,7 @@ pub struct GlobepayConnectorMetadata { image_data_url: url::Url, } -#[derive(Debug, Deserialize)] +#[derive(Debug, Deserialize, Serialize)] pub struct GlobepayPaymentsResponse { result_code: Option<GlobepayPaymentStatus>, order_id: Option<String>, @@ -132,7 +132,7 @@ pub struct GlobepayPaymentsResponse { return_msg: Option<String>, } -#[derive(Debug, Deserialize, PartialEq, strum::Display)] +#[derive(Debug, Deserialize, PartialEq, strum::Display, Serialize)] #[serde(rename_all = "SCREAMING_SNAKE_CASE")] pub enum GlobepayReturnCode { Success, @@ -210,7 +210,7 @@ impl<F, T> } } -#[derive(Debug, Deserialize)] +#[derive(Debug, Deserialize, Serialize)] pub struct GlobepaySyncResponse { pub result_code: Option<GlobepayPaymentPsyncStatus>, pub order_id: Option<String>, @@ -218,7 +218,7 @@ pub struct GlobepaySyncResponse { pub return_msg: Option<String>, } -#[derive(Debug, Deserialize)] +#[derive(Debug, Deserialize, Serialize)] #[serde(rename_all = "SCREAMING_SNAKE_CASE")] pub enum GlobepayPaymentPsyncStatus { Paying, @@ -313,7 +313,7 @@ impl<F> TryFrom<&types::RefundsRouterData<F>> for GlobepayRefundRequest { } } -#[derive(Debug, Deserialize)] +#[derive(Debug, Deserialize, Serialize)] pub enum GlobepayRefundStatus { Waiting, CreateFailed, @@ -335,7 +335,7 @@ impl From<GlobepayRefundStatus> for enums::RefundStatus { } } -#[derive(Debug, Deserialize)] +#[derive(Debug, Deserialize, Serialize)] pub struct GlobepayRefundResponse { pub result_code: Option<GlobepayRefundStatus>, pub refund_id: Option<String>, @@ -379,7 +379,7 @@ impl<T> TryFrom<types::RefundsResponseRouterData<T, GlobepayRefundResponse>> } } -#[derive(Debug, Deserialize)] +#[derive(Debug, Deserialize, Serialize)] pub struct GlobepayErrorResponse { pub return_msg: String, pub return_code: GlobepayReturnCode, diff --git a/crates/router/src/connector/gocardless.rs b/crates/router/src/connector/gocardless.rs index 542caa73ff3..720a13611c0 100644 --- a/crates/router/src/connector/gocardless.rs +++ b/crates/router/src/connector/gocardless.rs @@ -12,6 +12,7 @@ use crate::{ configs::settings, connector::utils as connector_utils, core::errors::{self, CustomResult}, + events::connector_api_logs::ConnectorEvent, headers, services::{ self, @@ -104,11 +105,16 @@ impl ConnectorCommon for Gocardless { fn build_error_response( &self, res: Response, + event_builder: Option<&mut ConnectorEvent>, ) -> CustomResult<ErrorResponse, errors::ConnectorError> { let response: gocardless::GocardlessErrorResponse = res .response .parse_struct("GocardlessErrorResponse") .change_context(errors::ConnectorError::ResponseDeserializationFailed)?; + + event_builder.map(|i| i.set_error_response_body(&response)); + router_env::logger::info!(connector_response=?response); + let error_iter = response.error.errors.iter(); let mut error_reason: Vec<String> = Vec::new(); for error in error_iter { @@ -185,6 +191,7 @@ impl fn handle_response( &self, data: &types::ConnectorCustomerRouterData, + event_builder: Option<&mut ConnectorEvent>, res: Response, ) -> CustomResult< types::RouterData< @@ -203,6 +210,10 @@ impl .response .parse_struct("GocardlessCustomerResponse") .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(), @@ -213,8 +224,9 @@ impl fn get_error_response( &self, res: Response, + event_builder: Option<&mut ConnectorEvent>, ) -> CustomResult<ErrorResponse, errors::ConnectorError> { - self.build_error_response(res) + self.build_error_response(res, event_builder) } } @@ -274,6 +286,7 @@ impl fn handle_response( &self, data: &types::TokenizationRouterData, + event_builder: Option<&mut ConnectorEvent>, res: Response, ) -> CustomResult<types::TokenizationRouterData, errors::ConnectorError> where @@ -285,6 +298,10 @@ impl .response .parse_struct("GocardlessBankAccountResponse") .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(), @@ -295,8 +312,9 @@ impl fn get_error_response( &self, res: Response, + event_builder: Option<&mut ConnectorEvent>, ) -> CustomResult<ErrorResponse, errors::ConnectorError> { - self.build_error_response(res) + self.build_error_response(res, event_builder) } } @@ -395,12 +413,17 @@ impl fn handle_response( &self, data: &types::SetupMandateRouterData, + event_builder: Option<&mut ConnectorEvent>, res: Response, ) -> CustomResult<types::SetupMandateRouterData, errors::ConnectorError> { let response: gocardless::GocardlessMandateResponse = res .response .parse_struct("GocardlessMandateResponse") .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(), @@ -411,8 +434,9 @@ impl fn get_error_response( &self, res: Response, + event_builder: Option<&mut ConnectorEvent>, ) -> CustomResult<ErrorResponse, errors::ConnectorError> { - self.build_error_response(res) + self.build_error_response(res, event_builder) } } @@ -480,12 +504,17 @@ impl ConnectorIntegration<api::Authorize, types::PaymentsAuthorizeData, types::P fn handle_response( &self, data: &types::PaymentsAuthorizeRouterData, + event_builder: Option<&mut ConnectorEvent>, res: Response, ) -> CustomResult<types::PaymentsAuthorizeRouterData, errors::ConnectorError> { let response: gocardless::GocardlessPaymentsResponse = res .response .parse_struct("GocardlessPaymentsResponse") .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(), @@ -496,8 +525,9 @@ impl ConnectorIntegration<api::Authorize, types::PaymentsAuthorizeData, types::P fn get_error_response( &self, res: Response, + event_builder: Option<&mut ConnectorEvent>, ) -> CustomResult<ErrorResponse, errors::ConnectorError> { - self.build_error_response(res) + self.build_error_response(res, event_builder) } } @@ -549,12 +579,17 @@ impl ConnectorIntegration<api::PSync, types::PaymentsSyncData, types::PaymentsRe fn handle_response( &self, data: &types::PaymentsSyncRouterData, + event_builder: Option<&mut ConnectorEvent>, res: Response, ) -> CustomResult<types::PaymentsSyncRouterData, errors::ConnectorError> { let response: gocardless::GocardlessPaymentsResponse = res .response .parse_struct("GocardlessPaymentsResponse") .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(), @@ -565,8 +600,9 @@ impl ConnectorIntegration<api::PSync, types::PaymentsSyncData, types::PaymentsRe fn get_error_response( &self, res: Response, + event_builder: Option<&mut ConnectorEvent>, ) -> CustomResult<ErrorResponse, errors::ConnectorError> { - self.build_error_response(res) + self.build_error_response(res, event_builder) } } @@ -640,12 +676,17 @@ impl ConnectorIntegration<api::Execute, types::RefundsData, types::RefundsRespon 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: gocardless::RefundResponse = res .response .parse_struct("gocardless 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(), @@ -656,8 +697,9 @@ impl ConnectorIntegration<api::Execute, types::RefundsData, types::RefundsRespon fn get_error_response( &self, res: Response, + event_builder: Option<&mut ConnectorEvent>, ) -> CustomResult<ErrorResponse, errors::ConnectorError> { - self.build_error_response(res) + self.build_error_response(res, event_builder) } } diff --git a/crates/router/src/connector/gocardless/transformers.rs b/crates/router/src/connector/gocardless/transformers.rs index 249dae370b1..d3703bc6bf8 100644 --- a/crates/router/src/connector/gocardless/transformers.rs +++ b/crates/router/src/connector/gocardless/transformers.rs @@ -172,12 +172,12 @@ fn get_region( } } -#[derive(Debug, Clone, Deserialize)] +#[derive(Debug, Clone, Deserialize, Serialize)] pub struct GocardlessCustomerResponse { customers: Customers, } -#[derive(Debug, Clone, Deserialize)] +#[derive(Debug, Clone, Deserialize, Serialize)] pub struct Customers { id: Secret<String>, } @@ -391,12 +391,12 @@ impl From<BankType> for AccountType { } } -#[derive(Debug, Clone, Deserialize)] +#[derive(Debug, Clone, Deserialize, Serialize)] pub struct GocardlessBankAccountResponse { customer_bank_accounts: CustomerBankAccountResponse, } -#[derive(Debug, Clone, Deserialize)] +#[derive(Debug, Clone, Deserialize, Serialize)] pub struct CustomerBankAccountResponse { pub id: Secret<String>, } @@ -540,12 +540,12 @@ impl TryFrom<&BankDebitData> for GocardlessScheme { } } -#[derive(Debug, Clone, Deserialize)] +#[derive(Debug, Clone, Deserialize, Serialize)] pub struct GocardlessMandateResponse { mandates: MandateResponse, } -#[derive(Debug, Clone, Deserialize)] +#[derive(Debug, Clone, Deserialize, Serialize)] pub struct MandateResponse { id: String, } @@ -817,7 +817,7 @@ impl<F> TryFrom<&GocardlessRouterData<&types::RefundsRouterData<F>>> for Gocardl } } -#[derive(Default, Debug, Clone, Deserialize)] +#[derive(Default, Debug, Clone, Deserialize, Serialize)] pub struct RefundResponse { id: String, } @@ -839,12 +839,12 @@ impl TryFrom<types::RefundsResponseRouterData<api::Execute, RefundResponse>> } } -#[derive(Clone, Debug, Deserialize)] +#[derive(Clone, Debug, Deserialize, Serialize)] pub struct GocardlessErrorResponse { pub error: GocardlessError, } -#[derive(Clone, Debug, Deserialize)] +#[derive(Clone, Debug, Deserialize, Serialize)] pub struct GocardlessError { pub message: String, pub code: u16, @@ -853,7 +853,7 @@ pub struct GocardlessError { pub error_type: String, } -#[derive(Clone, Debug, Deserialize)] +#[derive(Clone, Debug, Deserialize, Serialize)] pub struct Error { pub field: Option<String>, pub message: String, diff --git a/crates/router/src/connector/helcim.rs b/crates/router/src/connector/helcim.rs index 0b2cac5d766..5e03e5046ae 100644 --- a/crates/router/src/connector/helcim.rs +++ b/crates/router/src/connector/helcim.rs @@ -13,6 +13,7 @@ use crate::{ configs::settings, consts::NO_ERROR_CODE, core::errors::{self, CustomResult}, + events::connector_api_logs::ConnectorEvent, headers, services::{ self, @@ -123,11 +124,16 @@ impl ConnectorCommon for Helcim { fn build_error_response( &self, res: Response, + event_builder: Option<&mut ConnectorEvent>, ) -> CustomResult<ErrorResponse, errors::ConnectorError> { let response: helcim::HelcimErrorResponse = res .response .parse_struct("HelcimErrorResponse") .change_context(errors::ConnectorError::ResponseDeserializationFailed)?; + + event_builder.map(|i| i.set_error_response_body(&response)); + router_env::logger::info!(connector_response=?response); + let error_string = match response { transformers::HelcimErrorResponse::Payment(response) => match response.errors { transformers::HelcimErrorTypes::StringType(error) => error, @@ -229,12 +235,15 @@ impl fn handle_response( &self, data: &types::SetupMandateRouterData, + event_builder: Option<&mut ConnectorEvent>, res: Response, ) -> CustomResult<types::SetupMandateRouterData, errors::ConnectorError> { let response: helcim::HelcimPaymentsResponse = res .response .parse_struct("Helcim 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(), @@ -244,8 +253,9 @@ impl fn get_error_response( &self, res: Response, + event_builder: Option<&mut ConnectorEvent>, ) -> CustomResult<ErrorResponse, errors::ConnectorError> { - self.build_error_response(res) + self.build_error_response(res, event_builder) } } @@ -315,12 +325,17 @@ impl ConnectorIntegration<api::Authorize, types::PaymentsAuthorizeData, types::P fn handle_response( &self, data: &types::PaymentsAuthorizeRouterData, + event_builder: Option<&mut ConnectorEvent>, res: Response, ) -> CustomResult<types::PaymentsAuthorizeRouterData, errors::ConnectorError> { let response: helcim::HelcimPaymentsResponse = res .response .parse_struct("Helcim 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(), @@ -331,8 +346,9 @@ impl ConnectorIntegration<api::Authorize, types::PaymentsAuthorizeData, types::P fn get_error_response( &self, res: Response, + event_builder: Option<&mut ConnectorEvent>, ) -> CustomResult<ErrorResponse, errors::ConnectorError> { - self.build_error_response(res) + self.build_error_response(res, event_builder) } } @@ -394,12 +410,17 @@ impl ConnectorIntegration<api::PSync, types::PaymentsSyncData, types::PaymentsRe fn handle_response( &self, data: &types::PaymentsSyncRouterData, + event_builder: Option<&mut ConnectorEvent>, res: Response, ) -> CustomResult<types::PaymentsSyncRouterData, errors::ConnectorError> { let response: helcim::HelcimPaymentsResponse = res .response .parse_struct("helcim 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(), @@ -410,8 +431,9 @@ impl ConnectorIntegration<api::PSync, types::PaymentsSyncData, types::PaymentsRe fn get_error_response( &self, res: Response, + event_builder: Option<&mut ConnectorEvent>, ) -> CustomResult<ErrorResponse, errors::ConnectorError> { - self.build_error_response(res) + self.build_error_response(res, event_builder) } // fn get_multiple_capture_sync_method( @@ -482,12 +504,17 @@ impl ConnectorIntegration<api::Capture, types::PaymentsCaptureData, types::Payme fn handle_response( &self, data: &types::PaymentsCaptureRouterData, + event_builder: Option<&mut ConnectorEvent>, res: Response, ) -> CustomResult<types::PaymentsCaptureRouterData, errors::ConnectorError> { let response: helcim::HelcimPaymentsResponse = res .response .parse_struct("Helcim 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(), @@ -498,8 +525,9 @@ impl ConnectorIntegration<api::Capture, types::PaymentsCaptureData, types::Payme fn get_error_response( &self, res: Response, + event_builder: Option<&mut ConnectorEvent>, ) -> CustomResult<ErrorResponse, errors::ConnectorError> { - self.build_error_response(res) + self.build_error_response(res, event_builder) } } @@ -556,12 +584,17 @@ impl ConnectorIntegration<api::Void, types::PaymentsCancelData, types::PaymentsR fn handle_response( &self, data: &types::PaymentsCancelRouterData, + event_builder: Option<&mut ConnectorEvent>, res: Response, ) -> CustomResult<types::PaymentsCancelRouterData, errors::ConnectorError> { let response: helcim::HelcimPaymentsResponse = res .response .parse_struct("HelcimPaymentsResponse") .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(), @@ -573,8 +606,9 @@ impl ConnectorIntegration<api::Void, types::PaymentsCancelData, types::PaymentsR fn get_error_response( &self, res: Response, + event_builder: Option<&mut ConnectorEvent>, ) -> CustomResult<ErrorResponse, errors::ConnectorError> { - self.build_error_response(res) + self.build_error_response(res, event_builder) } } @@ -636,12 +670,17 @@ impl ConnectorIntegration<api::Execute, types::RefundsData, types::RefundsRespon 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: helcim::RefundResponse = res.response .parse_struct("helcim 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(), @@ -652,8 +691,9 @@ impl ConnectorIntegration<api::Execute, types::RefundsData, types::RefundsRespon fn get_error_response( &self, res: Response, + event_builder: Option<&mut ConnectorEvent>, ) -> CustomResult<ErrorResponse, errors::ConnectorError> { - self.build_error_response(res) + self.build_error_response(res, event_builder) } } @@ -713,12 +753,17 @@ impl ConnectorIntegration<api::RSync, types::RefundsData, types::RefundsResponse fn handle_response( &self, data: &types::RefundSyncRouterData, + event_builder: Option<&mut ConnectorEvent>, res: Response, ) -> CustomResult<types::RefundSyncRouterData, errors::ConnectorError> { let response: helcim::RefundResponse = res .response .parse_struct("helcim 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(), @@ -729,8 +774,9 @@ impl ConnectorIntegration<api::RSync, types::RefundsData, types::RefundsResponse fn get_error_response( &self, res: Response, + event_builder: Option<&mut ConnectorEvent>, ) -> CustomResult<ErrorResponse, errors::ConnectorError> { - self.build_error_response(res) + self.build_error_response(res, event_builder) } } diff --git a/crates/router/src/connector/helcim/transformers.rs b/crates/router/src/connector/helcim/transformers.rs index 5e076be651f..fba46bd721f 100644 --- a/crates/router/src/connector/helcim/transformers.rs +++ b/crates/router/src/connector/helcim/transformers.rs @@ -299,14 +299,14 @@ impl TryFrom<&types::ConnectorAuthType> for HelcimAuthType { } } // PaymentsResponse -#[derive(Debug, Deserialize)] +#[derive(Debug, Deserialize, Serialize)] #[serde(rename_all = "UPPERCASE")] pub enum HelcimPaymentStatus { Approved, Declined, } -#[derive(Debug, Deserialize)] +#[derive(Debug, Deserialize, Serialize)] #[serde(rename_all = "lowercase")] pub enum HelcimTransactionType { Purchase, @@ -339,7 +339,7 @@ impl From<HelcimPaymentsResponse> for enums::AttemptStatus { } } -#[derive(Debug, Deserialize)] +#[derive(Debug, Deserialize, Serialize)] #[serde(rename_all = "camelCase")] pub struct HelcimPaymentsResponse { status: HelcimPaymentStatus, @@ -689,12 +689,12 @@ impl<F> TryFrom<&HelcimRouterData<&types::RefundsRouterData<F>>> for HelcimRefun } } -#[derive(Debug, Deserialize)] +#[derive(Debug, Deserialize, Serialize)] #[serde(rename_all = "lowercase")] pub enum HelcimRefundTransactionType { Refund, } -#[derive(Debug, Deserialize)] +#[derive(Debug, Deserialize, Serialize)] #[serde(rename_all = "camelCase")] pub struct RefundResponse { status: HelcimPaymentStatus, @@ -748,19 +748,19 @@ impl TryFrom<types::RefundsResponseRouterData<api::RSync, RefundResponse>> } } -#[derive(Debug, strum::Display, Deserialize)] +#[derive(Debug, strum::Display, Deserialize, Serialize)] #[serde(untagged)] pub enum HelcimErrorTypes { StringType(String), JsonType(serde_json::Value), } -#[derive(Debug, Deserialize)] +#[derive(Debug, Deserialize, Serialize)] pub struct HelcimPaymentsErrorResponse { pub errors: HelcimErrorTypes, } -#[derive(Debug, Deserialize)] +#[derive(Debug, Deserialize, Serialize)] #[serde(untagged)] pub enum HelcimErrorResponse { Payment(HelcimPaymentsErrorResponse), diff --git a/crates/router/src/connector/iatapay.rs b/crates/router/src/connector/iatapay.rs index c5ac0f43833..c049520de28 100644 --- a/crates/router/src/connector/iatapay.rs +++ b/crates/router/src/connector/iatapay.rs @@ -14,6 +14,7 @@ use crate::{ configs::settings, consts, core::errors::{self, CustomResult}, + events::connector_api_logs::ConnectorEvent, headers, services::{ self, @@ -113,12 +114,16 @@ impl ConnectorCommon for Iatapay { fn build_error_response( &self, res: Response, + event_builder: Option<&mut ConnectorEvent>, ) -> CustomResult<ErrorResponse, errors::ConnectorError> { let response: iatapay::IatapayErrorResponse = res .response .parse_struct("IatapayErrorResponse") .change_context(errors::ConnectorError::ResponseDeserializationFailed)?; + event_builder.map(|i| i.set_error_response_body(&response)); + router_env::logger::info!(connector_response=?response); + Ok(ErrorResponse { status_code: res.status_code, code: response.error, @@ -207,6 +212,7 @@ impl ConnectorIntegration<api::AccessTokenAuth, types::AccessTokenRequestData, t fn handle_response( &self, data: &types::RefreshTokenRouterData, + event_builder: Option<&mut ConnectorEvent>, res: Response, ) -> CustomResult<types::RefreshTokenRouterData, errors::ConnectorError> { let response: iatapay::IatapayAuthUpdateResponse = res @@ -214,6 +220,9 @@ impl ConnectorIntegration<api::AccessTokenAuth, types::AccessTokenRequestData, t .parse_struct("iatapay IatapayAuthUpdateResponse") .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(), @@ -224,12 +233,16 @@ impl ConnectorIntegration<api::AccessTokenAuth, types::AccessTokenRequestData, t fn get_error_response( &self, res: Response, + event_builder: Option<&mut ConnectorEvent>, ) -> CustomResult<ErrorResponse, errors::ConnectorError> { let response: iatapay::IatapayAccessTokenErrorResponse = res .response .parse_struct("Iatapay AccessTokenErrorResponse") .change_context(errors::ConnectorError::ResponseDeserializationFailed)?; + event_builder.map(|i| i.set_error_response_body(&response)); + router_env::logger::info!(connector_response=?response); + Ok(ErrorResponse { status_code: res.status_code, code: response.error, @@ -327,12 +340,15 @@ impl ConnectorIntegration<api::Authorize, types::PaymentsAuthorizeData, types::P fn handle_response( &self, data: &types::PaymentsAuthorizeRouterData, + event_builder: Option<&mut ConnectorEvent>, res: Response, ) -> CustomResult<types::PaymentsAuthorizeRouterData, errors::ConnectorError> { let response: IatapayPaymentsResponse = res .response .parse_struct("Iatapay 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(), @@ -344,8 +360,9 @@ impl ConnectorIntegration<api::Authorize, types::PaymentsAuthorizeData, types::P fn get_error_response( &self, res: Response, + event_builder: Option<&mut ConnectorEvent>, ) -> CustomResult<ErrorResponse, errors::ConnectorError> { - self.build_error_response(res) + self.build_error_response(res, event_builder) } } @@ -397,12 +414,15 @@ impl ConnectorIntegration<api::PSync, types::PaymentsSyncData, types::PaymentsRe fn handle_response( &self, data: &types::PaymentsSyncRouterData, + event_builder: Option<&mut ConnectorEvent>, res: Response, ) -> CustomResult<types::PaymentsSyncRouterData, errors::ConnectorError> { let response: IatapayPaymentsResponse = res .response .parse_struct("iatapay 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(), @@ -414,8 +434,9 @@ impl ConnectorIntegration<api::PSync, types::PaymentsSyncData, types::PaymentsRe fn get_error_response( &self, res: Response, + event_builder: Option<&mut ConnectorEvent>, ) -> CustomResult<ErrorResponse, errors::ConnectorError> { - self.build_error_response(res) + self.build_error_response(res, event_builder) } } @@ -506,12 +527,15 @@ impl ConnectorIntegration<api::Execute, types::RefundsData, types::RefundsRespon 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: iatapay::RefundResponse = res .response .parse_struct("iatapay 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(), @@ -523,8 +547,9 @@ impl ConnectorIntegration<api::Execute, types::RefundsData, types::RefundsRespon fn get_error_response( &self, res: Response, + event_builder: Option<&mut ConnectorEvent>, ) -> CustomResult<ErrorResponse, errors::ConnectorError> { - self.build_error_response(res) + self.build_error_response(res, event_builder) } } @@ -575,12 +600,15 @@ impl ConnectorIntegration<api::RSync, types::RefundsData, types::RefundsResponse fn handle_response( &self, data: &types::RefundSyncRouterData, + event_builder: Option<&mut ConnectorEvent>, res: Response, ) -> CustomResult<types::RefundSyncRouterData, errors::ConnectorError> { let response: iatapay::RefundResponse = res .response .parse_struct("iatapay 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(), @@ -592,8 +620,9 @@ impl ConnectorIntegration<api::RSync, types::RefundsData, types::RefundsResponse fn get_error_response( &self, res: Response, + event_builder: Option<&mut ConnectorEvent>, ) -> CustomResult<ErrorResponse, errors::ConnectorError> { - self.build_error_response(res) + self.build_error_response(res, event_builder) } } diff --git a/crates/router/src/connector/iatapay/transformers.rs b/crates/router/src/connector/iatapay/transformers.rs index 4557fda0390..55778af882b 100644 --- a/crates/router/src/connector/iatapay/transformers.rs +++ b/crates/router/src/connector/iatapay/transformers.rs @@ -60,7 +60,7 @@ impl<T> }) } } -#[derive(Debug, Deserialize)] +#[derive(Debug, Deserialize, Serialize)] pub struct IatapayAuthUpdateResponse { pub access_token: Secret<String>, pub token_type: String, @@ -507,7 +507,7 @@ impl TryFrom<types::RefundsResponseRouterData<api::RSync, RefundResponse>> } } -#[derive(Debug, Deserialize)] +#[derive(Debug, Deserialize, Serialize)] pub struct IatapayErrorResponse { pub status: u16, pub error: String, @@ -515,7 +515,7 @@ pub struct IatapayErrorResponse { pub reason: Option<String>, } -#[derive(Deserialize, Debug)] +#[derive(Deserialize, Debug, Serialize)] pub struct IatapayAccessTokenErrorResponse { pub error: String, pub path: String, diff --git a/crates/router/src/connector/klarna.rs b/crates/router/src/connector/klarna.rs index 5361a636826..8b7ab0da7f2 100644 --- a/crates/router/src/connector/klarna.rs +++ b/crates/router/src/connector/klarna.rs @@ -11,6 +11,7 @@ use crate::{ connector::utils as connector_utils, consts, core::errors::{self, CustomResult}, + events::connector_api_logs::ConnectorEvent, headers, services::{ self, @@ -61,11 +62,16 @@ impl ConnectorCommon for Klarna { fn build_error_response( &self, res: types::Response, + event_builder: Option<&mut ConnectorEvent>, ) -> CustomResult<types::ErrorResponse, errors::ConnectorError> { let response: klarna::KlarnaErrorResponse = res .response .parse_struct("KlarnaErrorResponse") .change_context(errors::ConnectorError::ResponseDeserializationFailed)?; + + event_builder.map(|i| i.set_error_response_body(&response)); + router_env::logger::info!(connector_response=?response); + // KlarnaErrorResponse will either have error_messages or error_message field Ref: https://docs.klarna.com/api/errors/ let reason = response .error_messages @@ -186,12 +192,17 @@ impl fn handle_response( &self, data: &types::PaymentsSessionRouterData, + event_builder: Option<&mut ConnectorEvent>, res: types::Response, ) -> CustomResult<types::PaymentsSessionRouterData, errors::ConnectorError> { let response: klarna::KlarnaSessionResponse = res .response .parse_struct("KlarnaSessionResponse") .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(), @@ -203,8 +214,9 @@ impl fn get_error_response( &self, res: types::Response, + event_builder: Option<&mut ConnectorEvent>, ) -> CustomResult<types::ErrorResponse, errors::ConnectorError> { - self.build_error_response(res) + self.build_error_response(res, event_builder) } } @@ -463,12 +475,17 @@ impl fn handle_response( &self, data: &types::PaymentsAuthorizeRouterData, + event_builder: Option<&mut ConnectorEvent>, res: types::Response, ) -> CustomResult<types::PaymentsAuthorizeRouterData, errors::ConnectorError> { let response: klarna::KlarnaPaymentsResponse = res .response .parse_struct("KlarnaPaymentsResponse") .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(), @@ -480,8 +497,9 @@ impl fn get_error_response( &self, res: types::Response, + event_builder: Option<&mut ConnectorEvent>, ) -> CustomResult<types::ErrorResponse, errors::ConnectorError> { - self.build_error_response(res) + self.build_error_response(res, event_builder) } } diff --git a/crates/router/src/connector/klarna/transformers.rs b/crates/router/src/connector/klarna/transformers.rs index 0816dd82ec6..c12f8ed1b10 100644 --- a/crates/router/src/connector/klarna/transformers.rs +++ b/crates/router/src/connector/klarna/transformers.rs @@ -48,7 +48,7 @@ pub struct KlarnaPaymentsRequest { merchant_reference1: String, } -#[derive(Default, Debug, Deserialize)] +#[derive(Default, Debug, Deserialize, Serialize)] pub struct KlarnaPaymentsResponse { order_id: String, fraud_status: KlarnaFraudStatus, @@ -64,7 +64,7 @@ pub struct KlarnaSessionRequest { order_lines: Vec<OrderLines>, } -#[derive(Deserialize)] +#[derive(Deserialize, Serialize, Debug)] pub struct KlarnaSessionResponse { pub client_token: String, pub session_id: String, @@ -225,7 +225,7 @@ impl From<KlarnaFraudStatus> for enums::AttemptStatus { } } -#[derive(Deserialize)] +#[derive(Deserialize, Serialize, Debug)] pub struct KlarnaErrorResponse { pub error_code: String, pub error_messages: Option<Vec<String>>, diff --git a/crates/router/src/connector/mollie.rs b/crates/router/src/connector/mollie.rs index cee4225d861..e6bbd688376 100644 --- a/crates/router/src/connector/mollie.rs +++ b/crates/router/src/connector/mollie.rs @@ -14,6 +14,7 @@ use crate::{ errors::{self, CustomResult}, payments, }, + events::connector_api_logs::ConnectorEvent, headers, services::{ self, @@ -87,11 +88,16 @@ impl ConnectorCommon for Mollie { fn build_error_response( &self, res: Response, + event_builder: Option<&mut ConnectorEvent>, ) -> CustomResult<ErrorResponse, errors::ConnectorError> { let response: mollie::ErrorResponse = res .response .parse_struct("MollieErrorResponse") .change_context(errors::ConnectorError::ResponseDeserializationFailed)?; + + event_builder.map(|i| i.set_error_response_body(&response)); + router_env::logger::info!(connector_response=?response); + Ok(ErrorResponse { status_code: response.status, code: response @@ -178,6 +184,7 @@ impl fn handle_response( &self, data: &types::TokenizationRouterData, + event_builder: Option<&mut ConnectorEvent>, res: Response, ) -> CustomResult<types::TokenizationRouterData, errors::ConnectorError> where @@ -187,6 +194,10 @@ impl .response .parse_struct("MollieTokenResponse") .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(), @@ -197,8 +208,9 @@ impl fn get_error_response( &self, res: Response, + event_builder: Option<&mut ConnectorEvent>, ) -> CustomResult<ErrorResponse, errors::ConnectorError> { - self.build_error_response(res) + self.build_error_response(res, event_builder) } } @@ -284,12 +296,17 @@ impl ConnectorIntegration<api::Authorize, types::PaymentsAuthorizeData, types::P fn handle_response( &self, data: &types::PaymentsAuthorizeRouterData, + event_builder: Option<&mut ConnectorEvent>, res: Response, ) -> CustomResult<types::PaymentsAuthorizeRouterData, errors::ConnectorError> { let response: mollie::MolliePaymentsResponse = res .response .parse_struct("MolliePaymentsResponse") .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(), @@ -300,8 +317,9 @@ impl ConnectorIntegration<api::Authorize, types::PaymentsAuthorizeData, types::P fn get_error_response( &self, res: Response, + event_builder: Option<&mut ConnectorEvent>, ) -> CustomResult<ErrorResponse, errors::ConnectorError> { - self.build_error_response(res) + self.build_error_response(res, event_builder) } } @@ -358,12 +376,17 @@ impl ConnectorIntegration<api::PSync, types::PaymentsSyncData, types::PaymentsRe fn handle_response( &self, data: &types::PaymentsSyncRouterData, + event_builder: Option<&mut ConnectorEvent>, res: Response, ) -> CustomResult<types::PaymentsSyncRouterData, errors::ConnectorError> { let response: mollie::MolliePaymentsResponse = res .response .parse_struct("mollie 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(), @@ -374,8 +397,9 @@ impl ConnectorIntegration<api::PSync, types::PaymentsSyncData, types::PaymentsRe fn get_error_response( &self, res: Response, + event_builder: Option<&mut ConnectorEvent>, ) -> CustomResult<ErrorResponse, errors::ConnectorError> { - self.build_error_response(res) + self.build_error_response(res, event_builder) } } @@ -473,12 +497,17 @@ impl ConnectorIntegration<api::Execute, types::RefundsData, types::RefundsRespon 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: mollie::RefundResponse = res .response .parse_struct("MollieRefundResponse") .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 { response, data: data.clone(), @@ -489,8 +518,9 @@ impl ConnectorIntegration<api::Execute, types::RefundsData, types::RefundsRespon fn get_error_response( &self, res: Response, + event_builder: Option<&mut ConnectorEvent>, ) -> CustomResult<ErrorResponse, errors::ConnectorError> { - self.build_error_response(res) + self.build_error_response(res, event_builder) } } @@ -543,12 +573,17 @@ impl ConnectorIntegration<api::RSync, types::RefundsData, types::RefundsResponse fn handle_response( &self, data: &types::RefundSyncRouterData, + event_builder: Option<&mut ConnectorEvent>, res: Response, ) -> CustomResult<types::RefundSyncRouterData, errors::ConnectorError> { let response: mollie::RefundResponse = res .response .parse_struct("MollieRefundSyncResponse") .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(), @@ -559,8 +594,9 @@ impl ConnectorIntegration<api::RSync, types::RefundsData, types::RefundsResponse fn get_error_response( &self, res: Response, + event_builder: Option<&mut ConnectorEvent>, ) -> CustomResult<ErrorResponse, errors::ConnectorError> { - self.build_error_response(res) + self.build_error_response(res, event_builder) } } diff --git a/crates/router/src/connector/mollie/transformers.rs b/crates/router/src/connector/mollie/transformers.rs index 0fcb14d2cf5..af1159cd2c3 100644 --- a/crates/router/src/connector/mollie/transformers.rs +++ b/crates/router/src/connector/mollie/transformers.rs @@ -388,7 +388,7 @@ fn get_address_details( Ok(address_details) } -#[derive(Debug, Deserialize)] +#[derive(Debug, Deserialize, Serialize)] #[serde(rename_all = "camelCase")] pub struct MolliePaymentsResponse { pub resource: String, @@ -625,7 +625,7 @@ impl<T> TryFrom<types::RefundsResponseRouterData<T, RefundResponse>> } } -#[derive(Debug, Deserialize)] +#[derive(Debug, Deserialize, Serialize)] pub struct ErrorResponse { pub status: u16, pub title: Option<String>, diff --git a/crates/router/src/connector/multisafepay.rs b/crates/router/src/connector/multisafepay.rs index 8290a00661c..da3a87454ce 100644 --- a/crates/router/src/connector/multisafepay.rs +++ b/crates/router/src/connector/multisafepay.rs @@ -10,6 +10,7 @@ use transformers as multisafepay; use crate::{ configs::settings, core::errors::{self, CustomResult}, + events::connector_api_logs::ConnectorEvent, headers, services::{ self, @@ -74,11 +75,16 @@ impl ConnectorCommon for Multisafepay { fn build_error_response( &self, res: Response, + event_builder: Option<&mut ConnectorEvent>, ) -> CustomResult<ErrorResponse, errors::ConnectorError> { let response: multisafepay::MultisafepayErrorResponse = res .response .parse_struct("MultisafepayErrorResponse") .change_context(errors::ConnectorError::ResponseDeserializationFailed)?; + + event_builder.map(|i| i.set_error_response_body(&response)); + router_env::logger::info!(connector_response=?response); + Ok(ErrorResponse { status_code: res.status_code, code: response.error_code.to_string(), @@ -208,13 +214,15 @@ impl ConnectorIntegration<api::PSync, types::PaymentsSyncData, types::PaymentsRe fn get_error_response( &self, res: Response, + event_builder: Option<&mut ConnectorEvent>, ) -> CustomResult<ErrorResponse, errors::ConnectorError> { - self.build_error_response(res) + self.build_error_response(res, event_builder) } fn handle_response( &self, data: &types::PaymentsSyncRouterData, + event_builder: Option<&mut ConnectorEvent>, res: Response, ) -> CustomResult<types::PaymentsSyncRouterData, errors::ConnectorError> { let response: multisafepay::MultisafepayAuthResponse = res @@ -222,6 +230,9 @@ impl ConnectorIntegration<api::PSync, types::PaymentsSyncData, types::PaymentsRe .parse_struct("multisafepay PaymentsResponse") .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(), @@ -316,6 +327,7 @@ impl ConnectorIntegration<api::Authorize, types::PaymentsAuthorizeData, types::P fn handle_response( &self, data: &types::PaymentsAuthorizeRouterData, + event_builder: Option<&mut ConnectorEvent>, res: Response, ) -> CustomResult<types::PaymentsAuthorizeRouterData, errors::ConnectorError> { let response: multisafepay::MultisafepayAuthResponse = res @@ -323,6 +335,9 @@ impl ConnectorIntegration<api::Authorize, types::PaymentsAuthorizeData, types::P .parse_struct("MultisafepayPaymentsResponse") .change_context(errors::ConnectorError::ResponseDeserializationFailed)?; + event_builder.map(|i| i.set_response_body(&response)); + router_env::logger::info!(connector_response=?response); + types::ResponseRouterData { response, data: data.clone(), @@ -335,8 +350,9 @@ impl ConnectorIntegration<api::Authorize, types::PaymentsAuthorizeData, types::P fn get_error_response( &self, res: Response, + event_builder: Option<&mut ConnectorEvent>, ) -> CustomResult<ErrorResponse, errors::ConnectorError> { - self.build_error_response(res) + self.build_error_response(res, event_builder) } } @@ -413,12 +429,15 @@ impl ConnectorIntegration<api::Execute, types::RefundsData, types::RefundsRespon 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: multisafepay::MultisafepayRefundResponse = res .response .parse_struct("multisafepay RefundResponse") .change_context(errors::ConnectorError::ResponseDeserializationFailed)?; + event_builder.map(|i| i.set_response_body(&response)); + router_env::logger::info!(connector_response=?response); types::ResponseRouterData { response, data: data.clone(), @@ -431,8 +450,9 @@ impl ConnectorIntegration<api::Execute, types::RefundsData, types::RefundsRespon fn get_error_response( &self, res: Response, + event_builder: Option<&mut ConnectorEvent>, ) -> CustomResult<ErrorResponse, errors::ConnectorError> { - self.build_error_response(res) + self.build_error_response(res, event_builder) } } @@ -485,12 +505,15 @@ impl ConnectorIntegration<api::RSync, types::RefundsData, types::RefundsResponse fn handle_response( &self, data: &types::RefundSyncRouterData, + event_builder: Option<&mut ConnectorEvent>, res: Response, ) -> CustomResult<types::RefundSyncRouterData, errors::ConnectorError> { let response: multisafepay::MultisafepayRefundResponse = res .response .parse_struct("multisafepay RefundResponse") .change_context(errors::ConnectorError::ResponseDeserializationFailed)?; + event_builder.map(|i| i.set_response_body(&response)); + router_env::logger::info!(connector_response=?response); types::ResponseRouterData { response, data: data.clone(), @@ -503,8 +526,9 @@ impl ConnectorIntegration<api::RSync, types::RefundsData, types::RefundsResponse fn get_error_response( &self, res: Response, + event_builder: Option<&mut ConnectorEvent>, ) -> CustomResult<ErrorResponse, errors::ConnectorError> { - self.build_error_response(res) + self.build_error_response(res, event_builder) } } diff --git a/crates/router/src/connector/nexinets.rs b/crates/router/src/connector/nexinets.rs index 1f4a7f41f66..4457a0986f6 100644 --- a/crates/router/src/connector/nexinets.rs +++ b/crates/router/src/connector/nexinets.rs @@ -13,6 +13,7 @@ use crate::{ utils::{to_connector_meta, PaymentsSyncRequestData}, }, core::errors::{self, CustomResult}, + events::connector_api_logs::ConnectorEvent, headers, services::{ self, @@ -100,12 +101,16 @@ impl ConnectorCommon for Nexinets { fn build_error_response( &self, res: Response, + event_builder: Option<&mut ConnectorEvent>, ) -> CustomResult<ErrorResponse, errors::ConnectorError> { let response: nexinets::NexinetsErrorResponse = res .response .parse_struct("NexinetsErrorResponse") .change_context(errors::ConnectorError::ResponseDeserializationFailed)?; + event_builder.map(|i| i.set_error_response_body(&response)); + router_env::logger::info!(connector_response=?response); + let errors = response.errors; let mut message = String::new(); let mut static_message = String::new(); @@ -247,12 +252,17 @@ impl ConnectorIntegration<api::Authorize, types::PaymentsAuthorizeData, types::P fn handle_response( &self, data: &types::PaymentsAuthorizeRouterData, + event_builder: Option<&mut ConnectorEvent>, res: Response, ) -> CustomResult<types::PaymentsAuthorizeRouterData, errors::ConnectorError> { let response: nexinets::NexinetsPreAuthOrDebitResponse = res .response .parse_struct("Nexinets 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(), @@ -263,8 +273,9 @@ impl ConnectorIntegration<api::Authorize, types::PaymentsAuthorizeData, types::P fn get_error_response( &self, res: Response, + event_builder: Option<&mut ConnectorEvent>, ) -> CustomResult<ErrorResponse, errors::ConnectorError> { - self.build_error_response(res) + self.build_error_response(res, event_builder) } } @@ -322,12 +333,17 @@ impl ConnectorIntegration<api::PSync, types::PaymentsSyncData, types::PaymentsRe fn handle_response( &self, data: &types::PaymentsSyncRouterData, + event_builder: Option<&mut ConnectorEvent>, res: Response, ) -> CustomResult<types::PaymentsSyncRouterData, errors::ConnectorError> { let response: nexinets::NexinetsPaymentResponse = res .response .parse_struct("nexinets NexinetsPaymentResponse") .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(), @@ -338,8 +354,9 @@ impl ConnectorIntegration<api::PSync, types::PaymentsSyncData, types::PaymentsRe fn get_error_response( &self, res: Response, + event_builder: Option<&mut ConnectorEvent>, ) -> CustomResult<ErrorResponse, errors::ConnectorError> { - self.build_error_response(res) + self.build_error_response(res, event_builder) } } @@ -405,12 +422,17 @@ impl ConnectorIntegration<api::Capture, types::PaymentsCaptureData, types::Payme fn handle_response( &self, data: &types::PaymentsCaptureRouterData, + event_builder: Option<&mut ConnectorEvent>, res: Response, ) -> CustomResult<types::PaymentsCaptureRouterData, errors::ConnectorError> { let response: nexinets::NexinetsPaymentResponse = res .response .parse_struct("NexinetsPaymentResponse") .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(), @@ -421,8 +443,9 @@ impl ConnectorIntegration<api::Capture, types::PaymentsCaptureData, types::Payme fn get_error_response( &self, res: Response, + event_builder: Option<&mut ConnectorEvent>, ) -> CustomResult<ErrorResponse, errors::ConnectorError> { - self.build_error_response(res) + self.build_error_response(res, event_builder) } } @@ -485,12 +508,17 @@ impl ConnectorIntegration<api::Void, types::PaymentsCancelData, types::PaymentsR fn handle_response( &self, data: &types::PaymentsCancelRouterData, + event_builder: Option<&mut ConnectorEvent>, res: Response, ) -> CustomResult<types::PaymentsCancelRouterData, errors::ConnectorError> { let response: nexinets::NexinetsPaymentResponse = res .response .parse_struct("NexinetsPaymentResponse") .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(), @@ -501,8 +529,9 @@ impl ConnectorIntegration<api::Void, types::PaymentsCancelData, types::PaymentsR fn get_error_response( &self, res: Response, + event_builder: Option<&mut ConnectorEvent>, ) -> CustomResult<ErrorResponse, errors::ConnectorError> { - self.build_error_response(res) + self.build_error_response(res, event_builder) } } @@ -567,12 +596,17 @@ impl ConnectorIntegration<api::Execute, types::RefundsData, types::RefundsRespon 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: nexinets::NexinetsRefundResponse = res .response .parse_struct("nexinets 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(), @@ -583,8 +617,9 @@ impl ConnectorIntegration<api::Execute, types::RefundsData, types::RefundsRespon fn get_error_response( &self, res: Response, + event_builder: Option<&mut ConnectorEvent>, ) -> CustomResult<ErrorResponse, errors::ConnectorError> { - self.build_error_response(res) + self.build_error_response(res, event_builder) } } @@ -638,12 +673,17 @@ impl ConnectorIntegration<api::RSync, types::RefundsData, types::RefundsResponse fn handle_response( &self, data: &types::RefundSyncRouterData, + event_builder: Option<&mut ConnectorEvent>, res: Response, ) -> CustomResult<types::RefundSyncRouterData, errors::ConnectorError> { let response: nexinets::NexinetsRefundResponse = res .response .parse_struct("nexinets 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(), @@ -654,8 +694,9 @@ impl ConnectorIntegration<api::RSync, types::RefundsData, types::RefundsResponse fn get_error_response( &self, res: Response, + event_builder: Option<&mut ConnectorEvent>, ) -> CustomResult<ErrorResponse, errors::ConnectorError> { - self.build_error_response(res) + self.build_error_response(res, event_builder) } } diff --git a/crates/router/src/connector/nexinets/transformers.rs b/crates/router/src/connector/nexinets/transformers.rs index 698b2709a62..07488271aea 100644 --- a/crates/router/src/connector/nexinets/transformers.rs +++ b/crates/router/src/connector/nexinets/transformers.rs @@ -211,7 +211,7 @@ impl TryFrom<&types::ConnectorAuthType> for NexinetsAuthType { } } // PaymentsResponse -#[derive(Debug, Deserialize, Clone)] +#[derive(Debug, Deserialize, Clone, Serialize)] #[serde(rename_all = "SCREAMING_SNAKE_CASE")] pub enum NexinetsPaymentStatus { Success, @@ -275,7 +275,7 @@ impl TryFrom<&api_models::enums::BankNames> for NexinetsBIC { } } -#[derive(Debug, Deserialize)] +#[derive(Debug, Deserialize, Serialize)] #[serde(rename_all = "camelCase")] pub struct NexinetsPreAuthOrDebitResponse { order_id: String, @@ -285,7 +285,7 @@ pub struct NexinetsPreAuthOrDebitResponse { redirect_url: Option<Url>, } -#[derive(Debug, Deserialize)] +#[derive(Debug, Deserialize, Serialize)] #[serde(rename_all = "camelCase")] pub struct NexinetsTransaction { pub transaction_id: String, @@ -386,7 +386,7 @@ pub struct NexinetsCaptureOrVoidRequest { pub currency: enums::Currency, } -#[derive(Debug, Deserialize)] +#[derive(Debug, Deserialize, Serialize)] #[serde(rename_all = "camelCase")] pub struct NexinetsOrder { pub order_id: String, @@ -412,7 +412,7 @@ impl TryFrom<&types::PaymentsCancelRouterData> for NexinetsCaptureOrVoidRequest } } -#[derive(Debug, Deserialize)] +#[derive(Debug, Deserialize, Serialize)] #[serde(rename_all = "camelCase")] pub struct NexinetsPaymentResponse { pub transaction_id: String, @@ -483,7 +483,7 @@ impl<F> TryFrom<&types::RefundsRouterData<F>> for NexinetsRefundRequest { } // Type definition for Refund Response -#[derive(Debug, Deserialize)] +#[derive(Debug, Deserialize, Serialize)] #[serde(rename_all = "camelCase")] pub struct NexinetsRefundResponse { pub transaction_id: String, @@ -494,7 +494,7 @@ pub struct NexinetsRefundResponse { } #[allow(dead_code)] -#[derive(Debug, Deserialize)] +#[derive(Debug, Deserialize, Serialize)] #[serde(rename_all = "SCREAMING_SNAKE_CASE")] pub enum RefundStatus { Success, @@ -504,7 +504,7 @@ pub enum RefundStatus { InProgress, } -#[derive(Debug, Deserialize)] +#[derive(Debug, Deserialize, Serialize)] #[serde(rename_all = "SCREAMING_SNAKE_CASE")] pub enum RefundType { Refund, @@ -554,7 +554,7 @@ impl TryFrom<types::RefundsResponseRouterData<api::RSync, NexinetsRefundResponse } } -#[derive(Debug, Deserialize)] +#[derive(Debug, Deserialize, Serialize)] pub struct NexinetsErrorResponse { pub status: u16, pub code: u16, @@ -562,7 +562,7 @@ pub struct NexinetsErrorResponse { pub errors: Vec<OrderErrorDetails>, } -#[derive(Debug, Deserialize, Clone)] +#[derive(Debug, Deserialize, Clone, Serialize)] pub struct OrderErrorDetails { pub code: u16, pub message: String, diff --git a/crates/router/src/connector/nmi.rs b/crates/router/src/connector/nmi.rs index 0550908649f..a7c920a5f93 100644 --- a/crates/router/src/connector/nmi.rs +++ b/crates/router/src/connector/nmi.rs @@ -12,6 +12,7 @@ use super::utils as connector_utils; use crate::{ configs::settings, core::errors::{self, CustomResult}, + events::connector_api_logs::ConnectorEvent, services::{self, request, ConnectorIntegration, ConnectorValidation}, types::{ self, @@ -69,11 +70,16 @@ impl ConnectorCommon for Nmi { fn build_error_response( &self, res: types::Response, + event_builder: Option<&mut ConnectorEvent>, ) -> CustomResult<ErrorResponse, errors::ConnectorError> { let response: nmi::StandardResponse = res .response .parse_struct("StandardResponse") .change_context(errors::ConnectorError::ResponseDeserializationFailed)?; + + event_builder.map(|i| i.set_error_response_body(&response)); + router_env::logger::info!(connector_response=?response); + Ok(ErrorResponse { message: response.responsetext.to_owned(), status_code: res.status_code, @@ -181,11 +187,14 @@ impl fn handle_response( &self, data: &types::SetupMandateRouterData, + event_builder: Option<&mut ConnectorEvent>, res: types::Response, ) -> CustomResult<types::SetupMandateRouterData, errors::ConnectorError> { let response: nmi::StandardResponse = serde_urlencoded::from_bytes(&res.response) .into_report() .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(), @@ -196,8 +205,9 @@ impl fn get_error_response( &self, res: types::Response, + event_builder: Option<&mut ConnectorEvent>, ) -> CustomResult<ErrorResponse, errors::ConnectorError> { - self.build_error_response(res) + self.build_error_response(res, event_builder) } } @@ -265,11 +275,14 @@ impl fn handle_response( &self, data: &types::PaymentsPreProcessingRouterData, + event_builder: Option<&mut ConnectorEvent>, res: types::Response, ) -> CustomResult<types::PaymentsPreProcessingRouterData, errors::ConnectorError> { let response: nmi::NmiVaultResponse = serde_urlencoded::from_bytes(&res.response) .into_report() .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(), @@ -280,8 +293,9 @@ impl fn get_error_response( &self, res: types::Response, + event_builder: Option<&mut ConnectorEvent>, ) -> CustomResult<ErrorResponse, errors::ConnectorError> { - self.build_error_response(res) + self.build_error_response(res, event_builder) } } @@ -343,11 +357,14 @@ impl ConnectorIntegration<api::Authorize, types::PaymentsAuthorizeData, types::P fn handle_response( &self, data: &types::PaymentsAuthorizeRouterData, + event_builder: Option<&mut ConnectorEvent>, res: types::Response, ) -> CustomResult<types::PaymentsAuthorizeRouterData, errors::ConnectorError> { let response: nmi::StandardResponse = serde_urlencoded::from_bytes(&res.response) .into_report() .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(), @@ -358,8 +375,9 @@ impl ConnectorIntegration<api::Authorize, types::PaymentsAuthorizeData, types::P fn get_error_response( &self, res: types::Response, + event_builder: Option<&mut ConnectorEvent>, ) -> CustomResult<ErrorResponse, errors::ConnectorError> { - self.build_error_response(res) + self.build_error_response(res, event_builder) } } @@ -428,11 +446,14 @@ impl fn handle_response( &self, data: &types::PaymentsCompleteAuthorizeRouterData, + event_builder: Option<&mut ConnectorEvent>, res: types::Response, ) -> CustomResult<types::PaymentsCompleteAuthorizeRouterData, errors::ConnectorError> { let response: nmi::NmiCompleteResponse = serde_urlencoded::from_bytes(&res.response) .into_report() .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(), @@ -443,8 +464,9 @@ impl fn get_error_response( &self, res: types::Response, + event_builder: Option<&mut ConnectorEvent>, ) -> CustomResult<ErrorResponse, errors::ConnectorError> { - self.build_error_response(res) + self.build_error_response(res, event_builder) } } @@ -496,10 +518,15 @@ impl ConnectorIntegration<api::PSync, types::PaymentsSyncData, types::PaymentsRe fn handle_response( &self, data: &types::PaymentsSyncRouterData, + event_builder: Option<&mut ConnectorEvent>, res: types::Response, ) -> CustomResult<types::PaymentsSyncRouterData, errors::ConnectorError> { + let response = nmi::SyncResponse::try_from(res.response.to_vec())?; + + event_builder.map(|i| i.set_response_body(&response)); + types::RouterData::try_from(types::ResponseRouterData { - response: res.clone(), + response, data: data.clone(), http_code: res.status_code, }) @@ -508,8 +535,9 @@ impl ConnectorIntegration<api::PSync, types::PaymentsSyncData, types::PaymentsRe fn get_error_response( &self, res: types::Response, + event_builder: Option<&mut ConnectorEvent>, ) -> CustomResult<ErrorResponse, errors::ConnectorError> { - self.build_error_response(res) + self.build_error_response(res, event_builder) } } @@ -569,11 +597,14 @@ impl ConnectorIntegration<api::Capture, types::PaymentsCaptureData, types::Payme fn handle_response( &self, data: &types::PaymentsCaptureRouterData, + event_builder: Option<&mut ConnectorEvent>, res: types::Response, ) -> CustomResult<types::PaymentsCaptureRouterData, errors::ConnectorError> { let response: nmi::StandardResponse = serde_urlencoded::from_bytes(&res.response) .into_report() .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(), @@ -584,8 +615,9 @@ impl ConnectorIntegration<api::Capture, types::PaymentsCaptureData, types::Payme fn get_error_response( &self, res: types::Response, + event_builder: Option<&mut ConnectorEvent>, ) -> CustomResult<ErrorResponse, errors::ConnectorError> { - self.build_error_response(res) + self.build_error_response(res, event_builder) } } @@ -637,11 +669,14 @@ impl ConnectorIntegration<api::Void, types::PaymentsCancelData, types::PaymentsR fn handle_response( &self, data: &types::PaymentsCancelRouterData, + event_builder: Option<&mut ConnectorEvent>, res: types::Response, ) -> CustomResult<types::PaymentsCancelRouterData, errors::ConnectorError> { let response: nmi::StandardResponse = serde_urlencoded::from_bytes(&res.response) .into_report() .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(), @@ -652,8 +687,9 @@ impl ConnectorIntegration<api::Void, types::PaymentsCancelData, types::PaymentsR fn get_error_response( &self, res: types::Response, + event_builder: Option<&mut ConnectorEvent>, ) -> CustomResult<ErrorResponse, errors::ConnectorError> { - self.build_error_response(res) + self.build_error_response(res, event_builder) } } @@ -711,11 +747,14 @@ impl ConnectorIntegration<api::Execute, types::RefundsData, types::RefundsRespon fn handle_response( &self, data: &types::RefundsRouterData<api::Execute>, + event_builder: Option<&mut ConnectorEvent>, res: types::Response, ) -> CustomResult<types::RefundsRouterData<api::Execute>, errors::ConnectorError> { let response: nmi::StandardResponse = serde_urlencoded::from_bytes(&res.response) .into_report() .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(), @@ -726,8 +765,9 @@ impl ConnectorIntegration<api::Execute, types::RefundsData, types::RefundsRespon fn get_error_response( &self, res: types::Response, + event_builder: Option<&mut ConnectorEvent>, ) -> CustomResult<ErrorResponse, errors::ConnectorError> { - self.build_error_response(res) + self.build_error_response(res, event_builder) } } @@ -777,10 +817,16 @@ impl ConnectorIntegration<api::RSync, types::RefundsData, types::RefundsResponse fn handle_response( &self, data: &types::RefundsRouterData<api::RSync>, + event_builder: Option<&mut ConnectorEvent>, res: types::Response, ) -> CustomResult<types::RefundsRouterData<api::RSync>, errors::ConnectorError> { + let response = nmi::NmiRefundSyncResponse::try_from(res.response.to_vec())?; + + event_builder.map(|i| i.set_response_body(&response)); + router_env::logger::info!(connector_response=?response); + types::RouterData::try_from(types::ResponseRouterData { - response: res.clone(), + response, data: data.clone(), http_code: res.status_code, }) @@ -789,8 +835,9 @@ impl ConnectorIntegration<api::RSync, types::RefundsData, types::RefundsResponse fn get_error_response( &self, res: types::Response, + event_builder: Option<&mut ConnectorEvent>, ) -> CustomResult<ErrorResponse, errors::ConnectorError> { - self.build_error_response(res) + self.build_error_response(res, event_builder) } } diff --git a/crates/router/src/connector/nmi/transformers.rs b/crates/router/src/connector/nmi/transformers.rs index 65acb5832b4..c6d763fe568 100644 --- a/crates/router/src/connector/nmi/transformers.rs +++ b/crates/router/src/connector/nmi/transformers.rs @@ -137,7 +137,7 @@ fn get_card_details( } } -#[derive(Debug, Deserialize)] +#[derive(Debug, Deserialize, Serialize)] pub struct NmiVaultResponse { pub response: Response, pub responsetext: String, @@ -305,7 +305,7 @@ impl TryFrom<&NmiRouterData<&types::PaymentsCompleteAuthorizeRouterData>> for Nm } } -#[derive(Debug, Deserialize)] +#[derive(Debug, Deserialize, Serialize)] pub struct NmiCompleteResponse { pub response: Response, pub responsetext: String, @@ -707,7 +707,7 @@ impl TryFrom<&types::PaymentsCancelRouterData> for NmiCancelRequest { } } -#[derive(Debug, Deserialize)] +#[derive(Debug, Deserialize, Serialize)] pub enum Response { #[serde(alias = "1")] Approved, @@ -717,7 +717,7 @@ pub enum Response { Error, } -#[derive(Debug, Deserialize)] +#[derive(Debug, Deserialize, Serialize)] pub struct StandardResponse { pub response: Response, pub responsetext: String, @@ -898,15 +898,14 @@ pub enum NmiStatus { Unknown, } -impl TryFrom<types::PaymentsSyncResponseRouterData<types::Response>> - for types::PaymentsSyncRouterData +impl<F, T> TryFrom<types::ResponseRouterData<F, SyncResponse, T, types::PaymentsResponseData>> + for types::RouterData<F, T, types::PaymentsResponseData> { type Error = Error; fn try_from( - item: types::PaymentsSyncResponseRouterData<types::Response>, + item: types::ResponseRouterData<F, SyncResponse, T, types::PaymentsResponseData>, ) -> Result<Self, Self::Error> { - let response = SyncResponse::try_from(item.response.response.to_vec())?; - match response.transaction { + match item.response.transaction { Some(trn) => Ok(Self { status: enums::AttemptStatus::from(NmiStatus::from(trn.condition)), response: Ok(types::PaymentsResponseData::TransactionResponse { @@ -1050,19 +1049,18 @@ impl TryFrom<&types::RefundSyncRouterData> for NmiSyncRequest { } } -impl TryFrom<types::RefundsResponseRouterData<api::RSync, types::Response>> +impl TryFrom<types::RefundsResponseRouterData<api::RSync, NmiRefundSyncResponse>> for types::RefundsRouterData<api::RSync> { - type Error = Error; + type Error = Report<errors::ConnectorError>; fn try_from( - item: types::RefundsResponseRouterData<api::RSync, types::Response>, + item: types::RefundsResponseRouterData<api::RSync, NmiRefundSyncResponse>, ) -> Result<Self, Self::Error> { - let response = NmiRefundSyncResponse::try_from(item.response.response.to_vec())?; let refund_status = - enums::RefundStatus::from(NmiStatus::from(response.transaction.condition)); + enums::RefundStatus::from(NmiStatus::from(item.response.transaction.condition)); Ok(Self { response: Ok(types::RefundsResponseData { - connector_refund_id: response.transaction.order_id, + connector_refund_id: item.response.transaction.order_id, refund_status, }), ..item.data @@ -1110,14 +1108,14 @@ pub struct SyncResponse { pub transaction: Option<SyncTransactionResponse>, } -#[derive(Debug, Deserialize)] +#[derive(Debug, Deserialize, Serialize)] pub struct RefundSyncBody { order_id: String, condition: String, } -#[derive(Debug, Deserialize)] -struct NmiRefundSyncResponse { +#[derive(Debug, Deserialize, Serialize)] +pub struct NmiRefundSyncResponse { transaction: RefundSyncBody, } diff --git a/crates/router/src/connector/noon.rs b/crates/router/src/connector/noon.rs index 6e1959b46d0..56f3c7101b2 100644 --- a/crates/router/src/connector/noon.rs +++ b/crates/router/src/connector/noon.rs @@ -18,6 +18,7 @@ use crate::{ errors::{self, CustomResult}, payments, }, + events::connector_api_logs::ConnectorEvent, headers, services::{ self, @@ -127,20 +128,26 @@ impl ConnectorCommon for Noon { fn build_error_response( &self, res: Response, + event_builder: Option<&mut ConnectorEvent>, ) -> CustomResult<ErrorResponse, errors::ConnectorError> { let response: Result<noon::NoonErrorResponse, Report<common_utils::errors::ParsingError>> = res.response.parse_struct("NoonErrorResponse"); match response { - Ok(noon_error_response) => Ok(ErrorResponse { - status_code: res.status_code, - code: consts::NO_ERROR_CODE.to_string(), - message: noon_error_response.class_description, - reason: Some(noon_error_response.message), - attempt_status: None, - connector_transaction_id: None, - }), + Ok(noon_error_response) => { + event_builder.map(|i| i.set_error_response_body(&noon_error_response)); + router_env::logger::info!(connector_response=?noon_error_response); + Ok(ErrorResponse { + status_code: res.status_code, + code: consts::NO_ERROR_CODE.to_string(), + message: noon_error_response.class_description, + reason: Some(noon_error_response.message), + attempt_status: None, + connector_transaction_id: None, + }) + } Err(error_message) => { + event_builder.map(|event| event.set_error(serde_json::json!({"error": res.response.escape_ascii().to_string(), "status_code": res.status_code}))); logger::error!(deserialization_error =? error_message); utils::handle_json_response_deserialization_failure(res, "noon".to_owned()) } @@ -262,12 +269,17 @@ impl ConnectorIntegration<api::Authorize, types::PaymentsAuthorizeData, types::P fn handle_response( &self, data: &types::PaymentsAuthorizeRouterData, + event_builder: Option<&mut ConnectorEvent>, res: Response, ) -> CustomResult<types::PaymentsAuthorizeRouterData, errors::ConnectorError> { let response: noon::NoonPaymentsResponse = res .response .parse_struct("Noon 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(), @@ -278,8 +290,9 @@ impl ConnectorIntegration<api::Authorize, types::PaymentsAuthorizeData, types::P fn get_error_response( &self, res: Response, + event_builder: Option<&mut ConnectorEvent>, ) -> CustomResult<ErrorResponse, errors::ConnectorError> { - self.build_error_response(res) + self.build_error_response(res, event_builder) } } @@ -328,12 +341,17 @@ impl ConnectorIntegration<api::PSync, types::PaymentsSyncData, types::PaymentsRe fn handle_response( &self, data: &types::PaymentsSyncRouterData, + event_builder: Option<&mut ConnectorEvent>, res: Response, ) -> CustomResult<types::PaymentsSyncRouterData, errors::ConnectorError> { let response: noon::NoonPaymentsResponse = res .response .parse_struct("noon 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(), @@ -344,8 +362,9 @@ impl ConnectorIntegration<api::PSync, types::PaymentsSyncData, types::PaymentsRe fn get_error_response( &self, res: Response, + event_builder: Option<&mut ConnectorEvent>, ) -> CustomResult<ErrorResponse, errors::ConnectorError> { - self.build_error_response(res) + self.build_error_response(res, event_builder) } } @@ -404,12 +423,17 @@ impl ConnectorIntegration<api::Capture, types::PaymentsCaptureData, types::Payme fn handle_response( &self, data: &types::PaymentsCaptureRouterData, + event_builder: Option<&mut ConnectorEvent>, res: Response, ) -> CustomResult<types::PaymentsCaptureRouterData, errors::ConnectorError> { let response: noon::NoonPaymentsResponse = res .response .parse_struct("Noon 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(), @@ -420,8 +444,9 @@ impl ConnectorIntegration<api::Capture, types::PaymentsCaptureData, types::Payme fn get_error_response( &self, res: Response, + event_builder: Option<&mut ConnectorEvent>, ) -> CustomResult<ErrorResponse, errors::ConnectorError> { - self.build_error_response(res) + self.build_error_response(res, event_builder) } } @@ -477,12 +502,17 @@ impl ConnectorIntegration<api::Void, types::PaymentsCancelData, types::PaymentsR fn handle_response( &self, data: &types::PaymentsCancelRouterData, + event_builder: Option<&mut ConnectorEvent>, res: Response, ) -> CustomResult<types::PaymentsCancelRouterData, errors::ConnectorError> { let response: noon::NoonPaymentsResponse = res .response .parse_struct("Noon PaymentsCancelResponse") .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(), @@ -493,8 +523,9 @@ impl ConnectorIntegration<api::Void, types::PaymentsCancelData, types::PaymentsR fn get_error_response( &self, res: Response, + event_builder: Option<&mut ConnectorEvent>, ) -> CustomResult<ErrorResponse, errors::ConnectorError> { - self.build_error_response(res) + self.build_error_response(res, event_builder) } } @@ -553,12 +584,17 @@ impl fn handle_response( &self, data: &types::MandateRevokeRouterData, + event_builder: Option<&mut ConnectorEvent>, res: Response, ) -> CustomResult<types::MandateRevokeRouterData, errors::ConnectorError> { let response: noon::NoonRevokeMandateResponse = res .response .parse_struct("Noon NoonRevokeMandateResponse") .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(), @@ -568,8 +604,9 @@ impl fn get_error_response( &self, res: Response, + event_builder: Option<&mut ConnectorEvent>, ) -> CustomResult<ErrorResponse, errors::ConnectorError> { - self.build_error_response(res) + self.build_error_response(res, event_builder) } } @@ -625,12 +662,17 @@ impl ConnectorIntegration<api::Execute, types::RefundsData, types::RefundsRespon 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: noon::RefundResponse = res .response .parse_struct("noon 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(), @@ -641,8 +683,9 @@ impl ConnectorIntegration<api::Execute, types::RefundsData, types::RefundsRespon fn get_error_response( &self, res: Response, + event_builder: Option<&mut ConnectorEvent>, ) -> CustomResult<ErrorResponse, errors::ConnectorError> { - self.build_error_response(res) + self.build_error_response(res, event_builder) } } @@ -689,6 +732,7 @@ impl ConnectorIntegration<api::RSync, types::RefundsData, types::RefundsResponse fn handle_response( &self, data: &types::RefundSyncRouterData, + event_builder: Option<&mut ConnectorEvent>, res: Response, ) -> CustomResult<types::RefundSyncRouterData, errors::ConnectorError> { let response: noon::RefundSyncResponse = res @@ -696,6 +740,9 @@ impl ConnectorIntegration<api::RSync, types::RefundsData, types::RefundsResponse .parse_struct("noon 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(), @@ -707,8 +754,9 @@ impl ConnectorIntegration<api::RSync, types::RefundsData, types::RefundsResponse fn get_error_response( &self, res: Response, + event_builder: Option<&mut ConnectorEvent>, ) -> CustomResult<ErrorResponse, errors::ConnectorError> { - self.build_error_response(res) + self.build_error_response(res, event_builder) } } diff --git a/crates/router/src/connector/noon/transformers.rs b/crates/router/src/connector/noon/transformers.rs index 5818c10eea6..2f5f342d7ae 100644 --- a/crates/router/src/connector/noon/transformers.rs +++ b/crates/router/src/connector/noon/transformers.rs @@ -707,22 +707,22 @@ impl<F> TryFrom<&types::RefundsRouterData<F>> for NoonPaymentsActionRequest { }) } } -#[derive(Debug, Deserialize)] +#[derive(Debug, Deserialize, Serialize)] pub enum NoonRevokeStatus { Cancelled, } -#[derive(Debug, Deserialize)] +#[derive(Debug, Deserialize, Serialize)] pub struct NoonCancelSubscriptionObject { status: NoonRevokeStatus, } -#[derive(Debug, Deserialize)] +#[derive(Debug, Deserialize, Serialize)] pub struct NoonRevokeMandateResult { subscription: NoonCancelSubscriptionObject, } -#[derive(Debug, Deserialize)] +#[derive(Debug, Deserialize, Serialize)] pub struct NoonRevokeMandateResponse { result: NoonRevokeMandateResult, } @@ -757,7 +757,7 @@ impl<F> } } -#[derive(Debug, Default, Deserialize, Clone)] +#[derive(Debug, Default, Deserialize, Clone, Serialize)] #[serde(rename_all = "UPPERCASE")] pub enum RefundStatus { Success, @@ -776,19 +776,19 @@ impl From<RefundStatus> for enums::RefundStatus { } } -#[derive(Default, Debug, Deserialize)] +#[derive(Default, Debug, Deserialize, Serialize)] #[serde(rename_all = "camelCase")] pub struct NoonPaymentsTransactionResponse { id: String, status: RefundStatus, } -#[derive(Default, Debug, Deserialize)] +#[derive(Default, Debug, Deserialize, Serialize)] pub struct NoonRefundResponseResult { transaction: NoonPaymentsTransactionResponse, } -#[derive(Default, Debug, Deserialize)] +#[derive(Default, Debug, Deserialize, Serialize)] pub struct RefundResponse { result: NoonRefundResponseResult, } @@ -810,7 +810,7 @@ impl TryFrom<types::RefundsResponseRouterData<api::Execute, RefundResponse>> } } -#[derive(Default, Debug, Deserialize)] +#[derive(Default, Debug, Deserialize, Serialize)] #[serde(rename_all = "camelCase")] pub struct NoonRefundResponseTransactions { id: String, @@ -818,12 +818,12 @@ pub struct NoonRefundResponseTransactions { transaction_reference: Option<String>, } -#[derive(Default, Debug, Deserialize)] +#[derive(Default, Debug, Deserialize, Serialize)] pub struct NoonRefundSyncResponseResult { transactions: Vec<NoonRefundResponseTransactions>, } -#[derive(Default, Debug, Deserialize)] +#[derive(Default, Debug, Deserialize, Serialize)] pub struct RefundSyncResponse { result: NoonRefundSyncResponseResult, } @@ -927,7 +927,7 @@ impl From<NoonWebhookObject> for NoonPaymentsResponse { } } -#[derive(Debug, Deserialize)] +#[derive(Debug, Deserialize, Serialize)] #[serde(rename_all = "camelCase")] pub struct NoonErrorResponse { pub result_code: u32, diff --git a/crates/router/src/connector/nuvei.rs b/crates/router/src/connector/nuvei.rs index 35de293443e..59396766317 100644 --- a/crates/router/src/connector/nuvei.rs +++ b/crates/router/src/connector/nuvei.rs @@ -18,6 +18,7 @@ use crate::{ errors::{self, CustomResult}, payments, }, + events::connector_api_logs::ConnectorEvent, headers, services::{self, request, ConnectorIntegration, ConnectorValidation}, types::{ @@ -195,12 +196,17 @@ impl fn handle_response( &self, data: &types::PaymentsCompleteAuthorizeRouterData, + event_builder: Option<&mut ConnectorEvent>, res: Response, ) -> CustomResult<types::PaymentsCompleteAuthorizeRouterData, errors::ConnectorError> { let response: nuvei::NuveiPaymentsResponse = res .response .parse_struct("NuveiPaymentsResponse") .switch()?; + + 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(), @@ -212,8 +218,9 @@ impl fn get_error_response( &self, res: Response, + event_builder: Option<&mut ConnectorEvent>, ) -> CustomResult<ErrorResponse, errors::ConnectorError> { - self.build_error_response(res) + self.build_error_response(res, event_builder) } } @@ -272,12 +279,15 @@ impl ConnectorIntegration<api::Void, types::PaymentsCancelData, types::PaymentsR fn handle_response( &self, data: &types::PaymentsCancelRouterData, + event_builder: Option<&mut ConnectorEvent>, res: Response, ) -> CustomResult<types::PaymentsCancelRouterData, errors::ConnectorError> { let response: nuvei::NuveiPaymentsResponse = res .response .parse_struct("NuveiPaymentsResponse") .switch()?; + event_builder.map(|i| i.set_response_body(&response)); + router_env::logger::info!(connector_response=?response); types::PaymentsCancelRouterData::try_from(types::ResponseRouterData { response, data: data.clone(), @@ -289,8 +299,9 @@ impl ConnectorIntegration<api::Void, types::PaymentsCancelData, types::PaymentsR fn get_error_response( &self, res: Response, + event_builder: Option<&mut ConnectorEvent>, ) -> CustomResult<ErrorResponse, errors::ConnectorError> { - self.build_error_response(res) + self.build_error_response(res, event_builder) } } @@ -354,19 +365,25 @@ impl ConnectorIntegration<api::PSync, types::PaymentsSyncData, types::PaymentsRe fn get_error_response( &self, res: Response, + event_builder: Option<&mut ConnectorEvent>, ) -> CustomResult<ErrorResponse, errors::ConnectorError> { - self.build_error_response(res) + self.build_error_response(res, event_builder) } fn handle_response( &self, data: &types::PaymentsSyncRouterData, + event_builder: Option<&mut ConnectorEvent>, res: Response, ) -> CustomResult<types::PaymentsSyncRouterData, errors::ConnectorError> { let response: nuvei::NuveiPaymentsResponse = res .response .parse_struct("NuveiPaymentsResponse") .switch()?; + + 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(), @@ -434,12 +451,17 @@ impl ConnectorIntegration<api::Capture, types::PaymentsCaptureData, types::Payme fn handle_response( &self, data: &types::PaymentsCaptureRouterData, + event_builder: Option<&mut ConnectorEvent>, res: Response, ) -> CustomResult<types::PaymentsCaptureRouterData, errors::ConnectorError> { let response: nuvei::NuveiPaymentsResponse = res .response .parse_struct("NuveiPaymentsResponse") .switch()?; + + 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(), @@ -451,8 +473,9 @@ impl ConnectorIntegration<api::Capture, types::PaymentsCaptureData, types::Payme fn get_error_response( &self, res: Response, + event_builder: Option<&mut ConnectorEvent>, ) -> CustomResult<ErrorResponse, errors::ConnectorError> { - self.build_error_response(res) + self.build_error_response(res, event_builder) } } @@ -592,12 +615,17 @@ impl ConnectorIntegration<api::Authorize, types::PaymentsAuthorizeData, types::P fn handle_response( &self, data: &types::PaymentsAuthorizeRouterData, + event_builder: Option<&mut ConnectorEvent>, res: Response, ) -> CustomResult<types::PaymentsAuthorizeRouterData, errors::ConnectorError> { let response: nuvei::NuveiPaymentsResponse = res .response .parse_struct("NuveiPaymentsResponse") .switch()?; + + 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(), @@ -609,8 +637,9 @@ impl ConnectorIntegration<api::Authorize, types::PaymentsAuthorizeData, types::P fn get_error_response( &self, res: Response, + event_builder: Option<&mut ConnectorEvent>, ) -> CustomResult<ErrorResponse, errors::ConnectorError> { - self.build_error_response(res) + self.build_error_response(res, event_builder) } } @@ -678,10 +707,15 @@ impl fn handle_response( &self, data: &types::PaymentsAuthorizeSessionTokenRouterData, + event_builder: Option<&mut ConnectorEvent>, res: Response, ) -> CustomResult<types::PaymentsAuthorizeSessionTokenRouterData, errors::ConnectorError> { let response: nuvei::NuveiSessionResponse = res.response.parse_struct("NuveiSessionResponse").switch()?; + + 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(), @@ -692,8 +726,9 @@ impl fn get_error_response( &self, res: Response, + event_builder: Option<&mut ConnectorEvent>, ) -> CustomResult<ErrorResponse, errors::ConnectorError> { - self.build_error_response(res) + self.build_error_response(res, event_builder) } } @@ -754,12 +789,17 @@ impl ConnectorIntegration<InitPayment, types::PaymentsAuthorizeData, types::Paym fn handle_response( &self, data: &types::PaymentsInitRouterData, + event_builder: Option<&mut ConnectorEvent>, res: Response, ) -> CustomResult<types::PaymentsInitRouterData, errors::ConnectorError> { let response: nuvei::NuveiPaymentsResponse = res .response .parse_struct("NuveiPaymentsResponse") .switch()?; + + 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(), @@ -771,8 +811,9 @@ impl ConnectorIntegration<InitPayment, types::PaymentsAuthorizeData, types::Paym fn get_error_response( &self, res: Response, + event_builder: Option<&mut ConnectorEvent>, ) -> CustomResult<ErrorResponse, errors::ConnectorError> { - self.build_error_response(res) + self.build_error_response(res, event_builder) } } @@ -831,12 +872,17 @@ impl ConnectorIntegration<api::Execute, types::RefundsData, types::RefundsRespon 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: nuvei::NuveiPaymentsResponse = res .response .parse_struct("NuveiPaymentsResponse") .switch()?; + + 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(), @@ -848,8 +894,9 @@ impl ConnectorIntegration<api::Execute, types::RefundsData, types::RefundsRespon fn get_error_response( &self, res: Response, + event_builder: Option<&mut ConnectorEvent>, ) -> CustomResult<ErrorResponse, errors::ConnectorError> { - self.build_error_response(res) + self.build_error_response(res, event_builder) } } diff --git a/crates/router/src/connector/opayo.rs b/crates/router/src/connector/opayo.rs index 0ab5785a445..7285ce49fcd 100644 --- a/crates/router/src/connector/opayo.rs +++ b/crates/router/src/connector/opayo.rs @@ -12,6 +12,7 @@ use crate::{ configs::settings, connector::utils as connector_utils, core::errors::{self, CustomResult}, + events::connector_api_logs::ConnectorEvent, headers, services::{ self, @@ -97,12 +98,16 @@ impl ConnectorCommon for Opayo { fn build_error_response( &self, res: Response, + event_builder: Option<&mut ConnectorEvent>, ) -> CustomResult<ErrorResponse, errors::ConnectorError> { let response: opayo::OpayoErrorResponse = res.response .parse_struct("OpayoErrorResponse") .change_context(errors::ConnectorError::ResponseDeserializationFailed)?; + event_builder.map(|i| i.set_error_response_body(&response)); + router_env::logger::info!(connector_response=?response); + Ok(ErrorResponse { status_code: res.status_code, code: response.code, @@ -220,12 +225,17 @@ impl ConnectorIntegration<api::Authorize, types::PaymentsAuthorizeData, types::P fn handle_response( &self, data: &types::PaymentsAuthorizeRouterData, + event_builder: Option<&mut ConnectorEvent>, res: Response, ) -> CustomResult<types::PaymentsAuthorizeRouterData, errors::ConnectorError> { let response: opayo::OpayoPaymentsResponse = res .response .parse_struct("Opayo 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(), @@ -236,8 +246,9 @@ impl ConnectorIntegration<api::Authorize, types::PaymentsAuthorizeData, types::P fn get_error_response( &self, res: Response, + event_builder: Option<&mut ConnectorEvent>, ) -> CustomResult<ErrorResponse, errors::ConnectorError> { - self.build_error_response(res) + self.build_error_response(res, event_builder) } } @@ -282,12 +293,17 @@ impl ConnectorIntegration<api::PSync, types::PaymentsSyncData, types::PaymentsRe fn handle_response( &self, data: &types::PaymentsSyncRouterData, + event_builder: Option<&mut ConnectorEvent>, res: Response, ) -> CustomResult<types::PaymentsSyncRouterData, errors::ConnectorError> { let response: opayo::OpayoPaymentsResponse = res .response .parse_struct("opayo 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(), @@ -298,8 +314,9 @@ impl ConnectorIntegration<api::PSync, types::PaymentsSyncData, types::PaymentsRe fn get_error_response( &self, res: Response, + event_builder: Option<&mut ConnectorEvent>, ) -> CustomResult<ErrorResponse, errors::ConnectorError> { - self.build_error_response(res) + self.build_error_response(res, event_builder) } } @@ -357,12 +374,17 @@ impl ConnectorIntegration<api::Capture, types::PaymentsCaptureData, types::Payme fn handle_response( &self, data: &types::PaymentsCaptureRouterData, + event_builder: Option<&mut ConnectorEvent>, res: Response, ) -> CustomResult<types::PaymentsCaptureRouterData, errors::ConnectorError> { let response: opayo::OpayoPaymentsResponse = res .response .parse_struct("Opayo 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(), @@ -373,8 +395,9 @@ impl ConnectorIntegration<api::Capture, types::PaymentsCaptureData, types::Payme fn get_error_response( &self, res: Response, + event_builder: Option<&mut ConnectorEvent>, ) -> CustomResult<ErrorResponse, errors::ConnectorError> { - self.build_error_response(res) + self.build_error_response(res, event_builder) } } @@ -436,12 +459,17 @@ impl ConnectorIntegration<api::Execute, types::RefundsData, types::RefundsRespon 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: opayo::RefundResponse = res .response .parse_struct("opayo 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(), @@ -452,8 +480,9 @@ impl ConnectorIntegration<api::Execute, types::RefundsData, types::RefundsRespon fn get_error_response( &self, res: Response, + event_builder: Option<&mut ConnectorEvent>, ) -> CustomResult<ErrorResponse, errors::ConnectorError> { - self.build_error_response(res) + self.build_error_response(res, event_builder) } } @@ -496,12 +525,17 @@ impl ConnectorIntegration<api::RSync, types::RefundsData, types::RefundsResponse fn handle_response( &self, data: &types::RefundSyncRouterData, + event_builder: Option<&mut ConnectorEvent>, res: Response, ) -> CustomResult<types::RefundSyncRouterData, errors::ConnectorError> { let response: opayo::RefundResponse = res .response .parse_struct("opayo 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(), @@ -512,8 +546,9 @@ impl ConnectorIntegration<api::RSync, types::RefundsData, types::RefundsResponse fn get_error_response( &self, res: Response, + event_builder: Option<&mut ConnectorEvent>, ) -> CustomResult<ErrorResponse, errors::ConnectorError> { - self.build_error_response(res) + self.build_error_response(res, event_builder) } } diff --git a/crates/router/src/connector/opennode.rs b/crates/router/src/connector/opennode.rs index 1eafa67fdda..1bd7461b668 100644 --- a/crates/router/src/connector/opennode.rs +++ b/crates/router/src/connector/opennode.rs @@ -11,6 +11,7 @@ use crate::{ configs::settings, consts, core::errors::{self, CustomResult}, + events::connector_api_logs::ConnectorEvent, headers, services::{ self, @@ -99,12 +100,16 @@ impl ConnectorCommon for Opennode { fn build_error_response( &self, res: Response, + event_builder: Option<&mut ConnectorEvent>, ) -> CustomResult<ErrorResponse, errors::ConnectorError> { let response: opennode::OpennodeErrorResponse = res .response .parse_struct("OpennodeErrorResponse") .change_context(errors::ConnectorError::ResponseDeserializationFailed)?; + event_builder.map(|i| i.set_error_response_body(&response)); + router_env::logger::info!(connector_response=?response); + Ok(ErrorResponse { status_code: res.status_code, code: consts::NO_ERROR_CODE.to_string(), @@ -224,12 +229,17 @@ impl ConnectorIntegration<api::Authorize, types::PaymentsAuthorizeData, types::P fn handle_response( &self, data: &types::PaymentsAuthorizeRouterData, + event_builder: Option<&mut ConnectorEvent>, res: Response, ) -> CustomResult<types::PaymentsAuthorizeRouterData, errors::ConnectorError> { let response: opennode::OpennodePaymentsResponse = res .response .parse_struct("Opennode 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(), @@ -241,8 +251,9 @@ impl ConnectorIntegration<api::Authorize, types::PaymentsAuthorizeData, types::P fn get_error_response( &self, res: Response, + event_builder: Option<&mut ConnectorEvent>, ) -> CustomResult<ErrorResponse, errors::ConnectorError> { - self.build_error_response(res) + self.build_error_response(res, event_builder) } } @@ -295,12 +306,17 @@ impl ConnectorIntegration<api::PSync, types::PaymentsSyncData, types::PaymentsRe fn handle_response( &self, data: &types::PaymentsSyncRouterData, + event_builder: Option<&mut ConnectorEvent>, res: Response, ) -> CustomResult<types::PaymentsSyncRouterData, errors::ConnectorError> { let response: opennode::OpennodePaymentsResponse = res .response .parse_struct("opennode 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(), @@ -312,8 +328,9 @@ impl ConnectorIntegration<api::PSync, types::PaymentsSyncData, types::PaymentsRe fn get_error_response( &self, res: Response, + event_builder: Option<&mut ConnectorEvent>, ) -> CustomResult<ErrorResponse, errors::ConnectorError> { - self.build_error_response(res) + self.build_error_response(res, event_builder) } } diff --git a/crates/router/src/connector/opennode/transformers.rs b/crates/router/src/connector/opennode/transformers.rs index 7670166faba..3267caf60d6 100644 --- a/crates/router/src/connector/opennode/transformers.rs +++ b/crates/router/src/connector/opennode/transformers.rs @@ -252,7 +252,7 @@ impl TryFrom<types::RefundsResponseRouterData<api::RSync, RefundResponse>> } //TODO: Fill the struct with respective fields -#[derive(Debug, Deserialize)] +#[derive(Debug, Deserialize, Serialize)] pub struct OpennodeErrorResponse { pub message: String, } diff --git a/crates/router/src/connector/payeezy.rs b/crates/router/src/connector/payeezy.rs index 442bbaca312..6f6a366ee46 100644 --- a/crates/router/src/connector/payeezy.rs +++ b/crates/router/src/connector/payeezy.rs @@ -16,6 +16,7 @@ use crate::{ connector::utils as connector_utils, consts, core::errors::{self, CustomResult}, + events::connector_api_logs::ConnectorEvent, headers, services::{ self, @@ -104,12 +105,16 @@ impl ConnectorCommon for Payeezy { fn build_error_response( &self, res: Response, + event_builder: Option<&mut ConnectorEvent>, ) -> CustomResult<ErrorResponse, errors::ConnectorError> { let response: payeezy::PayeezyErrorResponse = res .response .parse_struct("payeezy ErrorResponse") .change_context(errors::ConnectorError::ResponseDeserializationFailed)?; + event_builder.map(|i| i.set_error_response_body(&response)); + router_env::logger::info!(connector_response=?response); + let error_messages: Vec<String> = response .error .messages @@ -240,12 +245,17 @@ impl ConnectorIntegration<api::Void, types::PaymentsCancelData, types::PaymentsR fn handle_response( &self, data: &types::PaymentsCancelRouterData, + event_builder: Option<&mut ConnectorEvent>, res: Response, ) -> CustomResult<types::PaymentsCancelRouterData, errors::ConnectorError> { let response: payeezy::PayeezyPaymentsResponse = res .response .parse_struct("Payeezy PaymentsResponse") .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(), @@ -257,8 +267,9 @@ impl ConnectorIntegration<api::Void, types::PaymentsCancelData, types::PaymentsR fn get_error_response( &self, res: Response, + event_builder: Option<&mut ConnectorEvent>, ) -> CustomResult<ErrorResponse, errors::ConnectorError> { - self.build_error_response(res) + self.build_error_response(res, event_builder) } } @@ -343,12 +354,17 @@ impl ConnectorIntegration<api::Capture, types::PaymentsCaptureData, types::Payme fn handle_response( &self, data: &types::PaymentsCaptureRouterData, + event_builder: Option<&mut ConnectorEvent>, res: Response, ) -> CustomResult<types::PaymentsCaptureRouterData, errors::ConnectorError> { let response: payeezy::PayeezyPaymentsResponse = res .response .parse_struct("Payeezy PaymentsResponse") .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(), @@ -360,8 +376,9 @@ impl ConnectorIntegration<api::Capture, types::PaymentsCaptureData, types::Payme fn get_error_response( &self, res: Response, + event_builder: Option<&mut ConnectorEvent>, ) -> CustomResult<ErrorResponse, errors::ConnectorError> { - self.build_error_response(res) + self.build_error_response(res, event_builder) } } @@ -438,12 +455,17 @@ impl ConnectorIntegration<api::Authorize, types::PaymentsAuthorizeData, types::P fn handle_response( &self, data: &types::PaymentsAuthorizeRouterData, + event_builder: Option<&mut ConnectorEvent>, res: Response, ) -> CustomResult<types::PaymentsAuthorizeRouterData, errors::ConnectorError> { let response: payeezy::PayeezyPaymentsResponse = res .response .parse_struct("payeezy Response") .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(), @@ -455,8 +477,9 @@ impl ConnectorIntegration<api::Authorize, types::PaymentsAuthorizeData, types::P fn get_error_response( &self, res: Response, + event_builder: Option<&mut ConnectorEvent>, ) -> CustomResult<ErrorResponse, errors::ConnectorError> { - self.build_error_response(res) + self.build_error_response(res, event_builder) } } @@ -528,6 +551,7 @@ impl ConnectorIntegration<api::Execute, types::RefundsData, types::RefundsRespon fn handle_response( &self, data: &types::RefundsRouterData<api::Execute>, + event_builder: Option<&mut ConnectorEvent>, res: Response, ) -> CustomResult<types::RefundsRouterData<api::Execute>, errors::ConnectorError> { // Parse the response into a payeezy::RefundResponse @@ -536,6 +560,9 @@ impl ConnectorIntegration<api::Execute, types::RefundsData, types::RefundsRespon .parse_struct("payeezy RefundResponse") .change_context(errors::ConnectorError::ResponseDeserializationFailed)?; + event_builder.map(|i| i.set_response_body(&response)); + router_env::logger::info!(connector_response=?response); + // Create a new instance of types::RefundsRouterData based on the response, input data, and HTTP code let response_data = types::ResponseRouterData { response, @@ -551,8 +578,9 @@ impl ConnectorIntegration<api::Execute, types::RefundsData, types::RefundsRespon fn get_error_response( &self, res: Response, + event_builder: Option<&mut ConnectorEvent>, ) -> CustomResult<ErrorResponse, errors::ConnectorError> { - self.build_error_response(res) + self.build_error_response(res, event_builder) } } diff --git a/crates/router/src/connector/payeezy/transformers.rs b/crates/router/src/connector/payeezy/transformers.rs index c633fd3d99f..e8801e3222b 100644 --- a/crates/router/src/connector/payeezy/transformers.rs +++ b/crates/router/src/connector/payeezy/transformers.rs @@ -298,7 +298,7 @@ impl TryFrom<&types::ConnectorAuthType> for PayeezyAuthType { } // PaymentsResponse -#[derive(Debug, Default, Deserialize)] +#[derive(Debug, Default, Deserialize, Serialize)] #[serde(rename_all = "lowercase")] pub enum PayeezyPaymentStatus { Approved, @@ -308,7 +308,7 @@ pub enum PayeezyPaymentStatus { NotProcessed, } -#[derive(Deserialize)] +#[derive(Debug, Deserialize, Serialize)] pub struct PayeezyPaymentsResponse { pub correlation_id: String, pub transaction_status: PayeezyPaymentStatus, @@ -327,7 +327,7 @@ pub struct PayeezyPaymentsResponse { pub reference: Option<String>, } -#[derive(Debug, Deserialize)] +#[derive(Debug, Deserialize, Serialize)] pub struct PaymentsStoredCredentials { cardbrand_original_transaction_id: String, } @@ -502,7 +502,7 @@ impl<F> TryFrom<&PayeezyRouterData<&types::RefundsRouterData<F>>> for PayeezyRef // Type definition for Refund Response -#[derive(Debug, Deserialize, Default)] +#[derive(Debug, Deserialize, Default, Serialize)] #[serde(rename_all = "lowercase")] pub enum RefundStatus { Approved, @@ -522,7 +522,7 @@ impl From<RefundStatus> for enums::RefundStatus { } } -#[derive(Deserialize)] +#[derive(Deserialize, Debug, Serialize)] pub struct RefundResponse { pub correlation_id: String, pub transaction_status: RefundStatus, @@ -556,18 +556,18 @@ impl TryFrom<types::RefundsResponseRouterData<api::Execute, RefundResponse>> } } -#[derive(Debug, Deserialize)] +#[derive(Debug, Deserialize, Serialize)] pub struct Message { pub code: String, pub description: String, } -#[derive(Debug, Deserialize)] +#[derive(Debug, Deserialize, Serialize)] pub struct PayeezyError { pub messages: Vec<Message>, } -#[derive(Debug, Deserialize)] +#[derive(Debug, Deserialize, Serialize)] pub struct PayeezyErrorResponse { pub transaction_status: String, #[serde(rename = "Error")] diff --git a/crates/router/src/connector/payme.rs b/crates/router/src/connector/payme.rs index 40f4c646e50..d84c87f2e46 100644 --- a/crates/router/src/connector/payme.rs +++ b/crates/router/src/connector/payme.rs @@ -16,6 +16,7 @@ use crate::{ errors::{self, CustomResult}, payments, }, + events::connector_api_logs::ConnectorEvent, headers, services::{self, request, ConnectorIntegration, ConnectorValidation}, types::{ @@ -80,11 +81,16 @@ impl ConnectorCommon for Payme { fn build_error_response( &self, res: Response, + event_builder: Option<&mut ConnectorEvent>, ) -> CustomResult<ErrorResponse, errors::ConnectorError> { let response: payme::PaymeErrorResponse = res.response .parse_struct("PaymeErrorResponse") .change_context(errors::ConnectorError::ResponseDeserializationFailed)?; + + event_builder.map(|i| i.set_error_response_body(&response)); + router_env::logger::info!(connector_response=?response); + let status_code = match res.status_code { 500..=511 => 200, _ => res.status_code, @@ -182,6 +188,7 @@ impl fn handle_response( &self, data: &types::TokenizationRouterData, + event_builder: Option<&mut ConnectorEvent>, res: Response, ) -> CustomResult<types::TokenizationRouterData, errors::ConnectorError> where @@ -192,6 +199,9 @@ impl .parse_struct("Payme CaptureBuyerResponse") .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(), @@ -202,16 +212,18 @@ impl fn get_error_response( &self, res: Response, + event_builder: Option<&mut ConnectorEvent>, ) -> CustomResult<ErrorResponse, errors::ConnectorError> { - self.build_error_response(res) + self.build_error_response(res, event_builder) } fn get_5xx_error_response( &self, res: Response, + event_builder: Option<&mut ConnectorEvent>, ) -> CustomResult<ErrorResponse, errors::ConnectorError> { // we are always getting 500 in error scenarios - self.build_error_response(res) + self.build_error_response(res, event_builder) } } @@ -288,12 +300,17 @@ impl fn handle_response( &self, data: &types::PaymentsPreProcessingRouterData, + event_builder: Option<&mut ConnectorEvent>, res: Response, ) -> CustomResult<types::PaymentsPreProcessingRouterData, errors::ConnectorError> { let response: payme::GenerateSaleResponse = res .response .parse_struct("Payme GenerateSaleResponse") .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(), @@ -304,16 +321,18 @@ impl fn get_error_response( &self, res: Response, + event_builder: Option<&mut ConnectorEvent>, ) -> CustomResult<ErrorResponse, errors::ConnectorError> { - self.build_error_response(res) + self.build_error_response(res, event_builder) } fn get_5xx_error_response( &self, res: Response, + event_builder: Option<&mut ConnectorEvent>, ) -> CustomResult<ErrorResponse, errors::ConnectorError> { // we are always getting 500 in error scenarios - self.build_error_response(res) + self.build_error_response(res, event_builder) } } @@ -416,12 +435,17 @@ impl fn handle_response( &self, data: &types::PaymentsCompleteAuthorizeRouterData, + event_builder: Option<&mut ConnectorEvent>, res: Response, ) -> CustomResult<types::PaymentsCompleteAuthorizeRouterData, errors::ConnectorError> { let response: payme::PaymePaySaleResponse = res .response .parse_struct("Payme PaymePaySaleResponse") .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(), @@ -432,15 +456,17 @@ impl fn get_error_response( &self, res: Response, + event_builder: Option<&mut ConnectorEvent>, ) -> CustomResult<ErrorResponse, errors::ConnectorError> { - self.build_error_response(res) + self.build_error_response(res, event_builder) } fn get_5xx_error_response( &self, res: Response, + event_builder: Option<&mut ConnectorEvent>, ) -> CustomResult<ErrorResponse, errors::ConnectorError> { - self.build_error_response(res) + self.build_error_response(res, event_builder) } } @@ -522,12 +548,17 @@ impl ConnectorIntegration<api::Authorize, types::PaymentsAuthorizeData, types::P fn handle_response( &self, data: &types::PaymentsAuthorizeRouterData, + event_builder: Option<&mut ConnectorEvent>, res: Response, ) -> CustomResult<types::PaymentsAuthorizeRouterData, errors::ConnectorError> { let response: payme::PaymePaySaleResponse = res .response .parse_struct("Payme 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(), @@ -538,16 +569,18 @@ impl ConnectorIntegration<api::Authorize, types::PaymentsAuthorizeData, types::P fn get_error_response( &self, res: Response, + event_builder: Option<&mut ConnectorEvent>, ) -> CustomResult<ErrorResponse, errors::ConnectorError> { - self.build_error_response(res) + self.build_error_response(res, event_builder) } fn get_5xx_error_response( &self, res: Response, + event_builder: Option<&mut ConnectorEvent>, ) -> CustomResult<ErrorResponse, errors::ConnectorError> { // we are always getting 500 in error scenarios - self.build_error_response(res) + self.build_error_response(res, event_builder) } } @@ -604,6 +637,7 @@ impl ConnectorIntegration<api::PSync, types::PaymentsSyncData, types::PaymentsRe fn handle_response( &self, data: &types::RouterData<api::PSync, types::PaymentsSyncData, types::PaymentsResponseData>, + event_builder: Option<&mut ConnectorEvent>, res: Response, ) -> CustomResult< types::RouterData<api::PSync, types::PaymentsSyncData, types::PaymentsResponseData>, @@ -618,6 +652,10 @@ impl ConnectorIntegration<api::PSync, types::PaymentsSyncData, types::PaymentsRe .response .parse_struct("PaymePaymentsResponse") .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(), @@ -628,9 +666,10 @@ impl ConnectorIntegration<api::PSync, types::PaymentsSyncData, types::PaymentsRe fn get_5xx_error_response( &self, res: Response, + event_builder: Option<&mut ConnectorEvent>, ) -> CustomResult<ErrorResponse, errors::ConnectorError> { // we are always getting 500 in error scenarios - self.build_error_response(res) + self.build_error_response(res, event_builder) } } @@ -695,12 +734,17 @@ impl ConnectorIntegration<api::Capture, types::PaymentsCaptureData, types::Payme fn handle_response( &self, data: &types::PaymentsCaptureRouterData, + event_builder: Option<&mut ConnectorEvent>, res: Response, ) -> CustomResult<types::PaymentsCaptureRouterData, errors::ConnectorError> { let response: payme::PaymePaySaleResponse = res .response .parse_struct("Payme 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(), @@ -711,16 +755,18 @@ impl ConnectorIntegration<api::Capture, types::PaymentsCaptureData, types::Payme fn get_error_response( &self, res: Response, + event_builder: Option<&mut ConnectorEvent>, ) -> CustomResult<ErrorResponse, errors::ConnectorError> { - self.build_error_response(res) + self.build_error_response(res, event_builder) } fn get_5xx_error_response( &self, res: Response, + event_builder: Option<&mut ConnectorEvent>, ) -> CustomResult<ErrorResponse, errors::ConnectorError> { // we are always getting 500 in error scenarios - self.build_error_response(res) + self.build_error_response(res, event_builder) } } @@ -798,12 +844,17 @@ impl ConnectorIntegration<api::Execute, types::RefundsData, types::RefundsRespon 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: payme::PaymeRefundResponse = res .response .parse_struct("PaymeRefundResponse") .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(), @@ -814,16 +865,18 @@ impl ConnectorIntegration<api::Execute, types::RefundsData, types::RefundsRespon fn get_error_response( &self, res: Response, + event_builder: Option<&mut ConnectorEvent>, ) -> CustomResult<ErrorResponse, errors::ConnectorError> { - self.build_error_response(res) + self.build_error_response(res, event_builder) } fn get_5xx_error_response( &self, res: Response, + event_builder: Option<&mut ConnectorEvent>, ) -> CustomResult<ErrorResponse, errors::ConnectorError> { // we are always getting 500 in error scenarios - self.build_error_response(res) + self.build_error_response(res, event_builder) } } @@ -877,6 +930,7 @@ impl ConnectorIntegration<api::RSync, types::RefundsData, types::RefundsResponse fn handle_response( &self, data: &types::RouterData<api::RSync, types::RefundsData, types::RefundsResponseData>, + event_builder: Option<&mut ConnectorEvent>, res: Response, ) -> CustomResult< types::RouterData<api::RSync, types::RefundsData, types::RefundsResponseData>, @@ -891,6 +945,10 @@ impl ConnectorIntegration<api::RSync, types::RefundsData, types::RefundsResponse .response .parse_struct("GetSalesResponse") .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(), @@ -901,16 +959,18 @@ impl ConnectorIntegration<api::RSync, types::RefundsData, types::RefundsResponse fn get_error_response( &self, res: Response, + event_builder: Option<&mut ConnectorEvent>, ) -> CustomResult<ErrorResponse, errors::ConnectorError> { - self.build_error_response(res) + self.build_error_response(res, event_builder) } fn get_5xx_error_response( &self, res: Response, + event_builder: Option<&mut ConnectorEvent>, ) -> CustomResult<ErrorResponse, errors::ConnectorError> { // we are always getting 500 in error scenarios - self.build_error_response(res) + self.build_error_response(res, event_builder) } } diff --git a/crates/router/src/connector/payme/transformers.rs b/crates/router/src/connector/payme/transformers.rs index a7b21ce292d..77dcb6429c9 100644 --- a/crates/router/src/connector/payme/transformers.rs +++ b/crates/router/src/connector/payme/transformers.rs @@ -119,7 +119,7 @@ pub struct CaptureBuyerRequest { card: PaymeCard, } -#[derive(Debug, Deserialize)] +#[derive(Debug, Deserialize, Serialize)] pub struct CaptureBuyerResponse { buyer_key: String, } @@ -156,7 +156,7 @@ pub struct ThreeDsSettings { active: bool, } -#[derive(Debug, Deserialize)] +#[derive(Debug, Deserialize, Serialize)] pub struct GenerateSaleResponse { payme_sale_id: String, } @@ -858,19 +858,19 @@ impl From<SaleStatus> for enums::AttemptStatus { } } -#[derive(Debug, Deserialize)] +#[derive(Debug, Deserialize, Serialize)] #[serde(untagged)] pub enum PaymePaymentsResponse { PaymePaySaleResponse(PaymePaySaleResponse), SaleQueryResponse(SaleQueryResponse), } -#[derive(Clone, Debug, Deserialize)] +#[derive(Clone, Debug, Deserialize, Serialize)] pub struct SaleQueryResponse { items: Vec<SaleQuery>, } -#[derive(Clone, Debug, Deserialize)] +#[derive(Clone, Debug, Deserialize, Serialize)] pub struct SaleQuery { sale_status: SaleStatus, sale_payme_id: String, @@ -978,7 +978,7 @@ impl TryFrom<SaleStatus> for enums::RefundStatus { } } -#[derive(Debug, Deserialize)] +#[derive(Debug, Deserialize, Serialize)] pub struct PaymeRefundResponse { sale_status: SaleStatus, payme_transaction_id: String, diff --git a/crates/router/src/connector/paypal.rs b/crates/router/src/connector/paypal.rs index 742c563407c..38d8b783d5d 100644 --- a/crates/router/src/connector/paypal.rs +++ b/crates/router/src/connector/paypal.rs @@ -21,6 +21,7 @@ use crate::{ errors::{self, CustomResult}, payments, }, + events::connector_api_logs::ConnectorEvent, headers, services::{ self, @@ -59,6 +60,7 @@ impl Paypal { pub fn get_order_error_response( &self, res: Response, + event_builder: Option<&mut ConnectorEvent>, ) -> CustomResult<ErrorResponse, errors::ConnectorError> { //Handled error response separately for Orders as the end point is different for Orders - (Authorize) and Payments - (Capture, void, refund, rsync). //Error response have different fields for Orders and Payments. @@ -67,6 +69,9 @@ impl Paypal { .parse_struct("Paypal ErrorResponse") .change_context(errors::ConnectorError::ResponseDeserializationFailed)?; + event_builder.map(|i| i.set_error_response_body(&response)); + router_env::logger::info!(connector_response=?response); + let error_reason = response.details.map(|order_errors| { order_errors .iter() @@ -207,12 +212,16 @@ impl ConnectorCommon for Paypal { fn build_error_response( &self, res: Response, + event_builder: Option<&mut ConnectorEvent>, ) -> CustomResult<ErrorResponse, errors::ConnectorError> { let response: paypal::PaypalPaymentErrorResponse = res .response .parse_struct("Paypal ErrorResponse") .change_context(errors::ConnectorError::ResponseDeserializationFailed)?; + event_builder.map(|i| i.set_error_response_body(&response)); + router_env::logger::info!(connector_response=?response); + let error_reason = response .details .map(|error_details| { @@ -345,6 +354,7 @@ impl ConnectorIntegration<api::AccessTokenAuth, types::AccessTokenRequestData, t fn handle_response( &self, data: &types::RefreshTokenRouterData, + event_builder: Option<&mut ConnectorEvent>, res: Response, ) -> CustomResult<types::RefreshTokenRouterData, errors::ConnectorError> { let response: paypal::PaypalAuthUpdateResponse = res @@ -352,6 +362,9 @@ impl ConnectorIntegration<api::AccessTokenAuth, types::AccessTokenRequestData, t .parse_struct("Paypal PaypalAuthUpdateResponse") .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(), @@ -362,12 +375,16 @@ impl ConnectorIntegration<api::AccessTokenAuth, types::AccessTokenRequestData, t fn get_error_response( &self, res: Response, + event_builder: Option<&mut ConnectorEvent>, ) -> CustomResult<ErrorResponse, errors::ConnectorError> { let response: paypal::PaypalAccessTokenErrorResponse = res .response .parse_struct("Paypal AccessTokenErrorResponse") .change_context(errors::ConnectorError::ResponseDeserializationFailed)?; + event_builder.map(|i| i.set_error_response_body(&response)); + router_env::logger::info!(connector_response=?response); + Ok(ErrorResponse { status_code: res.status_code, code: response.error, @@ -464,6 +481,7 @@ impl ConnectorIntegration<api::Authorize, types::PaymentsAuthorizeData, types::P fn handle_response( &self, data: &types::PaymentsAuthorizeRouterData, + event_builder: Option<&mut ConnectorEvent>, res: Response, ) -> CustomResult<types::PaymentsAuthorizeRouterData, errors::ConnectorError> { let response: PaypalAuthResponse = @@ -473,6 +491,9 @@ impl ConnectorIntegration<api::Authorize, types::PaymentsAuthorizeData, types::P match response { PaypalAuthResponse::PaypalOrdersResponse(response) => { + 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(), @@ -480,6 +501,8 @@ impl ConnectorIntegration<api::Authorize, types::PaymentsAuthorizeData, types::P }) } PaypalAuthResponse::PaypalRedirectResponse(response) => { + 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(), @@ -487,6 +510,8 @@ impl ConnectorIntegration<api::Authorize, types::PaymentsAuthorizeData, types::P }) } PaypalAuthResponse::PaypalThreeDsResponse(response) => { + 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(), @@ -499,8 +524,9 @@ impl ConnectorIntegration<api::Authorize, types::PaymentsAuthorizeData, types::P fn get_error_response( &self, res: Response, + event_builder: Option<&mut ConnectorEvent>, ) -> CustomResult<ErrorResponse, errors::ConnectorError> { - self.get_order_error_response(res) + self.get_order_error_response(res, event_builder) } } @@ -560,6 +586,7 @@ impl fn handle_response( &self, data: &types::PaymentsPreProcessingRouterData, + event_builder: Option<&mut ConnectorEvent>, res: Response, ) -> CustomResult<types::PaymentsPreProcessingRouterData, errors::ConnectorError> { let response: paypal::PaypalPreProcessingResponse = res @@ -567,6 +594,9 @@ impl .parse_struct("paypal PaypalPreProcessingResponse") .change_context(errors::ConnectorError::ResponseDeserializationFailed)?; + event_builder.map(|i| i.set_response_body(&response)); + router_env::logger::info!(connector_response=?response); + match response { // if card supports 3DS check for liability paypal::PaypalPreProcessingResponse::PaypalLiabilityResponse(liability_response) => { @@ -676,8 +706,9 @@ impl fn get_error_response( &self, res: Response, + event_builder: Option<&mut ConnectorEvent>, ) -> CustomResult<ErrorResponse, errors::ConnectorError> { - self.build_error_response(res) + self.build_error_response(res, event_builder) } } @@ -741,12 +772,15 @@ impl fn handle_response( &self, data: &types::PaymentsCompleteAuthorizeRouterData, + event_builder: Option<&mut ConnectorEvent>, res: Response, ) -> CustomResult<types::PaymentsCompleteAuthorizeRouterData, errors::ConnectorError> { let response: paypal::PaypalOrdersResponse = res .response .parse_struct("paypal PaypalOrdersResponse") .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(), @@ -757,8 +791,9 @@ impl fn get_error_response( &self, res: Response, + event_builder: Option<&mut ConnectorEvent>, ) -> CustomResult<ErrorResponse, errors::ConnectorError> { - self.build_error_response(res) + self.build_error_response(res, event_builder) } } @@ -847,12 +882,15 @@ impl ConnectorIntegration<api::PSync, types::PaymentsSyncData, types::PaymentsRe fn handle_response( &self, data: &types::PaymentsSyncRouterData, + event_builder: Option<&mut ConnectorEvent>, res: Response, ) -> CustomResult<types::PaymentsSyncRouterData, errors::ConnectorError> { let response: paypal::PaypalSyncResponse = res .response .parse_struct("paypal SyncResponse") .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(), @@ -863,8 +901,9 @@ impl ConnectorIntegration<api::PSync, types::PaymentsSyncData, types::PaymentsRe fn get_error_response( &self, res: Response, + event_builder: Option<&mut ConnectorEvent>, ) -> CustomResult<ErrorResponse, errors::ConnectorError> { - self.build_error_response(res) + self.build_error_response(res, event_builder) } } @@ -938,12 +977,15 @@ impl ConnectorIntegration<api::Capture, types::PaymentsCaptureData, types::Payme fn handle_response( &self, data: &types::PaymentsCaptureRouterData, + event_builder: Option<&mut ConnectorEvent>, res: Response, ) -> CustomResult<types::PaymentsCaptureRouterData, errors::ConnectorError> { let response: paypal::PaypalCaptureResponse = res .response .parse_struct("Paypal 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(), @@ -954,8 +996,9 @@ impl ConnectorIntegration<api::Capture, types::PaymentsCaptureData, types::Payme fn get_error_response( &self, res: Response, + event_builder: Option<&mut ConnectorEvent>, ) -> CustomResult<ErrorResponse, errors::ConnectorError> { - self.build_error_response(res) + self.build_error_response(res, event_builder) } } @@ -1009,12 +1052,15 @@ impl ConnectorIntegration<api::Void, types::PaymentsCancelData, types::PaymentsR fn handle_response( &self, data: &types::PaymentsCancelRouterData, + event_builder: Option<&mut ConnectorEvent>, res: Response, ) -> CustomResult<types::PaymentsCancelRouterData, errors::ConnectorError> { let response: paypal::PaypalPaymentsCancelResponse = res .response .parse_struct("PaymentCancelResponse") .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(), @@ -1024,8 +1070,9 @@ impl ConnectorIntegration<api::Void, types::PaymentsCancelData, types::PaymentsR fn get_error_response( &self, res: Response, + event_builder: Option<&mut ConnectorEvent>, ) -> CustomResult<ErrorResponse, errors::ConnectorError> { - self.build_error_response(res) + self.build_error_response(res, event_builder) } } @@ -1097,12 +1144,15 @@ impl ConnectorIntegration<api::Execute, types::RefundsData, types::RefundsRespon 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: paypal::RefundResponse = res.response .parse_struct("paypal 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(), @@ -1113,8 +1163,9 @@ impl ConnectorIntegration<api::Execute, types::RefundsData, types::RefundsRespon fn get_error_response( &self, res: Response, + event_builder: Option<&mut ConnectorEvent>, ) -> CustomResult<ErrorResponse, errors::ConnectorError> { - self.build_error_response(res) + self.build_error_response(res, event_builder) } } @@ -1160,12 +1211,15 @@ impl ConnectorIntegration<api::RSync, types::RefundsData, types::RefundsResponse fn handle_response( &self, data: &types::RefundSyncRouterData, + event_builder: Option<&mut ConnectorEvent>, res: Response, ) -> CustomResult<types::RefundSyncRouterData, errors::ConnectorError> { let response: paypal::RefundSyncResponse = res .response .parse_struct("paypal 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(), @@ -1176,8 +1230,9 @@ impl ConnectorIntegration<api::RSync, types::RefundsData, types::RefundsResponse fn get_error_response( &self, res: Response, + event_builder: Option<&mut ConnectorEvent>, ) -> CustomResult<ErrorResponse, errors::ConnectorError> { - self.build_error_response(res) + self.build_error_response(res, event_builder) } } @@ -1268,12 +1323,15 @@ impl fn handle_response( &self, data: &types::VerifyWebhookSourceRouterData, + event_builder: Option<&mut ConnectorEvent>, res: Response, ) -> CustomResult<types::VerifyWebhookSourceRouterData, errors::ConnectorError> { let response: paypal::PaypalSourceVerificationResponse = res .response .parse_struct("paypal PaypalSourceVerificationResponse") .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(), @@ -1283,8 +1341,9 @@ impl fn get_error_response( &self, res: Response, + event_builder: Option<&mut ConnectorEvent>, ) -> CustomResult<ErrorResponse, errors::ConnectorError> { - self.build_error_response(res) + self.build_error_response(res, event_builder) } } diff --git a/crates/router/src/connector/paypal/transformers.rs b/crates/router/src/connector/paypal/transformers.rs index 1447cf75be7..a584fe98165 100644 --- a/crates/router/src/connector/paypal/transformers.rs +++ b/crates/router/src/connector/paypal/transformers.rs @@ -762,7 +762,7 @@ impl TryFrom<&types::RefreshTokenRouterData> for PaypalAuthUpdateRequest { } } -#[derive(Default, Debug, Clone, Deserialize, PartialEq)] +#[derive(Default, Debug, Clone, Deserialize, PartialEq, Serialize)] pub struct PaypalAuthUpdateResponse { pub access_token: Secret<String>, pub token_type: String, @@ -1063,7 +1063,7 @@ pub enum PaypalAuthResponse { } // Note: Don't change order of deserialization of variant, priority is in descending order -#[derive(Debug, Deserialize)] +#[derive(Debug, Deserialize, Serialize)] #[serde(untagged)] pub enum PaypalSyncResponse { PaypalOrdersSyncResponse(PaypalOrdersResponse), @@ -1742,7 +1742,7 @@ pub struct PaypalPaymentErrorResponse { pub details: Option<Vec<ErrorDetails>>, } -#[derive(Deserialize, Debug)] +#[derive(Deserialize, Debug, Serialize)] pub struct PaypalAccessTokenErrorResponse { pub error: String, pub error_description: String, diff --git a/crates/router/src/connector/payu.rs b/crates/router/src/connector/payu.rs index c44b4d5d6ff..bd850cf1e89 100644 --- a/crates/router/src/connector/payu.rs +++ b/crates/router/src/connector/payu.rs @@ -12,6 +12,7 @@ use crate::{ configs::settings, connector::utils as connector_utils, core::errors::{self, CustomResult}, + events::connector_api_logs::ConnectorEvent, headers, services::{ self, @@ -86,12 +87,16 @@ impl ConnectorCommon for Payu { fn build_error_response( &self, res: types::Response, + event_builder: Option<&mut ConnectorEvent>, ) -> CustomResult<ErrorResponse, errors::ConnectorError> { let response: payu::PayuErrorResponse = res .response .parse_struct("Payu ErrorResponse") .change_context(errors::ConnectorError::ResponseDeserializationFailed)?; + event_builder.map(|i| i.set_error_response_body(&response)); + router_env::logger::info!(connector_response=?response); + Ok(ErrorResponse { status_code: res.status_code, code: response.status.status_code, @@ -202,12 +207,17 @@ impl ConnectorIntegration<api::Void, types::PaymentsCancelData, types::PaymentsR fn handle_response( &self, data: &types::PaymentsCancelRouterData, + event_builder: Option<&mut ConnectorEvent>, res: types::Response, ) -> CustomResult<types::PaymentsCancelRouterData, errors::ConnectorError> { let response: payu::PayuPaymentsCancelResponse = res .response .parse_struct("PaymentCancelResponse") .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(), @@ -218,8 +228,9 @@ impl ConnectorIntegration<api::Void, types::PaymentsCancelData, types::PaymentsR fn get_error_response( &self, res: types::Response, + event_builder: Option<&mut ConnectorEvent>, ) -> CustomResult<ErrorResponse, errors::ConnectorError> { - self.build_error_response(res) + self.build_error_response(res, event_builder) } } @@ -289,6 +300,7 @@ impl ConnectorIntegration<api::AccessTokenAuth, types::AccessTokenRequestData, t fn handle_response( &self, data: &types::RefreshTokenRouterData, + event_builder: Option<&mut ConnectorEvent>, res: types::Response, ) -> CustomResult<types::RefreshTokenRouterData, errors::ConnectorError> { let response: payu::PayuAuthUpdateResponse = res @@ -296,6 +308,9 @@ impl ConnectorIntegration<api::AccessTokenAuth, types::AccessTokenRequestData, t .parse_struct("payu PayuAuthUpdateResponse") .change_context(errors::ConnectorError::ResponseDeserializationFailed)?; + event_builder.map(|i| i.set_response_body(&response)); + router_env::logger::info!(connector_response=?response); + types::ResponseRouterData { response, data: data.clone(), @@ -308,12 +323,16 @@ impl ConnectorIntegration<api::AccessTokenAuth, types::AccessTokenRequestData, t fn get_error_response( &self, res: types::Response, + event_builder: Option<&mut ConnectorEvent>, ) -> CustomResult<ErrorResponse, errors::ConnectorError> { let response: payu::PayuAccessTokenErrorResponse = res .response .parse_struct("Payu AccessTokenErrorResponse") .change_context(errors::ConnectorError::ResponseDeserializationFailed)?; + event_builder.map(|i| i.set_error_response_body(&response)); + router_env::logger::info!(connector_response=?response); + Ok(ErrorResponse { status_code: res.status_code, code: response.error, @@ -377,12 +396,15 @@ impl ConnectorIntegration<api::PSync, types::PaymentsSyncData, types::PaymentsRe fn handle_response( &self, data: &types::PaymentsSyncRouterData, + event_builder: Option<&mut ConnectorEvent>, res: types::Response, ) -> CustomResult<types::PaymentsSyncRouterData, errors::ConnectorError> { let response: payu::PayuPaymentsSyncResponse = res .response .parse_struct("payu OrderResponse") .change_context(errors::ConnectorError::ResponseDeserializationFailed)?; + event_builder.map(|i| i.set_response_body(&response)); + router_env::logger::info!(connector_response=?response); types::ResponseRouterData { response, data: data.clone(), @@ -395,8 +417,9 @@ impl ConnectorIntegration<api::PSync, types::PaymentsSyncData, types::PaymentsRe fn get_error_response( &self, res: types::Response, + event_builder: Option<&mut ConnectorEvent>, ) -> CustomResult<ErrorResponse, errors::ConnectorError> { - self.build_error_response(res) + self.build_error_response(res, event_builder) } } @@ -462,12 +485,15 @@ impl ConnectorIntegration<api::Capture, types::PaymentsCaptureData, types::Payme fn handle_response( &self, data: &types::PaymentsCaptureRouterData, + event_builder: Option<&mut ConnectorEvent>, res: types::Response, ) -> CustomResult<types::PaymentsCaptureRouterData, errors::ConnectorError> { let response: payu::PayuPaymentsCaptureResponse = res .response .parse_struct("payu CaptureResponse") .change_context(errors::ConnectorError::RequestEncodingFailed)?; + event_builder.map(|i| i.set_response_body(&response)); + router_env::logger::info!(connector_response=?response); types::ResponseRouterData { response, data: data.clone(), @@ -480,8 +506,9 @@ impl ConnectorIntegration<api::Capture, types::PaymentsCaptureData, types::Payme fn get_error_response( &self, res: types::Response, + event_builder: Option<&mut ConnectorEvent>, ) -> CustomResult<ErrorResponse, errors::ConnectorError> { - self.build_error_response(res) + self.build_error_response(res, event_builder) } } @@ -560,12 +587,15 @@ impl ConnectorIntegration<api::Authorize, types::PaymentsAuthorizeData, types::P fn handle_response( &self, data: &types::PaymentsAuthorizeRouterData, + event_builder: Option<&mut ConnectorEvent>, res: types::Response, ) -> CustomResult<types::PaymentsAuthorizeRouterData, errors::ConnectorError> { let response: payu::PayuPaymentsResponse = res .response .parse_struct("PayuPaymentsResponse") .change_context(errors::ConnectorError::ResponseDeserializationFailed)?; + event_builder.map(|i| i.set_response_body(&response)); + router_env::logger::info!(connector_response=?response); types::ResponseRouterData { response, data: data.clone(), @@ -578,8 +608,9 @@ impl ConnectorIntegration<api::Authorize, types::PaymentsAuthorizeData, types::P fn get_error_response( &self, res: types::Response, + event_builder: Option<&mut ConnectorEvent>, ) -> CustomResult<ErrorResponse, errors::ConnectorError> { - self.build_error_response(res) + self.build_error_response(res, event_builder) } } @@ -645,12 +676,15 @@ impl ConnectorIntegration<api::Execute, types::RefundsData, types::RefundsRespon fn handle_response( &self, data: &types::RefundsRouterData<api::Execute>, + event_builder: Option<&mut ConnectorEvent>, res: types::Response, ) -> CustomResult<types::RefundsRouterData<api::Execute>, errors::ConnectorError> { let response: payu::RefundResponse = res .response .parse_struct("payu RefundResponse") .change_context(errors::ConnectorError::RequestEncodingFailed)?; + event_builder.map(|i| i.set_response_body(&response)); + router_env::logger::info!(connector_response=?response); types::ResponseRouterData { response, data: data.clone(), @@ -663,8 +697,9 @@ impl ConnectorIntegration<api::Execute, types::RefundsData, types::RefundsRespon fn get_error_response( &self, res: types::Response, + event_builder: Option<&mut ConnectorEvent>, ) -> CustomResult<ErrorResponse, errors::ConnectorError> { - self.build_error_response(res) + self.build_error_response(res, event_builder) } } @@ -713,12 +748,15 @@ impl ConnectorIntegration<api::RSync, types::RefundsData, types::RefundsResponse fn handle_response( &self, data: &types::RefundSyncRouterData, + event_builder: Option<&mut ConnectorEvent>, res: types::Response, ) -> CustomResult<types::RefundSyncRouterData, errors::ConnectorError> { let response: payu::RefundSyncResponse = res.response .parse_struct("payu RefundResponse") .change_context(errors::ConnectorError::ResponseDeserializationFailed)?; + event_builder.map(|i| i.set_response_body(&response)); + router_env::logger::info!(connector_response=?response); types::ResponseRouterData { response, data: data.clone(), @@ -731,8 +769,9 @@ impl ConnectorIntegration<api::RSync, types::RefundsData, types::RefundsResponse fn get_error_response( &self, res: types::Response, + event_builder: Option<&mut ConnectorEvent>, ) -> CustomResult<ErrorResponse, errors::ConnectorError> { - self.build_error_response(res) + self.build_error_response(res, event_builder) } } diff --git a/crates/router/src/connector/payu/transformers.rs b/crates/router/src/connector/payu/transformers.rs index 6edc570eb45..e3ad6f8b426 100644 --- a/crates/router/src/connector/payu/transformers.rs +++ b/crates/router/src/connector/payu/transformers.rs @@ -172,7 +172,7 @@ impl From<PayuPaymentStatus> for enums::AttemptStatus { } } -#[derive(Debug, Clone, Deserialize, PartialEq)] +#[derive(Debug, Clone, Deserialize, PartialEq, Serialize)] #[serde(rename_all = "camelCase")] pub struct PayuPaymentsResponse { pub status: PayuPaymentStatusData, @@ -230,7 +230,7 @@ impl TryFrom<&types::PaymentsCaptureRouterData> for PayuPaymentsCaptureRequest { } } -#[derive(Default, Debug, Clone, Deserialize, PartialEq)] +#[derive(Default, Debug, Clone, Deserialize, PartialEq, Serialize)] pub struct PayuPaymentsCaptureResponse { status: PayuPaymentStatusData, } @@ -283,7 +283,7 @@ impl TryFrom<&types::RefreshTokenRouterData> for PayuAuthUpdateRequest { }) } } -#[derive(Default, Debug, Clone, Deserialize, PartialEq)] +#[derive(Default, Debug, Clone, Deserialize, PartialEq, Serialize)] pub struct PayuAuthUpdateResponse { pub access_token: Secret<String>, pub token_type: String, @@ -394,7 +394,7 @@ pub struct PayuProductData { listing_date: Option<String>, } -#[derive(Debug, Clone, Deserialize, PartialEq)] +#[derive(Debug, Clone, Deserialize, PartialEq, Serialize)] #[serde(rename_all = "camelCase")] pub struct PayuOrderResponseData { order_id: String, @@ -428,7 +428,7 @@ pub struct PayuOrderResponseBuyerData { customer_id: Option<String>, } -#[derive(Debug, Clone, Deserialize, PartialEq)] +#[derive(Debug, Clone, Deserialize, PartialEq, Serialize)] #[serde(tag = "type", rename_all = "SCREAMING_SNAKE_CASE")] pub enum PayuOrderResponsePayMethod { CardToken, @@ -442,7 +442,7 @@ pub struct PayuOrderResponseProperty { value: String, } -#[derive(Default, Debug, Clone, Deserialize, PartialEq)] +#[derive(Default, Debug, Clone, Deserialize, PartialEq, Serialize)] pub struct PayuPaymentsSyncResponse { orders: Vec<PayuOrderResponseData>, status: PayuPaymentStatusData, @@ -542,7 +542,7 @@ impl From<RefundStatus> for enums::RefundStatus { } } -#[derive(Default, Debug, Clone, Eq, PartialEq, Deserialize)] +#[derive(Default, Debug, Clone, Eq, PartialEq, Deserialize, Serialize)] #[serde(rename_all = "camelCase")] pub struct PayuRefundResponseData { refund_id: String, @@ -555,7 +555,7 @@ pub struct PayuRefundResponseData { status_date_time: Option<String>, } -#[derive(Default, Debug, Clone, Deserialize)] +#[derive(Default, Debug, Clone, Deserialize, Serialize)] #[serde(rename_all = "camelCase")] pub struct RefundResponse { refund: PayuRefundResponseData, @@ -579,7 +579,7 @@ impl TryFrom<types::RefundsResponseRouterData<api::Execute, RefundResponse>> } } -#[derive(Default, Debug, Clone, Deserialize)] +#[derive(Default, Debug, Clone, Deserialize, Serialize)] pub struct RefundSyncResponse { refunds: Vec<PayuRefundResponseData>, } @@ -617,7 +617,7 @@ pub struct PayuErrorResponse { pub status: PayuErrorData, } -#[derive(Deserialize, Debug)] +#[derive(Deserialize, Debug, Serialize)] pub struct PayuAccessTokenErrorResponse { pub error: String, pub error_description: String, diff --git a/crates/router/src/connector/placetopay.rs b/crates/router/src/connector/placetopay.rs index ef51f1d6e4b..ab33bf1039d 100644 --- a/crates/router/src/connector/placetopay.rs +++ b/crates/router/src/connector/placetopay.rs @@ -10,6 +10,7 @@ use crate::{ configs::settings, connector::utils::{self}, core::errors::{self, CustomResult}, + events::connector_api_logs::ConnectorEvent, headers, services::{ self, @@ -89,12 +90,16 @@ impl ConnectorCommon for Placetopay { fn build_error_response( &self, res: Response, + event_builder: Option<&mut ConnectorEvent>, ) -> CustomResult<ErrorResponse, errors::ConnectorError> { let response: placetopay::PlacetopayErrorResponse = res .response .parse_struct("PlacetopayErrorResponse") .change_context(errors::ConnectorError::ResponseDeserializationFailed)?; + event_builder.map(|i| i.set_error_response_body(&response)); + router_env::logger::info!(connector_response=?response); + Ok(ErrorResponse { status_code: res.status_code, code: response.status.reason.to_owned(), @@ -220,12 +225,17 @@ impl ConnectorIntegration<api::Authorize, types::PaymentsAuthorizeData, types::P fn handle_response( &self, data: &types::PaymentsAuthorizeRouterData, + event_builder: Option<&mut ConnectorEvent>, res: Response, ) -> CustomResult<types::PaymentsAuthorizeRouterData, errors::ConnectorError> { let response: placetopay::PlacetopayPaymentsResponse = res .response .parse_struct("Placetopay PlacetopayPaymentsResponse") .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(), @@ -236,8 +246,9 @@ impl ConnectorIntegration<api::Authorize, types::PaymentsAuthorizeData, types::P fn get_error_response( &self, res: Response, + event_builder: Option<&mut ConnectorEvent>, ) -> CustomResult<ErrorResponse, errors::ConnectorError> { - self.build_error_response(res) + self.build_error_response(res, event_builder) } } @@ -294,12 +305,17 @@ impl ConnectorIntegration<api::PSync, types::PaymentsSyncData, types::PaymentsRe fn handle_response( &self, data: &types::PaymentsSyncRouterData, + event_builder: Option<&mut ConnectorEvent>, res: Response, ) -> CustomResult<types::PaymentsSyncRouterData, errors::ConnectorError> { let response: placetopay::PlacetopayPaymentsResponse = res .response .parse_struct("placetopay 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(), @@ -310,8 +326,9 @@ impl ConnectorIntegration<api::PSync, types::PaymentsSyncData, types::PaymentsRe fn get_error_response( &self, res: Response, + event_builder: Option<&mut ConnectorEvent>, ) -> CustomResult<ErrorResponse, errors::ConnectorError> { - self.build_error_response(res) + self.build_error_response(res, event_builder) } } @@ -370,12 +387,17 @@ impl ConnectorIntegration<api::Capture, types::PaymentsCaptureData, types::Payme fn handle_response( &self, data: &types::PaymentsCaptureRouterData, + event_builder: Option<&mut ConnectorEvent>, res: Response, ) -> CustomResult<types::PaymentsCaptureRouterData, errors::ConnectorError> { let response: placetopay::PlacetopayPaymentsResponse = res .response .parse_struct("Placetopay 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(), @@ -386,8 +408,9 @@ impl ConnectorIntegration<api::Capture, types::PaymentsCaptureData, types::Payme fn get_error_response( &self, res: Response, + event_builder: Option<&mut ConnectorEvent>, ) -> CustomResult<ErrorResponse, errors::ConnectorError> { - self.build_error_response(res) + self.build_error_response(res, event_builder) } } @@ -444,12 +467,17 @@ impl ConnectorIntegration<api::Void, types::PaymentsCancelData, types::PaymentsR fn handle_response( &self, data: &types::PaymentsCancelRouterData, + event_builder: Option<&mut ConnectorEvent>, res: Response, ) -> CustomResult<types::PaymentsCancelRouterData, errors::ConnectorError> { let response: placetopay::PlacetopayPaymentsResponse = res .response .parse_struct("Placetopay PaymentCancelResponse") .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(), @@ -460,8 +488,9 @@ impl ConnectorIntegration<api::Void, types::PaymentsCancelData, types::PaymentsR fn get_error_response( &self, res: Response, + event_builder: Option<&mut ConnectorEvent>, ) -> CustomResult<ErrorResponse, errors::ConnectorError> { - self.build_error_response(res) + self.build_error_response(res, event_builder) } } @@ -519,12 +548,17 @@ impl ConnectorIntegration<api::Execute, types::RefundsData, types::RefundsRespon 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: placetopay::PlacetopayRefundResponse = res .response .parse_struct("placetopay PlacetopayRefundResponse") .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(), @@ -535,8 +569,9 @@ impl ConnectorIntegration<api::Execute, types::RefundsData, types::RefundsRespon fn get_error_response( &self, res: Response, + event_builder: Option<&mut ConnectorEvent>, ) -> CustomResult<ErrorResponse, errors::ConnectorError> { - self.build_error_response(res) + self.build_error_response(res, event_builder) } } @@ -593,12 +628,17 @@ impl ConnectorIntegration<api::RSync, types::RefundsData, types::RefundsResponse fn handle_response( &self, data: &types::RefundSyncRouterData, + event_builder: Option<&mut ConnectorEvent>, res: Response, ) -> CustomResult<types::RefundSyncRouterData, errors::ConnectorError> { let response: placetopay::PlacetopayRefundResponse = res .response .parse_struct("placetopay PlacetopayRefundResponse") .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(), @@ -609,8 +649,9 @@ impl ConnectorIntegration<api::RSync, types::RefundsData, types::RefundsResponse fn get_error_response( &self, res: Response, + event_builder: Option<&mut ConnectorEvent>, ) -> CustomResult<ErrorResponse, errors::ConnectorError> { - self.build_error_response(res) + self.build_error_response(res, event_builder) } } diff --git a/crates/router/src/connector/placetopay/transformers.rs b/crates/router/src/connector/placetopay/transformers.rs index dfdd3f904df..f1c054b960b 100644 --- a/crates/router/src/connector/placetopay/transformers.rs +++ b/crates/router/src/connector/placetopay/transformers.rs @@ -204,7 +204,7 @@ impl TryFrom<&types::ConnectorAuthType> for PlacetopayAuthType { } } -#[derive(Debug, Clone, Deserialize)] +#[derive(Debug, Clone, Deserialize, Serialize)] #[serde(rename_all = "SCREAMING_SNAKE_CASE")] pub enum PlacetopayStatus { Ok, @@ -216,7 +216,7 @@ pub enum PlacetopayStatus { PendingProcess, } -#[derive(Debug, Deserialize)] +#[derive(Debug, Deserialize, Serialize)] #[serde(rename_all = "camelCase")] pub struct PlacetopayStatusResponse { status: PlacetopayStatus, @@ -234,7 +234,7 @@ impl From<PlacetopayStatus> for enums::AttemptStatus { } } -#[derive(Debug, Deserialize)] +#[derive(Debug, Deserialize, Serialize)] #[serde(rename_all = "camelCase")] pub struct PlacetopayPaymentsResponse { status: PlacetopayStatusResponse, @@ -315,14 +315,14 @@ impl From<PlacetopayRefundStatus> for enums::RefundStatus { } } -#[derive(Debug, Deserialize)] +#[derive(Debug, Deserialize, Serialize)] #[serde(rename_all = "camelCase")] pub struct PlacetopayRefundResponse { status: PlacetopayRefundStatus, internal_reference: u64, } -#[derive(Debug, Deserialize)] +#[derive(Debug, Deserialize, Serialize)] #[serde(rename_all = "SCREAMING_SNAKE_CASE")] pub enum PlacetopayRefundStatus { Refunded, @@ -390,13 +390,13 @@ impl TryFrom<types::RefundsResponseRouterData<api::RSync, PlacetopayRefundRespon } } -#[derive(Debug, Deserialize)] +#[derive(Debug, Deserialize, Serialize)] #[serde(rename_all = "camelCase")] pub struct PlacetopayErrorResponse { pub status: PlacetopayError, } -#[derive(Debug, Deserialize)] +#[derive(Debug, Deserialize, Serialize)] #[serde(rename_all = "camelCase")] pub struct PlacetopayError { pub status: PlacetopayErrorStatus, @@ -404,7 +404,7 @@ pub struct PlacetopayError { pub reason: String, } -#[derive(Debug, Deserialize)] +#[derive(Debug, Deserialize, Serialize)] #[serde(rename_all = "SCREAMING_SNAKE_CASE")] pub enum PlacetopayErrorStatus { Failed, diff --git a/crates/router/src/connector/powertranz.rs b/crates/router/src/connector/powertranz.rs index 654128bb3fd..5023f6b743a 100644 --- a/crates/router/src/connector/powertranz.rs +++ b/crates/router/src/connector/powertranz.rs @@ -16,6 +16,7 @@ use crate::{ configs::settings, consts, core::errors::{self, CustomResult}, + events::connector_api_logs::ConnectorEvent, headers, services::{ self, @@ -112,9 +113,12 @@ impl ConnectorCommon for Powertranz { fn build_error_response( &self, res: Response, + event_builder: Option<&mut ConnectorEvent>, ) -> CustomResult<ErrorResponse, errors::ConnectorError> { // For error scenerios connector respond with 200 http status code and error response object in response // For http status code other than 200 they send empty response back + event_builder.map(|i: &mut ConnectorEvent| i.set_error_response_body(&serde_json::json!({"error_response": std::str::from_utf8(&res.response).unwrap_or("")}))); + Ok(ErrorResponse { status_code: res.status_code, code: consts::NO_ERROR_CODE.to_string(), @@ -240,12 +244,17 @@ impl ConnectorIntegration<api::Authorize, types::PaymentsAuthorizeData, types::P fn handle_response( &self, data: &types::PaymentsAuthorizeRouterData, + event_builder: Option<&mut ConnectorEvent>, res: Response, ) -> CustomResult<types::PaymentsAuthorizeRouterData, errors::ConnectorError> { let response: powertranz::PowertranzBaseResponse = res .response .parse_struct("Powertranz 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(), @@ -256,8 +265,9 @@ impl ConnectorIntegration<api::Authorize, types::PaymentsAuthorizeData, types::P fn get_error_response( &self, res: Response, + event_builder: Option<&mut ConnectorEvent>, ) -> CustomResult<ErrorResponse, errors::ConnectorError> { - self.build_error_response(res) + self.build_error_response(res, event_builder) } } @@ -327,12 +337,17 @@ impl fn handle_response( &self, data: &types::PaymentsCompleteAuthorizeRouterData, + event_builder: Option<&mut ConnectorEvent>, res: Response, ) -> CustomResult<types::PaymentsCompleteAuthorizeRouterData, errors::ConnectorError> { let response: powertranz::PowertranzBaseResponse = res .response .parse_struct("Powertranz PaymentsCompleteAuthorizeResponse") .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(), @@ -343,8 +358,9 @@ impl fn get_error_response( &self, res: Response, + event_builder: Option<&mut ConnectorEvent>, ) -> CustomResult<ErrorResponse, errors::ConnectorError> { - self.build_error_response(res) + self.build_error_response(res, event_builder) } } @@ -409,12 +425,17 @@ impl ConnectorIntegration<api::Capture, types::PaymentsCaptureData, types::Payme fn handle_response( &self, data: &types::PaymentsCaptureRouterData, + event_builder: Option<&mut ConnectorEvent>, res: Response, ) -> CustomResult<types::PaymentsCaptureRouterData, errors::ConnectorError> { let response: powertranz::PowertranzBaseResponse = res .response .parse_struct("Powertranz 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(), @@ -425,8 +446,9 @@ impl ConnectorIntegration<api::Capture, types::PaymentsCaptureData, types::Payme fn get_error_response( &self, res: Response, + event_builder: Option<&mut ConnectorEvent>, ) -> CustomResult<ErrorResponse, errors::ConnectorError> { - self.build_error_response(res) + self.build_error_response(res, event_builder) } } @@ -461,12 +483,17 @@ impl ConnectorIntegration<api::Void, types::PaymentsCancelData, types::PaymentsR fn handle_response( &self, data: &types::RouterData<api::Void, types::PaymentsCancelData, types::PaymentsResponseData>, + event_builder: Option<&mut ConnectorEvent>, res: Response, ) -> CustomResult<types::PaymentsCancelRouterData, errors::ConnectorError> { let response: powertranz::PowertranzBaseResponse = res .response .parse_struct("powertranz CancelResponse") .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(), @@ -495,8 +522,9 @@ impl ConnectorIntegration<api::Void, types::PaymentsCancelData, types::PaymentsR fn get_error_response( &self, res: Response, + event_builder: Option<&mut ConnectorEvent>, ) -> CustomResult<ErrorResponse, errors::ConnectorError> { - self.build_error_response(res) + self.build_error_response(res, event_builder) } } @@ -554,12 +582,17 @@ impl ConnectorIntegration<api::Execute, types::RefundsData, types::RefundsRespon 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: powertranz::PowertranzBaseResponse = res .response .parse_struct("powertranz 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(), @@ -570,8 +603,9 @@ impl ConnectorIntegration<api::Execute, types::RefundsData, types::RefundsRespon fn get_error_response( &self, res: Response, + event_builder: Option<&mut ConnectorEvent>, ) -> CustomResult<ErrorResponse, errors::ConnectorError> { - self.build_error_response(res) + self.build_error_response(res, event_builder) } } diff --git a/crates/router/src/connector/powertranz/transformers.rs b/crates/router/src/connector/powertranz/transformers.rs index 8dc3688da9e..54849f8bf1d 100644 --- a/crates/router/src/connector/powertranz/transformers.rs +++ b/crates/router/src/connector/powertranz/transformers.rs @@ -247,7 +247,7 @@ impl TryFrom<&types::ConnectorAuthType> for PowertranzAuthType { } // Common struct used in Payment, Capture, Void, Refund -#[derive(Debug, Deserialize)] +#[derive(Debug, Deserialize, Serialize)] #[serde(rename_all = "PascalCase")] pub struct PowertranzBaseResponse { transaction_type: u8, @@ -475,7 +475,7 @@ pub struct PowertranzErrorResponse { pub errors: Vec<Error>, } -#[derive(Debug, Deserialize)] +#[derive(Debug, Deserialize, Serialize)] #[serde(rename_all = "PascalCase")] pub struct Error { pub code: String, diff --git a/crates/router/src/connector/prophetpay.rs b/crates/router/src/connector/prophetpay.rs index fc14f37a2b2..04b3e7b6d65 100644 --- a/crates/router/src/connector/prophetpay.rs +++ b/crates/router/src/connector/prophetpay.rs @@ -12,6 +12,7 @@ use crate::{ configs::settings, consts, core::errors::{self, CustomResult}, + events::connector_api_logs::ConnectorEvent, headers, services::{ self, @@ -107,11 +108,16 @@ impl ConnectorCommon for Prophetpay { fn build_error_response( &self, res: Response, + event_builder: Option<&mut ConnectorEvent>, ) -> CustomResult<ErrorResponse, errors::ConnectorError> { let response: serde_json::Value = res .response .parse_struct("ProphetPayErrorResponse") .change_context(errors::ConnectorError::ResponseDeserializationFailed)?; + + event_builder.map(|i| i.set_error_response_body(&response)); + router_env::logger::info!(connector_response=?response); + Ok(ErrorResponse { status_code: res.status_code, code: consts::NO_ERROR_CODE.to_string(), @@ -228,6 +234,7 @@ impl ConnectorIntegration<api::Authorize, types::PaymentsAuthorizeData, types::P fn handle_response( &self, data: &types::PaymentsAuthorizeRouterData, + event_builder: Option<&mut ConnectorEvent>, res: Response, ) -> CustomResult<types::PaymentsAuthorizeRouterData, errors::ConnectorError> where @@ -238,6 +245,9 @@ impl ConnectorIntegration<api::Authorize, types::PaymentsAuthorizeData, types::P .parse_struct("prophetpay ProphetpayTokenResponse") .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(), @@ -248,8 +258,9 @@ impl ConnectorIntegration<api::Authorize, types::PaymentsAuthorizeData, types::P fn get_error_response( &self, res: Response, + event_builder: Option<&mut ConnectorEvent>, ) -> CustomResult<ErrorResponse, errors::ConnectorError> { - self.build_error_response(res) + self.build_error_response(res, event_builder) } } @@ -325,6 +336,7 @@ impl fn handle_response( &self, data: &types::PaymentsCompleteAuthorizeRouterData, + event_builder: Option<&mut ConnectorEvent>, res: Response, ) -> CustomResult<types::PaymentsCompleteAuthorizeRouterData, errors::ConnectorError> where @@ -334,6 +346,10 @@ impl .response .parse_struct("prophetpay ProphetpayResponse") .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(), @@ -344,8 +360,9 @@ impl fn get_error_response( &self, res: Response, + event_builder: Option<&mut ConnectorEvent>, ) -> CustomResult<ErrorResponse, errors::ConnectorError> { - self.build_error_response(res) + self.build_error_response(res, event_builder) } } @@ -406,12 +423,17 @@ impl ConnectorIntegration<api::PSync, types::PaymentsSyncData, types::PaymentsRe fn handle_response( &self, data: &types::PaymentsSyncRouterData, + event_builder: Option<&mut ConnectorEvent>, res: Response, ) -> CustomResult<types::PaymentsSyncRouterData, errors::ConnectorError> { let response: prophetpay::ProphetpaySyncResponse = res .response .parse_struct("prophetpay 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(), @@ -422,8 +444,9 @@ impl ConnectorIntegration<api::PSync, types::PaymentsSyncData, types::PaymentsRe fn get_error_response( &self, res: Response, + event_builder: Option<&mut ConnectorEvent>, ) -> CustomResult<ErrorResponse, errors::ConnectorError> { - self.build_error_response(res) + self.build_error_response(res, event_builder) } } @@ -500,8 +523,9 @@ impl ConnectorIntegration<api::Void, types::PaymentsCancelData, types::PaymentsR fn get_error_response( &self, res: Response, + event_builder: Option<&mut ConnectorEvent> ) -> CustomResult<ErrorResponse, errors::ConnectorError> { - self.build_error_response(res) + self.build_error_response(res,event_builder) } */ } @@ -569,6 +593,7 @@ impl ConnectorIntegration<api::Execute, types::RefundsData, types::RefundsRespon 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: prophetpay::ProphetpayRefundResponse = res @@ -576,6 +601,9 @@ impl ConnectorIntegration<api::Execute, types::RefundsData, types::RefundsRespon .parse_struct("prophetpay ProphetpayRefundResponse") .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(), @@ -586,8 +614,9 @@ impl ConnectorIntegration<api::Execute, types::RefundsData, types::RefundsRespon fn get_error_response( &self, res: Response, + event_builder: Option<&mut ConnectorEvent>, ) -> CustomResult<ErrorResponse, errors::ConnectorError> { - self.build_error_response(res) + self.build_error_response(res, event_builder) } } @@ -648,12 +677,17 @@ impl ConnectorIntegration<api::RSync, types::RefundsData, types::RefundsResponse fn handle_response( &self, data: &types::RefundSyncRouterData, + event_builder: Option<&mut ConnectorEvent>, res: Response, ) -> CustomResult<types::RefundSyncRouterData, errors::ConnectorError> { let response: prophetpay::ProphetpayRefundSyncResponse = res .response .parse_struct("prophetpay ProphetpayRefundResponse") .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(), @@ -664,8 +698,9 @@ impl ConnectorIntegration<api::RSync, types::RefundsData, types::RefundsResponse fn get_error_response( &self, res: Response, + event_builder: Option<&mut ConnectorEvent>, ) -> CustomResult<ErrorResponse, errors::ConnectorError> { - self.build_error_response(res) + self.build_error_response(res, event_builder) } } diff --git a/crates/router/src/connector/prophetpay/transformers.rs b/crates/router/src/connector/prophetpay/transformers.rs index 23cffa3da22..b3b641b6d24 100644 --- a/crates/router/src/connector/prophetpay/transformers.rs +++ b/crates/router/src/connector/prophetpay/transformers.rs @@ -169,7 +169,7 @@ impl TryFrom<&ProphetpayRouterData<&types::PaymentsAuthorizeRouterData>> } } -#[derive(Debug, Clone, Deserialize)] +#[derive(Debug, Clone, Deserialize, Serialize)] #[serde(rename_all = "camelCase")] pub struct ProphetpayTokenResponse { hosted_tokenize_id: String, @@ -366,7 +366,7 @@ impl TryFrom<&types::PaymentsSyncRouterData> for ProphetpaySyncRequest { } } -#[derive(Debug, Clone, Deserialize)] +#[derive(Debug, Clone, Deserialize, Serialize)] #[serde(rename_all = "camelCase")] pub struct ProphetpayCompleteAuthResponse { pub success: bool, @@ -438,7 +438,7 @@ impl<F> } } -#[derive(Debug, Clone, Deserialize)] +#[derive(Debug, Clone, Deserialize, Serialize)] #[serde(rename_all = "camelCase")] pub struct ProphetpaySyncResponse { success: bool, @@ -601,7 +601,7 @@ impl<F> TryFrom<&ProphetpayRouterData<&types::RefundsRouterData<F>>> for Prophet } } -#[derive(Debug, Clone, Deserialize)] +#[derive(Debug, Clone, Deserialize, Serialize)] #[serde(rename_all = "camelCase")] pub struct ProphetpayRefundResponse { pub success: bool, @@ -646,7 +646,7 @@ impl TryFrom<types::RefundsResponseRouterData<api::Execute, ProphetpayRefundResp } } -#[derive(Debug, Clone, Deserialize)] +#[derive(Debug, Clone, Deserialize, Serialize)] #[serde(rename_all = "camelCase")] pub struct ProphetpayRefundSyncResponse { pub success: bool, diff --git a/crates/router/src/connector/rapyd.rs b/crates/router/src/connector/rapyd.rs index 5272a8ab21e..389893b5529 100644 --- a/crates/router/src/connector/rapyd.rs +++ b/crates/router/src/connector/rapyd.rs @@ -15,6 +15,7 @@ use crate::{ configs::settings, consts, core::errors::{self, CustomResult}, + events::connector_api_logs::ConnectorEvent, headers, logger, services::{ self, @@ -86,6 +87,7 @@ impl ConnectorCommon for Rapyd { fn build_error_response( &self, res: types::Response, + event_builder: Option<&mut ConnectorEvent>, ) -> CustomResult<ErrorResponse, errors::ConnectorError> { let response: Result< rapyd::RapydPaymentsResponse, @@ -93,15 +95,20 @@ impl ConnectorCommon for Rapyd { > = res.response.parse_struct("Rapyd ErrorResponse"); match response { - Ok(response_data) => Ok(ErrorResponse { - status_code: res.status_code, - code: response_data.status.error_code, - message: response_data.status.status.unwrap_or_default(), - reason: response_data.status.message, - attempt_status: None, - connector_transaction_id: None, - }), + Ok(response_data) => { + event_builder.map(|i| i.set_error_response_body(&response_data)); + router_env::logger::info!(connector_response=?response_data); + Ok(ErrorResponse { + status_code: res.status_code, + code: response_data.status.error_code, + message: response_data.status.status.unwrap_or_default(), + reason: response_data.status.message, + attempt_status: None, + connector_transaction_id: None, + }) + } Err(error_msg) => { + event_builder.map(|event| event.set_error(serde_json::json!({"error": res.response.escape_ascii().to_string(), "status_code": res.status_code}))); logger::error!(deserialization_error =? error_msg); utils::handle_json_response_deserialization_failure(res, "rapyd".to_owned()) } @@ -239,12 +246,15 @@ impl fn handle_response( &self, data: &types::PaymentsAuthorizeRouterData, + event_builder: Option<&mut ConnectorEvent>, res: types::Response, ) -> CustomResult<types::PaymentsAuthorizeRouterData, errors::ConnectorError> { let response: rapyd::RapydPaymentsResponse = res .response .parse_struct("Rapyd PaymentResponse") .change_context(errors::ConnectorError::ResponseDeserializationFailed)?; + event_builder.map(|i| i.set_response_body(&response)); + router_env::logger::info!(connector_response=?response); types::ResponseRouterData { response, data: data.clone(), @@ -257,8 +267,9 @@ impl fn get_error_response( &self, res: types::Response, + event_builder: Option<&mut ConnectorEvent>, ) -> CustomResult<ErrorResponse, errors::ConnectorError> { - self.build_error_response(res) + self.build_error_response(res, event_builder) } } @@ -358,12 +369,15 @@ impl fn handle_response( &self, data: &types::PaymentsCancelRouterData, + event_builder: Option<&mut ConnectorEvent>, res: types::Response, ) -> CustomResult<types::PaymentsCancelRouterData, errors::ConnectorError> { let response: rapyd::RapydPaymentsResponse = res .response .parse_struct("Rapyd PaymentResponse") .change_context(errors::ConnectorError::ResponseDeserializationFailed)?; + event_builder.map(|i| i.set_response_body(&response)); + router_env::logger::info!(connector_response=?response); types::ResponseRouterData { response, data: data.clone(), @@ -376,8 +390,9 @@ impl fn get_error_response( &self, res: types::Response, + event_builder: Option<&mut ConnectorEvent>, ) -> CustomResult<ErrorResponse, errors::ConnectorError> { - self.build_error_response(res) + self.build_error_response(res, event_builder) } } @@ -454,19 +469,23 @@ impl fn get_error_response( &self, res: types::Response, + event_builder: Option<&mut ConnectorEvent>, ) -> CustomResult<ErrorResponse, errors::ConnectorError> { - self.build_error_response(res) + self.build_error_response(res, event_builder) } fn handle_response( &self, data: &types::PaymentsSyncRouterData, + event_builder: Option<&mut ConnectorEvent>, res: types::Response, ) -> CustomResult<types::PaymentsSyncRouterData, errors::ConnectorError> { let response: rapyd::RapydPaymentsResponse = res .response .parse_struct("Rapyd PaymentResponse") .change_context(errors::ConnectorError::ResponseDeserializationFailed)?; + event_builder.map(|i| i.set_response_body(&response)); + router_env::logger::info!(connector_response=?response); types::ResponseRouterData { response, data: data.clone(), @@ -558,6 +577,7 @@ impl fn handle_response( &self, data: &types::PaymentsCaptureRouterData, + event_builder: Option<&mut ConnectorEvent>, res: types::Response, ) -> CustomResult<types::PaymentsCaptureRouterData, errors::ConnectorError> { let response: rapyd::RapydPaymentsResponse = res @@ -565,6 +585,9 @@ impl .parse_struct("RapydPaymentResponse") .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(), @@ -588,8 +611,9 @@ impl fn get_error_response( &self, res: types::Response, + event_builder: Option<&mut ConnectorEvent>, ) -> CustomResult<ErrorResponse, errors::ConnectorError> { - self.build_error_response(res) + self.build_error_response(res, event_builder) } } @@ -687,12 +711,15 @@ impl services::ConnectorIntegration<api::Execute, types::RefundsData, types::Ref fn handle_response( &self, data: &types::RefundsRouterData<api::Execute>, + event_builder: Option<&mut ConnectorEvent>, res: types::Response, ) -> CustomResult<types::RefundsRouterData<api::Execute>, errors::ConnectorError> { let response: rapyd::RefundResponse = res .response .parse_struct("rapyd RefundResponse") .change_context(errors::ConnectorError::RequestEncodingFailed)?; + event_builder.map(|i| i.set_response_body(&response)); + router_env::logger::info!(connector_response=?response); types::ResponseRouterData { response, data: data.clone(), @@ -705,8 +732,9 @@ impl services::ConnectorIntegration<api::Execute, types::RefundsData, types::Ref fn get_error_response( &self, res: types::Response, + event_builder: Option<&mut ConnectorEvent>, ) -> CustomResult<ErrorResponse, errors::ConnectorError> { - self.build_error_response(res) + self.build_error_response(res, event_builder) } } @@ -717,12 +745,15 @@ impl services::ConnectorIntegration<api::RSync, types::RefundsData, types::Refun fn handle_response( &self, data: &types::RefundSyncRouterData, + event_builder: Option<&mut ConnectorEvent>, res: types::Response, ) -> CustomResult<types::RefundSyncRouterData, errors::ConnectorError> { let response: rapyd::RefundResponse = res .response .parse_struct("rapyd RefundResponse") .change_context(errors::ConnectorError::ResponseDeserializationFailed)?; + event_builder.map(|i| i.set_response_body(&response)); + router_env::logger::info!(connector_response=?response); types::ResponseRouterData { response, data: data.clone(), diff --git a/crates/router/src/connector/riskified.rs b/crates/router/src/connector/riskified.rs index 29d57ee28cd..72a9f6dbdbf 100644 --- a/crates/router/src/connector/riskified.rs +++ b/crates/router/src/connector/riskified.rs @@ -22,6 +22,7 @@ use crate::{ }; #[cfg(feature = "frm")] use crate::{ + events::connector_api_logs::ConnectorEvent, types::{api::fraud_check as frm_api, fraud_check as frm_types, ErrorResponse, Response}, utils::BytesExt, }; @@ -108,11 +109,16 @@ impl ConnectorCommon for Riskified { fn build_error_response( &self, res: Response, + event_builder: Option<&mut ConnectorEvent>, ) -> CustomResult<ErrorResponse, errors::ConnectorError> { let response: riskified::ErrorResponse = res .response .parse_struct("ErrorResponse") .change_context(errors::ConnectorError::ResponseDeserializationFailed)?; + + event_builder.map(|i| i.set_error_response_body(&response)); + router_env::logger::info!(connector_response=?response); + Ok(ErrorResponse { status_code: res.status_code, attempt_status: None, @@ -184,12 +190,15 @@ impl fn handle_response( &self, data: &frm_types::FrmCheckoutRouterData, + event_builder: Option<&mut ConnectorEvent>, res: Response, ) -> CustomResult<frm_types::FrmCheckoutRouterData, errors::ConnectorError> { let response: riskified::RiskifiedPaymentsResponse = res .response .parse_struct("RiskifiedPaymentsResponse Checkout") .change_context(errors::ConnectorError::ResponseDeserializationFailed)?; + event_builder.map(|i| i.set_response_body(&response)); + router_env::logger::info!(connector_response=?response); <frm_types::FrmCheckoutRouterData>::try_from(types::ResponseRouterData { response, data: data.clone(), @@ -199,8 +208,9 @@ impl fn get_error_response( &self, res: Response, + event_builder: Option<&mut ConnectorEvent>, ) -> CustomResult<ErrorResponse, errors::ConnectorError> { - self.build_error_response(res) + self.build_error_response(res, event_builder) } } @@ -312,6 +322,7 @@ impl fn handle_response( &self, data: &frm_types::FrmTransactionRouterData, + event_builder: Option<&mut ConnectorEvent>, res: Response, ) -> CustomResult<frm_types::FrmTransactionRouterData, errors::ConnectorError> { let response: riskified::RiskifiedTransactionResponse = res @@ -319,6 +330,9 @@ impl .parse_struct("RiskifiedPaymentsResponse Transaction") .change_context(errors::ConnectorError::ResponseDeserializationFailed)?; + event_builder.map(|i| i.set_response_body(&response)); + router_env::logger::info!(connector_response=?response); + match response { riskified::RiskifiedTransactionResponse::FailedResponse(response_data) => { <frm_types::FrmTransactionRouterData>::try_from(types::ResponseRouterData { @@ -339,8 +353,9 @@ impl fn get_error_response( &self, res: Response, + event_builder: Option<&mut ConnectorEvent>, ) -> CustomResult<ErrorResponse, errors::ConnectorError> { - self.build_error_response(res) + self.build_error_response(res, event_builder) } } @@ -406,6 +421,7 @@ impl fn handle_response( &self, data: &frm_types::FrmFulfillmentRouterData, + event_builder: Option<&mut ConnectorEvent>, res: Response, ) -> CustomResult<frm_types::FrmFulfillmentRouterData, errors::ConnectorError> { let response: riskified::RiskifiedFulfilmentResponse = res @@ -413,6 +429,9 @@ impl .parse_struct("RiskifiedFulfilmentResponse fulfilment") .change_context(errors::ConnectorError::ResponseDeserializationFailed)?; + event_builder.map(|i| i.set_response_body(&response)); + router_env::logger::info!(connector_response=?response); + frm_types::FrmFulfillmentRouterData::try_from(types::ResponseRouterData { response, data: data.clone(), @@ -423,8 +442,9 @@ impl fn get_error_response( &self, res: Response, + event_builder: Option<&mut ConnectorEvent>, ) -> CustomResult<ErrorResponse, errors::ConnectorError> { - self.build_error_response(res) + self.build_error_response(res, event_builder) } } diff --git a/crates/router/src/connector/shift4.rs b/crates/router/src/connector/shift4.rs index c38fac56efc..352ec4787a1 100644 --- a/crates/router/src/connector/shift4.rs +++ b/crates/router/src/connector/shift4.rs @@ -15,6 +15,7 @@ use crate::{ errors::{self, CustomResult}, payments, }, + events::connector_api_logs::ConnectorEvent, headers, routes, services::{ self, @@ -85,12 +86,16 @@ impl ConnectorCommon for Shift4 { fn build_error_response( &self, res: types::Response, + event_builder: Option<&mut ConnectorEvent>, ) -> CustomResult<ErrorResponse, errors::ConnectorError> { let response: shift4::ErrorResponse = res .response .parse_struct("Shift4 ErrorResponse") .change_context(errors::ConnectorError::ResponseDeserializationFailed)?; + event_builder.map(|i| i.set_error_response_body(&response)); + router_env::logger::info!(connector_response=?response); + Ok(ErrorResponse { status_code: res.status_code, code: response @@ -269,12 +274,17 @@ impl ConnectorIntegration<api::Authorize, types::PaymentsAuthorizeData, types::P fn handle_response( &self, data: &types::PaymentsAuthorizeRouterData, + event_builder: Option<&mut ConnectorEvent>, res: types::Response, ) -> CustomResult<types::PaymentsAuthorizeRouterData, errors::ConnectorError> { let response: shift4::Shift4NonThreeDsResponse = res .response .parse_struct("Shift4NonThreeDsResponse") .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(), @@ -286,8 +296,9 @@ impl ConnectorIntegration<api::Authorize, types::PaymentsAuthorizeData, types::P fn get_error_response( &self, res: types::Response, + event_builder: Option<&mut ConnectorEvent>, ) -> CustomResult<ErrorResponse, errors::ConnectorError> { - self.build_error_response(res) + self.build_error_response(res, event_builder) } } @@ -346,19 +357,25 @@ impl ConnectorIntegration<api::PSync, types::PaymentsSyncData, types::PaymentsRe fn get_error_response( &self, res: types::Response, + event_builder: Option<&mut ConnectorEvent>, ) -> CustomResult<ErrorResponse, errors::ConnectorError> { - self.build_error_response(res) + self.build_error_response(res, event_builder) } fn handle_response( &self, data: &types::PaymentsSyncRouterData, + event_builder: Option<&mut ConnectorEvent>, res: types::Response, ) -> CustomResult<types::PaymentsSyncRouterData, errors::ConnectorError> { let response: shift4::Shift4NonThreeDsResponse = res .response .parse_struct("Shift4NonThreeDsResponse") .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(), @@ -403,12 +420,17 @@ impl ConnectorIntegration<api::Capture, types::PaymentsCaptureData, types::Payme fn handle_response( &self, data: &types::PaymentsCaptureRouterData, + event_builder: Option<&mut ConnectorEvent>, res: types::Response, ) -> CustomResult<types::PaymentsCaptureRouterData, errors::ConnectorError> { let response: shift4::Shift4NonThreeDsResponse = res .response .parse_struct("Shift4NonThreeDsResponse") .change_context(errors::ConnectorError::ResponseDeserializationFailed)?; + + event_builder.map(|i| i.set_response_body(&response)); + router_env::logger::info!(connector_response=?response); + types::ResponseRouterData { response, data: data.clone(), @@ -434,8 +456,9 @@ impl ConnectorIntegration<api::Capture, types::PaymentsCaptureData, types::Payme fn get_error_response( &self, res: types::Response, + event_builder: Option<&mut ConnectorEvent>, ) -> CustomResult<ErrorResponse, errors::ConnectorError> { - self.build_error_response(res) + self.build_error_response(res, event_builder) } } @@ -514,12 +537,17 @@ impl fn handle_response( &self, data: &types::PaymentsInitRouterData, + event_builder: Option<&mut ConnectorEvent>, res: types::Response, ) -> CustomResult<types::PaymentsInitRouterData, errors::ConnectorError> { let response: shift4::Shift4ThreeDsResponse = res .response .parse_struct("Shift4ThreeDsResponse") .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(), @@ -531,8 +559,9 @@ impl fn get_error_response( &self, res: types::Response, + event_builder: Option<&mut ConnectorEvent>, ) -> CustomResult<ErrorResponse, errors::ConnectorError> { - self.build_error_response(res) + self.build_error_response(res, event_builder) } } @@ -596,12 +625,17 @@ impl fn handle_response( &self, data: &types::PaymentsCompleteAuthorizeRouterData, + event_builder: Option<&mut ConnectorEvent>, res: types::Response, ) -> CustomResult<types::PaymentsCompleteAuthorizeRouterData, errors::ConnectorError> { let response: shift4::Shift4NonThreeDsResponse = res .response .parse_struct("Shift4NonThreeDsResponse") .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(), @@ -613,8 +647,9 @@ impl fn get_error_response( &self, res: types::Response, + event_builder: Option<&mut ConnectorEvent>, ) -> CustomResult<ErrorResponse, errors::ConnectorError> { - self.build_error_response(res) + self.build_error_response(res, event_builder) } } @@ -670,12 +705,17 @@ impl ConnectorIntegration<api::Execute, types::RefundsData, types::RefundsRespon fn handle_response( &self, data: &types::RefundsRouterData<api::Execute>, + event_builder: Option<&mut ConnectorEvent>, res: types::Response, ) -> CustomResult<types::RefundsRouterData<api::Execute>, errors::ConnectorError> { let response: shift4::RefundResponse = res .response .parse_struct("RefundResponse") .change_context(errors::ConnectorError::ResponseDeserializationFailed)?; + + event_builder.map(|i| i.set_response_body(&response)); + router_env::logger::info!(connector_response=?response); + types::ResponseRouterData { response, data: data.clone(), @@ -688,8 +728,9 @@ impl ConnectorIntegration<api::Execute, types::RefundsData, types::RefundsRespon fn get_error_response( &self, res: types::Response, + event_builder: Option<&mut ConnectorEvent>, ) -> CustomResult<ErrorResponse, errors::ConnectorError> { - self.build_error_response(res) + self.build_error_response(res, event_builder) } } @@ -737,12 +778,15 @@ impl ConnectorIntegration<api::RSync, types::RefundsData, types::RefundsResponse fn handle_response( &self, data: &types::RefundSyncRouterData, + event_builder: Option<&mut ConnectorEvent>, res: types::Response, ) -> CustomResult<types::RefundSyncRouterData, errors::ConnectorError> { let response: shift4::RefundResponse = res.response .parse_struct("shift4 RefundResponse") .change_context(errors::ConnectorError::ResponseDeserializationFailed)?; + event_builder.map(|i| i.set_response_body(&response)); + router_env::logger::info!(connector_response=?response); types::ResponseRouterData { response, data: data.clone(), @@ -755,8 +799,9 @@ impl ConnectorIntegration<api::RSync, types::RefundsData, types::RefundsResponse fn get_error_response( &self, res: types::Response, + event_builder: Option<&mut ConnectorEvent>, ) -> CustomResult<ErrorResponse, errors::ConnectorError> { - self.build_error_response(res) + self.build_error_response(res, event_builder) } } diff --git a/crates/router/src/connector/shift4/transformers.rs b/crates/router/src/connector/shift4/transformers.rs index 949082f4253..97c19c49af8 100644 --- a/crates/router/src/connector/shift4/transformers.rs +++ b/crates/router/src/connector/shift4/transformers.rs @@ -555,7 +555,7 @@ pub struct Shift4WebhookObjectResource { pub data: serde_json::Value, } -#[derive(Default, Debug, Deserialize)] +#[derive(Default, Debug, Deserialize, Serialize)] pub struct Shift4NonThreeDsResponse { pub id: String, pub currency: String, @@ -566,7 +566,7 @@ pub struct Shift4NonThreeDsResponse { pub flow: Option<FlowResponse>, } -#[derive(Default, Debug, Deserialize)] +#[derive(Default, Debug, Deserialize, Serialize)] pub struct Shift4ThreeDsResponse { pub enrolled: bool, pub version: Option<String>, @@ -575,7 +575,7 @@ pub struct Shift4ThreeDsResponse { pub token: Token, } -#[derive(Default, Debug, Deserialize)] +#[derive(Default, Debug, Deserialize, Serialize)] pub struct Token { pub id: String, pub created: i64, @@ -593,7 +593,7 @@ pub struct Token { pub three_d_secure_info: ThreeDSecureInfo, } -#[derive(Default, Debug, Deserialize)] +#[derive(Default, Debug, Deserialize, Serialize)] pub struct ThreeDSecureInfo { pub amount: i64, pub currency: String, @@ -605,7 +605,7 @@ pub struct ThreeDSecureInfo { pub authentication_flow: Option<SecretSerdeValue>, } -#[derive(Debug, Deserialize)] +#[derive(Debug, Deserialize, Serialize)] #[serde(rename_all = "camelCase")] pub struct FlowResponse { pub next_action: Option<NextAction>, @@ -613,13 +613,13 @@ pub struct FlowResponse { pub return_url: Option<Url>, } -#[derive(Debug, Deserialize)] +#[derive(Debug, Deserialize, Serialize)] #[serde(rename_all = "camelCase")] pub struct Redirect { pub redirect_url: Option<Url>, } -#[derive(Debug, Deserialize)] +#[derive(Debug, Deserialize, Serialize)] #[serde(rename_all = "lowercase")] pub enum NextAction { Redirect, @@ -810,12 +810,12 @@ impl TryFrom<types::RefundsResponseRouterData<api::RSync, RefundResponse>> } } -#[derive(Debug, Default, Deserialize)] +#[derive(Debug, Default, Deserialize, Serialize)] pub struct ErrorResponse { pub error: ApiErrorResponse, } -#[derive(Default, Debug, Clone, Deserialize, Eq, PartialEq)] +#[derive(Default, Debug, Clone, Deserialize, Eq, PartialEq, Serialize)] pub struct ApiErrorResponse { pub code: Option<String>, pub message: String, diff --git a/crates/router/src/connector/signifyd.rs b/crates/router/src/connector/signifyd.rs index 544dfd137db..7d19df12221 100644 --- a/crates/router/src/connector/signifyd.rs +++ b/crates/router/src/connector/signifyd.rs @@ -19,6 +19,7 @@ use crate::{ }; #[cfg(feature = "frm")] use crate::{ + events::connector_api_logs::ConnectorEvent, types::{api::fraud_check as frm_api, fraud_check as frm_types, ErrorResponse, Response}, utils::BytesExt, }; @@ -76,11 +77,16 @@ impl ConnectorCommon for Signifyd { fn build_error_response( &self, res: Response, + event_builder: Option<&mut ConnectorEvent>, ) -> CustomResult<ErrorResponse, errors::ConnectorError> { let response: signifyd::SignifydErrorResponse = res .response .parse_struct("SignifydErrorResponse") .change_context(errors::ConnectorError::ResponseDeserializationFailed)?; + + event_builder.map(|i| i.set_error_response_body(&response)); + router_env::logger::info!(connector_response=?response); + Ok(ErrorResponse { status_code: res.status_code, code: crate::consts::NO_ERROR_CODE.to_string(), @@ -251,12 +257,17 @@ impl fn handle_response( &self, data: &frm_types::FrmSaleRouterData, + event_builder: Option<&mut ConnectorEvent>, res: Response, ) -> CustomResult<frm_types::FrmSaleRouterData, errors::ConnectorError> { let response: signifyd::SignifydPaymentsResponse = res .response .parse_struct("SignifydPaymentsResponse Sale") .change_context(errors::ConnectorError::ResponseDeserializationFailed)?; + + event_builder.map(|i| i.set_response_body(&response)); + router_env::logger::info!(connector_response=?response); + <frm_types::FrmSaleRouterData>::try_from(types::ResponseRouterData { response, data: data.clone(), @@ -266,8 +277,9 @@ impl fn get_error_response( &self, res: Response, + event_builder: Option<&mut ConnectorEvent>, ) -> CustomResult<ErrorResponse, errors::ConnectorError> { - self.build_error_response(res) + self.build_error_response(res, event_builder) } } @@ -335,12 +347,15 @@ impl fn handle_response( &self, data: &frm_types::FrmCheckoutRouterData, + event_builder: Option<&mut ConnectorEvent>, res: Response, ) -> CustomResult<frm_types::FrmCheckoutRouterData, errors::ConnectorError> { let response: signifyd::SignifydPaymentsResponse = res .response .parse_struct("SignifydPaymentsResponse Checkout") .change_context(errors::ConnectorError::ResponseDeserializationFailed)?; + event_builder.map(|i| i.set_response_body(&response)); + router_env::logger::info!(connector_response=?response); <frm_types::FrmCheckoutRouterData>::try_from(types::ResponseRouterData { response, data: data.clone(), @@ -350,8 +365,9 @@ impl fn get_error_response( &self, res: Response, + event_builder: Option<&mut ConnectorEvent>, ) -> CustomResult<ErrorResponse, errors::ConnectorError> { - self.build_error_response(res) + self.build_error_response(res, event_builder) } } @@ -421,12 +437,15 @@ impl fn handle_response( &self, data: &frm_types::FrmTransactionRouterData, + event_builder: Option<&mut ConnectorEvent>, res: Response, ) -> CustomResult<frm_types::FrmTransactionRouterData, errors::ConnectorError> { let response: signifyd::SignifydPaymentsResponse = res .response .parse_struct("SignifydPaymentsResponse Transaction") .change_context(errors::ConnectorError::ResponseDeserializationFailed)?; + event_builder.map(|i| i.set_response_body(&response)); + router_env::logger::info!(connector_response=?response); <frm_types::FrmTransactionRouterData>::try_from(types::ResponseRouterData { response, data: data.clone(), @@ -436,8 +455,9 @@ impl fn get_error_response( &self, res: Response, + event_builder: Option<&mut ConnectorEvent>, ) -> CustomResult<ErrorResponse, errors::ConnectorError> { - self.build_error_response(res) + self.build_error_response(res, event_builder) } } @@ -507,12 +527,15 @@ impl fn handle_response( &self, data: &frm_types::FrmFulfillmentRouterData, + event_builder: Option<&mut ConnectorEvent>, res: Response, ) -> CustomResult<frm_types::FrmFulfillmentRouterData, errors::ConnectorError> { let response: signifyd::FrmFullfillmentSignifydApiResponse = res .response .parse_struct("FrmFullfillmentSignifydApiResponse Sale") .change_context(errors::ConnectorError::ResponseDeserializationFailed)?; + event_builder.map(|i| i.set_response_body(&response)); + router_env::logger::info!(connector_response=?response); frm_types::FrmFulfillmentRouterData::try_from(types::ResponseRouterData { response, data: data.clone(), @@ -522,8 +545,9 @@ impl fn get_error_response( &self, res: Response, + event_builder: Option<&mut ConnectorEvent>, ) -> CustomResult<ErrorResponse, errors::ConnectorError> { - self.build_error_response(res) + self.build_error_response(res, event_builder) } } @@ -593,12 +617,15 @@ impl fn handle_response( &self, data: &frm_types::FrmRecordReturnRouterData, + event_builder: Option<&mut ConnectorEvent>, res: Response, ) -> CustomResult<frm_types::FrmRecordReturnRouterData, errors::ConnectorError> { let response: signifyd::SignifydPaymentsRecordReturnResponse = res .response .parse_struct("SignifydPaymentsResponse Transaction") .change_context(errors::ConnectorError::ResponseDeserializationFailed)?; + event_builder.map(|i| i.set_response_body(&response)); + router_env::logger::info!(connector_response=?response); <frm_types::FrmRecordReturnRouterData>::try_from(types::ResponseRouterData { response, data: data.clone(), @@ -608,8 +635,9 @@ impl fn get_error_response( &self, res: Response, + event_builder: Option<&mut ConnectorEvent>, ) -> CustomResult<ErrorResponse, errors::ConnectorError> { - self.build_error_response(res) + self.build_error_response(res, event_builder) } } diff --git a/crates/router/src/connector/signifyd/transformers/api.rs b/crates/router/src/connector/signifyd/transformers/api.rs index 66d6f0e48cd..b738ec00fcf 100644 --- a/crates/router/src/connector/signifyd/transformers/api.rs +++ b/crates/router/src/connector/signifyd/transformers/api.rs @@ -211,7 +211,7 @@ impl<F, T> } } -#[derive(Debug, Deserialize, PartialEq)] +#[derive(Debug, Deserialize, PartialEq, Serialize)] pub struct SignifydErrorResponse { pub messages: Vec<String>, pub errors: serde_json::Value, diff --git a/crates/router/src/connector/square.rs b/crates/router/src/connector/square.rs index e210a851dfc..ea6bd42ffe0 100644 --- a/crates/router/src/connector/square.rs +++ b/crates/router/src/connector/square.rs @@ -17,6 +17,7 @@ use crate::{ errors::{self, CustomResult}, payments, }, + events::connector_api_logs::ConnectorEvent, headers, services::{ self, @@ -96,12 +97,16 @@ impl ConnectorCommon for Square { fn build_error_response( &self, res: Response, + event_builder: Option<&mut ConnectorEvent>, ) -> CustomResult<ErrorResponse, errors::ConnectorError> { let response: square::SquareErrorResponse = res .response .parse_struct("SquareErrorResponse") .change_context(errors::ConnectorError::ResponseDeserializationFailed)?; + event_builder.map(|i| i.set_error_response_body(&response)); + router_env::logger::info!(connector_response=?response); + let mut reason_list = Vec::new(); for error_iter in response.errors.iter() { if let Some(error) = error_iter.detail.clone() { @@ -289,6 +294,7 @@ impl fn handle_response( &self, data: &types::TokenizationRouterData, + event_builder: Option<&mut ConnectorEvent>, res: Response, ) -> CustomResult<types::TokenizationRouterData, errors::ConnectorError> where @@ -299,6 +305,9 @@ impl .parse_struct("SquareTokenResponse") .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(), @@ -308,8 +317,9 @@ impl fn get_error_response( &self, res: Response, + event_builder: Option<&mut ConnectorEvent>, ) -> CustomResult<ErrorResponse, errors::ConnectorError> { - self.build_error_response(res) + self.build_error_response(res, event_builder) } } @@ -378,6 +388,7 @@ impl fn handle_response( &self, data: &types::PaymentsAuthorizeSessionTokenRouterData, + event_builder: Option<&mut ConnectorEvent>, res: Response, ) -> CustomResult<types::PaymentsAuthorizeSessionTokenRouterData, errors::ConnectorError> { let response: square::SquareSessionResponse = res @@ -385,6 +396,9 @@ impl .parse_struct("SquareSessionResponse") .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(), @@ -395,8 +409,9 @@ impl fn get_error_response( &self, res: Response, + event_builder: Option<&mut ConnectorEvent>, ) -> CustomResult<ErrorResponse, errors::ConnectorError> { - self.build_error_response(res) + self.build_error_response(res, event_builder) } } @@ -458,12 +473,17 @@ impl ConnectorIntegration<api::Authorize, types::PaymentsAuthorizeData, types::P fn handle_response( &self, data: &types::PaymentsAuthorizeRouterData, + event_builder: Option<&mut ConnectorEvent>, res: Response, ) -> CustomResult<types::PaymentsAuthorizeRouterData, errors::ConnectorError> { let response: square::SquarePaymentsResponse = res .response .parse_struct("SquarePaymentsAuthorizeResponse") .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(), @@ -474,8 +494,9 @@ impl ConnectorIntegration<api::Authorize, types::PaymentsAuthorizeData, types::P fn get_error_response( &self, res: Response, + event_builder: Option<&mut ConnectorEvent>, ) -> CustomResult<ErrorResponse, errors::ConnectorError> { - self.build_error_response(res) + self.build_error_response(res, event_builder) } } @@ -529,12 +550,17 @@ impl ConnectorIntegration<api::PSync, types::PaymentsSyncData, types::PaymentsRe fn handle_response( &self, data: &types::PaymentsSyncRouterData, + event_builder: Option<&mut ConnectorEvent>, res: Response, ) -> CustomResult<types::PaymentsSyncRouterData, errors::ConnectorError> { let response: square::SquarePaymentsResponse = res .response .parse_struct("SquarePaymentsSyncResponse") .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(), @@ -545,8 +571,9 @@ impl ConnectorIntegration<api::PSync, types::PaymentsSyncData, types::PaymentsRe fn get_error_response( &self, res: Response, + event_builder: Option<&mut ConnectorEvent>, ) -> CustomResult<ErrorResponse, errors::ConnectorError> { - self.build_error_response(res) + self.build_error_response(res, event_builder) } } @@ -603,12 +630,17 @@ impl ConnectorIntegration<api::Capture, types::PaymentsCaptureData, types::Payme fn handle_response( &self, data: &types::PaymentsCaptureRouterData, + event_builder: Option<&mut ConnectorEvent>, res: Response, ) -> CustomResult<types::PaymentsCaptureRouterData, errors::ConnectorError> { let response: square::SquarePaymentsResponse = res .response .parse_struct("SquarePaymentsCaptureResponse") .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(), @@ -619,8 +651,9 @@ impl ConnectorIntegration<api::Capture, types::PaymentsCaptureData, types::Payme fn get_error_response( &self, res: Response, + event_builder: Option<&mut ConnectorEvent>, ) -> CustomResult<ErrorResponse, errors::ConnectorError> { - self.build_error_response(res) + self.build_error_response(res, event_builder) } } @@ -669,12 +702,17 @@ impl ConnectorIntegration<api::Void, types::PaymentsCancelData, types::PaymentsR fn handle_response( &self, data: &types::PaymentsCancelRouterData, + event_builder: Option<&mut ConnectorEvent>, res: Response, ) -> CustomResult<types::PaymentsCancelRouterData, errors::ConnectorError> { let response: square::SquarePaymentsResponse = res .response .parse_struct("SquarePaymentsVoidResponse") .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(), @@ -685,8 +723,9 @@ impl ConnectorIntegration<api::Void, types::PaymentsCancelData, types::PaymentsR fn get_error_response( &self, res: Response, + event_builder: Option<&mut ConnectorEvent>, ) -> CustomResult<ErrorResponse, errors::ConnectorError> { - self.build_error_response(res) + self.build_error_response(res, event_builder) } } @@ -742,12 +781,17 @@ impl ConnectorIntegration<api::Execute, types::RefundsData, types::RefundsRespon 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: square::RefundResponse = res .response .parse_struct("SquareRefundResponse") .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(), @@ -758,8 +802,9 @@ impl ConnectorIntegration<api::Execute, types::RefundsData, types::RefundsRespon fn get_error_response( &self, res: Response, + event_builder: Option<&mut ConnectorEvent>, ) -> CustomResult<ErrorResponse, errors::ConnectorError> { - self.build_error_response(res) + self.build_error_response(res, event_builder) } } @@ -806,6 +851,7 @@ impl ConnectorIntegration<api::RSync, types::RefundsData, types::RefundsResponse fn handle_response( &self, data: &types::RefundSyncRouterData, + event_builder: Option<&mut ConnectorEvent>, res: Response, ) -> CustomResult<types::RefundSyncRouterData, errors::ConnectorError> { let response: square::RefundResponse = res @@ -813,6 +859,9 @@ impl ConnectorIntegration<api::RSync, types::RefundsData, types::RefundsResponse .parse_struct("SquareRefundSyncResponse") .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(), @@ -823,8 +872,9 @@ impl ConnectorIntegration<api::RSync, types::RefundsData, types::RefundsResponse fn get_error_response( &self, res: Response, + event_builder: Option<&mut ConnectorEvent>, ) -> CustomResult<ErrorResponse, errors::ConnectorError> { - self.build_error_response(res) + self.build_error_response(res, event_builder) } } diff --git a/crates/router/src/connector/square/transformers.rs b/crates/router/src/connector/square/transformers.rs index 7343ef58bb0..e159b1d8ade 100644 --- a/crates/router/src/connector/square/transformers.rs +++ b/crates/router/src/connector/square/transformers.rs @@ -200,7 +200,7 @@ impl TryFrom<&types::TokenizationRouterData> for SquareTokenRequest { } } -#[derive(Debug, Deserialize)] +#[derive(Debug, Deserialize, Serialize)] #[serde(rename_all = "camelCase")] pub struct SquareSessionResponse { session_id: String, @@ -225,7 +225,7 @@ impl<F, T> } } -#[derive(Debug, Deserialize)] +#[derive(Debug, Deserialize, Serialize)] pub struct SquareTokenResponse { card_nonce: Secret<String>, } @@ -373,7 +373,7 @@ pub struct SquarePaymentsResponseDetails { amount_money: SquarePaymentsAmountData, reference_id: Option<String>, } -#[derive(Debug, Deserialize)] +#[derive(Debug, Deserialize, Serialize)] pub struct SquarePaymentsResponse { payment: SquarePaymentsResponseDetails, } @@ -456,7 +456,7 @@ pub struct SquareRefundResponseDetails { status: RefundStatus, id: String, } -#[derive(Debug, Deserialize)] +#[derive(Debug, Deserialize, Serialize)] pub struct RefundResponse { refund: SquareRefundResponseDetails, } diff --git a/crates/router/src/connector/stax.rs b/crates/router/src/connector/stax.rs index 75bb8e68184..db090cdf78b 100644 --- a/crates/router/src/connector/stax.rs +++ b/crates/router/src/connector/stax.rs @@ -14,6 +14,7 @@ use crate::{ configs::settings, consts, core::errors::{self, CustomResult}, + events::connector_api_logs::ConnectorEvent, headers, services::{ self, @@ -98,6 +99,7 @@ impl ConnectorCommon for Stax { fn build_error_response( &self, res: Response, + _event_builder: Option<&mut ConnectorEvent>, ) -> CustomResult<ErrorResponse, errors::ConnectorError> { Ok(ErrorResponse { status_code: res.status_code, @@ -194,6 +196,7 @@ impl fn handle_response( &self, data: &types::ConnectorCustomerRouterData, + event_builder: Option<&mut ConnectorEvent>, res: Response, ) -> CustomResult<types::ConnectorCustomerRouterData, errors::ConnectorError> where @@ -204,6 +207,9 @@ impl .parse_struct("StaxCustomerResponse") .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(), @@ -214,8 +220,9 @@ impl fn get_error_response( &self, res: Response, + event_builder: Option<&mut ConnectorEvent>, ) -> CustomResult<ErrorResponse, errors::ConnectorError> { - self.build_error_response(res) + self.build_error_response(res, event_builder) } } @@ -277,6 +284,7 @@ impl fn handle_response( &self, data: &types::TokenizationRouterData, + event_builder: Option<&mut ConnectorEvent>, res: Response, ) -> CustomResult<types::TokenizationRouterData, errors::ConnectorError> where @@ -287,6 +295,9 @@ impl .parse_struct("StaxTokenResponse") .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(), @@ -297,8 +308,9 @@ impl fn get_error_response( &self, res: Response, + event_builder: Option<&mut ConnectorEvent>, ) -> CustomResult<ErrorResponse, errors::ConnectorError> { - self.build_error_response(res) + self.build_error_response(res, event_builder) } } @@ -400,12 +412,17 @@ impl ConnectorIntegration<api::Authorize, types::PaymentsAuthorizeData, types::P fn handle_response( &self, data: &types::PaymentsAuthorizeRouterData, + event_builder: Option<&mut ConnectorEvent>, res: Response, ) -> CustomResult<types::PaymentsAuthorizeRouterData, errors::ConnectorError> { let response: stax::StaxPaymentsResponse = res .response .parse_struct("StaxPaymentsAuthorizeResponse") .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(), @@ -416,8 +433,9 @@ impl ConnectorIntegration<api::Authorize, types::PaymentsAuthorizeData, types::P fn get_error_response( &self, res: Response, + event_builder: Option<&mut ConnectorEvent>, ) -> CustomResult<ErrorResponse, errors::ConnectorError> { - self.build_error_response(res) + self.build_error_response(res, event_builder) } } @@ -471,12 +489,17 @@ impl ConnectorIntegration<api::PSync, types::PaymentsSyncData, types::PaymentsRe fn handle_response( &self, data: &types::PaymentsSyncRouterData, + event_builder: Option<&mut ConnectorEvent>, res: Response, ) -> CustomResult<types::PaymentsSyncRouterData, errors::ConnectorError> { let response: stax::StaxPaymentsResponse = res .response .parse_struct("StaxPaymentsSyncResponse") .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(), @@ -487,8 +510,9 @@ impl ConnectorIntegration<api::PSync, types::PaymentsSyncData, types::PaymentsRe fn get_error_response( &self, res: Response, + event_builder: Option<&mut ConnectorEvent>, ) -> CustomResult<ErrorResponse, errors::ConnectorError> { - self.build_error_response(res) + self.build_error_response(res, event_builder) } } @@ -557,12 +581,17 @@ impl ConnectorIntegration<api::Capture, types::PaymentsCaptureData, types::Payme fn handle_response( &self, data: &types::PaymentsCaptureRouterData, + event_builder: Option<&mut ConnectorEvent>, res: Response, ) -> CustomResult<types::PaymentsCaptureRouterData, errors::ConnectorError> { let response: stax::StaxPaymentsResponse = res .response .parse_struct("StaxPaymentsCaptureResponse") .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(), @@ -573,8 +602,9 @@ impl ConnectorIntegration<api::Capture, types::PaymentsCaptureData, types::Payme fn get_error_response( &self, res: Response, + event_builder: Option<&mut ConnectorEvent>, ) -> CustomResult<ErrorResponse, errors::ConnectorError> { - self.build_error_response(res) + self.build_error_response(res, event_builder) } } @@ -623,12 +653,17 @@ impl ConnectorIntegration<api::Void, types::PaymentsCancelData, types::PaymentsR fn handle_response( &self, data: &types::PaymentsCancelRouterData, + event_builder: Option<&mut ConnectorEvent>, res: Response, ) -> CustomResult<types::PaymentsCancelRouterData, errors::ConnectorError> { let response: stax::StaxPaymentsResponse = res .response .parse_struct("StaxPaymentsVoidResponse") .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(), @@ -639,8 +674,9 @@ impl ConnectorIntegration<api::Void, types::PaymentsCancelData, types::PaymentsR fn get_error_response( &self, res: Response, + event_builder: Option<&mut ConnectorEvent>, ) -> CustomResult<ErrorResponse, errors::ConnectorError> { - self.build_error_response(res) + self.build_error_response(res, event_builder) } } @@ -714,12 +750,17 @@ impl ConnectorIntegration<api::Execute, types::RefundsData, types::RefundsRespon 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: stax::RefundResponse = res .response .parse_struct("StaxRefundResponse") .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(), @@ -730,8 +771,9 @@ impl ConnectorIntegration<api::Execute, types::RefundsData, types::RefundsRespon fn get_error_response( &self, res: Response, + event_builder: Option<&mut ConnectorEvent>, ) -> CustomResult<ErrorResponse, errors::ConnectorError> { - self.build_error_response(res) + self.build_error_response(res, event_builder) } } @@ -778,12 +820,17 @@ impl ConnectorIntegration<api::RSync, types::RefundsData, types::RefundsResponse fn handle_response( &self, data: &types::RefundSyncRouterData, + event_builder: Option<&mut ConnectorEvent>, res: Response, ) -> CustomResult<types::RefundSyncRouterData, errors::ConnectorError> { let response: stax::RefundResponse = res .response .parse_struct("StaxRefundSyncResponse") .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(), @@ -794,8 +841,9 @@ impl ConnectorIntegration<api::RSync, types::RefundsData, types::RefundsResponse fn get_error_response( &self, res: Response, + event_builder: Option<&mut ConnectorEvent>, ) -> CustomResult<ErrorResponse, errors::ConnectorError> { - self.build_error_response(res) + self.build_error_response(res, event_builder) } } diff --git a/crates/router/src/connector/stax/transformers.rs b/crates/router/src/connector/stax/transformers.rs index 596ea1145ec..a9bb68d558e 100644 --- a/crates/router/src/connector/stax/transformers.rs +++ b/crates/router/src/connector/stax/transformers.rs @@ -167,7 +167,7 @@ impl TryFrom<&types::ConnectorCustomerRouterData> for StaxCustomerRequest { } } -#[derive(Debug, Deserialize)] +#[derive(Debug, Deserialize, Serialize)] pub struct StaxCustomerResponse { id: Secret<String>, } @@ -277,7 +277,7 @@ impl TryFrom<&types::TokenizationRouterData> for StaxTokenRequest { } } -#[derive(Debug, Deserialize)] +#[derive(Debug, Deserialize, Serialize)] pub struct StaxTokenResponse { id: Secret<String>, } @@ -298,19 +298,19 @@ impl<F, T> TryFrom<types::ResponseRouterData<F, StaxTokenResponse, T, types::Pay } } -#[derive(Debug, Deserialize)] +#[derive(Debug, Deserialize, Serialize)] #[serde(rename_all = "snake_case")] pub enum StaxPaymentResponseTypes { Charge, PreAuth, } -#[derive(Debug, Deserialize)] +#[derive(Debug, Deserialize, Serialize)] pub struct StaxChildCapture { id: String, } -#[derive(Debug, Deserialize)] +#[derive(Debug, Deserialize, Serialize)] pub struct StaxPaymentsResponse { success: bool, id: String, @@ -406,14 +406,14 @@ impl<F> TryFrom<&StaxRouterData<&types::RefundsRouterData<F>>> for StaxRefundReq } } -#[derive(Debug, Deserialize)] +#[derive(Debug, Deserialize, Serialize)] pub struct ChildTransactionsInResponse { id: String, success: bool, created_at: String, total: f64, } -#[derive(Debug, Deserialize)] +#[derive(Debug, Deserialize, Serialize)] pub struct RefundResponse { id: String, success: bool, diff --git a/crates/router/src/connector/stripe.rs b/crates/router/src/connector/stripe.rs index c151c5af455..01848f704e4 100644 --- a/crates/router/src/connector/stripe.rs +++ b/crates/router/src/connector/stripe.rs @@ -17,7 +17,8 @@ use crate::{ errors::{self, CustomResult}, payments, }, - headers, logger, + events::connector_api_logs::ConnectorEvent, + headers, services::{ self, request::{self, Mask}, @@ -177,13 +178,16 @@ impl fn handle_response( &self, data: &types::PaymentsPreProcessingRouterData, + event_builder: Option<&mut ConnectorEvent>, res: types::Response, ) -> CustomResult<types::PaymentsPreProcessingRouterData, errors::ConnectorError> { let response: stripe::StripeSourceResponse = res .response .parse_struct("StripeSourceResponse") .change_context(errors::ConnectorError::ResponseDeserializationFailed)?; - logger::info!(connector_response=?response); + + event_builder.map(|i| i.set_response_body(&response)); + router_env::logger::info!(connector_response=?response); types::RouterData::try_from(types::ResponseRouterData { response, @@ -196,12 +200,16 @@ impl fn get_error_response( &self, res: types::Response, + event_builder: Option<&mut ConnectorEvent>, ) -> CustomResult<types::ErrorResponse, errors::ConnectorError> { let response: stripe::ErrorResponse = res .response .parse_struct("ErrorResponse") .change_context(errors::ConnectorError::ResponseDeserializationFailed)?; - router_env::logger::info!(error_response=?response); + + event_builder.map(|i| i.set_error_response_body(&response)); + router_env::logger::info!(connector_response=?response); + Ok(types::ErrorResponse { status_code: res.status_code, code: response @@ -299,6 +307,7 @@ impl fn handle_response( &self, data: &types::ConnectorCustomerRouterData, + event_builder: Option<&mut ConnectorEvent>, res: types::Response, ) -> CustomResult<types::ConnectorCustomerRouterData, errors::ConnectorError> where @@ -308,7 +317,9 @@ impl .response .parse_struct("StripeCustomerResponse") .change_context(errors::ConnectorError::ResponseDeserializationFailed)?; - logger::info!(connector_response=?response); + + event_builder.map(|i| i.set_response_body(&response)); + router_env::logger::info!(connector_response=?response); types::RouterData::try_from(types::ResponseRouterData { response, @@ -321,12 +332,15 @@ impl fn get_error_response( &self, res: types::Response, + event_builder: Option<&mut ConnectorEvent>, ) -> CustomResult<types::ErrorResponse, errors::ConnectorError> { let response: stripe::ErrorResponse = res .response .parse_struct("ErrorResponse") .change_context(errors::ConnectorError::ResponseDeserializationFailed)?; - router_env::logger::info!(error_response=?response); + + event_builder.map(|i| i.set_error_response_body(&response)); + router_env::logger::info!(connector_response=?response); Ok(types::ErrorResponse { status_code: res.status_code, @@ -421,6 +435,7 @@ impl fn handle_response( &self, data: &types::TokenizationRouterData, + event_builder: Option<&mut ConnectorEvent>, res: types::Response, ) -> CustomResult<types::TokenizationRouterData, errors::ConnectorError> where @@ -430,7 +445,9 @@ impl .response .parse_struct("StripeTokenResponse") .change_context(errors::ConnectorError::ResponseDeserializationFailed)?; - logger::info!(connector_response=?response); + + event_builder.map(|i| i.set_response_body(&response)); + router_env::logger::info!(connector_response=?response); types::RouterData::try_from(types::ResponseRouterData { response, @@ -443,12 +460,15 @@ impl fn get_error_response( &self, res: types::Response, + event_builder: Option<&mut ConnectorEvent>, ) -> CustomResult<types::ErrorResponse, errors::ConnectorError> { let response: stripe::ErrorResponse = res .response .parse_struct("ErrorResponse") .change_context(errors::ConnectorError::ResponseDeserializationFailed)?; - router_env::logger::info!(error_response=?response); + + event_builder.map(|i| i.set_response_body(&response)); + router_env::logger::info!(connector_response=?response); Ok(types::ErrorResponse { status_code: res.status_code, @@ -551,6 +571,7 @@ impl fn handle_response( &self, data: &types::PaymentsCaptureRouterData, + event_builder: Option<&mut ConnectorEvent>, res: types::Response, ) -> CustomResult<types::PaymentsCaptureRouterData, errors::ConnectorError> where @@ -561,7 +582,10 @@ impl .response .parse_struct("PaymentIntentResponse") .change_context(errors::ConnectorError::ResponseDeserializationFailed)?; - logger::info!(connector_response=?response); + + 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(), @@ -573,12 +597,15 @@ impl fn get_error_response( &self, res: types::Response, + event_builder: Option<&mut ConnectorEvent>, ) -> CustomResult<types::ErrorResponse, errors::ConnectorError> { let response: stripe::ErrorResponse = res .response .parse_struct("ErrorResponse") .change_context(errors::ConnectorError::ResponseDeserializationFailed)?; - router_env::logger::info!(error_response=?response); + + event_builder.map(|i| i.set_error_response_body(&response)); + router_env::logger::info!(connector_response=?response); Ok(types::ErrorResponse { status_code: res.status_code, @@ -673,6 +700,7 @@ impl fn handle_response( &self, data: &types::PaymentsSyncRouterData, + event_builder: Option<&mut ConnectorEvent>, res: types::Response, ) -> CustomResult<types::PaymentsSyncRouterData, errors::ConnectorError> where @@ -686,7 +714,10 @@ impl .response .parse_struct("SetupIntentSyncResponse") .change_context(errors::ConnectorError::ResponseDeserializationFailed)?; - logger::info!(connector_response=?response); + + 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(), @@ -698,7 +729,10 @@ impl .response .parse_struct("PaymentIntentSyncResponse") .change_context(errors::ConnectorError::ResponseDeserializationFailed)?; - logger::info!(connector_response=?response); + + 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(), @@ -714,12 +748,14 @@ impl fn get_error_response( &self, res: types::Response, + event_builder: Option<&mut ConnectorEvent>, ) -> CustomResult<types::ErrorResponse, errors::ConnectorError> { let response: stripe::ErrorResponse = res .response .parse_struct("ErrorResponse") .change_context(errors::ConnectorError::ResponseDeserializationFailed)?; - router_env::logger::info!(error_response=?response); + event_builder.map(|i| i.set_error_response_body(&response)); + router_env::logger::info!(connector_response=?response); Ok(types::ErrorResponse { status_code: res.status_code, @@ -843,18 +879,57 @@ impl fn handle_response( &self, data: &types::PaymentsAuthorizeRouterData, + event_builder: Option<&mut ConnectorEvent>, res: types::Response, ) -> CustomResult<types::PaymentsAuthorizeRouterData, errors::ConnectorError> { match &data.request.payment_method_data { api_models::payments::PaymentMethodData::BankTransfer(bank_transfer_data) => { - stripe::get_bank_transfer_authorize_response(data, res, bank_transfer_data.deref()) + match bank_transfer_data.deref() { + api_models::payments::BankTransferData::AchBankTransfer { .. } + | api_models::payments::BankTransferData::MultibancoBankTransfer { .. } => { + let response: stripe::ChargesResponse = res + .response + .parse_struct("ChargesResponse") + .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, + }) + } + _ => { + let response: stripe::PaymentIntentResponse = res + .response + .parse_struct("PaymentIntentResponse") + .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, + }) + } + } } _ => { let response: stripe::PaymentIntentResponse = res .response .parse_struct("PaymentIntentResponse") .change_context(errors::ConnectorError::ResponseDeserializationFailed)?; - logger::info!(connector_response=?response); + + event_builder.map(|i| i.set_response_body(&response)); + router_env::logger::info!(connector_response=?response); types::RouterData::try_from(types::ResponseRouterData { response, @@ -869,12 +944,14 @@ impl fn get_error_response( &self, res: types::Response, + event_builder: Option<&mut ConnectorEvent>, ) -> CustomResult<types::ErrorResponse, errors::ConnectorError> { let response: stripe::ErrorResponse = res .response .parse_struct("ErrorResponse") .change_context(errors::ConnectorError::ResponseDeserializationFailed)?; - router_env::logger::info!(error_response=?response); + event_builder.map(|i| i.set_error_response_body(&response)); + router_env::logger::info!(connector_response=?response); Ok(types::ErrorResponse { status_code: res.status_code, code: response @@ -970,13 +1047,17 @@ impl fn handle_response( &self, data: &types::PaymentsCancelRouterData, + event_builder: Option<&mut ConnectorEvent>, res: types::Response, ) -> CustomResult<types::PaymentsCancelRouterData, errors::ConnectorError> { let response: stripe::PaymentIntentResponse = res .response .parse_struct("PaymentIntentResponse") .change_context(errors::ConnectorError::ResponseDeserializationFailed)?; - logger::info!(connector_response=?response); + + 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(), @@ -988,12 +1069,16 @@ impl fn get_error_response( &self, res: types::Response, + event_builder: Option<&mut ConnectorEvent>, ) -> CustomResult<types::ErrorResponse, errors::ConnectorError> { let response: stripe::ErrorResponse = res .response .parse_struct("ErrorResponse") .change_context(errors::ConnectorError::ResponseDeserializationFailed)?; - router_env::logger::info!(error_response=?response); + + event_builder.map(|i| i.set_error_response_body(&response)); + router_env::logger::info!(connector_response=?response); + Ok(types::ErrorResponse { status_code: res.status_code, code: response @@ -1110,6 +1195,7 @@ impl types::SetupMandateRequestData, types::PaymentsResponseData, >, + event_builder: Option<&mut ConnectorEvent>, res: types::Response, ) -> CustomResult< types::RouterData< @@ -1128,7 +1214,10 @@ impl .response .parse_struct("SetupIntentResponse") .change_context(errors::ConnectorError::ResponseDeserializationFailed)?; - logger::info!(connector_response=?response); + + 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(), @@ -1140,12 +1229,16 @@ impl fn get_error_response( &self, res: types::Response, + event_builder: Option<&mut ConnectorEvent>, ) -> CustomResult<types::ErrorResponse, errors::ConnectorError> { let response: stripe::ErrorResponse = res .response .parse_struct("ErrorResponse") .change_context(errors::ConnectorError::ResponseDeserializationFailed)?; - router_env::logger::info!(error_response=?response); + + event_builder.map(|i| i.set_error_response_body(&response)); + router_env::logger::info!(connector_response=?response); + Ok(types::ErrorResponse { status_code: res.status_code, code: response @@ -1239,13 +1332,17 @@ impl services::ConnectorIntegration<api::Execute, types::RefundsData, types::Ref fn handle_response( &self, data: &types::RefundsRouterData<api::Execute>, + event_builder: Option<&mut ConnectorEvent>, res: types::Response, ) -> CustomResult<types::RefundsRouterData<api::Execute>, errors::ConnectorError> { let response: stripe::RefundResponse = res.response .parse_struct("Stripe RefundResponse") .change_context(errors::ConnectorError::ResponseDeserializationFailed)?; - logger::info!(connector_response=?response); + + 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(), @@ -1257,12 +1354,16 @@ impl services::ConnectorIntegration<api::Execute, types::RefundsData, types::Ref fn get_error_response( &self, res: types::Response, + event_builder: Option<&mut ConnectorEvent>, ) -> CustomResult<types::ErrorResponse, errors::ConnectorError> { let response: stripe::ErrorResponse = res .response .parse_struct("ErrorResponse") .change_context(errors::ConnectorError::ResponseDeserializationFailed)?; - router_env::logger::info!(error_response=?response); + + event_builder.map(|i| i.set_error_response_body(&response)); + router_env::logger::info!(connector_response=?response); + Ok(types::ErrorResponse { status_code: res.status_code, code: response @@ -1340,6 +1441,7 @@ impl services::ConnectorIntegration<api::RSync, types::RefundsData, types::Refun fn handle_response( &self, data: &types::RefundsRouterData<api::RSync>, + event_builder: Option<&mut ConnectorEvent>, res: types::Response, ) -> CustomResult< types::RouterData<api::RSync, types::RefundsData, types::RefundsResponseData>, @@ -1349,7 +1451,10 @@ impl services::ConnectorIntegration<api::RSync, types::RefundsData, types::Refun res.response .parse_struct("Stripe RefundResponse") .change_context(errors::ConnectorError::ResponseDeserializationFailed)?; - logger::info!(connector_response=?response); + + 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(), @@ -1361,12 +1466,16 @@ impl services::ConnectorIntegration<api::RSync, types::RefundsData, types::Refun fn get_error_response( &self, res: types::Response, + event_builder: Option<&mut ConnectorEvent>, ) -> CustomResult<types::ErrorResponse, errors::ConnectorError> { let response: stripe::ErrorResponse = res .response .parse_struct("ErrorResponse") .change_context(errors::ConnectorError::ResponseDeserializationFailed)?; - router_env::logger::info!(error_response=?response); + + event_builder.map(|i| i.set_error_response_body(&response)); + router_env::logger::info!(connector_response=?response); + Ok(types::ErrorResponse { status_code: res.status_code, code: response @@ -1488,6 +1597,7 @@ impl fn handle_response( &self, data: &types::UploadFileRouterData, + event_builder: Option<&mut ConnectorEvent>, res: types::Response, ) -> CustomResult< types::RouterData<api::Upload, types::UploadFileRequestData, types::UploadFileResponse>, @@ -1497,7 +1607,8 @@ impl .response .parse_struct("Stripe FileUploadResponse") .change_context(errors::ConnectorError::ResponseDeserializationFailed)?; - logger::info!(connector_response=?response); + event_builder.map(|i| i.set_response_body(&response)); + router_env::logger::info!(connector_response=?response); Ok(types::UploadFileRouterData { response: Ok(types::UploadFileResponse { provider_file_id: response.file_id, @@ -1509,12 +1620,16 @@ impl fn get_error_response( &self, res: types::Response, + event_builder: Option<&mut ConnectorEvent>, ) -> CustomResult<types::ErrorResponse, errors::ConnectorError> { let response: stripe::ErrorResponse = res .response .parse_struct("ErrorResponse") .change_context(errors::ConnectorError::ResponseDeserializationFailed)?; - router_env::logger::info!(error_response=?response); + + event_builder.map(|i| i.set_error_response_body(&response)); + router_env::logger::info!(connector_response=?response); + Ok(types::ErrorResponse { status_code: res.status_code, code: response @@ -1592,6 +1707,7 @@ impl fn handle_response( &self, data: &types::RetrieveFileRouterData, + _event_builder: Option<&mut ConnectorEvent>, res: types::Response, ) -> CustomResult< types::RouterData< @@ -1602,6 +1718,7 @@ impl errors::ConnectorError, > { let response = res.response; + router_env::logger::info!(connector_response=?response); Ok(types::RetrieveFileRouterData { response: Ok(types::RetrieveFileResponse { file_data: response.to_vec(), @@ -1613,12 +1730,15 @@ impl fn get_error_response( &self, res: types::Response, + event_builder: Option<&mut ConnectorEvent>, ) -> CustomResult<types::ErrorResponse, errors::ConnectorError> { let response: stripe::ErrorResponse = res .response .parse_struct("ErrorResponse") .change_context(errors::ConnectorError::ResponseDeserializationFailed)?; - router_env::logger::info!(error_response=?response); + event_builder.map(|i| i.set_error_response_body(&response)); + router_env::logger::info!(connector_response=?response); + Ok(types::ErrorResponse { status_code: res.status_code, code: response @@ -1719,13 +1839,15 @@ impl fn handle_response( &self, data: &types::SubmitEvidenceRouterData, + event_builder: Option<&mut ConnectorEvent>, res: types::Response, ) -> CustomResult<types::SubmitEvidenceRouterData, errors::ConnectorError> { let response: stripe::DisputeObj = res .response .parse_struct("Stripe DisputeObj") .change_context(errors::ConnectorError::ResponseDeserializationFailed)?; - logger::info!(connector_response=?response); + event_builder.map(|i| i.set_response_body(&response)); + router_env::logger::info!(connector_response=?response); Ok(types::SubmitEvidenceRouterData { response: Ok(types::SubmitEvidenceResponse { dispute_status: api_models::enums::DisputeStatus::DisputeChallenged, @@ -1738,12 +1860,16 @@ impl fn get_error_response( &self, res: types::Response, + event_builder: Option<&mut ConnectorEvent>, ) -> CustomResult<types::ErrorResponse, errors::ConnectorError> { let response: stripe::ErrorResponse = res .response .parse_struct("ErrorResponse") .change_context(errors::ConnectorError::ResponseDeserializationFailed)?; - router_env::logger::info!(error_response=?response); + + event_builder.map(|i| i.set_error_response_body(&response)); + router_env::logger::info!(connector_response=?response); + Ok(types::ErrorResponse { status_code: res.status_code, code: response diff --git a/crates/router/src/connector/stripe/transformers.rs b/crates/router/src/connector/stripe/transformers.rs index 3558d6e487b..6a89232d4e8 100644 --- a/crates/router/src/connector/stripe/transformers.rs +++ b/crates/router/src/connector/stripe/transformers.rs @@ -3,7 +3,7 @@ use std::{collections::HashMap, ops::Deref}; use api_models::{self, enums as api_enums, payments}; use common_utils::{ errors::CustomResult, - ext_traits::{ByteSliceExt, BytesExt}, + ext_traits::ByteSliceExt, pii::{self, Email}, request::RequestContent, }; @@ -186,7 +186,7 @@ pub struct TokenRequest { pub token_data: StripePaymentMethodData, } -#[derive(Debug, Eq, PartialEq, Deserialize)] +#[derive(Debug, Eq, PartialEq, Deserialize, Serialize)] pub struct StripeTokenResponse { pub id: String, pub object: String, @@ -201,7 +201,7 @@ pub struct CustomerRequest { pub source: Option<String>, } -#[derive(Debug, Eq, PartialEq, Deserialize)] +#[derive(Debug, Eq, PartialEq, Deserialize, Serialize)] pub struct StripeCustomerResponse { pub id: String, pub description: Option<String>, @@ -220,7 +220,7 @@ pub struct ChargesRequest { pub meta_data: Option<HashMap<String, String>>, } -#[derive(Clone, Debug, Default, Eq, PartialEq, Deserialize)] +#[derive(Clone, Debug, Default, Eq, PartialEq, Deserialize, Serialize)] pub struct ChargesResponse { pub id: String, pub amount: u64, @@ -2085,7 +2085,7 @@ impl From<StripePaymentStatus> for enums::AttemptStatus { } } -#[derive(Debug, Default, Eq, PartialEq, Deserialize)] +#[derive(Debug, Default, Eq, PartialEq, Deserialize, Serialize)] pub struct PaymentIntentResponse { pub id: String, pub object: String, @@ -2182,7 +2182,7 @@ pub struct LastPaymentError { decline_code: Option<String>, } -#[derive(Deserialize, Debug)] +#[derive(Deserialize, Debug, Serialize)] pub struct PaymentIntentSyncResponse { #[serde(flatten)] payment_intent_fields: PaymentIntentResponse, @@ -2190,20 +2190,20 @@ pub struct PaymentIntentSyncResponse { pub latest_charge: Option<StripeChargeEnum>, } -#[derive(Deserialize, Debug, Clone)] +#[derive(Deserialize, Debug, Clone, Serialize)] #[serde(untagged)] pub enum StripeChargeEnum { ChargeId(String), ChargeObject(StripeCharge), } -#[derive(Deserialize, Clone, Debug)] +#[derive(Deserialize, Clone, Debug, Serialize)] pub struct StripeCharge { pub id: String, pub payment_method_details: Option<StripePaymentMethodDetailsResponse>, } -#[derive(Deserialize, Clone, Debug)] +#[derive(Deserialize, Clone, Debug, Serialize)] pub struct StripeBankRedirectDetails { #[serde(rename = "generated_sepa_debit")] attached_payment_method: Option<String>, @@ -2217,7 +2217,7 @@ impl Deref for PaymentIntentSyncResponse { } } -#[derive(Deserialize, Clone, Debug)] +#[derive(Deserialize, Clone, Debug, Serialize)] #[serde(rename_all = "snake_case", tag = "type")] pub enum StripePaymentMethodDetailsResponse { //only ideal, sofort and bancontact is supported by stripe for recurring payment in bank redirect @@ -2302,7 +2302,7 @@ impl From<SetupIntentResponse> for PaymentIntentResponse { } } -#[derive(Clone, Debug, Default, Eq, PartialEq, Deserialize)] +#[derive(Clone, Debug, Default, Eq, PartialEq, Deserialize, Serialize)] pub struct SetupIntentResponse { pub id: String, pub object: String, @@ -2627,7 +2627,7 @@ impl ForeignFrom<Option<LatestAttempt>> for Option<String> { } } -#[derive(Clone, Debug, Eq, PartialEq, Deserialize)] +#[derive(Clone, Debug, Eq, PartialEq, Deserialize, Serialize)] #[serde(rename_all = "snake_case", remote = "Self")] pub enum StripeNextActionResponse { CashappHandleRedirectOrDisplayQrCode(StripeCashappQrResponse), @@ -2686,6 +2686,27 @@ impl<'de> Deserialize<'de> for StripeNextActionResponse { } } +impl Serialize for StripeNextActionResponse { + fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error> + where + S: serde::Serializer, + { + match *self { + Self::CashappHandleRedirectOrDisplayQrCode(ref i) => { + serde::Serialize::serialize(i, serializer) + } + Self::RedirectToUrl(ref i) => serde::Serialize::serialize(i, serializer), + Self::AlipayHandleRedirect(ref i) => serde::Serialize::serialize(i, serializer), + Self::VerifyWithMicrodeposits(ref i) => serde::Serialize::serialize(i, serializer), + Self::WechatPayDisplayQrCode(ref i) => serde::Serialize::serialize(i, serializer), + Self::DisplayBankTransferInstructions(ref i) => { + serde::Serialize::serialize(i, serializer) + } + Self::NoNextActionBody => serde::Serialize::serialize("NoNextActionBody", serializer), + } + } +} + #[derive(Clone, Debug, Eq, PartialEq, Deserialize, Serialize)] pub struct StripeRedirectToUrlResponse { return_url: String, @@ -2701,7 +2722,7 @@ pub struct WechatPayRedirectToQr { image_data_url: Url, } -#[derive(Clone, Debug, Eq, PartialEq, Deserialize)] +#[derive(Clone, Debug, Eq, PartialEq, Deserialize, Serialize)] pub struct StripeVerifyWithMicroDepositsResponse { hosted_verification_url: Url, } @@ -3013,13 +3034,13 @@ pub struct MitExemption { pub network_transaction_id: Secret<String>, } -#[derive(Clone, Debug, Eq, PartialEq, Deserialize)] +#[derive(Clone, Debug, Eq, PartialEq, Deserialize, Serialize)] #[serde(untagged)] pub enum LatestAttempt { PaymentIntentAttempt(LatestPaymentAttempt), SetupAttempt(String), } -#[derive(Clone, Debug, Default, Eq, PartialEq, Deserialize)] +#[derive(Clone, Debug, Default, Eq, PartialEq, Deserialize, Serialize)] pub struct LatestPaymentAttempt { pub payment_method_options: Option<StripePaymentMethodOptions>, } @@ -3588,40 +3609,6 @@ pub fn get_bank_transfer_request_data( } } -pub fn get_bank_transfer_authorize_response( - data: &types::PaymentsAuthorizeRouterData, - res: types::Response, - bank_transfer_data: &api_models::payments::BankTransferData, -) -> CustomResult<types::PaymentsAuthorizeRouterData, errors::ConnectorError> { - match bank_transfer_data { - api_models::payments::BankTransferData::AchBankTransfer { .. } - | api_models::payments::BankTransferData::MultibancoBankTransfer { .. } => { - let response: ChargesResponse = res - .response - .parse_struct("ChargesResponse") - .change_context(errors::ConnectorError::ResponseDeserializationFailed)?; - - types::RouterData::try_from(types::ResponseRouterData { - response, - data: data.clone(), - http_code: res.status_code, - }) - } - _ => { - let response: PaymentIntentResponse = res - .response - .parse_struct("PaymentIntentResponse") - .change_context(errors::ConnectorError::ResponseDeserializationFailed)?; - - types::RouterData::try_from(types::ResponseRouterData { - response, - data: data.clone(), - http_code: res.status_code, - }) - } - } -} - pub fn construct_file_upload_request( file_upload_router_data: types::UploadFileRouterData, ) -> CustomResult<reqwest::multipart::Form, errors::ConnectorError> { @@ -3636,7 +3623,7 @@ pub fn construct_file_upload_request( Ok(multipart) } -#[derive(Debug, Deserialize)] +#[derive(Debug, Deserialize, Serialize)] pub struct FileUploadResponse { #[serde(rename = "id")] pub file_id: String, @@ -3768,7 +3755,7 @@ impl TryFrom<&types::SubmitEvidenceRouterData> for Evidence { } } -#[derive(Debug, Deserialize)] +#[derive(Debug, Deserialize, Serialize)] pub struct DisputeObj { #[serde(rename = "id")] pub dispute_id: String, diff --git a/crates/router/src/connector/trustpay.rs b/crates/router/src/connector/trustpay.rs index 61ee2e2659d..18775dd3981 100644 --- a/crates/router/src/connector/trustpay.rs +++ b/crates/router/src/connector/trustpay.rs @@ -21,6 +21,7 @@ use crate::{ errors::{self, CustomResult}, payments, }, + events::connector_api_logs::ConnectorEvent, headers, logger, services::{ self, @@ -109,6 +110,7 @@ impl ConnectorCommon for Trustpay { fn build_error_response( &self, res: Response, + event_builder: Option<&mut ConnectorEvent>, ) -> CustomResult<ErrorResponse, errors::ConnectorError> { let response: Result< trustpay::TrustpayErrorResponse, @@ -117,6 +119,8 @@ impl ConnectorCommon for Trustpay { match response { Ok(response_data) => { + event_builder.map(|i| i.set_error_response_body(&response_data)); + router_env::logger::info!(connector_response=?response_data); let error_list = response_data.errors.clone().unwrap_or_default(); let option_error_code_message = get_error_code_error_message_based_on_priority( self.clone(), @@ -147,6 +151,7 @@ impl ConnectorCommon for Trustpay { }) } Err(error_msg) => { + event_builder.map(|event| event.set_error(serde_json::json!({"error": res.response.escape_ascii().to_string(), "status_code": res.status_code}))); logger::error!(deserialization_error =? error_msg); utils::handle_json_response_deserialization_failure(res, "trustpay".to_owned()) } @@ -279,12 +284,17 @@ impl ConnectorIntegration<api::AccessTokenAuth, types::AccessTokenRequestData, t fn handle_response( &self, data: &types::RefreshTokenRouterData, + event_builder: Option<&mut ConnectorEvent>, res: Response, ) -> CustomResult<types::RefreshTokenRouterData, errors::ConnectorError> { let response: trustpay::TrustpayAuthUpdateResponse = res .response .parse_struct("trustpay TrustpayAuthUpdateResponse") .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(), @@ -296,11 +306,16 @@ impl ConnectorIntegration<api::AccessTokenAuth, types::AccessTokenRequestData, t fn get_error_response( &self, res: Response, + event_builder: Option<&mut ConnectorEvent>, ) -> CustomResult<ErrorResponse, errors::ConnectorError> { let response: trustpay::TrustpayAccessTokenErrorResponse = res .response .parse_struct("Trustpay AccessTokenErrorResponse") .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.result_info.result_code.to_string(), @@ -371,19 +386,25 @@ impl ConnectorIntegration<api::PSync, types::PaymentsSyncData, types::PaymentsRe fn get_error_response( &self, res: Response, + event_builder: Option<&mut ConnectorEvent>, ) -> CustomResult<ErrorResponse, errors::ConnectorError> { - self.build_error_response(res) + self.build_error_response(res, event_builder) } fn handle_response( &self, data: &types::PaymentsSyncRouterData, + event_builder: Option<&mut ConnectorEvent>, res: Response, ) -> CustomResult<types::PaymentsSyncRouterData, errors::ConnectorError> { let response: trustpay::TrustpayPaymentsResponse = res .response .parse_struct("trustpay PaymentsResponse") .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(), @@ -480,12 +501,17 @@ impl fn handle_response( &self, data: &types::PaymentsPreProcessingRouterData, + event_builder: Option<&mut ConnectorEvent>, res: Response, ) -> CustomResult<types::PaymentsPreProcessingRouterData, errors::ConnectorError> { let response: trustpay::TrustpayCreateIntentResponse = res .response .parse_struct("TrustpayCreateIntentResponse") .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(), @@ -497,8 +523,9 @@ impl fn get_error_response( &self, res: Response, + event_builder: Option<&mut ConnectorEvent>, ) -> CustomResult<ErrorResponse, errors::ConnectorError> { - self.build_error_response(res) + self.build_error_response(res, event_builder) } } @@ -590,12 +617,17 @@ impl ConnectorIntegration<api::Authorize, types::PaymentsAuthorizeData, types::P fn handle_response( &self, data: &types::PaymentsAuthorizeRouterData, + event_builder: Option<&mut ConnectorEvent>, res: Response, ) -> CustomResult<types::PaymentsAuthorizeRouterData, errors::ConnectorError> { let response: trustpay::TrustpayPaymentsResponse = res .response .parse_struct("trustpay PaymentsResponse") .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(), @@ -607,8 +639,9 @@ impl ConnectorIntegration<api::Authorize, types::PaymentsAuthorizeData, types::P fn get_error_response( &self, res: Response, + event_builder: Option<&mut ConnectorEvent>, ) -> CustomResult<ErrorResponse, errors::ConnectorError> { - self.build_error_response(res) + self.build_error_response(res, event_builder) } } @@ -690,12 +723,17 @@ impl ConnectorIntegration<api::Execute, types::RefundsData, types::RefundsRespon 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: trustpay::RefundResponse = res .response .parse_struct("trustpay 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 { response, data: data.clone(), @@ -707,8 +745,9 @@ impl ConnectorIntegration<api::Execute, types::RefundsData, types::RefundsRespon fn get_error_response( &self, res: Response, + event_builder: Option<&mut ConnectorEvent>, ) -> CustomResult<ErrorResponse, errors::ConnectorError> { - self.build_error_response(res) + self.build_error_response(res, event_builder) } } @@ -767,12 +806,17 @@ impl ConnectorIntegration<api::RSync, types::RefundsData, types::RefundsResponse fn handle_response( &self, data: &types::RefundSyncRouterData, + event_builder: Option<&mut ConnectorEvent>, res: Response, ) -> CustomResult<types::RefundSyncRouterData, errors::ConnectorError> { let response: trustpay::RefundResponse = res .response .parse_struct("trustpay 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(), @@ -784,8 +828,9 @@ impl ConnectorIntegration<api::RSync, types::RefundsData, types::RefundsResponse fn get_error_response( &self, res: Response, + event_builder: Option<&mut ConnectorEvent>, ) -> CustomResult<ErrorResponse, errors::ConnectorError> { - self.build_error_response(res) + self.build_error_response(res, event_builder) } } diff --git a/crates/router/src/connector/trustpay/transformers.rs b/crates/router/src/connector/trustpay/transformers.rs index c266753423e..71286bda3f1 100644 --- a/crates/router/src/connector/trustpay/transformers.rs +++ b/crates/router/src/connector/trustpay/transformers.rs @@ -946,7 +946,7 @@ pub struct ResultInfo { pub correlation_id: Option<String>, } -#[derive(Default, Debug, Clone, Deserialize, PartialEq)] +#[derive(Default, Debug, Clone, Deserialize, Serialize, PartialEq)] pub struct TrustpayAuthUpdateResponse { pub access_token: Option<Secret<String>>, pub token_type: Option<String>, @@ -955,7 +955,7 @@ pub struct TrustpayAuthUpdateResponse { pub result_info: ResultInfo, } -#[derive(Default, Debug, Clone, Deserialize, PartialEq)] +#[derive(Default, Debug, Clone, Deserialize, PartialEq, Serialize)] #[serde(rename_all = "PascalCase")] pub struct TrustpayAccessTokenErrorResponse { pub result_info: ResultInfo, @@ -1038,7 +1038,7 @@ impl TryFrom<&TrustpayRouterData<&types::PaymentsPreProcessingRouterData>> } } -#[derive(Clone, Debug, Deserialize)] +#[derive(Clone, Debug, Deserialize, Serialize)] #[serde(rename_all = "camelCase")] pub struct TrustpayCreateIntentResponse { // TrustPay's authorization secrets used by client @@ -1050,14 +1050,14 @@ pub struct TrustpayCreateIntentResponse { pub instance_id: String, } -#[derive(Clone, Debug, Deserialize)] +#[derive(Clone, Debug, Deserialize, Serialize)] #[serde(rename_all = "camelCase")] pub enum InitResultData { AppleInitResultData(TrustpayApplePayResponse), GoogleInitResultData(TrustpayGooglePayResponse), } -#[derive(Clone, Default, Debug, Deserialize)] +#[derive(Clone, Default, Debug, Deserialize, Serialize)] #[serde(rename_all = "camelCase")] pub struct GooglePayTransactionInfo { pub country_code: api_models::enums::CountryAlpha2, @@ -1066,14 +1066,14 @@ pub struct GooglePayTransactionInfo { pub total_price: String, } -#[derive(Clone, Default, Debug, Deserialize)] +#[derive(Clone, Default, Debug, Deserialize, Serialize)] #[serde(rename_all = "camelCase")] pub struct GooglePayMerchantInfo { pub merchant_name: String, pub merchant_id: String, } -#[derive(Clone, Default, Debug, Deserialize)] +#[derive(Clone, Default, Debug, Deserialize, Serialize)] #[serde(rename_all = "camelCase")] pub struct GooglePayAllowedPaymentMethods { #[serde(rename = "type")] @@ -1082,14 +1082,14 @@ pub struct GooglePayAllowedPaymentMethods { pub tokenization_specification: GpayTokenizationSpecification, } -#[derive(Clone, Default, Debug, Deserialize)] +#[derive(Clone, Default, Debug, Deserialize, Serialize)] #[serde(rename_all = "camelCase")] pub struct GpayTokenParameters { pub gateway: String, pub gateway_merchant_id: String, } -#[derive(Clone, Default, Debug, Deserialize)] +#[derive(Clone, Default, Debug, Deserialize, Serialize)] #[serde(rename_all = "camelCase")] pub struct GpayTokenizationSpecification { #[serde(rename = "type")] @@ -1097,14 +1097,14 @@ pub struct GpayTokenizationSpecification { pub parameters: GpayTokenParameters, } -#[derive(Clone, Default, Debug, Deserialize)] +#[derive(Clone, Default, Debug, Deserialize, Serialize)] #[serde(rename_all = "camelCase")] pub struct GpayAllowedMethodsParameters { pub allowed_auth_methods: Vec<String>, pub allowed_card_networks: Vec<String>, } -#[derive(Clone, Default, Debug, Deserialize)] +#[derive(Clone, Default, Debug, Deserialize, Serialize)] #[serde(rename_all = "camelCase")] pub struct TrustpayGooglePayResponse { pub merchant_info: GooglePayMerchantInfo, @@ -1112,14 +1112,14 @@ pub struct TrustpayGooglePayResponse { pub transaction_info: GooglePayTransactionInfo, } -#[derive(Clone, Default, Debug, Deserialize)] +#[derive(Clone, Default, Debug, Deserialize, Serialize)] #[serde(rename_all = "camelCase")] pub struct SdkSecretInfo { pub display: Secret<String>, pub payment: Secret<String>, } -#[derive(Clone, Default, Debug, Deserialize)] +#[derive(Clone, Default, Debug, Deserialize, Serialize)] #[serde(rename_all = "camelCase")] pub struct TrustpayApplePayResponse { pub country_code: api_models::enums::CountryAlpha2, @@ -1129,7 +1129,7 @@ pub struct TrustpayApplePayResponse { pub total: ApplePayTotalInfo, } -#[derive(Clone, Default, Debug, Deserialize)] +#[derive(Clone, Default, Debug, Deserialize, Serialize)] #[serde(rename_all = "camelCase")] pub struct ApplePayTotalInfo { pub label: String, diff --git a/crates/router/src/connector/tsys.rs b/crates/router/src/connector/tsys.rs index 8c19f9f823a..8117bc8901b 100644 --- a/crates/router/src/connector/tsys.rs +++ b/crates/router/src/connector/tsys.rs @@ -11,6 +11,7 @@ use crate::{ configs::settings, connector::utils as connector_utils, core::errors::{self, CustomResult}, + events::connector_api_logs::ConnectorEvent, headers, services::{ self, @@ -189,12 +190,17 @@ impl ConnectorIntegration<api::Authorize, types::PaymentsAuthorizeData, types::P fn handle_response( &self, data: &types::PaymentsAuthorizeRouterData, + event_builder: Option<&mut ConnectorEvent>, res: Response, ) -> CustomResult<types::PaymentsAuthorizeRouterData, errors::ConnectorError> { let response: tsys::TsysPaymentsResponse = res .response .parse_struct("Tsys 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(), @@ -205,8 +211,9 @@ impl ConnectorIntegration<api::Authorize, types::PaymentsAuthorizeData, types::P fn get_error_response( &self, res: Response, + event_builder: Option<&mut ConnectorEvent>, ) -> CustomResult<ErrorResponse, errors::ConnectorError> { - self.build_error_response(res) + self.build_error_response(res, event_builder) } } @@ -266,12 +273,17 @@ impl ConnectorIntegration<api::PSync, types::PaymentsSyncData, types::PaymentsRe fn handle_response( &self, data: &types::PaymentsSyncRouterData, + event_builder: Option<&mut ConnectorEvent>, res: Response, ) -> CustomResult<types::PaymentsSyncRouterData, errors::ConnectorError> { let response: tsys::TsysSyncResponse = res .response .parse_struct("tsys 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(), @@ -282,8 +294,9 @@ impl ConnectorIntegration<api::PSync, types::PaymentsSyncData, types::PaymentsRe fn get_error_response( &self, res: Response, + event_builder: Option<&mut ConnectorEvent>, ) -> CustomResult<ErrorResponse, errors::ConnectorError> { - self.build_error_response(res) + self.build_error_response(res, event_builder) } } @@ -345,12 +358,17 @@ impl ConnectorIntegration<api::Capture, types::PaymentsCaptureData, types::Payme fn handle_response( &self, data: &types::PaymentsCaptureRouterData, + event_builder: Option<&mut ConnectorEvent>, res: Response, ) -> CustomResult<types::PaymentsCaptureRouterData, errors::ConnectorError> { let response: tsys::TsysPaymentsResponse = res .response .parse_struct("Tsys 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(), @@ -361,8 +379,9 @@ impl ConnectorIntegration<api::Capture, types::PaymentsCaptureData, types::Payme fn get_error_response( &self, res: Response, + event_builder: Option<&mut ConnectorEvent>, ) -> CustomResult<ErrorResponse, errors::ConnectorError> { - self.build_error_response(res) + self.build_error_response(res, event_builder) } } @@ -420,12 +439,17 @@ impl ConnectorIntegration<api::Void, types::PaymentsCancelData, types::PaymentsR fn handle_response( &self, data: &types::PaymentsCancelRouterData, + event_builder: Option<&mut ConnectorEvent>, res: Response, ) -> CustomResult<types::PaymentsCancelRouterData, errors::ConnectorError> { let response: tsys::TsysPaymentsResponse = res .response .parse_struct("PaymentCancelResponse") .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(), @@ -435,8 +459,9 @@ impl ConnectorIntegration<api::Void, types::PaymentsCancelData, types::PaymentsR fn get_error_response( &self, res: Response, + event_builder: Option<&mut ConnectorEvent>, ) -> CustomResult<ErrorResponse, errors::ConnectorError> { - self.build_error_response(res) + self.build_error_response(res, event_builder) } } @@ -495,12 +520,17 @@ impl ConnectorIntegration<api::Execute, types::RefundsData, types::RefundsRespon 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: tsys::RefundResponse = res .response .parse_struct("tsys 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(), @@ -511,8 +541,9 @@ impl ConnectorIntegration<api::Execute, types::RefundsData, types::RefundsRespon fn get_error_response( &self, res: Response, + event_builder: Option<&mut ConnectorEvent>, ) -> CustomResult<ErrorResponse, errors::ConnectorError> { - self.build_error_response(res) + self.build_error_response(res, event_builder) } } @@ -570,12 +601,17 @@ impl ConnectorIntegration<api::RSync, types::RefundsData, types::RefundsResponse fn handle_response( &self, data: &types::RefundSyncRouterData, + event_builder: Option<&mut ConnectorEvent>, res: Response, ) -> CustomResult<types::RefundSyncRouterData, errors::ConnectorError> { let response: tsys::TsysSyncResponse = res .response .parse_struct("tsys 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(), @@ -586,8 +622,9 @@ impl ConnectorIntegration<api::RSync, types::RefundsData, types::RefundsResponse fn get_error_response( &self, res: Response, + event_builder: Option<&mut ConnectorEvent>, ) -> CustomResult<ErrorResponse, errors::ConnectorError> { - self.build_error_response(res) + self.build_error_response(res, event_builder) } } diff --git a/crates/router/src/connector/tsys/transformers.rs b/crates/router/src/connector/tsys/transformers.rs index dd700d11bcb..a01576bbb20 100644 --- a/crates/router/src/connector/tsys/transformers.rs +++ b/crates/router/src/connector/tsys/transformers.rs @@ -111,14 +111,14 @@ impl TryFrom<&types::ConnectorAuthType> for TsysAuthType { } // PaymentsResponse -#[derive(Debug, Clone, Deserialize)] +#[derive(Debug, Clone, Deserialize, Serialize)] #[serde(rename_all = "UPPERCASE")] pub enum TsysPaymentStatus { Pass, Fail, } -#[derive(Debug, Clone, Deserialize)] +#[derive(Debug, Clone, Deserialize, Serialize)] #[serde(rename_all = "UPPERCASE")] pub enum TsysTransactionStatus { Approved, @@ -142,7 +142,7 @@ impl From<TsysTransactionDetails> for enums::AttemptStatus { } } -#[derive(Debug, Clone, Deserialize)] +#[derive(Debug, Clone, Deserialize, Serialize)] #[serde(rename_all = "camelCase")] pub struct TsysErrorResponse { pub status: TsysPaymentStatus, @@ -150,7 +150,7 @@ pub struct TsysErrorResponse { pub response_message: String, } -#[derive(Debug, Clone, Deserialize)] +#[derive(Debug, Clone, Deserialize, Serialize)] #[serde(rename_all = "camelCase")] pub struct TsysTransactionDetails { #[serde(rename = "transactionID")] @@ -159,7 +159,7 @@ pub struct TsysTransactionDetails { transaction_status: TsysTransactionStatus, } -#[derive(Debug, Clone, Deserialize)] +#[derive(Debug, Clone, Deserialize, Serialize)] #[serde(rename_all = "camelCase")] pub struct TsysPaymentsSyncResponse { pub status: TsysPaymentStatus, @@ -168,7 +168,7 @@ pub struct TsysPaymentsSyncResponse { pub transaction_details: TsysTransactionDetails, } -#[derive(Debug, Clone, Deserialize)] +#[derive(Debug, Clone, Deserialize, Serialize)] #[serde(rename_all = "camelCase")] pub struct TsysResponse { pub status: TsysPaymentStatus, @@ -178,14 +178,14 @@ pub struct TsysResponse { pub transaction_id: String, } -#[derive(Debug, Clone, Deserialize)] +#[derive(Debug, Clone, Deserialize, Serialize)] #[serde(untagged)] pub enum TsysResponseTypes { SuccessResponse(TsysResponse), ErrorResponse(TsysErrorResponse), } -#[derive(Debug, Clone, Deserialize)] +#[derive(Debug, Clone, Deserialize, Serialize)] #[allow(clippy::enum_variant_names)] pub enum TsysPaymentsResponse { AuthResponse(TsysResponseTypes), @@ -195,13 +195,13 @@ pub enum TsysPaymentsResponse { } fn get_error_response( - connector_error_response: TsysErrorResponse, + connector_response: TsysErrorResponse, status_code: u16, ) -> types::ErrorResponse { types::ErrorResponse { - code: connector_error_response.response_code, - message: connector_error_response.response_message.clone(), - reason: Some(connector_error_response.response_message), + code: connector_response.response_code, + message: connector_response.response_message.clone(), + reason: Some(connector_response.response_message), status_code, attempt_status: None, connector_transaction_id: None, @@ -260,8 +260,8 @@ impl<F, T> Ok(get_payments_response(auth_response)), enums::AttemptStatus::Authorized, ), - TsysResponseTypes::ErrorResponse(connector_error_response) => ( - Err(get_error_response(connector_error_response, item.http_code)), + TsysResponseTypes::ErrorResponse(connector_response) => ( + Err(get_error_response(connector_response, item.http_code)), enums::AttemptStatus::AuthorizationFailed, ), }, @@ -270,8 +270,8 @@ impl<F, T> Ok(get_payments_response(sale_response)), enums::AttemptStatus::Charged, ), - TsysResponseTypes::ErrorResponse(connector_error_response) => ( - Err(get_error_response(connector_error_response, item.http_code)), + TsysResponseTypes::ErrorResponse(connector_response) => ( + Err(get_error_response(connector_response, item.http_code)), enums::AttemptStatus::Failure, ), }, @@ -280,8 +280,8 @@ impl<F, T> Ok(get_payments_response(capture_response)), enums::AttemptStatus::Charged, ), - TsysResponseTypes::ErrorResponse(connector_error_response) => ( - Err(get_error_response(connector_error_response, item.http_code)), + TsysResponseTypes::ErrorResponse(connector_response) => ( + Err(get_error_response(connector_response, item.http_code)), enums::AttemptStatus::CaptureFailed, ), }, @@ -290,8 +290,8 @@ impl<F, T> Ok(get_payments_response(void_response)), enums::AttemptStatus::Voided, ), - TsysResponseTypes::ErrorResponse(connector_error_response) => ( - Err(get_error_response(connector_error_response, item.http_code)), + TsysResponseTypes::ErrorResponse(connector_response) => ( + Err(get_error_response(connector_response, item.http_code)), enums::AttemptStatus::VoidFailed, ), }, @@ -340,14 +340,14 @@ impl TryFrom<&types::PaymentsSyncRouterData> for TsysSyncRequest { } } -#[derive(Debug, Deserialize)] +#[derive(Debug, Deserialize, Serialize)] #[serde(untagged)] pub enum SearchResponseTypes { SuccessResponse(TsysPaymentsSyncResponse), ErrorResponse(TsysErrorResponse), } -#[derive(Debug, Deserialize)] +#[derive(Debug, Deserialize, Serialize)] #[serde(rename_all = "PascalCase")] pub struct TsysSyncResponse { search_transaction_response: SearchResponseTypes, @@ -366,8 +366,8 @@ impl<F, T> TryFrom<types::ResponseRouterData<F, TsysSyncResponse, T, types::Paym Ok(get_payments_sync_response(&search_response)), enums::AttemptStatus::from(search_response.transaction_details), ), - SearchResponseTypes::ErrorResponse(connector_error_response) => ( - Err(get_error_response(connector_error_response, item.http_code)), + SearchResponseTypes::ErrorResponse(connector_response) => ( + Err(get_error_response(connector_response, item.http_code)), item.data.status, ), }; @@ -498,7 +498,7 @@ impl From<TsysTransactionDetails> for enums::RefundStatus { } } -#[derive(Debug, Deserialize)] +#[derive(Debug, Deserialize, Serialize)] #[serde(rename_all = "PascalCase")] pub struct RefundResponse { return_response: TsysResponseTypes, @@ -517,8 +517,8 @@ impl TryFrom<types::RefundsResponseRouterData<api::Execute, RefundResponse>> connector_refund_id: return_response.transaction_id, refund_status: enums::RefundStatus::from(return_response.status), }), - TsysResponseTypes::ErrorResponse(connector_error_response) => { - Err(get_error_response(connector_error_response, item.http_code)) + TsysResponseTypes::ErrorResponse(connector_response) => { + Err(get_error_response(connector_response, item.http_code)) } }; Ok(Self { @@ -557,8 +557,8 @@ impl TryFrom<types::RefundsResponseRouterData<api::RSync, TsysSyncResponse>> refund_status: enums::RefundStatus::from(search_response.transaction_details), }) } - SearchResponseTypes::ErrorResponse(connector_error_response) => { - Err(get_error_response(connector_error_response, item.http_code)) + SearchResponseTypes::ErrorResponse(connector_response) => { + Err(get_error_response(connector_response, item.http_code)) } }; Ok(Self { diff --git a/crates/router/src/connector/volt.rs b/crates/router/src/connector/volt.rs index f125f90d93a..4a08bc1ad6b 100644 --- a/crates/router/src/connector/volt.rs +++ b/crates/router/src/connector/volt.rs @@ -12,6 +12,7 @@ use super::utils; use crate::{ configs::settings, core::errors::{self, CustomResult}, + events::connector_api_logs::ConnectorEvent, headers, services::{ self, @@ -112,12 +113,16 @@ impl ConnectorCommon for Volt { fn build_error_response( &self, res: Response, + event_builder: Option<&mut ConnectorEvent>, ) -> CustomResult<ErrorResponse, errors::ConnectorError> { let response: volt::VoltErrorResponse = res .response .parse_struct("VoltErrorResponse") .change_context(errors::ConnectorError::ResponseDeserializationFailed)?; + event_builder.map(|i| i.set_response_body(&response)); + router_env::logger::info!(connector_response=?response); + let reason = match &response.exception.error_list { Some(error_list) => error_list .iter() @@ -207,6 +212,7 @@ impl ConnectorIntegration<api::AccessTokenAuth, types::AccessTokenRequestData, t fn handle_response( &self, data: &types::RefreshTokenRouterData, + event_builder: Option<&mut ConnectorEvent>, res: Response, ) -> CustomResult<types::RefreshTokenRouterData, errors::ConnectorError> { let response: volt::VoltAuthUpdateResponse = res @@ -214,6 +220,9 @@ impl ConnectorIntegration<api::AccessTokenAuth, types::AccessTokenRequestData, t .parse_struct("Volt VoltAuthUpdateResponse") .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(), @@ -224,6 +233,7 @@ impl ConnectorIntegration<api::AccessTokenAuth, types::AccessTokenRequestData, t fn get_error_response( &self, res: Response, + event_builder: Option<&mut ConnectorEvent>, ) -> CustomResult<ErrorResponse, errors::ConnectorError> { // auth error have different structure than common error let response: volt::VoltAuthErrorResponse = res @@ -231,6 +241,9 @@ impl ConnectorIntegration<api::AccessTokenAuth, types::AccessTokenRequestData, t .parse_struct("VoltAuthErrorResponse") .change_context(errors::ConnectorError::ResponseDeserializationFailed)?; + event_builder.map(|i| i.set_error_response_body(&response)); + router_env::logger::info!(connector_response=?response); + Ok(ErrorResponse { status_code: res.status_code, code: response.code.to_string(), @@ -328,12 +341,17 @@ impl ConnectorIntegration<api::Authorize, types::PaymentsAuthorizeData, types::P fn handle_response( &self, data: &types::PaymentsAuthorizeRouterData, + event_builder: Option<&mut ConnectorEvent>, res: Response, ) -> CustomResult<types::PaymentsAuthorizeRouterData, errors::ConnectorError> { let response: volt::VoltPaymentsResponse = res .response .parse_struct("Volt 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(), @@ -344,8 +362,9 @@ impl ConnectorIntegration<api::Authorize, types::PaymentsAuthorizeData, types::P fn get_error_response( &self, res: Response, + event_builder: Option<&mut ConnectorEvent>, ) -> CustomResult<ErrorResponse, errors::ConnectorError> { - self.build_error_response(res) + self.build_error_response(res, event_builder) } } @@ -398,12 +417,17 @@ impl ConnectorIntegration<api::PSync, types::PaymentsSyncData, types::PaymentsRe fn handle_response( &self, data: &types::PaymentsSyncRouterData, + event_builder: Option<&mut ConnectorEvent>, res: Response, ) -> CustomResult<types::PaymentsSyncRouterData, errors::ConnectorError> { let response: volt::VoltPaymentsResponseData = res .response .parse_struct("volt 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(), @@ -414,8 +438,9 @@ impl ConnectorIntegration<api::PSync, types::PaymentsSyncData, types::PaymentsRe fn get_error_response( &self, res: Response, + event_builder: Option<&mut ConnectorEvent>, ) -> CustomResult<ErrorResponse, errors::ConnectorError> { - self.build_error_response(res) + self.build_error_response(res, event_builder) } } @@ -473,12 +498,17 @@ impl ConnectorIntegration<api::Capture, types::PaymentsCaptureData, types::Payme fn handle_response( &self, data: &types::PaymentsCaptureRouterData, + event_builder: Option<&mut ConnectorEvent>, res: Response, ) -> CustomResult<types::PaymentsCaptureRouterData, errors::ConnectorError> { let response: volt::VoltPaymentsResponse = res .response .parse_struct("Volt 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(), @@ -489,8 +519,9 @@ impl ConnectorIntegration<api::Capture, types::PaymentsCaptureData, types::Payme fn get_error_response( &self, res: Response, + event_builder: Option<&mut ConnectorEvent>, ) -> CustomResult<ErrorResponse, errors::ConnectorError> { - self.build_error_response(res) + self.build_error_response(res, event_builder) } } @@ -561,12 +592,17 @@ impl ConnectorIntegration<api::Execute, types::RefundsData, types::RefundsRespon 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: volt::RefundResponse = res .response .parse_struct("volt 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(), @@ -577,8 +613,9 @@ impl ConnectorIntegration<api::Execute, types::RefundsData, types::RefundsRespon fn get_error_response( &self, res: Response, + event_builder: Option<&mut ConnectorEvent>, ) -> CustomResult<ErrorResponse, errors::ConnectorError> { - self.build_error_response(res) + self.build_error_response(res, event_builder) } } diff --git a/crates/router/src/connector/volt/transformers.rs b/crates/router/src/connector/volt/transformers.rs index b1d77f3416f..ccb482d5b7c 100644 --- a/crates/router/src/connector/volt/transformers.rs +++ b/crates/router/src/connector/volt/transformers.rs @@ -185,7 +185,7 @@ impl TryFrom<&types::RefreshTokenRouterData> for VoltAuthUpdateRequest { } } -#[derive(Debug, Clone, Deserialize)] +#[derive(Debug, Clone, Deserialize, Serialize)] pub struct VoltAuthUpdateResponse { pub access_token: Secret<String>, pub token_type: String, @@ -451,7 +451,7 @@ impl<F> TryFrom<&VoltRouterData<&types::RefundsRouterData<F>>> for VoltRefundReq } } -#[derive(Default, Debug, Clone, Deserialize)] +#[derive(Default, Debug, Clone, Deserialize, Serialize)] pub struct RefundResponse { id: String, } @@ -598,7 +598,7 @@ pub struct VoltErrorResponse { pub exception: VoltErrorException, } -#[derive(Debug, Deserialize)] +#[derive(Debug, Deserialize, Serialize)] pub struct VoltAuthErrorResponse { pub code: u64, pub message: String, diff --git a/crates/router/src/connector/wise.rs b/crates/router/src/connector/wise.rs index 66ccf22c100..152786b46a3 100644 --- a/crates/router/src/connector/wise.rs +++ b/crates/router/src/connector/wise.rs @@ -13,6 +13,7 @@ use self::transformers as wise; use crate::{ configs::settings, core::errors::{self, CustomResult}, + events::connector_api_logs::ConnectorEvent, headers, services::{ self, @@ -82,11 +83,16 @@ impl ConnectorCommon for Wise { fn build_error_response( &self, res: types::Response, + event_builder: Option<&mut ConnectorEvent>, ) -> CustomResult<types::ErrorResponse, errors::ConnectorError> { let response: wise::ErrorResponse = res .response .parse_struct("ErrorResponse") .change_context(errors::ConnectorError::ResponseDeserializationFailed)?; + + event_builder.map(|i| i.set_response_body(&response)); + router_env::logger::info!(connector_response=?response); + let default_status = response.status.unwrap_or_default().to_string(); match response.errors { Some(errs) => { @@ -278,12 +284,17 @@ impl services::ConnectorIntegration<api::PoCancel, types::PayoutsData, types::Pa fn handle_response( &self, data: &types::PayoutsRouterData<api::PoCancel>, + event_builder: Option<&mut ConnectorEvent>, res: types::Response, ) -> CustomResult<types::PayoutsRouterData<api::PoCancel>, errors::ConnectorError> { let response: wise::WisePayoutResponse = res .response .parse_struct("WisePayoutResponse") .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(), @@ -294,11 +305,16 @@ impl services::ConnectorIntegration<api::PoCancel, types::PayoutsData, types::Pa fn get_error_response( &self, res: types::Response, + event_builder: Option<&mut ConnectorEvent>, ) -> CustomResult<types::ErrorResponse, errors::ConnectorError> { let response: wise::ErrorResponse = res .response .parse_struct("ErrorResponse") .change_context(errors::ConnectorError::ResponseDeserializationFailed)?; + + event_builder.map(|i| i.set_error_response_body(&response)); + router_env::logger::info!(connector_response=?response); + let def_res = response.status.unwrap_or_default().to_string(); let errors = response.errors.unwrap_or_default(); let (code, message) = if let Some(e) = errors.first() { @@ -374,12 +390,17 @@ impl services::ConnectorIntegration<api::PoQuote, types::PayoutsData, types::Pay fn handle_response( &self, data: &types::PayoutsRouterData<api::PoQuote>, + event_builder: Option<&mut ConnectorEvent>, res: types::Response, ) -> CustomResult<types::PayoutsRouterData<api::PoQuote>, errors::ConnectorError> { let response: wise::WisePayoutQuoteResponse = res .response .parse_struct("WisePayoutQuoteResponse") .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(), @@ -390,8 +411,9 @@ impl services::ConnectorIntegration<api::PoQuote, types::PayoutsData, types::Pay fn get_error_response( &self, res: types::Response, + event_builder: Option<&mut ConnectorEvent>, ) -> CustomResult<types::ErrorResponse, errors::ConnectorError> { - self.build_error_response(res) + self.build_error_response(res, event_builder) } } @@ -449,12 +471,17 @@ impl fn handle_response( &self, data: &types::PayoutsRouterData<api::PoRecipient>, + event_builder: Option<&mut ConnectorEvent>, res: types::Response, ) -> CustomResult<types::PayoutsRouterData<api::PoRecipient>, errors::ConnectorError> { let response: wise::WiseRecipientCreateResponse = res .response .parse_struct("WiseRecipientCreateResponse") .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(), @@ -465,8 +492,9 @@ impl fn get_error_response( &self, res: types::Response, + event_builder: Option<&mut ConnectorEvent>, ) -> CustomResult<types::ErrorResponse, errors::ConnectorError> { - self.build_error_response(res) + self.build_error_response(res, event_builder) } } @@ -560,12 +588,17 @@ impl services::ConnectorIntegration<api::PoCreate, types::PayoutsData, types::Pa fn handle_response( &self, data: &types::PayoutsRouterData<api::PoCreate>, + event_builder: Option<&mut ConnectorEvent>, res: types::Response, ) -> CustomResult<types::PayoutsRouterData<api::PoCreate>, errors::ConnectorError> { let response: wise::WisePayoutResponse = res .response .parse_struct("WisePayoutResponse") .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(), @@ -576,8 +609,9 @@ impl services::ConnectorIntegration<api::PoCreate, types::PayoutsData, types::Pa fn get_error_response( &self, res: types::Response, + event_builder: Option<&mut ConnectorEvent>, ) -> CustomResult<types::ErrorResponse, errors::ConnectorError> { - self.build_error_response(res) + self.build_error_response(res, event_builder) } } @@ -667,12 +701,17 @@ impl services::ConnectorIntegration<api::PoFulfill, types::PayoutsData, types::P fn handle_response( &self, data: &types::PayoutsRouterData<api::PoFulfill>, + event_builder: Option<&mut ConnectorEvent>, res: types::Response, ) -> CustomResult<types::PayoutsRouterData<api::PoFulfill>, errors::ConnectorError> { let response: wise::WiseFulfillResponse = res .response .parse_struct("WiseFulfillResponse") .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(), @@ -683,8 +722,9 @@ impl services::ConnectorIntegration<api::PoFulfill, types::PayoutsData, types::P fn get_error_response( &self, res: types::Response, + event_builder: Option<&mut ConnectorEvent>, ) -> CustomResult<types::ErrorResponse, errors::ConnectorError> { - self.build_error_response(res) + self.build_error_response(res, event_builder) } } diff --git a/crates/router/src/connector/wise/transformers.rs b/crates/router/src/connector/wise/transformers.rs index b213c62212c..82ae59205b1 100644 --- a/crates/router/src/connector/wise/transformers.rs +++ b/crates/router/src/connector/wise/transformers.rs @@ -3,9 +3,7 @@ use api_models::payouts::PayoutMethodData; #[cfg(feature = "payouts")] use common_utils::pii::Email; use masking::Secret; -use serde::Deserialize; -#[cfg(feature = "payouts")] -use serde::Serialize; +use serde::{Deserialize, Serialize}; type Error = error_stack::Report<errors::ConnectorError>; @@ -40,7 +38,7 @@ impl TryFrom<&types::ConnectorAuthType> for WiseAuthType { } // Wise error response -#[derive(Debug, Deserialize)] +#[derive(Debug, Deserialize, Serialize)] pub struct ErrorResponse { pub timestamp: Option<String>, pub errors: Option<Vec<SubError>>, @@ -51,7 +49,7 @@ pub struct ErrorResponse { pub path: Option<String>, } -#[derive(Debug, Deserialize)] +#[derive(Debug, Deserialize, Serialize)] pub struct SubError { pub code: String, pub message: String, @@ -140,7 +138,7 @@ pub struct WiseAddressDetails { #[allow(dead_code)] #[cfg(feature = "payouts")] -#[derive(Debug, Deserialize)] +#[derive(Debug, Deserialize, Serialize)] #[serde(rename_all = "camelCase")] pub struct WiseRecipientCreateResponse { id: i64, @@ -179,7 +177,7 @@ pub enum WisePayOutOption { #[allow(dead_code)] #[cfg(feature = "payouts")] -#[derive(Debug, Default, Deserialize)] +#[derive(Debug, Default, Deserialize, Serialize)] #[serde(rename_all = "camelCase")] pub struct WisePayoutQuoteResponse { source_amount: f64, @@ -196,7 +194,7 @@ pub struct WisePayoutQuoteResponse { } #[cfg(feature = "payouts")] -#[derive(Debug, Default, Deserialize)] +#[derive(Debug, Default, Deserialize, Serialize)] #[serde(rename_all = "SCREAMING_SNAKE_CASE")] pub enum WiseRateType { #[default] @@ -225,7 +223,7 @@ pub struct WiseTransferDetails { #[allow(dead_code)] #[cfg(feature = "payouts")] -#[derive(Debug, Deserialize)] +#[derive(Debug, Deserialize, Serialize)] #[serde(rename_all = "camelCase")] pub struct WisePayoutResponse { id: i64, @@ -265,7 +263,7 @@ pub enum FundType { #[allow(dead_code)] #[cfg(feature = "payouts")] -#[derive(Debug, Deserialize)] +#[derive(Debug, Deserialize, Serialize)] #[serde(rename_all = "camelCase")] pub struct WiseFulfillResponse { status: WiseStatus, diff --git a/crates/router/src/connector/worldline.rs b/crates/router/src/connector/worldline.rs index a1ca8a110bc..e46062a312b 100644 --- a/crates/router/src/connector/worldline.rs +++ b/crates/router/src/connector/worldline.rs @@ -16,6 +16,7 @@ use crate::{ configs::settings::Connectors, consts, core::errors::{self, CustomResult}, + events::connector_api_logs::ConnectorEvent, headers, logger, services::{ self, @@ -122,11 +123,16 @@ impl ConnectorCommon for Worldline { fn build_error_response( &self, res: types::Response, + event_builder: Option<&mut ConnectorEvent>, ) -> CustomResult<ErrorResponse, errors::ConnectorError> { let response: worldline::ErrorResponse = res .response .parse_struct("Worldline ErrorResponse") .change_context(errors::ConnectorError::ResponseDeserializationFailed)?; + + event_builder.map(|i| i.set_error_response_body(&response)); + router_env::logger::info!(connector_response=?response); + let error = response.errors.into_iter().next().unwrap_or_default(); Ok(ErrorResponse { status_code: res.status_code, @@ -247,13 +253,17 @@ impl ConnectorIntegration<api::Void, types::PaymentsCancelData, types::PaymentsR fn handle_response( &self, data: &types::PaymentsCancelRouterData, + event_builder: Option<&mut ConnectorEvent>, res: types::Response, ) -> CustomResult<types::PaymentsCancelRouterData, errors::ConnectorError> { let response: worldline::PaymentResponse = res .response .parse_struct("Worldline PaymentResponse") .change_context(errors::ConnectorError::ResponseDeserializationFailed)?; - logger::debug!(payments_cancel_response=?response); + + 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(), @@ -265,8 +275,9 @@ impl ConnectorIntegration<api::Void, types::PaymentsCancelData, types::PaymentsR fn get_error_response( &self, res: types::Response, + event_builder: Option<&mut ConnectorEvent>, ) -> CustomResult<ErrorResponse, errors::ConnectorError> { - self.build_error_response(res) + self.build_error_response(res, event_builder) } } @@ -326,13 +337,15 @@ impl ConnectorIntegration<api::PSync, types::PaymentsSyncData, types::PaymentsRe fn get_error_response( &self, res: types::Response, + event_builder: Option<&mut ConnectorEvent>, ) -> CustomResult<ErrorResponse, errors::ConnectorError> { - self.build_error_response(res) + self.build_error_response(res, event_builder) } fn handle_response( &self, data: &types::PaymentsSyncRouterData, + event_builder: Option<&mut ConnectorEvent>, res: types::Response, ) -> CustomResult<types::PaymentsSyncRouterData, errors::ConnectorError> { logger::debug!(payment_sync_response=?res); @@ -341,6 +354,10 @@ impl ConnectorIntegration<api::PSync, types::PaymentsSyncData, types::PaymentsRe .parse_struct("Worldline Payment") .change_context(errors::ConnectorError::ResponseDeserializationFailed)?; 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); + types::RouterData::try_from(types::ResponseRouterData { response, data: data.clone(), @@ -429,6 +446,7 @@ impl ConnectorIntegration<api::Capture, types::PaymentsCaptureData, types::Payme types::PaymentsCaptureData, types::PaymentsResponseData, >, + event_builder: Option<&mut ConnectorEvent>, res: types::Response, ) -> CustomResult< types::RouterData<api::Capture, types::PaymentsCaptureData, types::PaymentsResponseData>, @@ -445,6 +463,10 @@ impl ConnectorIntegration<api::Capture, types::PaymentsCaptureData, types::Payme .parse_struct("Worldline PaymentResponse") .change_context(errors::ConnectorError::ResponseDeserializationFailed)?; response.payment.capture_method = enums::CaptureMethod::Manual; + + 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(), @@ -456,8 +478,9 @@ impl ConnectorIntegration<api::Capture, types::PaymentsCaptureData, types::Payme fn get_error_response( &self, res: types::Response, + event_builder: Option<&mut ConnectorEvent>, ) -> CustomResult<ErrorResponse, errors::ConnectorError> { - self.build_error_response(res) + self.build_error_response(res, event_builder) } } @@ -540,6 +563,7 @@ impl ConnectorIntegration<api::Authorize, types::PaymentsAuthorizeData, types::P fn handle_response( &self, data: &types::PaymentsAuthorizeRouterData, + event_builder: Option<&mut ConnectorEvent>, res: types::Response, ) -> CustomResult<types::PaymentsAuthorizeRouterData, errors::ConnectorError> { logger::debug!(payment_authorize_response=?res); @@ -548,6 +572,8 @@ impl ConnectorIntegration<api::Authorize, types::PaymentsAuthorizeData, types::P .parse_struct("Worldline PaymentResponse") .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::ResponseRouterData { response, data: data.clone(), @@ -560,8 +586,9 @@ impl ConnectorIntegration<api::Authorize, types::PaymentsAuthorizeData, types::P fn get_error_response( &self, res: types::Response, + event_builder: Option<&mut ConnectorEvent>, ) -> CustomResult<ErrorResponse, errors::ConnectorError> { - self.build_error_response(res) + self.build_error_response(res, event_builder) } } @@ -625,6 +652,7 @@ impl ConnectorIntegration<api::Execute, types::RefundsData, types::RefundsRespon fn handle_response( &self, data: &types::RefundsRouterData<api::Execute>, + event_builder: Option<&mut ConnectorEvent>, res: types::Response, ) -> CustomResult<types::RefundsRouterData<api::Execute>, errors::ConnectorError> { logger::debug!(target: "router::connector::worldline", response=?res); @@ -632,6 +660,8 @@ impl ConnectorIntegration<api::Execute, types::RefundsData, types::RefundsRespon .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::ResponseRouterData { response, data: data.clone(), @@ -644,8 +674,9 @@ impl ConnectorIntegration<api::Execute, types::RefundsData, types::RefundsRespon fn get_error_response( &self, res: types::Response, + event_builder: Option<&mut ConnectorEvent>, ) -> CustomResult<ErrorResponse, errors::ConnectorError> { - self.build_error_response(res) + self.build_error_response(res, event_builder) } } @@ -701,6 +732,7 @@ impl ConnectorIntegration<api::RSync, types::RefundsData, types::RefundsResponse fn handle_response( &self, data: &types::RefundSyncRouterData, + event_builder: Option<&mut ConnectorEvent>, res: types::Response, ) -> CustomResult<types::RefundSyncRouterData, errors::ConnectorError> { logger::debug!(target: "router::connector::worldline", response=?res); @@ -708,6 +740,8 @@ impl ConnectorIntegration<api::RSync, types::RefundsData, types::RefundsResponse .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::ResponseRouterData { response, data: data.clone(), @@ -720,8 +754,9 @@ impl ConnectorIntegration<api::RSync, types::RefundsData, types::RefundsResponse fn get_error_response( &self, res: types::Response, + event_builder: Option<&mut ConnectorEvent>, ) -> CustomResult<ErrorResponse, errors::ConnectorError> { - self.build_error_response(res) + self.build_error_response(res, event_builder) } } diff --git a/crates/router/src/connector/worldline/transformers.rs b/crates/router/src/connector/worldline/transformers.rs index a21c88a2ce9..1eb22fc52d2 100644 --- a/crates/router/src/connector/worldline/transformers.rs +++ b/crates/router/src/connector/worldline/transformers.rs @@ -528,7 +528,7 @@ impl TryFrom<&types::ConnectorAuthType> for WorldlineAuthType { } } -#[derive(Debug, Clone, Default, Deserialize, PartialEq)] +#[derive(Debug, Clone, Default, Deserialize, PartialEq, Serialize)] #[serde(rename_all = "SCREAMING_SNAKE_CASE")] pub enum PaymentStatus { Captured, @@ -573,7 +573,7 @@ impl ForeignFrom<(PaymentStatus, enums::CaptureMethod)> for enums::AttemptStatus /// capture_method is not part of response from connector. /// This is used to decide payment status while converting connector response to RouterData. /// To keep this try_from logic generic in case of AUTHORIZE, SYNC and CAPTURE flows capture_method will be set from RouterData request. -#[derive(Default, Debug, Clone, Deserialize, PartialEq)] +#[derive(Default, Debug, Clone, Deserialize, PartialEq, Serialize)] pub struct Payment { pub id: String, pub status: PaymentStatus, @@ -607,20 +607,20 @@ impl<F, T> TryFrom<types::ResponseRouterData<F, Payment, T, PaymentsResponseData } } -#[derive(Debug, Deserialize)] +#[derive(Debug, Deserialize, Serialize)] #[serde(rename_all = "camelCase")] pub struct PaymentResponse { pub payment: Payment, pub merchant_action: Option<MerchantAction>, } -#[derive(Debug, Deserialize)] +#[derive(Debug, Deserialize, Serialize)] #[serde(rename_all = "camelCase")] pub struct MerchantAction { pub redirect_data: RedirectData, } -#[derive(Debug, Deserialize)] +#[derive(Debug, Deserialize, Serialize)] pub struct RedirectData { #[serde(rename = "redirectURL")] pub redirect_url: Url, @@ -688,7 +688,7 @@ impl<F> TryFrom<&types::RefundsRouterData<F>> for WorldlineRefundRequest { } #[allow(dead_code)] -#[derive(Debug, Default, Deserialize, Clone)] +#[derive(Debug, Default, Deserialize, Clone, Serialize)] #[serde(rename_all = "UPPERCASE")] pub enum RefundStatus { Cancelled, @@ -708,7 +708,7 @@ impl From<RefundStatus> for enums::RefundStatus { } } -#[derive(Default, Debug, Clone, Deserialize)] +#[derive(Default, Debug, Clone, Deserialize, Serialize)] pub struct RefundResponse { id: String, status: RefundStatus, @@ -750,7 +750,7 @@ impl TryFrom<types::RefundsResponseRouterData<api::RSync, RefundResponse>> } } -#[derive(Default, Debug, Deserialize, PartialEq)] +#[derive(Default, Debug, Deserialize, PartialEq, Serialize)] #[serde(rename_all = "camelCase")] pub struct Error { pub code: Option<String>, @@ -758,7 +758,7 @@ pub struct Error { pub message: Option<String>, } -#[derive(Default, Debug, Deserialize, PartialEq)] +#[derive(Default, Debug, Deserialize, PartialEq, Serialize)] #[serde(rename_all = "camelCase")] pub struct ErrorResponse { pub error_id: Option<String>, diff --git a/crates/router/src/connector/worldpay.rs b/crates/router/src/connector/worldpay.rs index d4ac530172d..fa534a8806f 100644 --- a/crates/router/src/connector/worldpay.rs +++ b/crates/router/src/connector/worldpay.rs @@ -15,6 +15,7 @@ use crate::{ configs::settings, connector::utils as connector_utils, core::errors::{self, CustomResult}, + events::connector_api_logs::ConnectorEvent, headers, services::{ self, @@ -84,11 +85,16 @@ impl ConnectorCommon for Worldpay { fn build_error_response( &self, res: Response, + event_builder: Option<&mut ConnectorEvent>, ) -> CustomResult<ErrorResponse, errors::ConnectorError> { let response: WorldpayErrorResponse = res .response .parse_struct("WorldpayErrorResponse") .change_context(errors::ConnectorError::ResponseDeserializationFailed)?; + + event_builder.map(|i| i.set_error_response_body(&response)); + router_env::logger::info!(connector_response=?response); + Ok(ErrorResponse { status_code: res.status_code, code: response.error_name, @@ -201,6 +207,7 @@ impl ConnectorIntegration<api::Void, types::PaymentsCancelData, types::PaymentsR fn handle_response( &self, data: &types::PaymentsCancelRouterData, + event_builder: Option<&mut ConnectorEvent>, res: Response, ) -> CustomResult<types::PaymentsCancelRouterData, errors::ConnectorError> where @@ -214,6 +221,8 @@ impl ConnectorIntegration<api::Void, types::PaymentsCancelData, types::PaymentsR .response .parse_struct("Worldpay PaymentsResponse") .change_context(errors::ConnectorError::ResponseDeserializationFailed)?; + event_builder.map(|i| i.set_response_body(&response)); + router_env::logger::info!(connector_response=?response); Ok(types::PaymentsCancelRouterData { status: enums::AttemptStatus::Voided, response: Ok(types::PaymentsResponseData::TransactionResponse { @@ -235,8 +244,9 @@ impl ConnectorIntegration<api::Void, types::PaymentsCancelData, types::PaymentsR fn get_error_response( &self, res: Response, + event_builder: Option<&mut ConnectorEvent>, ) -> CustomResult<ErrorResponse, errors::ConnectorError> { - self.build_error_response(res) + self.build_error_response(res, event_builder) } } @@ -298,13 +308,15 @@ impl ConnectorIntegration<api::PSync, types::PaymentsSyncData, types::PaymentsRe fn get_error_response( &self, res: Response, + event_builder: Option<&mut ConnectorEvent>, ) -> CustomResult<ErrorResponse, errors::ConnectorError> { - self.build_error_response(res) + self.build_error_response(res, event_builder) } fn handle_response( &self, data: &types::PaymentsSyncRouterData, + event_builder: Option<&mut ConnectorEvent>, res: Response, ) -> CustomResult<types::PaymentsSyncRouterData, errors::ConnectorError> { let response: WorldpayEventResponse = @@ -312,6 +324,9 @@ impl ConnectorIntegration<api::PSync, types::PaymentsSyncData, types::PaymentsRe .parse_struct("Worldpay EventResponse") .change_context(errors::ConnectorError::ResponseDeserializationFailed)?; + event_builder.map(|i| i.set_response_body(&response)); + router_env::logger::info!(connector_response=?response); + Ok(types::PaymentsSyncRouterData { status: enums::AttemptStatus::from(response.last_event), response: Ok(types::PaymentsResponseData::TransactionResponse { @@ -364,6 +379,7 @@ impl ConnectorIntegration<api::Capture, types::PaymentsCaptureData, types::Payme fn handle_response( &self, data: &types::PaymentsCaptureRouterData, + event_builder: Option<&mut ConnectorEvent>, res: Response, ) -> CustomResult<types::PaymentsCaptureRouterData, errors::ConnectorError> { match res.status_code { @@ -372,6 +388,8 @@ impl ConnectorIntegration<api::Capture, types::PaymentsCaptureData, types::Payme .response .parse_struct("Worldpay PaymentsResponse") .change_context(errors::ConnectorError::ResponseDeserializationFailed)?; + event_builder.map(|i| i.set_response_body(&response)); + router_env::logger::info!(connector_response=?response); Ok(types::PaymentsCaptureRouterData { status: enums::AttemptStatus::Charged, response: Ok(types::PaymentsResponseData::TransactionResponse { @@ -406,8 +424,9 @@ impl ConnectorIntegration<api::Capture, types::PaymentsCaptureData, types::Payme fn get_error_response( &self, res: Response, + event_builder: Option<&mut ConnectorEvent>, ) -> CustomResult<ErrorResponse, errors::ConnectorError> { - self.build_error_response(res) + self.build_error_response(res, event_builder) } } @@ -486,12 +505,17 @@ impl ConnectorIntegration<api::Authorize, types::PaymentsAuthorizeData, types::P fn handle_response( &self, data: &types::PaymentsAuthorizeRouterData, + event_builder: Option<&mut ConnectorEvent>, res: Response, ) -> CustomResult<types::PaymentsAuthorizeRouterData, errors::ConnectorError> { let response: WorldpayPaymentsResponse = res .response .parse_struct("Worldpay PaymentsResponse") .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(), @@ -503,8 +527,9 @@ impl ConnectorIntegration<api::Authorize, types::PaymentsAuthorizeData, types::P fn get_error_response( &self, res: Response, + event_builder: Option<&mut ConnectorEvent>, ) -> CustomResult<ErrorResponse, errors::ConnectorError> { - self.build_error_response(res) + self.build_error_response(res, event_builder) } } @@ -571,6 +596,7 @@ impl ConnectorIntegration<api::Execute, types::RefundsData, types::RefundsRespon fn handle_response( &self, data: &types::RefundsRouterData<api::Execute>, + event_builder: Option<&mut ConnectorEvent>, res: Response, ) -> CustomResult<types::RefundsRouterData<api::Execute>, errors::ConnectorError> { match res.status_code { @@ -579,6 +605,8 @@ impl ConnectorIntegration<api::Execute, types::RefundsData, types::RefundsRespon .response .parse_struct("Worldpay PaymentsResponse") .change_context(errors::ConnectorError::ResponseDeserializationFailed)?; + event_builder.map(|i| i.set_response_body(&response)); + router_env::logger::info!(connector_response=?response); Ok(types::RefundExecuteRouterData { response: Ok(types::RefundsResponseData { connector_refund_id: ResponseIdStr::try_from(response.links)?.id, @@ -594,8 +622,9 @@ impl ConnectorIntegration<api::Execute, types::RefundsData, types::RefundsRespon fn get_error_response( &self, res: Response, + event_builder: Option<&mut ConnectorEvent>, ) -> CustomResult<ErrorResponse, errors::ConnectorError> { - self.build_error_response(res) + self.build_error_response(res, event_builder) } } @@ -642,12 +671,15 @@ impl ConnectorIntegration<api::RSync, types::RefundsData, types::RefundsResponse fn handle_response( &self, data: &types::RefundSyncRouterData, + event_builder: Option<&mut ConnectorEvent>, res: Response, ) -> CustomResult<types::RefundSyncRouterData, errors::ConnectorError> { let response: WorldpayEventResponse = res.response .parse_struct("Worldpay EventResponse") .change_context(errors::ConnectorError::ResponseDeserializationFailed)?; + event_builder.map(|i| i.set_response_body(&response)); + router_env::logger::info!(connector_response=?response); Ok(types::RefundSyncRouterData { response: Ok(types::RefundsResponseData { connector_refund_id: data.request.refund_id.clone(), @@ -660,8 +692,9 @@ impl ConnectorIntegration<api::RSync, types::RefundsData, types::RefundsResponse fn get_error_response( &self, res: Response, + event_builder: Option<&mut ConnectorEvent>, ) -> CustomResult<ErrorResponse, errors::ConnectorError> { - self.build_error_response(res) + self.build_error_response(res, event_builder) } } diff --git a/crates/router/src/connector/zen.rs b/crates/router/src/connector/zen.rs index 0d5634c40c3..537e97cb577 100644 --- a/crates/router/src/connector/zen.rs +++ b/crates/router/src/connector/zen.rs @@ -16,6 +16,7 @@ use crate::{ errors::{self, CustomResult}, payments, }, + events::connector_api_logs::ConnectorEvent, headers, services::{ self, @@ -104,12 +105,15 @@ impl ConnectorCommon for Zen { fn build_error_response( &self, res: Response, + event_builder: Option<&mut ConnectorEvent>, ) -> CustomResult<ErrorResponse, errors::ConnectorError> { let response: zen::ZenErrorResponse = res .response .parse_struct("Zen ErrorResponse") .change_context(errors::ConnectorError::ResponseDeserializationFailed)?; - router_env::logger::info!(error_response=?response); + + event_builder.map(|i| i.set_error_response_body(&response)); + router_env::logger::info!(connector_response=?response); Ok(ErrorResponse { status_code: res.status_code, @@ -265,12 +269,14 @@ impl ConnectorIntegration<api::Authorize, types::PaymentsAuthorizeData, types::P fn handle_response( &self, data: &types::PaymentsAuthorizeRouterData, + event_builder: Option<&mut ConnectorEvent>, res: Response, ) -> CustomResult<types::PaymentsAuthorizeRouterData, errors::ConnectorError> { let response: zen::ZenPaymentsResponse = res .response .parse_struct("Zen 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, @@ -282,8 +288,9 @@ impl ConnectorIntegration<api::Authorize, types::PaymentsAuthorizeData, types::P fn get_error_response( &self, res: Response, + event_builder: Option<&mut ConnectorEvent>, ) -> CustomResult<ErrorResponse, errors::ConnectorError> { - self.build_error_response(res) + self.build_error_response(res, event_builder) } } @@ -334,12 +341,14 @@ impl ConnectorIntegration<api::PSync, types::PaymentsSyncData, types::PaymentsRe fn handle_response( &self, data: &types::PaymentsSyncRouterData, + event_builder: Option<&mut ConnectorEvent>, res: Response, ) -> CustomResult<types::PaymentsSyncRouterData, errors::ConnectorError> { let response: zen::ZenPaymentsResponse = res .response .parse_struct("zen 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, @@ -351,8 +360,9 @@ impl ConnectorIntegration<api::PSync, types::PaymentsSyncData, types::PaymentsRe fn get_error_response( &self, res: Response, + event_builder: Option<&mut ConnectorEvent>, ) -> CustomResult<ErrorResponse, errors::ConnectorError> { - self.build_error_response(res) + self.build_error_response(res, event_builder) } } @@ -455,13 +465,16 @@ impl ConnectorIntegration<api::Execute, types::RefundsData, types::RefundsRespon 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: zen::RefundResponse = res .response .parse_struct("zen 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 { response, data: data.clone(), @@ -472,8 +485,9 @@ impl ConnectorIntegration<api::Execute, types::RefundsData, types::RefundsRespon fn get_error_response( &self, res: Response, + event_builder: Option<&mut ConnectorEvent>, ) -> CustomResult<ErrorResponse, errors::ConnectorError> { - self.build_error_response(res) + self.build_error_response(res, event_builder) } } @@ -522,13 +536,17 @@ impl ConnectorIntegration<api::RSync, types::RefundsData, types::RefundsResponse fn handle_response( &self, data: &types::RefundSyncRouterData, + event_builder: Option<&mut ConnectorEvent>, res: Response, ) -> CustomResult<types::RefundSyncRouterData, errors::ConnectorError> { let response: zen::RefundResponse = res .response .parse_struct("zen 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(), @@ -539,8 +557,9 @@ impl ConnectorIntegration<api::RSync, types::RefundsData, types::RefundsResponse fn get_error_response( &self, res: Response, + event_builder: Option<&mut ConnectorEvent>, ) -> CustomResult<ErrorResponse, errors::ConnectorError> { - self.build_error_response(res) + self.build_error_response(res, event_builder) } } diff --git a/crates/router/src/connector/zen/transformers.rs b/crates/router/src/connector/zen/transformers.rs index 0adae0d00bd..ebea61304a1 100644 --- a/crates/router/src/connector/zen/transformers.rs +++ b/crates/router/src/connector/zen/transformers.rs @@ -819,7 +819,7 @@ impl TryFrom<&api_models::payments::GiftCardData> for ZenPaymentsRequest { } // PaymentsResponse -#[derive(Debug, Default, Deserialize, Clone, strum::Display)] +#[derive(Debug, Default, Deserialize, Clone, strum::Display, Serialize)] #[serde(rename_all = "UPPERCASE")] pub enum ZenPaymentStatus { Authorized, @@ -849,7 +849,7 @@ impl ForeignTryFrom<(ZenPaymentStatus, Option<ZenActions>)> for enums::AttemptSt } } -#[derive(Debug, Clone, Deserialize)] +#[derive(Debug, Clone, Deserialize, Serialize)] #[serde(rename_all = "camelCase")] pub struct ApiResponse { status: ZenPaymentStatus, @@ -860,14 +860,14 @@ pub struct ApiResponse { reject_reason: Option<String>, } -#[derive(Debug, Deserialize)] +#[derive(Debug, Deserialize, Serialize)] #[serde(untagged)] pub enum ZenPaymentsResponse { ApiResponse(ApiResponse), CheckoutResponse(CheckoutResponse), } -#[derive(Debug, Deserialize)] +#[derive(Debug, Deserialize, Serialize)] #[serde(rename_all = "camelCase")] pub struct CheckoutResponse { redirect_url: url::Url, @@ -1034,7 +1034,7 @@ impl<F> TryFrom<&ZenRouterData<&types::RefundsRouterData<F>>> for ZenRefundReque } } -#[derive(Debug, Default, Deserialize)] +#[derive(Debug, Default, Deserialize, Serialize)] #[serde(rename_all = "UPPERCASE")] pub enum RefundStatus { Authorized, @@ -1054,7 +1054,7 @@ impl From<RefundStatus> for enums::RefundStatus { } } -#[derive(Default, Debug, Deserialize)] +#[derive(Default, Debug, Deserialize, Serialize)] #[serde(rename_all = "camelCase")] pub struct RefundResponse { id: String, @@ -1169,13 +1169,13 @@ pub enum ZenWebhookTxnType { Unknown, } -#[derive(Debug, Deserialize)] +#[derive(Debug, Deserialize, Serialize)] pub struct ZenErrorResponse { pub error: Option<ZenErrorBody>, pub message: Option<String>, } -#[derive(Debug, Deserialize, Clone)] +#[derive(Debug, Deserialize, Clone, Serialize)] pub struct ZenErrorBody { pub message: String, pub code: String, diff --git a/crates/router/src/events/connector_api_logs.rs b/crates/router/src/events/connector_api_logs.rs index 4d3aadc3c45..31ee4a2d989 100644 --- a/crates/router/src/events/connector_api_logs.rs +++ b/crates/router/src/events/connector_api_logs.rs @@ -1,6 +1,7 @@ use common_utils::request::Method; use router_env::tracing_actix_web::RequestId; use serde::Serialize; +use serde_json::json; use time::OffsetDateTime; use super::{EventType, RawEvent}; @@ -10,7 +11,8 @@ pub struct ConnectorEvent { connector_name: String, flow: String, request: String, - response: Option<String>, + masked_response: Option<String>, + error: Option<String>, url: String, method: String, payment_id: String, @@ -29,7 +31,6 @@ impl ConnectorEvent { connector_name: String, flow: &str, request: serde_json::Value, - response: Option<String>, url: String, method: Method, payment_id: String, @@ -48,7 +49,8 @@ impl ConnectorEvent { .unwrap_or(flow) .to_string(), request: request.to_string(), - response, + masked_response: None, + error: None, url, method: method.to_string(), payment_id, @@ -63,6 +65,28 @@ impl ConnectorEvent { status_code, } } + + pub fn set_response_body<T: Serialize>(&mut self, response: &T) { + match masking::masked_serialize(response) { + Ok(masked) => { + self.masked_response = Some(masked.to_string()); + } + Err(er) => self.set_error(json!({"error": er.to_string()})), + } + } + + pub fn set_error_response_body<T: Serialize>(&mut self, response: &T) { + match masking::masked_serialize(response) { + Ok(masked) => { + self.error = Some(masked.to_string()); + } + Err(er) => self.set_error(json!({"error": er.to_string()})), + } + } + + pub fn set_error(&mut self, error: serde_json::Value) { + self.error = Some(error.to_string()); + } } impl TryFrom<ConnectorEvent> for RawEvent { diff --git a/crates/router/src/services/api.rs b/crates/router/src/services/api.rs index 28405c001eb..fbaaec62243 100644 --- a/crates/router/src/services/api.rs +++ b/crates/router/src/services/api.rs @@ -184,6 +184,7 @@ pub trait ConnectorIntegration<T, Req, Resp>: ConnectorIntegrationAny<T, Req, Re fn handle_response( &self, data: &types::RouterData<T, Req, Resp>, + event_builder: Option<&mut ConnectorEvent>, _res: types::Response, ) -> CustomResult<types::RouterData<T, Req, Resp>, errors::ConnectorError> where @@ -191,20 +192,25 @@ pub trait ConnectorIntegration<T, Req, Resp>: ConnectorIntegrationAny<T, Req, Re Req: Clone, Resp: Clone, { + event_builder.map(|e| e.set_error(json!({"error": "Not Implemented"}))); Ok(data.clone()) } fn get_error_response( &self, - _res: types::Response, + res: types::Response, + event_builder: Option<&mut ConnectorEvent>, ) -> CustomResult<ErrorResponse, errors::ConnectorError> { + event_builder.map(|event| event.set_error(json!({"error": res.response.escape_ascii().to_string(), "status_code": res.status_code}))); Ok(ErrorResponse::get_not_implemented()) } fn get_5xx_error_response( &self, res: types::Response, + event_builder: Option<&mut ConnectorEvent>, ) -> CustomResult<ErrorResponse, errors::ConnectorError> { + event_builder.map(|event| event.set_error(json!({"error": res.response.escape_ascii().to_string(), "status_code": res.status_code}))); let error_message = match res.status_code { 500 => "internal_server_error", 501 => "not_implemented", @@ -288,8 +294,7 @@ where response: res.into(), status_code: 200, }; - - connector_integration.handle_response(req, response) + connector_integration.handle_response(req, None, response) } payments::CallConnectorAction::Avoid => Ok(router_data), payments::CallConnectorAction::StatusUpdate { @@ -379,21 +384,10 @@ where .map_or_else(|value| value.status_code, |value| value.status_code) }) .unwrap_or_default(); - let connector_event = ConnectorEvent::new( + let mut connector_event = ConnectorEvent::new( req.connector.clone(), std::any::type_name::<T>(), masked_request_body, - response - .as_ref() - .map(|response| { - response - .as_ref() - .map_or_else(|value| value, |value| value) - .response - .escape_ascii() - .to_string() - }) - .ok(), request_url, request_method, req.payment_id.clone(), @@ -405,22 +399,13 @@ where status_code, ); - match connector_event.try_into() { - Ok(event) => { - state.event_handler().log_event(event); - } - Err(err) => { - logger::error!(error=?err, "Error Logging Connector Event"); - } - } - match response { Ok(body) => { let response = match body { Ok(body) => { let connector_http_status_code = Some(body.status_code); - let mut data = connector_integration - .handle_response(req, body) + match connector_integration + .handle_response(req, Some(&mut connector_event), body) .map_err(|error| { if error.current_context() == &errors::ConnectorError::ResponseDeserializationFailed @@ -435,14 +420,40 @@ where ) } error - })?; - data.connector_http_status_code = connector_http_status_code; - // Add up multiple external latencies in case of multiple external calls within the same request. - data.external_latency = Some( - data.external_latency - .map_or(external_latency, |val| val + external_latency), - ); - data + }) { + Ok(mut data) => { + + match connector_event.try_into() { + Ok(event) => { + state.event_handler().log_event(event); + } + Err(err) => { + logger::error!(error=?err, "Error Logging Connector Event"); + } + }; + data.connector_http_status_code = connector_http_status_code; + // Add up multiple external latencies in case of multiple external calls within the same request. + data.external_latency = Some( + data.external_latency + .map_or(external_latency, |val| val + external_latency), + ); + Ok(data) + }, + Err(err) => { + + connector_event.set_error(json!({"error": err.to_string()})); + + match connector_event.try_into() { + Ok(event) => { + state.event_handler().log_event(event); + } + Err(err) => { + logger::error!(error=?err, "Error Logging Connector Event"); + } + } + Err(err) + }, + }? } Err(body) => { router_data.connector_http_status_code = Some(body.status_code); @@ -459,13 +470,30 @@ where req.connector.clone(), )], ); + let error = match body.status_code { 500..=511 => { - connector_integration.get_5xx_error_response(body)? + let error_res = connector_integration + .get_5xx_error_response( + body, + Some(&mut connector_event), + )?; + match connector_event.try_into() { + Ok(event) => { + state.event_handler().log_event(event); + } + Err(err) => { + logger::error!(error=?err, "Error Logging Connector Event"); + } + }; + error_res } _ => { - let error_res = - connector_integration.get_error_response(body)?; + let error_res = connector_integration + .get_error_response( + body, + Some(&mut connector_event), + )?; if let Some(status) = error_res.attempt_status { router_data.status = status; }; @@ -481,6 +509,15 @@ where Ok(response) } Err(error) => { + connector_event.set_error(json!({"error": error.to_string()})); + match connector_event.try_into() { + Ok(event) => { + state.event_handler().log_event(event); + } + Err(err) => { + logger::error!(error=?err, "Error Logging Connector Event"); + } + }; if error.current_context().is_upstream_timeout() { let error_response = ErrorResponse { code: consts::REQUEST_TIMEOUT_ERROR_CODE.to_string(), diff --git a/crates/router/src/types/api.rs b/crates/router/src/types/api.rs index b60153eaf19..db6cb8236b3 100644 --- a/crates/router/src/types/api.rs +++ b/crates/router/src/types/api.rs @@ -39,6 +39,7 @@ use crate::{ errors::{self, CustomResult}, payments::types as payments_types, }, + events::connector_api_logs::ConnectorEvent, services::{request, ConnectorIntegration, ConnectorRedirectResponse, ConnectorValidation}, types::{self, api::enums as api_enums}, }; @@ -129,6 +130,7 @@ pub trait ConnectorCommon { fn build_error_response( &self, res: types::Response, + _event_builder: Option<&mut ConnectorEvent>, ) -> CustomResult<ErrorResponse, errors::ConnectorError> { Ok(ErrorResponse { status_code: res.status_code, diff --git a/crates/router/src/types/api/verify_connector.rs b/crates/router/src/types/api/verify_connector.rs index c03f492e8b8..e4c347187cb 100644 --- a/crates/router/src/types/api/verify_connector.rs +++ b/crates/router/src/types/api/verify_connector.rs @@ -161,7 +161,7 @@ pub trait VerifyConnector { dyn types::api::Connector + Sync: ConnectorIntegration<F, R1, R2>, { let error = connector - .get_error_response(error_response) + .get_error_response(error_response, None) .change_context(errors::ApiErrorResponse::InternalServerError)?; Err(errors::ApiErrorResponse::InvalidRequestData { message: error.reason.unwrap_or(error.message), @@ -177,7 +177,7 @@ pub trait VerifyConnector { dyn types::api::Connector + Sync: ConnectorIntegration<F, R1, R2>, { let error = connector - .get_error_response(error_response) + .get_error_response(error_response, None) .change_context(errors::ApiErrorResponse::InternalServerError)?; Err(errors::ApiErrorResponse::InvalidRequestData { message: error.reason.unwrap_or(error.message), diff --git a/crates/router/src/types/api/verify_connector/paypal.rs b/crates/router/src/types/api/verify_connector/paypal.rs index 33e848f909d..721562bd4a3 100644 --- a/crates/router/src/types/api/verify_connector/paypal.rs +++ b/crates/router/src/types/api/verify_connector/paypal.rs @@ -35,7 +35,7 @@ impl VerifyConnector for connector::Paypal { Ok(res) => Some( connector_data .connector - .handle_response(&router_data, res) + .handle_response(&router_data, None, res) .change_context(errors::ApiErrorResponse::InternalServerError)? .response .map_err(|_| errors::ApiErrorResponse::InternalServerError.into()), diff --git a/crates/router/src/types/api/verify_connector/stripe.rs b/crates/router/src/types/api/verify_connector/stripe.rs index ece9fa15a1d..3fc55291d9c 100644 --- a/crates/router/src/types/api/verify_connector/stripe.rs +++ b/crates/router/src/types/api/verify_connector/stripe.rs @@ -19,7 +19,7 @@ impl VerifyConnector for connector::Stripe { dyn types::api::Connector + Sync: ConnectorIntegration<F, R1, R2>, { let error = connector - .get_error_response(error_response) + .get_error_response(error_response, None) .change_context(errors::ApiErrorResponse::InternalServerError)?; match (env::which(), error.code.as_str()) { // In situations where an attempt is made to process a payment using a
2024-02-06T12:12: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 --> Mask connector response in the click house ### Test Case In click house check if connector response fields are masked _Note: Only fields that are of type Secret<> is masked_ Test all the flows for all the connectors especially NMI as changes are made in response. All connector flows to be tested ## Area of Impact All connector response including, 4xx and 5xx error responses. ## 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 - [ ] I added a [CHANGELOG](/CHANGELOG.md) entry if applicable
09c2a5c2a90f2773b00ab11ad67ab149f8225e3a
juspay/hyperswitch
juspay__hyperswitch-3475
Bug: Support to inject TLS certificate inside Hyperswith App Server
diff --git a/Cargo.lock b/Cargo.lock index 9b08fcbd57b..af7b0048355 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -43,6 +43,7 @@ dependencies = [ "actix-codec", "actix-rt", "actix-service", + "actix-tls", "actix-utils", "ahash 0.8.11", "base64 0.21.7", @@ -187,8 +188,10 @@ dependencies = [ "http 1.1.0", "impl-more", "pin-project-lite", + "rustls-pki-types", "tokio 1.37.0", "tokio-rustls 0.23.4", + "tokio-rustls 0.25.0", "tokio-util", "tracing", "webpki-roots 0.22.6", @@ -217,6 +220,7 @@ dependencies = [ "actix-rt", "actix-server", "actix-service", + "actix-tls", "actix-utils", "actix-web-codegen", "ahash 0.8.11", @@ -5798,7 +5802,7 @@ dependencies = [ "percent-encoding", "pin-project-lite", "rustls 0.21.10", - "rustls-pemfile", + "rustls-pemfile 1.0.4", "serde", "serde_json", "serde_urlencoded", @@ -5988,6 +5992,8 @@ dependencies = [ "roxmltree", "rust_decimal", "rustc-hash", + "rustls 0.22.4", + "rustls-pemfile 2.1.2", "scheduler", "serde", "serde_json", @@ -6217,10 +6223,24 @@ checksum = "f9d5a6813c0759e4609cd494e8e725babae6a2ca7b62a5536a13daaec6fcb7ba" dependencies = [ "log", "ring 0.17.8", - "rustls-webpki", + "rustls-webpki 0.101.7", "sct", ] +[[package]] +name = "rustls" +version = "0.22.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "bf4ef73721ac7bcd79b2b315da7779d8fc09718c6b3d2d1b2d94850eb8c18432" +dependencies = [ + "log", + "ring 0.17.8", + "rustls-pki-types", + "rustls-webpki 0.102.3", + "subtle", + "zeroize", +] + [[package]] name = "rustls-native-certs" version = "0.6.3" @@ -6228,7 +6248,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "a9aace74cb666635c918e9c12bc0d348266037aa8eb599b5cba565709a8dff00" dependencies = [ "openssl-probe", - "rustls-pemfile", + "rustls-pemfile 1.0.4", "schannel", "security-framework", ] @@ -6242,6 +6262,22 @@ dependencies = [ "base64 0.21.7", ] +[[package]] +name = "rustls-pemfile" +version = "2.1.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "29993a25686778eb88d4189742cd713c9bce943bc54251a33509dc63cbacf73d" +dependencies = [ + "base64 0.22.0", + "rustls-pki-types", +] + +[[package]] +name = "rustls-pki-types" +version = "1.5.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "beb461507cee2c2ff151784c52762cf4d9ff6a61f3e80968600ed24fa837fa54" + [[package]] name = "rustls-webpki" version = "0.101.7" @@ -6252,6 +6288,17 @@ dependencies = [ "untrusted 0.9.0", ] +[[package]] +name = "rustls-webpki" +version = "0.102.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f3bce581c0dd41bce533ce695a1437fa16a7ab5ac3ccfa99fe1a620a7885eabf" +dependencies = [ + "ring 0.17.8", + "rustls-pki-types", + "untrusted 0.9.0", +] + [[package]] name = "rustversion" version = "1.0.14" @@ -7623,6 +7670,17 @@ dependencies = [ "tokio 1.37.0", ] +[[package]] +name = "tokio-rustls" +version = "0.25.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "775e0c0f0adb3a2f22a00c4745d728b479985fc15ee7ca6a2608388c5569860f" +dependencies = [ + "rustls 0.22.4", + "rustls-pki-types", + "tokio 1.37.0", +] + [[package]] name = "tokio-stream" version = "0.1.15" diff --git a/config/config.example.toml b/config/config.example.toml index 10f8ba7a5e7..1c3d9ebd98e 100644 --- a/config/config.example.toml +++ b/config/config.example.toml @@ -11,6 +11,15 @@ host = "127.0.0.1" shutdown_timeout = 30 # HTTP Request body limit. Defaults to 32kB request_body_limit = 32_768 + +# HTTPS Server Configuration +# Self-signed Private Key and Certificate can be generated with mkcert for local development +[server.tls] +port = 8081 +host = "127.0.0.1" +private_key = "/path/to/private_key.pem" +certificate = "/path/to/certificate.pem" + # Proxy server configuration for connecting to payment gateways. # Don't define the fields if a Proxy isn't needed. Empty strings will cause failure. [proxy] diff --git a/config/deployments/env_specific.toml b/config/deployments/env_specific.toml index 68df3d28e24..27567ec6cc7 100644 --- a/config/deployments/env_specific.toml +++ b/config/deployments/env_specific.toml @@ -265,6 +265,14 @@ shutdown_timeout = 30 # HTTP Request body limit. Defaults to 32kB request_body_limit = 32_768 +# HTTPS Server Configuration +# Self-signed Private Key and Certificate can be generated with mkcert for local development +[server.tls] +port = 8081 +host = "127.0.0.1" +private_key = "/path/to/private_key.pem" +certificate = "/path/to/certificate.pem" + [secrets_management] secrets_manager = "aws_kms" # Secrets manager client to be used diff --git a/crates/router/Cargo.toml b/crates/router/Cargo.toml index dd14c8d8960..e4bfb4a454d 100644 --- a/crates/router/Cargo.toml +++ b/crates/router/Cargo.toml @@ -9,7 +9,8 @@ readme = "README.md" license.workspace = true [features] -default = ["kv_store", "stripe", "oltp", "olap", "backwards_compatibility", "accounts_cache", "dummy_connector", "payouts", "payout_retry", "business_profile_routing", "connector_choice_mca_id", "profile_specific_fallback_routing", "retry", "frm"] +default = ["kv_store", "stripe", "oltp", "olap", "backwards_compatibility", "accounts_cache", "dummy_connector", "payouts", "payout_retry", "business_profile_routing", "connector_choice_mca_id", "profile_specific_fallback_routing", "retry", "frm", "tls"] +tls = ["actix-web/rustls-0_22"] email = ["external_services/email", "scheduler/email", "olap"] frm = ["api_models/frm", "hyperswitch_domain_models/frm"] stripe = ["dep:serde_qs"] @@ -77,6 +78,8 @@ ring = "0.17.8" roxmltree = "0.19.0" rust_decimal = { version = "1.35.0", features = ["serde-with-float", "serde-with-str"] } rustc-hash = "1.1.0" +rustls = "0.22" +rustls-pemfile = "2" serde = { version = "1.0.197", features = ["derive"] } serde_json = "1.0.115" serde_path_to_error = "0.1.16" diff --git a/crates/router/src/configs/defaults.rs b/crates/router/src/configs/defaults.rs index 35bfbc88f69..80ac62a5df3 100644 --- a/crates/router/src/configs/defaults.rs +++ b/crates/router/src/configs/defaults.rs @@ -12,6 +12,8 @@ impl Default for super::settings::Server { host: "localhost".into(), request_body_limit: 16 * 1024, // POST request body is limited to 16KiB shutdown_timeout: 30, + #[cfg(feature = "tls")] + tls: None, } } } diff --git a/crates/router/src/configs/settings.rs b/crates/router/src/configs/settings.rs index 0569c4dbed6..66df317d7db 100644 --- a/crates/router/src/configs/settings.rs +++ b/crates/router/src/configs/settings.rs @@ -537,6 +537,8 @@ pub struct Server { pub host: String, pub request_body_limit: usize, pub shutdown_timeout: u64, + #[cfg(feature = "tls")] + pub tls: Option<ServerTls>, } #[derive(Debug, Deserialize, Clone)] @@ -816,6 +818,19 @@ pub struct PayPalOnboarding { pub enabled: bool, } +#[cfg(feature = "tls")] +#[derive(Debug, Deserialize, Clone)] +pub struct ServerTls { + /// Port to host the TLS secure server on + pub port: u16, + /// Use a different host (optional) (defaults to the host provided in [`Server`] config) + pub host: Option<String>, + /// private key file path associated with TLS (path to the private key file (`pem` format)) + pub private_key: PathBuf, + /// certificate file associated with TLS (path to the certificate file (`pem` format)) + pub certificate: PathBuf, +} + fn deserialize_hashset_inner<T>(value: impl AsRef<str>) -> Result<HashSet<T>, String> where T: Eq + std::str::FromStr + std::hash::Hash, diff --git a/crates/router/src/lib.rs b/crates/router/src/lib.rs index f0d332514d1..b653c31ec63 100644 --- a/crates/router/src/lib.rs +++ b/crates/router/src/lib.rs @@ -200,11 +200,65 @@ pub async fn start_server(conf: settings::Settings<SecuredSecret>) -> Applicatio ); let state = Box::pin(AppState::new(conf, tx, api_client)).await; let request_body_limit = server.request_body_limit; - let server = actix_web::HttpServer::new(move || mk_app(state.clone(), request_body_limit)) - .bind((server.host.as_str(), server.port))? - .workers(server.workers) - .shutdown_timeout(server.shutdown_timeout) - .run(); + + let server_builder = + actix_web::HttpServer::new(move || mk_app(state.clone(), request_body_limit)) + .bind((server.host.as_str(), server.port))? + .workers(server.workers) + .shutdown_timeout(server.shutdown_timeout); + + #[cfg(feature = "tls")] + let server = match server.tls { + None => server_builder.run(), + Some(tls_conf) => { + let cert_file = + &mut std::io::BufReader::new(std::fs::File::open(tls_conf.certificate).map_err( + |err| errors::ApplicationError::InvalidConfigurationValueError(err.to_string()), + )?); + let key_file = + &mut std::io::BufReader::new(std::fs::File::open(tls_conf.private_key).map_err( + |err| errors::ApplicationError::InvalidConfigurationValueError(err.to_string()), + )?); + + let cert_chain = rustls_pemfile::certs(cert_file) + .collect::<Result<Vec<_>, _>>() + .map_err(|err| { + errors::ApplicationError::InvalidConfigurationValueError(err.to_string()) + })?; + + let mut keys = rustls_pemfile::pkcs8_private_keys(key_file) + .map(|key| key.map(rustls::pki_types::PrivateKeyDer::Pkcs8)) + .collect::<Result<Vec<_>, _>>() + .map_err(|err| { + errors::ApplicationError::InvalidConfigurationValueError(err.to_string()) + })?; + + // exit if no keys could be parsed + if keys.is_empty() { + return Err(errors::ApplicationError::InvalidConfigurationValueError( + "Could not locate PKCS8 private keys.".into(), + )); + } + + let config_builder = rustls::ServerConfig::builder().with_no_client_auth(); + let config = config_builder + .with_single_cert(cert_chain, keys.remove(0)) + .map_err(|err| { + errors::ApplicationError::InvalidConfigurationValueError(err.to_string()) + })?; + + server_builder + .bind_rustls_0_22( + (tls_conf.host.unwrap_or(server.host).as_str(), tls_conf.port), + config, + )? + .run() + } + }; + + #[cfg(not(feature = "tls"))] + let server = server_builder.run(); + let _task_handle = tokio::spawn(receiver_for_error(rx, server.handle()).in_current_span()); Ok(server) }
2024-06-23T15:17:58Z
## 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 --> Added support for TLS server within `actix-web` using `rustls` ### 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 #3475. ## 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)? --> ![tls](https://github.com/juspay/hyperswitch/assets/130567821/ee01116b-f353-4453-9e4a-9b1f9712207c) Test Parameters: - HTTP Server: 8080 (default) - HTTPS Server: 8081 - Cert and Key generated using `mkcert` for `localhost` and `127.0.0.1`: `mkcert -key-file key.pem -cert-file cert.pem 127.0.0.1 localhost` ## 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
57055ecab2300c2284d0e674a22247fa65776ed8
![tls](https://github.com/juspay/hyperswitch/assets/130567821/ee01116b-f353-4453-9e4a-9b1f9712207c) Test Parameters: - HTTP Server: 8080 (default) - HTTPS Server: 8081 - Cert and Key generated using `mkcert` for `localhost` and `127.0.0.1`: `mkcert -key-file key.pem -cert-file cert.pem 127.0.0.1 localhost`
juspay/hyperswitch
juspay__hyperswitch-3480
Bug: fix(invite): change status to active after resetting the password for invitee
diff --git a/crates/diesel_models/src/query/user.rs b/crates/diesel_models/src/query/user.rs index b4d5976ba29..6fb5b79ddc1 100644 --- a/crates/diesel_models/src/query/user.rs +++ b/crates/diesel_models/src/query/user.rs @@ -3,7 +3,7 @@ use diesel::{ associations::HasTable, debug_query, result::Error as DieselError, ExpressionMethods, JoinOnDsl, QueryDsl, }; -use error_stack::{report, IntoReport}; +use error_stack::IntoReport; use router_env::{ logger, tracing::{self, instrument}, @@ -49,19 +49,37 @@ impl User { pub async fn update_by_user_id( conn: &PgPooledConn, user_id: &str, - user: UserUpdate, + user_update: UserUpdate, ) -> StorageResult<Self> { - generics::generic_update_with_results::<<Self as HasTable>::Table, _, _, _>( + generics::generic_update_with_unique_predicate_get_result::< + <Self as HasTable>::Table, + _, + _, + _, + >( conn, users_dsl::user_id.eq(user_id.to_owned()), - UserUpdateInternal::from(user), + UserUpdateInternal::from(user_update), ) - .await? - .first() - .cloned() - .ok_or_else(|| { - report!(errors::DatabaseError::NotFound).attach_printable("Error while updating user") - }) + .await + } + + pub async fn update_by_user_email( + conn: &PgPooledConn, + user_email: &str, + user_update: UserUpdate, + ) -> StorageResult<Self> { + generics::generic_update_with_unique_predicate_get_result::< + <Self as HasTable>::Table, + _, + _, + _, + >( + conn, + users_dsl::email.eq(user_email.to_owned()), + UserUpdateInternal::from(user_update), + ) + .await } pub async fn delete_by_user_id(conn: &PgPooledConn, user_id: &str) -> StorageResult<bool> { diff --git a/crates/router/src/core/user.rs b/crates/router/src/core/user.rs index ae66728e140..4f50845c8d4 100644 --- a/crates/router/src/core/user.rs +++ b/crates/router/src/core/user.rs @@ -1,4 +1,6 @@ use api_models::user::{self as user_api, InviteMultipleUserResponse}; +#[cfg(feature = "email")] +use diesel_models::user_role::UserRoleUpdate; use diesel_models::{enums::UserStatus, user as storage_user, user_role::UserRoleNew}; #[cfg(feature = "email")] use error_stack::IntoReport; @@ -357,18 +359,10 @@ pub async fn reset_password( let hash_password = utils::user::password::generate_password_hash(password.get_secret())?; - //TODO: Create Update by email query - let user_id = state - .store - .find_user_by_email(token.get_email()) - .await - .change_context(UserErrors::InternalServerError)? - .user_id; - - state + let user = state .store - .update_user_by_user_id( - user_id.as_str(), + .update_user_by_email( + token.get_email(), storage_user::UserUpdate::AccountUpdate { name: None, password: Some(hash_password), @@ -379,7 +373,20 @@ pub async fn reset_password( .await .change_context(UserErrors::InternalServerError)?; - //TODO: Update User role status for invited user + if let Some(inviter_merchant_id) = token.get_merchant_id() { + let update_status_result = state + .store + .update_user_role_by_user_id_merchant_id( + user.user_id.clone().as_str(), + inviter_merchant_id, + UserRoleUpdate::UpdateStatus { + status: UserStatus::Active, + modified_by: user.user_id, + }, + ) + .await; + logger::info!(?update_status_result); + } Ok(ApplicationResponse::StatusOk) } @@ -462,7 +469,7 @@ pub async fn invite_user( .store .insert_user_role(UserRoleNew { user_id: new_user.get_user_id().to_owned(), - merchant_id: user_from_token.merchant_id, + merchant_id: user_from_token.merchant_id.clone(), role_id: request.role_id, org_id: user_from_token.org_id, status: invitation_status, @@ -488,6 +495,7 @@ pub async fn invite_user( 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, }; let send_email_result = state .email_client @@ -664,6 +672,7 @@ async fn handle_new_user_invitation( 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(), }; let send_email_result = state .email_client diff --git a/crates/router/src/db/kafka_store.rs b/crates/router/src/db/kafka_store.rs index e88d59ea9f3..67f4230d878 100644 --- a/crates/router/src/db/kafka_store.rs +++ b/crates/router/src/db/kafka_store.rs @@ -1896,6 +1896,16 @@ impl UserInterface for KafkaStore { .await } + async fn update_user_by_email( + &self, + user_email: &str, + user: storage::UserUpdate, + ) -> CustomResult<storage::User, errors::StorageError> { + self.diesel_store + .update_user_by_email(user_email, user) + .await + } + async fn delete_user_by_user_id( &self, user_id: &str, diff --git a/crates/router/src/db/user.rs b/crates/router/src/db/user.rs index ecd71f7e2c9..c7c005a0b52 100644 --- a/crates/router/src/db/user.rs +++ b/crates/router/src/db/user.rs @@ -33,6 +33,12 @@ pub trait UserInterface { user: storage::UserUpdate, ) -> CustomResult<storage::User, errors::StorageError>; + async fn update_user_by_email( + &self, + user_email: &str, + user: storage::UserUpdate, + ) -> CustomResult<storage::User, errors::StorageError>; + async fn delete_user_by_user_id( &self, user_id: &str, @@ -92,6 +98,18 @@ impl UserInterface for Store { .into_report() } + async fn update_user_by_email( + &self, + user_email: &str, + user: storage::UserUpdate, + ) -> CustomResult<storage::User, errors::StorageError> { + let conn = connection::pg_connection_write(self).await?; + storage::User::update_by_user_email(&conn, user_email, user) + .await + .map_err(Into::into) + .into_report() + } + async fn delete_user_by_user_id( &self, user_id: &str, @@ -229,6 +247,50 @@ impl UserInterface for MockDb { ) } + async fn update_user_by_email( + &self, + user_email: &str, + update_user: storage::UserUpdate, + ) -> CustomResult<storage::User, errors::StorageError> { + let mut users = self.users.lock().await; + let user_email_pii: common_utils::pii::Email = user_email + .to_string() + .try_into() + .map_err(|_| errors::StorageError::MockDbError)?; + users + .iter_mut() + .find(|user| user.email == user_email_pii) + .map(|user| { + *user = match &update_user { + storage::UserUpdate::VerifyUser => storage::User { + is_verified: true, + ..user.to_owned() + }, + storage::UserUpdate::AccountUpdate { + name, + password, + is_verified, + preferred_merchant_id, + } => storage::User { + name: name.clone().map(Secret::new).unwrap_or(user.name.clone()), + password: password.clone().unwrap_or(user.password.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() + }, + }; + user.to_owned() + }) + .ok_or( + errors::StorageError::ValueNotFound(format!( + "No user available for user_email = {user_email}" + )) + .into(), + ) + } + async fn delete_user_by_user_id( &self, user_id: &str, diff --git a/crates/router/src/services/email/types.rs b/crates/router/src/services/email/types.rs index d5aa9926130..c68907c2846 100644 --- a/crates/router/src/services/email/types.rs +++ b/crates/router/src/services/email/types.rs @@ -92,18 +92,21 @@ Email : {user_email} #[derive(serde::Serialize, serde::Deserialize)] pub struct EmailToken { email: String, + merchant_id: Option<String>, exp: u64, } impl EmailToken { pub async fn new_token( email: domain::UserEmail, + merchant_id: Option<String>, settings: &configs::settings::Settings, ) -> CustomResult<String, UserErrors> { let expiration_duration = std::time::Duration::from_secs(consts::EMAIL_TOKEN_TIME_IN_SECS); let exp = jwt::generate_exp(expiration_duration)?.as_secs(); let token_payload = Self { email: email.get_secret().expose(), + merchant_id, exp, }; jwt::generate_jwt(&token_payload, settings).await @@ -112,6 +115,10 @@ impl EmailToken { pub fn get_email(&self) -> &str { self.email.as_str() } + + pub fn get_merchant_id(&self) -> Option<&str> { + self.merchant_id.as_deref() + } } pub fn get_link_with_token( @@ -132,7 +139,7 @@ pub struct VerifyEmail { #[async_trait::async_trait] impl EmailData for VerifyEmail { async fn get_email_data(&self) -> CustomResult<EmailContents, EmailError> { - let token = EmailToken::new_token(self.recipient_email.clone(), &self.settings) + let token = EmailToken::new_token(self.recipient_email.clone(), None, &self.settings) .await .change_context(EmailError::TokenGenerationFailure)?; @@ -161,7 +168,7 @@ pub struct ResetPassword { #[async_trait::async_trait] impl EmailData for ResetPassword { async fn get_email_data(&self) -> CustomResult<EmailContents, EmailError> { - let token = EmailToken::new_token(self.recipient_email.clone(), &self.settings) + let token = EmailToken::new_token(self.recipient_email.clone(), None, &self.settings) .await .change_context(EmailError::TokenGenerationFailure)?; @@ -191,7 +198,7 @@ pub struct MagicLink { #[async_trait::async_trait] impl EmailData for MagicLink { async fn get_email_data(&self) -> CustomResult<EmailContents, EmailError> { - let token = EmailToken::new_token(self.recipient_email.clone(), &self.settings) + let token = EmailToken::new_token(self.recipient_email.clone(), None, &self.settings) .await .change_context(EmailError::TokenGenerationFailure)?; @@ -216,14 +223,19 @@ pub struct InviteUser { pub user_name: domain::UserName, pub settings: std::sync::Arc<configs::settings::Settings>, pub subject: &'static str, + pub merchant_id: String, } #[async_trait::async_trait] impl EmailData for InviteUser { async fn get_email_data(&self) -> CustomResult<EmailContents, EmailError> { - let token = EmailToken::new_token(self.recipient_email.clone(), &self.settings) - .await - .change_context(EmailError::TokenGenerationFailure)?; + let token = EmailToken::new_token( + self.recipient_email.clone(), + Some(self.merchant_id.clone()), + &self.settings, + ) + .await + .change_context(EmailError::TokenGenerationFailure)?; let invite_user_link = get_link_with_token(&self.settings.email.base_url, token, "set_password");
2024-01-29T12:53:52Z
## 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 PR will add an optional `merchant_id` field in `EmailToken` struct. And also changes the status of the user from `invitation_sent` to `active` if the `EmailToken` has `merchant_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). --> To change the status of the user to active once the user resets the password. ## 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)? --> Postman. 1. Invite a user using this curl ``` curl --location 'http://localhost:8080/user/user/invite' \ --header 'Content-Type: application/json' \ --header 'Authorization: Bearer JWT' \ --data-raw '{ "email": "new email", "name": "user name", "role_id": "merchant_admin" }' ``` You should get invite email to the email you have provided and this following response from the api. ``` { "is_email_sent": true, "password": null } ``` 2. Use the link in the email to hit the reset password api from the dashboard or the following curl can be used to hit the api if email token is extracted. ``` curl --location 'http://localhost:8080/user/reset_password' \ --header 'Content-Type: application/json' \ --data-raw '{ "token": "Email Token", "password": "new password" }' ``` You will get 200 OK and the status of the `user_role` with the corresponding `user_id` and `merchant_id` will be active. ## 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 - [ ] I added a [CHANGELOG](/CHANGELOG.md) entry if applicable
dfb14a34c96ba05e7ff1993fdcd97ee294c02d65
Postman. 1. Invite a user using this curl ``` curl --location 'http://localhost:8080/user/user/invite' \ --header 'Content-Type: application/json' \ --header 'Authorization: Bearer JWT' \ --data-raw '{ "email": "new email", "name": "user name", "role_id": "merchant_admin" }' ``` You should get invite email to the email you have provided and this following response from the api. ``` { "is_email_sent": true, "password": null } ``` 2. Use the link in the email to hit the reset password api from the dashboard or the following curl can be used to hit the api if email token is extracted. ``` curl --location 'http://localhost:8080/user/reset_password' \ --header 'Content-Type: application/json' \ --data-raw '{ "token": "Email Token", "password": "new password" }' ``` You will get 200 OK and the status of the `user_role` with the corresponding `user_id` and `merchant_id` will be active.
juspay/hyperswitch
juspay__hyperswitch-3467
Bug: [FEATURE]: Api for enable/disable Blocklist guard This Api mentioned will be for toggling the `blocklist-guard` for a particular merchant. So the changes will be as mentioned: > It will try to find a config associated with that merchant (guard_blocklist_for_{merchant_id}) which in tern is a boolean config. > If present it will enable/disable it accordingly. > If not present it will create a config and assign it appropriate value. ## So what happens if the guard is enabled for a particular merchant: He will have the ability to block certain payment instruments on basis of >fingerprint >card-bins >extended-bins. Moreover, if guard is enabled, fingerprint generation for each and every payment attempt is insured and every payment will be tested against the blocklist of the merchant. ## If guard is disabled: None of the above steps will be valid and every payment attempt will have fingerprint as null. ## Testing The curl for the above mentioned api is as follows: `POST /blocklist/toggle?status=true` ``` curl --location --request POST 'http://127.0.0.1:8080/blocklist/toggle?status=false' \ --header 'api-key: dev_xiikraRGPeYjPzsef71DjOllw0hy4M9feqqSBCdzJc9XT2kPay3MJnY4o6Ui93jS' ``` Enabled response: ``` { "blocklist_guard_status": "blocklist guard is enabled" } ``` Disabled response: ``` { "blocklist_guard_status": "blocklist guard is disabled" } ```
diff --git a/crates/api_models/src/blocklist.rs b/crates/api_models/src/blocklist.rs index 888b9106ccc..9672b6de6ee 100644 --- a/crates/api_models/src/blocklist.rs +++ b/crates/api_models/src/blocklist.rs @@ -22,6 +22,11 @@ pub struct BlocklistResponse { pub created_at: time::PrimitiveDateTime, } +#[derive(Debug, Clone, serde::Serialize, serde::Deserialize, ToSchema)] +pub struct ToggleBlocklistResponse { + pub blocklist_guard_status: String, +} + pub type AddToBlocklistResponse = BlocklistResponse; pub type DeleteFromBlocklistResponse = BlocklistResponse; @@ -39,6 +44,14 @@ fn default_list_limit() -> u16 { 10 } +#[derive(Debug, Clone, serde::Serialize, serde::Deserialize, ToSchema)] +pub struct ToggleBlocklistQuery { + #[schema(value_type = BlocklistDataKind)] + pub status: bool, +} + impl ApiEventMetric for BlocklistRequest {} impl ApiEventMetric for BlocklistResponse {} +impl ApiEventMetric for ToggleBlocklistResponse {} impl ApiEventMetric for ListBlocklistQuery {} +impl ApiEventMetric for ToggleBlocklistQuery {} diff --git a/crates/openapi/src/openapi.rs b/crates/openapi/src/openapi.rs index 982072e8c09..1936300ee14 100644 --- a/crates/openapi/src/openapi.rs +++ b/crates/openapi/src/openapi.rs @@ -151,6 +151,7 @@ Never share your secret api keys. Keep them guarded and secure. routes::blocklist::remove_entry_from_blocklist, routes::blocklist::list_blocked_payment_methods, routes::blocklist::add_entry_to_blocklist, + routes::blocklist::toggle_blocklist_guard, // Routes for payouts routes::payouts::payouts_create, @@ -450,6 +451,7 @@ Never share your secret api keys. Keep them guarded and secure. api_models::payments::PaymentLinkStatus, api_models::blocklist::BlocklistRequest, api_models::blocklist::BlocklistResponse, + api_models::blocklist::ToggleBlocklistResponse, api_models::blocklist::ListBlocklistQuery, api_models::enums::BlocklistDataKind )), diff --git a/crates/openapi/src/routes/blocklist.rs b/crates/openapi/src/routes/blocklist.rs index bf683259e08..741925b93d2 100644 --- a/crates/openapi/src/routes/blocklist.rs +++ b/crates/openapi/src/routes/blocklist.rs @@ -1,3 +1,19 @@ +#[utoipa::path( + post, + path = "/blocklist/toggle", + params ( + ("status" = bool, Query, description = "Boolean value to enable/disable blocklist"), + ), + responses( + (status = 200, description = "Blocklist guard enabled/disabled", body = ToggleBlocklistResponse), + (status = 400, description = "Invalid Data") + ), + tag = "Blocklist", + operation_id = "Toggle blocklist guard for a particular merchant", + security(("api_key" = [])) +)] +pub async fn toggle_blocklist_guard() {} + #[utoipa::path( post, path = "/blocklist", diff --git a/crates/router/src/core/blocklist.rs b/crates/router/src/core/blocklist.rs index 85845602449..12a0802517c 100644 --- a/crates/router/src/core/blocklist.rs +++ b/crates/router/src/core/blocklist.rs @@ -39,3 +39,13 @@ pub async fn list_blocklist_entries( .await .map(services::ApplicationResponse::Json) } + +pub async fn toggle_blocklist_guard( + state: AppState, + merchant_account: domain::MerchantAccount, + query: api_blocklist::ToggleBlocklistQuery, +) -> RouterResponse<api_blocklist::ToggleBlocklistResponse> { + utils::toggle_blocklist_guard_for_merchant(&state, merchant_account.merchant_id, query) + .await + .map(services::ApplicationResponse::Json) +} diff --git a/crates/router/src/core/blocklist/utils.rs b/crates/router/src/core/blocklist/utils.rs index bc0a7335f1e..43701c80786 100644 --- a/crates/router/src/core/blocklist/utils.rs +++ b/crates/router/src/core/blocklist/utils.rs @@ -4,6 +4,7 @@ use common_utils::{ crypto::{self, SignMessage}, errors::CustomResult, }; +use diesel_models::configs; use error_stack::{IntoReport, ResultExt}; #[cfg(feature = "aws_kms")] use external_services::aws_kms; @@ -85,6 +86,56 @@ pub async fn delete_entry_from_blocklist( Ok(blocklist_entry.foreign_into()) } +pub async fn toggle_blocklist_guard_for_merchant( + state: &AppState, + merchant_id: String, + query: api_blocklist::ToggleBlocklistQuery, +) -> CustomResult<api_blocklist::ToggleBlocklistResponse, errors::ApiErrorResponse> { + let key = get_blocklist_guard_key(merchant_id.as_str()); + let maybe_guard = state.store.find_config_by_key(&key).await; + let new_config = configs::ConfigNew { + key: key.clone(), + config: query.status.to_string(), + }; + match maybe_guard { + Ok(_config) => { + let updated_config = configs::ConfigUpdate::Update { + config: Some(query.status.to_string()), + }; + state + .store + .update_config_by_key(&key, updated_config) + .await + .change_context(errors::ApiErrorResponse::InternalServerError) + .attach_printable("Error enabling the blocklist guard")?; + } + Err(e) if e.current_context().is_db_not_found() => { + state + .store + .insert_config(new_config) + .await + .change_context(errors::ApiErrorResponse::InternalServerError) + .attach_printable("Error enabling the blocklist guard")?; + } + Err(e) => { + logger::error!(error=?e); + Err(e) + .change_context(errors::ApiErrorResponse::InternalServerError) + .attach_printable("Error enabling the blocklist guard")?; + } + }; + let guard_status = if query.status { "enabled" } else { "disabled" }; + Ok(api_blocklist::ToggleBlocklistResponse { + blocklist_guard_status: guard_status.to_string(), + }) +} + +/// Provides the identifier for the specific merchant's blocklist guard config +#[inline(always)] +pub fn get_blocklist_guard_key(merchant_id: &str) -> String { + format!("guard_blocklist_for_{merchant_id}") +} + pub async fn list_blocklist_entries_for_merchant( state: &AppState, merchant_id: String, diff --git a/crates/router/src/routes/app.rs b/crates/router/src/routes/app.rs index f71592c5448..651d3c0026f 100644 --- a/crates/router/src/routes/app.rs +++ b/crates/router/src/routes/app.rs @@ -658,6 +658,9 @@ impl Blocklist { .route(web::post().to(blocklist::add_entry_to_blocklist)) .route(web::delete().to(blocklist::remove_entry_from_blocklist)), ) + .service( + web::resource("/toggle").route(web::post().to(blocklist::toggle_blocklist_guard)), + ) } } diff --git a/crates/router/src/routes/blocklist.rs b/crates/router/src/routes/blocklist.rs index 9c93f49ab83..87072d2c777 100644 --- a/crates/router/src/routes/blocklist.rs +++ b/crates/router/src/routes/blocklist.rs @@ -117,3 +117,41 @@ pub async fn list_blocked_payment_methods( )) .await } + +#[utoipa::path( + post, + path = "/blocklist/toggle", + params ( + ("status" = bool, Query, description = "Boolean value to enable/disable blocklist"), + ), + responses( + (status = 200, description = "Blocklist guard enabled/disabled", body = ToggleBlocklistResponse), + (status = 400, description = "Invalid Data") + ), + tag = "Blocklist", + operation_id = "Toggle blocklist guard for a particular merchant", + security(("api_key" = [])) +)] +pub async fn toggle_blocklist_guard( + state: web::Data<AppState>, + req: HttpRequest, + query_payload: web::Query<api_blocklist::ToggleBlocklistQuery>, +) -> HttpResponse { + let flow = Flow::ListBlocklist; + Box::pin(api::server_wrap( + flow, + state, + &req, + query_payload.into_inner(), + |state, auth: auth::AuthenticationData, query| { + blocklist::toggle_blocklist_guard(state, auth.merchant_account, query) + }, + auth::auth_type( + &auth::ApiKeyAuth, + &auth::JWTAuth(Permission::MerchantAccountWrite), + req.headers(), + ), + api_locking::LockAction::NotApplicable, + )) + .await +} diff --git a/crates/router/src/routes/lock_utils.rs b/crates/router/src/routes/lock_utils.rs index 042e89fdd52..1636ed3a764 100644 --- a/crates/router/src/routes/lock_utils.rs +++ b/crates/router/src/routes/lock_utils.rs @@ -63,6 +63,7 @@ impl From<Flow> for ApiIdentifier { Flow::AddToBlocklist => Self::Blocklist, Flow::DeleteFromBlocklist => Self::Blocklist, Flow::ListBlocklist => Self::Blocklist, + Flow::ToggleBlocklistGuard => Self::Blocklist, Flow::MerchantConnectorsCreate | Flow::MerchantConnectorsRetrieve diff --git a/crates/router_env/src/logger/types.rs b/crates/router_env/src/logger/types.rs index 11e6f9c0ed8..4344acf89ff 100644 --- a/crates/router_env/src/logger/types.rs +++ b/crates/router_env/src/logger/types.rs @@ -201,6 +201,8 @@ pub enum Flow { DeleteFromBlocklist, /// List entries from blocklist ListBlocklist, + /// Toggle blocklist for merchant + ToggleBlocklistGuard, /// Incoming Webhook Receive IncomingWebhookReceive, /// Validate payment method flow diff --git a/openapi/openapi_spec.json b/openapi/openapi_spec.json index 7f234661b51..b6531771e11 100644 --- a/openapi/openapi_spec.json +++ b/openapi/openapi_spec.json @@ -1233,6 +1233,45 @@ ] } }, + "/blocklist/toggle": { + "post": { + "tags": [ + "Blocklist" + ], + "operationId": "Toggle blocklist guard for a particular merchant", + "parameters": [ + { + "name": "status", + "in": "query", + "description": "Boolean value to enable/disable blocklist", + "required": true, + "schema": { + "type": "boolean" + } + } + ], + "responses": { + "200": { + "description": "Blocklist guard enabled/disabled", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ToggleBlocklistResponse" + } + } + } + }, + "400": { + "description": "Invalid Data" + } + }, + "security": [ + { + "api_key": [] + } + ] + } + }, "/customers": { "post": { "tags": [ @@ -16114,6 +16153,17 @@ } } }, + "ToggleBlocklistResponse": { + "type": "object", + "required": [ + "blocklist_guard_status" + ], + "properties": { + "blocklist_guard_status": { + "type": "string" + } + } + }, "TouchNGoRedirection": { "type": "object" },
2024-02-06T14:08:09Z
## 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 Api mentioned will be for toggling the `blocklist-guard` for a particular merchant. So the changes will be as mentioned: > It will try to find a config associated with that merchant (guard_blocklist_for_{merchant_id}) which in tern is a boolean config. > If present it will enable/disable it accordingly. > If not present it will create a config and assign it appropriate value. More in the linked issue. ### 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). --> ## 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 can be found out in the linked issue. ## 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 - [ ] I added a [CHANGELOG](/CHANGELOG.md) entry if applicable
a15e7ae9b156659e61de752ca94b6f43932d9de5
This can be found out in the linked issue.